xref: /linux/kernel/bpf/verifier.c (revision a93fbb002310ef04fce504dbf1510f6eb8265188)
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 bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191 {
192 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
193 }
194 
195 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196 {
197 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
198 }
199 
200 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
201 			      const struct bpf_map *map, bool unpriv)
202 {
203 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
204 	unpriv |= bpf_map_ptr_unpriv(aux);
205 	aux->map_ptr_state = (unsigned long)map |
206 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
207 }
208 
209 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_key_state & BPF_MAP_KEY_POISON;
212 }
213 
214 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215 {
216 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
217 }
218 
219 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220 {
221 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
222 }
223 
224 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225 {
226 	bool poisoned = bpf_map_key_poisoned(aux);
227 
228 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
229 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
230 }
231 
232 static bool bpf_pseudo_call(const struct bpf_insn *insn)
233 {
234 	return insn->code == (BPF_JMP | BPF_CALL) &&
235 	       insn->src_reg == BPF_PSEUDO_CALL;
236 }
237 
238 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
239 {
240 	return insn->code == (BPF_JMP | BPF_CALL) &&
241 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
242 }
243 
244 struct bpf_call_arg_meta {
245 	struct bpf_map *map_ptr;
246 	bool raw_mode;
247 	bool pkt_access;
248 	int regno;
249 	int access_size;
250 	int mem_size;
251 	u64 msize_max_value;
252 	int ref_obj_id;
253 	int map_uid;
254 	int func_id;
255 	struct btf *btf;
256 	u32 btf_id;
257 	struct btf *ret_btf;
258 	u32 ret_btf_id;
259 	u32 subprogno;
260 };
261 
262 struct btf *btf_vmlinux;
263 
264 static DEFINE_MUTEX(bpf_verifier_lock);
265 
266 static const struct bpf_line_info *
267 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
268 {
269 	const struct bpf_line_info *linfo;
270 	const struct bpf_prog *prog;
271 	u32 i, nr_linfo;
272 
273 	prog = env->prog;
274 	nr_linfo = prog->aux->nr_linfo;
275 
276 	if (!nr_linfo || insn_off >= prog->len)
277 		return NULL;
278 
279 	linfo = prog->aux->linfo;
280 	for (i = 1; i < nr_linfo; i++)
281 		if (insn_off < linfo[i].insn_off)
282 			break;
283 
284 	return &linfo[i - 1];
285 }
286 
287 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
288 		       va_list args)
289 {
290 	unsigned int n;
291 
292 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
293 
294 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
295 		  "verifier log line truncated - local buffer too short\n");
296 
297 	if (log->level == BPF_LOG_KERNEL) {
298 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
299 
300 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
301 		return;
302 	}
303 
304 	n = min(log->len_total - log->len_used - 1, n);
305 	log->kbuf[n] = '\0';
306 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
307 		log->len_used += n;
308 	else
309 		log->ubuf = NULL;
310 }
311 
312 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
313 {
314 	char zero = 0;
315 
316 	if (!bpf_verifier_log_needed(log))
317 		return;
318 
319 	log->len_used = new_pos;
320 	if (put_user(zero, log->ubuf + new_pos))
321 		log->ubuf = NULL;
322 }
323 
324 /* log_level controls verbosity level of eBPF verifier.
325  * bpf_verifier_log_write() is used to dump the verification trace to the log,
326  * so the user can figure out what's wrong with the program
327  */
328 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
329 					   const char *fmt, ...)
330 {
331 	va_list args;
332 
333 	if (!bpf_verifier_log_needed(&env->log))
334 		return;
335 
336 	va_start(args, fmt);
337 	bpf_verifier_vlog(&env->log, fmt, args);
338 	va_end(args);
339 }
340 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
341 
342 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
343 {
344 	struct bpf_verifier_env *env = private_data;
345 	va_list args;
346 
347 	if (!bpf_verifier_log_needed(&env->log))
348 		return;
349 
350 	va_start(args, fmt);
351 	bpf_verifier_vlog(&env->log, fmt, args);
352 	va_end(args);
353 }
354 
355 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
356 			    const char *fmt, ...)
357 {
358 	va_list args;
359 
360 	if (!bpf_verifier_log_needed(log))
361 		return;
362 
363 	va_start(args, fmt);
364 	bpf_verifier_vlog(log, fmt, args);
365 	va_end(args);
366 }
367 
368 static const char *ltrim(const char *s)
369 {
370 	while (isspace(*s))
371 		s++;
372 
373 	return s;
374 }
375 
376 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
377 					 u32 insn_off,
378 					 const char *prefix_fmt, ...)
379 {
380 	const struct bpf_line_info *linfo;
381 
382 	if (!bpf_verifier_log_needed(&env->log))
383 		return;
384 
385 	linfo = find_linfo(env, insn_off);
386 	if (!linfo || linfo == env->prev_linfo)
387 		return;
388 
389 	if (prefix_fmt) {
390 		va_list args;
391 
392 		va_start(args, prefix_fmt);
393 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
394 		va_end(args);
395 	}
396 
397 	verbose(env, "%s\n",
398 		ltrim(btf_name_by_offset(env->prog->aux->btf,
399 					 linfo->line_off)));
400 
401 	env->prev_linfo = linfo;
402 }
403 
404 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
405 				   struct bpf_reg_state *reg,
406 				   struct tnum *range, const char *ctx,
407 				   const char *reg_name)
408 {
409 	char tn_buf[48];
410 
411 	verbose(env, "At %s the register %s ", ctx, reg_name);
412 	if (!tnum_is_unknown(reg->var_off)) {
413 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
414 		verbose(env, "has value %s", tn_buf);
415 	} else {
416 		verbose(env, "has unknown scalar value");
417 	}
418 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
419 	verbose(env, " should have been in %s\n", tn_buf);
420 }
421 
422 static bool type_is_pkt_pointer(enum bpf_reg_type type)
423 {
424 	return type == PTR_TO_PACKET ||
425 	       type == PTR_TO_PACKET_META;
426 }
427 
428 static bool type_is_sk_pointer(enum bpf_reg_type type)
429 {
430 	return type == PTR_TO_SOCKET ||
431 		type == PTR_TO_SOCK_COMMON ||
432 		type == PTR_TO_TCP_SOCK ||
433 		type == PTR_TO_XDP_SOCK;
434 }
435 
436 static bool reg_type_not_null(enum bpf_reg_type type)
437 {
438 	return type == PTR_TO_SOCKET ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_MAP_VALUE ||
441 		type == PTR_TO_MAP_KEY ||
442 		type == PTR_TO_SOCK_COMMON;
443 }
444 
445 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
446 {
447 	return reg->type == PTR_TO_MAP_VALUE &&
448 		map_value_has_spin_lock(reg->map_ptr);
449 }
450 
451 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
452 {
453 	return base_type(type) == PTR_TO_SOCKET ||
454 		base_type(type) == PTR_TO_TCP_SOCK ||
455 		base_type(type) == PTR_TO_MEM ||
456 		base_type(type) == PTR_TO_BTF_ID;
457 }
458 
459 static bool type_is_rdonly_mem(u32 type)
460 {
461 	return type & MEM_RDONLY;
462 }
463 
464 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
465 {
466 	return type == ARG_PTR_TO_SOCK_COMMON;
467 }
468 
469 static bool type_may_be_null(u32 type)
470 {
471 	return type & PTR_MAYBE_NULL;
472 }
473 
474 /* Determine whether the function releases some resources allocated by another
475  * function call. The first reference type argument will be assumed to be
476  * released by release_reference().
477  */
478 static bool is_release_function(enum bpf_func_id func_id)
479 {
480 	return func_id == BPF_FUNC_sk_release ||
481 	       func_id == BPF_FUNC_ringbuf_submit ||
482 	       func_id == BPF_FUNC_ringbuf_discard;
483 }
484 
485 static bool may_be_acquire_function(enum bpf_func_id func_id)
486 {
487 	return func_id == BPF_FUNC_sk_lookup_tcp ||
488 		func_id == BPF_FUNC_sk_lookup_udp ||
489 		func_id == BPF_FUNC_skc_lookup_tcp ||
490 		func_id == BPF_FUNC_map_lookup_elem ||
491 	        func_id == BPF_FUNC_ringbuf_reserve;
492 }
493 
494 static bool is_acquire_function(enum bpf_func_id func_id,
495 				const struct bpf_map *map)
496 {
497 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
498 
499 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
500 	    func_id == BPF_FUNC_sk_lookup_udp ||
501 	    func_id == BPF_FUNC_skc_lookup_tcp ||
502 	    func_id == BPF_FUNC_ringbuf_reserve)
503 		return true;
504 
505 	if (func_id == BPF_FUNC_map_lookup_elem &&
506 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
507 	     map_type == BPF_MAP_TYPE_SOCKHASH))
508 		return true;
509 
510 	return false;
511 }
512 
513 static bool is_ptr_cast_function(enum bpf_func_id func_id)
514 {
515 	return func_id == BPF_FUNC_tcp_sock ||
516 		func_id == BPF_FUNC_sk_fullsock ||
517 		func_id == BPF_FUNC_skc_to_tcp_sock ||
518 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
519 		func_id == BPF_FUNC_skc_to_udp6_sock ||
520 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
521 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
522 }
523 
524 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
525 {
526 	return BPF_CLASS(insn->code) == BPF_STX &&
527 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
528 	       insn->imm == BPF_CMPXCHG;
529 }
530 
531 /* string representation of 'enum bpf_reg_type'
532  *
533  * Note that reg_type_str() can not appear more than once in a single verbose()
534  * statement.
535  */
536 static const char *reg_type_str(struct bpf_verifier_env *env,
537 				enum bpf_reg_type type)
538 {
539 	char postfix[16] = {0}, prefix[32] = {0};
540 	static const char * const str[] = {
541 		[NOT_INIT]		= "?",
542 		[SCALAR_VALUE]		= "scalar",
543 		[PTR_TO_CTX]		= "ctx",
544 		[CONST_PTR_TO_MAP]	= "map_ptr",
545 		[PTR_TO_MAP_VALUE]	= "map_value",
546 		[PTR_TO_STACK]		= "fp",
547 		[PTR_TO_PACKET]		= "pkt",
548 		[PTR_TO_PACKET_META]	= "pkt_meta",
549 		[PTR_TO_PACKET_END]	= "pkt_end",
550 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
551 		[PTR_TO_SOCKET]		= "sock",
552 		[PTR_TO_SOCK_COMMON]	= "sock_common",
553 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
554 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
555 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
556 		[PTR_TO_BTF_ID]		= "ptr_",
557 		[PTR_TO_MEM]		= "mem",
558 		[PTR_TO_BUF]		= "buf",
559 		[PTR_TO_FUNC]		= "func",
560 		[PTR_TO_MAP_KEY]	= "map_key",
561 	};
562 
563 	if (type & PTR_MAYBE_NULL) {
564 		if (base_type(type) == PTR_TO_BTF_ID)
565 			strncpy(postfix, "or_null_", 16);
566 		else
567 			strncpy(postfix, "_or_null", 16);
568 	}
569 
570 	if (type & MEM_RDONLY)
571 		strncpy(prefix, "rdonly_", 32);
572 	if (type & MEM_ALLOC)
573 		strncpy(prefix, "alloc_", 32);
574 	if (type & MEM_USER)
575 		strncpy(prefix, "user_", 32);
576 	if (type & MEM_PERCPU)
577 		strncpy(prefix, "percpu_", 32);
578 
579 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
580 		 prefix, str[base_type(type)], postfix);
581 	return env->type_str_buf;
582 }
583 
584 static char slot_type_char[] = {
585 	[STACK_INVALID]	= '?',
586 	[STACK_SPILL]	= 'r',
587 	[STACK_MISC]	= 'm',
588 	[STACK_ZERO]	= '0',
589 };
590 
591 static void print_liveness(struct bpf_verifier_env *env,
592 			   enum bpf_reg_liveness live)
593 {
594 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
595 	    verbose(env, "_");
596 	if (live & REG_LIVE_READ)
597 		verbose(env, "r");
598 	if (live & REG_LIVE_WRITTEN)
599 		verbose(env, "w");
600 	if (live & REG_LIVE_DONE)
601 		verbose(env, "D");
602 }
603 
604 static struct bpf_func_state *func(struct bpf_verifier_env *env,
605 				   const struct bpf_reg_state *reg)
606 {
607 	struct bpf_verifier_state *cur = env->cur_state;
608 
609 	return cur->frame[reg->frameno];
610 }
611 
612 static const char *kernel_type_name(const struct btf* btf, u32 id)
613 {
614 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
615 }
616 
617 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
618 {
619 	env->scratched_regs |= 1U << regno;
620 }
621 
622 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
623 {
624 	env->scratched_stack_slots |= 1ULL << spi;
625 }
626 
627 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
628 {
629 	return (env->scratched_regs >> regno) & 1;
630 }
631 
632 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
633 {
634 	return (env->scratched_stack_slots >> regno) & 1;
635 }
636 
637 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
638 {
639 	return env->scratched_regs || env->scratched_stack_slots;
640 }
641 
642 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
643 {
644 	env->scratched_regs = 0U;
645 	env->scratched_stack_slots = 0ULL;
646 }
647 
648 /* Used for printing the entire verifier state. */
649 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
650 {
651 	env->scratched_regs = ~0U;
652 	env->scratched_stack_slots = ~0ULL;
653 }
654 
655 /* The reg state of a pointer or a bounded scalar was saved when
656  * it was spilled to the stack.
657  */
658 static bool is_spilled_reg(const struct bpf_stack_state *stack)
659 {
660 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
661 }
662 
663 static void scrub_spilled_slot(u8 *stype)
664 {
665 	if (*stype != STACK_INVALID)
666 		*stype = STACK_MISC;
667 }
668 
669 static void print_verifier_state(struct bpf_verifier_env *env,
670 				 const struct bpf_func_state *state,
671 				 bool print_all)
672 {
673 	const struct bpf_reg_state *reg;
674 	enum bpf_reg_type t;
675 	int i;
676 
677 	if (state->frameno)
678 		verbose(env, " frame%d:", state->frameno);
679 	for (i = 0; i < MAX_BPF_REG; i++) {
680 		reg = &state->regs[i];
681 		t = reg->type;
682 		if (t == NOT_INIT)
683 			continue;
684 		if (!print_all && !reg_scratched(env, i))
685 			continue;
686 		verbose(env, " R%d", i);
687 		print_liveness(env, reg->live);
688 		verbose(env, "=");
689 		if (t == SCALAR_VALUE && reg->precise)
690 			verbose(env, "P");
691 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
692 		    tnum_is_const(reg->var_off)) {
693 			/* reg->off should be 0 for SCALAR_VALUE */
694 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
695 			verbose(env, "%lld", reg->var_off.value + reg->off);
696 		} else {
697 			const char *sep = "";
698 
699 			verbose(env, "%s", reg_type_str(env, t));
700 			if (base_type(t) == PTR_TO_BTF_ID)
701 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
702 			verbose(env, "(");
703 /*
704  * _a stands for append, was shortened to avoid multiline statements below.
705  * This macro is used to output a comma separated list of attributes.
706  */
707 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
708 
709 			if (reg->id)
710 				verbose_a("id=%d", reg->id);
711 			if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
712 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
713 			if (t != SCALAR_VALUE)
714 				verbose_a("off=%d", reg->off);
715 			if (type_is_pkt_pointer(t))
716 				verbose_a("r=%d", reg->range);
717 			else if (base_type(t) == CONST_PTR_TO_MAP ||
718 				 base_type(t) == PTR_TO_MAP_KEY ||
719 				 base_type(t) == PTR_TO_MAP_VALUE)
720 				verbose_a("ks=%d,vs=%d",
721 					  reg->map_ptr->key_size,
722 					  reg->map_ptr->value_size);
723 			if (tnum_is_const(reg->var_off)) {
724 				/* Typically an immediate SCALAR_VALUE, but
725 				 * could be a pointer whose offset is too big
726 				 * for reg->off
727 				 */
728 				verbose_a("imm=%llx", reg->var_off.value);
729 			} else {
730 				if (reg->smin_value != reg->umin_value &&
731 				    reg->smin_value != S64_MIN)
732 					verbose_a("smin=%lld", (long long)reg->smin_value);
733 				if (reg->smax_value != reg->umax_value &&
734 				    reg->smax_value != S64_MAX)
735 					verbose_a("smax=%lld", (long long)reg->smax_value);
736 				if (reg->umin_value != 0)
737 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
738 				if (reg->umax_value != U64_MAX)
739 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
740 				if (!tnum_is_unknown(reg->var_off)) {
741 					char tn_buf[48];
742 
743 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
744 					verbose_a("var_off=%s", tn_buf);
745 				}
746 				if (reg->s32_min_value != reg->smin_value &&
747 				    reg->s32_min_value != S32_MIN)
748 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
749 				if (reg->s32_max_value != reg->smax_value &&
750 				    reg->s32_max_value != S32_MAX)
751 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
752 				if (reg->u32_min_value != reg->umin_value &&
753 				    reg->u32_min_value != U32_MIN)
754 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
755 				if (reg->u32_max_value != reg->umax_value &&
756 				    reg->u32_max_value != U32_MAX)
757 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
758 			}
759 #undef verbose_a
760 
761 			verbose(env, ")");
762 		}
763 	}
764 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
765 		char types_buf[BPF_REG_SIZE + 1];
766 		bool valid = false;
767 		int j;
768 
769 		for (j = 0; j < BPF_REG_SIZE; j++) {
770 			if (state->stack[i].slot_type[j] != STACK_INVALID)
771 				valid = true;
772 			types_buf[j] = slot_type_char[
773 					state->stack[i].slot_type[j]];
774 		}
775 		types_buf[BPF_REG_SIZE] = 0;
776 		if (!valid)
777 			continue;
778 		if (!print_all && !stack_slot_scratched(env, i))
779 			continue;
780 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
781 		print_liveness(env, state->stack[i].spilled_ptr.live);
782 		if (is_spilled_reg(&state->stack[i])) {
783 			reg = &state->stack[i].spilled_ptr;
784 			t = reg->type;
785 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
786 			if (t == SCALAR_VALUE && reg->precise)
787 				verbose(env, "P");
788 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
789 				verbose(env, "%lld", reg->var_off.value + reg->off);
790 		} else {
791 			verbose(env, "=%s", types_buf);
792 		}
793 	}
794 	if (state->acquired_refs && state->refs[0].id) {
795 		verbose(env, " refs=%d", state->refs[0].id);
796 		for (i = 1; i < state->acquired_refs; i++)
797 			if (state->refs[i].id)
798 				verbose(env, ",%d", state->refs[i].id);
799 	}
800 	if (state->in_callback_fn)
801 		verbose(env, " cb");
802 	if (state->in_async_callback_fn)
803 		verbose(env, " async_cb");
804 	verbose(env, "\n");
805 	mark_verifier_state_clean(env);
806 }
807 
808 static inline u32 vlog_alignment(u32 pos)
809 {
810 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
811 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
812 }
813 
814 static void print_insn_state(struct bpf_verifier_env *env,
815 			     const struct bpf_func_state *state)
816 {
817 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
818 		/* remove new line character */
819 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
820 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
821 	} else {
822 		verbose(env, "%d:", env->insn_idx);
823 	}
824 	print_verifier_state(env, state, false);
825 }
826 
827 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
828  * small to hold src. This is different from krealloc since we don't want to preserve
829  * the contents of dst.
830  *
831  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
832  * not be allocated.
833  */
834 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
835 {
836 	size_t bytes;
837 
838 	if (ZERO_OR_NULL_PTR(src))
839 		goto out;
840 
841 	if (unlikely(check_mul_overflow(n, size, &bytes)))
842 		return NULL;
843 
844 	if (ksize(dst) < bytes) {
845 		kfree(dst);
846 		dst = kmalloc_track_caller(bytes, flags);
847 		if (!dst)
848 			return NULL;
849 	}
850 
851 	memcpy(dst, src, bytes);
852 out:
853 	return dst ? dst : ZERO_SIZE_PTR;
854 }
855 
856 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
857  * small to hold new_n items. new items are zeroed out if the array grows.
858  *
859  * Contrary to krealloc_array, does not free arr if new_n is zero.
860  */
861 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
862 {
863 	if (!new_n || old_n == new_n)
864 		goto out;
865 
866 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
867 	if (!arr)
868 		return NULL;
869 
870 	if (new_n > old_n)
871 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
872 
873 out:
874 	return arr ? arr : ZERO_SIZE_PTR;
875 }
876 
877 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
878 {
879 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
880 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
881 	if (!dst->refs)
882 		return -ENOMEM;
883 
884 	dst->acquired_refs = src->acquired_refs;
885 	return 0;
886 }
887 
888 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
889 {
890 	size_t n = src->allocated_stack / BPF_REG_SIZE;
891 
892 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
893 				GFP_KERNEL);
894 	if (!dst->stack)
895 		return -ENOMEM;
896 
897 	dst->allocated_stack = src->allocated_stack;
898 	return 0;
899 }
900 
901 static int resize_reference_state(struct bpf_func_state *state, size_t n)
902 {
903 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
904 				    sizeof(struct bpf_reference_state));
905 	if (!state->refs)
906 		return -ENOMEM;
907 
908 	state->acquired_refs = n;
909 	return 0;
910 }
911 
912 static int grow_stack_state(struct bpf_func_state *state, int size)
913 {
914 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
915 
916 	if (old_n >= n)
917 		return 0;
918 
919 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
920 	if (!state->stack)
921 		return -ENOMEM;
922 
923 	state->allocated_stack = size;
924 	return 0;
925 }
926 
927 /* Acquire a pointer id from the env and update the state->refs to include
928  * this new pointer reference.
929  * On success, returns a valid pointer id to associate with the register
930  * On failure, returns a negative errno.
931  */
932 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
933 {
934 	struct bpf_func_state *state = cur_func(env);
935 	int new_ofs = state->acquired_refs;
936 	int id, err;
937 
938 	err = resize_reference_state(state, state->acquired_refs + 1);
939 	if (err)
940 		return err;
941 	id = ++env->id_gen;
942 	state->refs[new_ofs].id = id;
943 	state->refs[new_ofs].insn_idx = insn_idx;
944 
945 	return id;
946 }
947 
948 /* release function corresponding to acquire_reference_state(). Idempotent. */
949 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
950 {
951 	int i, last_idx;
952 
953 	last_idx = state->acquired_refs - 1;
954 	for (i = 0; i < state->acquired_refs; i++) {
955 		if (state->refs[i].id == ptr_id) {
956 			if (last_idx && i != last_idx)
957 				memcpy(&state->refs[i], &state->refs[last_idx],
958 				       sizeof(*state->refs));
959 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
960 			state->acquired_refs--;
961 			return 0;
962 		}
963 	}
964 	return -EINVAL;
965 }
966 
967 static void free_func_state(struct bpf_func_state *state)
968 {
969 	if (!state)
970 		return;
971 	kfree(state->refs);
972 	kfree(state->stack);
973 	kfree(state);
974 }
975 
976 static void clear_jmp_history(struct bpf_verifier_state *state)
977 {
978 	kfree(state->jmp_history);
979 	state->jmp_history = NULL;
980 	state->jmp_history_cnt = 0;
981 }
982 
983 static void free_verifier_state(struct bpf_verifier_state *state,
984 				bool free_self)
985 {
986 	int i;
987 
988 	for (i = 0; i <= state->curframe; i++) {
989 		free_func_state(state->frame[i]);
990 		state->frame[i] = NULL;
991 	}
992 	clear_jmp_history(state);
993 	if (free_self)
994 		kfree(state);
995 }
996 
997 /* copy verifier state from src to dst growing dst stack space
998  * when necessary to accommodate larger src stack
999  */
1000 static int copy_func_state(struct bpf_func_state *dst,
1001 			   const struct bpf_func_state *src)
1002 {
1003 	int err;
1004 
1005 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1006 	err = copy_reference_state(dst, src);
1007 	if (err)
1008 		return err;
1009 	return copy_stack_state(dst, src);
1010 }
1011 
1012 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1013 			       const struct bpf_verifier_state *src)
1014 {
1015 	struct bpf_func_state *dst;
1016 	int i, err;
1017 
1018 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1019 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1020 					    GFP_USER);
1021 	if (!dst_state->jmp_history)
1022 		return -ENOMEM;
1023 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1024 
1025 	/* if dst has more stack frames then src frame, free them */
1026 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1027 		free_func_state(dst_state->frame[i]);
1028 		dst_state->frame[i] = NULL;
1029 	}
1030 	dst_state->speculative = src->speculative;
1031 	dst_state->curframe = src->curframe;
1032 	dst_state->active_spin_lock = src->active_spin_lock;
1033 	dst_state->branches = src->branches;
1034 	dst_state->parent = src->parent;
1035 	dst_state->first_insn_idx = src->first_insn_idx;
1036 	dst_state->last_insn_idx = src->last_insn_idx;
1037 	for (i = 0; i <= src->curframe; i++) {
1038 		dst = dst_state->frame[i];
1039 		if (!dst) {
1040 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1041 			if (!dst)
1042 				return -ENOMEM;
1043 			dst_state->frame[i] = dst;
1044 		}
1045 		err = copy_func_state(dst, src->frame[i]);
1046 		if (err)
1047 			return err;
1048 	}
1049 	return 0;
1050 }
1051 
1052 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1053 {
1054 	while (st) {
1055 		u32 br = --st->branches;
1056 
1057 		/* WARN_ON(br > 1) technically makes sense here,
1058 		 * but see comment in push_stack(), hence:
1059 		 */
1060 		WARN_ONCE((int)br < 0,
1061 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1062 			  br);
1063 		if (br)
1064 			break;
1065 		st = st->parent;
1066 	}
1067 }
1068 
1069 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1070 		     int *insn_idx, bool pop_log)
1071 {
1072 	struct bpf_verifier_state *cur = env->cur_state;
1073 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1074 	int err;
1075 
1076 	if (env->head == NULL)
1077 		return -ENOENT;
1078 
1079 	if (cur) {
1080 		err = copy_verifier_state(cur, &head->st);
1081 		if (err)
1082 			return err;
1083 	}
1084 	if (pop_log)
1085 		bpf_vlog_reset(&env->log, head->log_pos);
1086 	if (insn_idx)
1087 		*insn_idx = head->insn_idx;
1088 	if (prev_insn_idx)
1089 		*prev_insn_idx = head->prev_insn_idx;
1090 	elem = head->next;
1091 	free_verifier_state(&head->st, false);
1092 	kfree(head);
1093 	env->head = elem;
1094 	env->stack_size--;
1095 	return 0;
1096 }
1097 
1098 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1099 					     int insn_idx, int prev_insn_idx,
1100 					     bool speculative)
1101 {
1102 	struct bpf_verifier_state *cur = env->cur_state;
1103 	struct bpf_verifier_stack_elem *elem;
1104 	int err;
1105 
1106 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1107 	if (!elem)
1108 		goto err;
1109 
1110 	elem->insn_idx = insn_idx;
1111 	elem->prev_insn_idx = prev_insn_idx;
1112 	elem->next = env->head;
1113 	elem->log_pos = env->log.len_used;
1114 	env->head = elem;
1115 	env->stack_size++;
1116 	err = copy_verifier_state(&elem->st, cur);
1117 	if (err)
1118 		goto err;
1119 	elem->st.speculative |= speculative;
1120 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1121 		verbose(env, "The sequence of %d jumps is too complex.\n",
1122 			env->stack_size);
1123 		goto err;
1124 	}
1125 	if (elem->st.parent) {
1126 		++elem->st.parent->branches;
1127 		/* WARN_ON(branches > 2) technically makes sense here,
1128 		 * but
1129 		 * 1. speculative states will bump 'branches' for non-branch
1130 		 * instructions
1131 		 * 2. is_state_visited() heuristics may decide not to create
1132 		 * a new state for a sequence of branches and all such current
1133 		 * and cloned states will be pointing to a single parent state
1134 		 * which might have large 'branches' count.
1135 		 */
1136 	}
1137 	return &elem->st;
1138 err:
1139 	free_verifier_state(env->cur_state, true);
1140 	env->cur_state = NULL;
1141 	/* pop all elements and return */
1142 	while (!pop_stack(env, NULL, NULL, false));
1143 	return NULL;
1144 }
1145 
1146 #define CALLER_SAVED_REGS 6
1147 static const int caller_saved[CALLER_SAVED_REGS] = {
1148 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1149 };
1150 
1151 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1152 				struct bpf_reg_state *reg);
1153 
1154 /* This helper doesn't clear reg->id */
1155 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1156 {
1157 	reg->var_off = tnum_const(imm);
1158 	reg->smin_value = (s64)imm;
1159 	reg->smax_value = (s64)imm;
1160 	reg->umin_value = imm;
1161 	reg->umax_value = imm;
1162 
1163 	reg->s32_min_value = (s32)imm;
1164 	reg->s32_max_value = (s32)imm;
1165 	reg->u32_min_value = (u32)imm;
1166 	reg->u32_max_value = (u32)imm;
1167 }
1168 
1169 /* Mark the unknown part of a register (variable offset or scalar value) as
1170  * known to have the value @imm.
1171  */
1172 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1173 {
1174 	/* Clear id, off, and union(map_ptr, range) */
1175 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1176 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1177 	___mark_reg_known(reg, imm);
1178 }
1179 
1180 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1181 {
1182 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1183 	reg->s32_min_value = (s32)imm;
1184 	reg->s32_max_value = (s32)imm;
1185 	reg->u32_min_value = (u32)imm;
1186 	reg->u32_max_value = (u32)imm;
1187 }
1188 
1189 /* Mark the 'variable offset' part of a register as zero.  This should be
1190  * used only on registers holding a pointer type.
1191  */
1192 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1193 {
1194 	__mark_reg_known(reg, 0);
1195 }
1196 
1197 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1198 {
1199 	__mark_reg_known(reg, 0);
1200 	reg->type = SCALAR_VALUE;
1201 }
1202 
1203 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1204 				struct bpf_reg_state *regs, u32 regno)
1205 {
1206 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1207 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1208 		/* Something bad happened, let's kill all regs */
1209 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1210 			__mark_reg_not_init(env, regs + regno);
1211 		return;
1212 	}
1213 	__mark_reg_known_zero(regs + regno);
1214 }
1215 
1216 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1217 {
1218 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1219 		const struct bpf_map *map = reg->map_ptr;
1220 
1221 		if (map->inner_map_meta) {
1222 			reg->type = CONST_PTR_TO_MAP;
1223 			reg->map_ptr = map->inner_map_meta;
1224 			/* transfer reg's id which is unique for every map_lookup_elem
1225 			 * as UID of the inner map.
1226 			 */
1227 			if (map_value_has_timer(map->inner_map_meta))
1228 				reg->map_uid = reg->id;
1229 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1230 			reg->type = PTR_TO_XDP_SOCK;
1231 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1232 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1233 			reg->type = PTR_TO_SOCKET;
1234 		} else {
1235 			reg->type = PTR_TO_MAP_VALUE;
1236 		}
1237 		return;
1238 	}
1239 
1240 	reg->type &= ~PTR_MAYBE_NULL;
1241 }
1242 
1243 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1244 {
1245 	return type_is_pkt_pointer(reg->type);
1246 }
1247 
1248 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1249 {
1250 	return reg_is_pkt_pointer(reg) ||
1251 	       reg->type == PTR_TO_PACKET_END;
1252 }
1253 
1254 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1255 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1256 				    enum bpf_reg_type which)
1257 {
1258 	/* The register can already have a range from prior markings.
1259 	 * This is fine as long as it hasn't been advanced from its
1260 	 * origin.
1261 	 */
1262 	return reg->type == which &&
1263 	       reg->id == 0 &&
1264 	       reg->off == 0 &&
1265 	       tnum_equals_const(reg->var_off, 0);
1266 }
1267 
1268 /* Reset the min/max bounds of a register */
1269 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1270 {
1271 	reg->smin_value = S64_MIN;
1272 	reg->smax_value = S64_MAX;
1273 	reg->umin_value = 0;
1274 	reg->umax_value = U64_MAX;
1275 
1276 	reg->s32_min_value = S32_MIN;
1277 	reg->s32_max_value = S32_MAX;
1278 	reg->u32_min_value = 0;
1279 	reg->u32_max_value = U32_MAX;
1280 }
1281 
1282 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1283 {
1284 	reg->smin_value = S64_MIN;
1285 	reg->smax_value = S64_MAX;
1286 	reg->umin_value = 0;
1287 	reg->umax_value = U64_MAX;
1288 }
1289 
1290 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1291 {
1292 	reg->s32_min_value = S32_MIN;
1293 	reg->s32_max_value = S32_MAX;
1294 	reg->u32_min_value = 0;
1295 	reg->u32_max_value = U32_MAX;
1296 }
1297 
1298 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1299 {
1300 	struct tnum var32_off = tnum_subreg(reg->var_off);
1301 
1302 	/* min signed is max(sign bit) | min(other bits) */
1303 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1304 			var32_off.value | (var32_off.mask & S32_MIN));
1305 	/* max signed is min(sign bit) | max(other bits) */
1306 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1307 			var32_off.value | (var32_off.mask & S32_MAX));
1308 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1309 	reg->u32_max_value = min(reg->u32_max_value,
1310 				 (u32)(var32_off.value | var32_off.mask));
1311 }
1312 
1313 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1314 {
1315 	/* min signed is max(sign bit) | min(other bits) */
1316 	reg->smin_value = max_t(s64, reg->smin_value,
1317 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1318 	/* max signed is min(sign bit) | max(other bits) */
1319 	reg->smax_value = min_t(s64, reg->smax_value,
1320 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1321 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1322 	reg->umax_value = min(reg->umax_value,
1323 			      reg->var_off.value | reg->var_off.mask);
1324 }
1325 
1326 static void __update_reg_bounds(struct bpf_reg_state *reg)
1327 {
1328 	__update_reg32_bounds(reg);
1329 	__update_reg64_bounds(reg);
1330 }
1331 
1332 /* Uses signed min/max values to inform unsigned, and vice-versa */
1333 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1334 {
1335 	/* Learn sign from signed bounds.
1336 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1337 	 * are the same, so combine.  This works even in the negative case, e.g.
1338 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1339 	 */
1340 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1341 		reg->s32_min_value = reg->u32_min_value =
1342 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1343 		reg->s32_max_value = reg->u32_max_value =
1344 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1345 		return;
1346 	}
1347 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1348 	 * boundary, so we must be careful.
1349 	 */
1350 	if ((s32)reg->u32_max_value >= 0) {
1351 		/* Positive.  We can't learn anything from the smin, but smax
1352 		 * is positive, hence safe.
1353 		 */
1354 		reg->s32_min_value = reg->u32_min_value;
1355 		reg->s32_max_value = reg->u32_max_value =
1356 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1357 	} else if ((s32)reg->u32_min_value < 0) {
1358 		/* Negative.  We can't learn anything from the smax, but smin
1359 		 * is negative, hence safe.
1360 		 */
1361 		reg->s32_min_value = reg->u32_min_value =
1362 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1363 		reg->s32_max_value = reg->u32_max_value;
1364 	}
1365 }
1366 
1367 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1368 {
1369 	/* Learn sign from signed bounds.
1370 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1371 	 * are the same, so combine.  This works even in the negative case, e.g.
1372 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1373 	 */
1374 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1375 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1376 							  reg->umin_value);
1377 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1378 							  reg->umax_value);
1379 		return;
1380 	}
1381 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1382 	 * boundary, so we must be careful.
1383 	 */
1384 	if ((s64)reg->umax_value >= 0) {
1385 		/* Positive.  We can't learn anything from the smin, but smax
1386 		 * is positive, hence safe.
1387 		 */
1388 		reg->smin_value = reg->umin_value;
1389 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1390 							  reg->umax_value);
1391 	} else if ((s64)reg->umin_value < 0) {
1392 		/* Negative.  We can't learn anything from the smax, but smin
1393 		 * is negative, hence safe.
1394 		 */
1395 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1396 							  reg->umin_value);
1397 		reg->smax_value = reg->umax_value;
1398 	}
1399 }
1400 
1401 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1402 {
1403 	__reg32_deduce_bounds(reg);
1404 	__reg64_deduce_bounds(reg);
1405 }
1406 
1407 /* Attempts to improve var_off based on unsigned min/max information */
1408 static void __reg_bound_offset(struct bpf_reg_state *reg)
1409 {
1410 	struct tnum var64_off = tnum_intersect(reg->var_off,
1411 					       tnum_range(reg->umin_value,
1412 							  reg->umax_value));
1413 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1414 						tnum_range(reg->u32_min_value,
1415 							   reg->u32_max_value));
1416 
1417 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1418 }
1419 
1420 static bool __reg32_bound_s64(s32 a)
1421 {
1422 	return a >= 0 && a <= S32_MAX;
1423 }
1424 
1425 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1426 {
1427 	reg->umin_value = reg->u32_min_value;
1428 	reg->umax_value = reg->u32_max_value;
1429 
1430 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1431 	 * be positive otherwise set to worse case bounds and refine later
1432 	 * from tnum.
1433 	 */
1434 	if (__reg32_bound_s64(reg->s32_min_value) &&
1435 	    __reg32_bound_s64(reg->s32_max_value)) {
1436 		reg->smin_value = reg->s32_min_value;
1437 		reg->smax_value = reg->s32_max_value;
1438 	} else {
1439 		reg->smin_value = 0;
1440 		reg->smax_value = U32_MAX;
1441 	}
1442 }
1443 
1444 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1445 {
1446 	/* special case when 64-bit register has upper 32-bit register
1447 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1448 	 * allowing us to use 32-bit bounds directly,
1449 	 */
1450 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1451 		__reg_assign_32_into_64(reg);
1452 	} else {
1453 		/* Otherwise the best we can do is push lower 32bit known and
1454 		 * unknown bits into register (var_off set from jmp logic)
1455 		 * then learn as much as possible from the 64-bit tnum
1456 		 * known and unknown bits. The previous smin/smax bounds are
1457 		 * invalid here because of jmp32 compare so mark them unknown
1458 		 * so they do not impact tnum bounds calculation.
1459 		 */
1460 		__mark_reg64_unbounded(reg);
1461 		__update_reg_bounds(reg);
1462 	}
1463 
1464 	/* Intersecting with the old var_off might have improved our bounds
1465 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1466 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1467 	 */
1468 	__reg_deduce_bounds(reg);
1469 	__reg_bound_offset(reg);
1470 	__update_reg_bounds(reg);
1471 }
1472 
1473 static bool __reg64_bound_s32(s64 a)
1474 {
1475 	return a >= S32_MIN && a <= S32_MAX;
1476 }
1477 
1478 static bool __reg64_bound_u32(u64 a)
1479 {
1480 	return a >= U32_MIN && a <= U32_MAX;
1481 }
1482 
1483 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1484 {
1485 	__mark_reg32_unbounded(reg);
1486 
1487 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1488 		reg->s32_min_value = (s32)reg->smin_value;
1489 		reg->s32_max_value = (s32)reg->smax_value;
1490 	}
1491 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1492 		reg->u32_min_value = (u32)reg->umin_value;
1493 		reg->u32_max_value = (u32)reg->umax_value;
1494 	}
1495 
1496 	/* Intersecting with the old var_off might have improved our bounds
1497 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1498 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1499 	 */
1500 	__reg_deduce_bounds(reg);
1501 	__reg_bound_offset(reg);
1502 	__update_reg_bounds(reg);
1503 }
1504 
1505 /* Mark a register as having a completely unknown (scalar) value. */
1506 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1507 			       struct bpf_reg_state *reg)
1508 {
1509 	/*
1510 	 * Clear type, id, off, and union(map_ptr, range) and
1511 	 * padding between 'type' and union
1512 	 */
1513 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1514 	reg->type = SCALAR_VALUE;
1515 	reg->var_off = tnum_unknown;
1516 	reg->frameno = 0;
1517 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1518 	__mark_reg_unbounded(reg);
1519 }
1520 
1521 static void mark_reg_unknown(struct bpf_verifier_env *env,
1522 			     struct bpf_reg_state *regs, u32 regno)
1523 {
1524 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1525 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1526 		/* Something bad happened, let's kill all regs except FP */
1527 		for (regno = 0; regno < BPF_REG_FP; regno++)
1528 			__mark_reg_not_init(env, regs + regno);
1529 		return;
1530 	}
1531 	__mark_reg_unknown(env, regs + regno);
1532 }
1533 
1534 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1535 				struct bpf_reg_state *reg)
1536 {
1537 	__mark_reg_unknown(env, reg);
1538 	reg->type = NOT_INIT;
1539 }
1540 
1541 static void mark_reg_not_init(struct bpf_verifier_env *env,
1542 			      struct bpf_reg_state *regs, u32 regno)
1543 {
1544 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1545 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1546 		/* Something bad happened, let's kill all regs except FP */
1547 		for (regno = 0; regno < BPF_REG_FP; regno++)
1548 			__mark_reg_not_init(env, regs + regno);
1549 		return;
1550 	}
1551 	__mark_reg_not_init(env, regs + regno);
1552 }
1553 
1554 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1555 			    struct bpf_reg_state *regs, u32 regno,
1556 			    enum bpf_reg_type reg_type,
1557 			    struct btf *btf, u32 btf_id,
1558 			    enum bpf_type_flag flag)
1559 {
1560 	if (reg_type == SCALAR_VALUE) {
1561 		mark_reg_unknown(env, regs, regno);
1562 		return;
1563 	}
1564 	mark_reg_known_zero(env, regs, regno);
1565 	regs[regno].type = PTR_TO_BTF_ID | flag;
1566 	regs[regno].btf = btf;
1567 	regs[regno].btf_id = btf_id;
1568 }
1569 
1570 #define DEF_NOT_SUBREG	(0)
1571 static void init_reg_state(struct bpf_verifier_env *env,
1572 			   struct bpf_func_state *state)
1573 {
1574 	struct bpf_reg_state *regs = state->regs;
1575 	int i;
1576 
1577 	for (i = 0; i < MAX_BPF_REG; i++) {
1578 		mark_reg_not_init(env, regs, i);
1579 		regs[i].live = REG_LIVE_NONE;
1580 		regs[i].parent = NULL;
1581 		regs[i].subreg_def = DEF_NOT_SUBREG;
1582 	}
1583 
1584 	/* frame pointer */
1585 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1586 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1587 	regs[BPF_REG_FP].frameno = state->frameno;
1588 }
1589 
1590 #define BPF_MAIN_FUNC (-1)
1591 static void init_func_state(struct bpf_verifier_env *env,
1592 			    struct bpf_func_state *state,
1593 			    int callsite, int frameno, int subprogno)
1594 {
1595 	state->callsite = callsite;
1596 	state->frameno = frameno;
1597 	state->subprogno = subprogno;
1598 	init_reg_state(env, state);
1599 	mark_verifier_state_scratched(env);
1600 }
1601 
1602 /* Similar to push_stack(), but for async callbacks */
1603 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1604 						int insn_idx, int prev_insn_idx,
1605 						int subprog)
1606 {
1607 	struct bpf_verifier_stack_elem *elem;
1608 	struct bpf_func_state *frame;
1609 
1610 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1611 	if (!elem)
1612 		goto err;
1613 
1614 	elem->insn_idx = insn_idx;
1615 	elem->prev_insn_idx = prev_insn_idx;
1616 	elem->next = env->head;
1617 	elem->log_pos = env->log.len_used;
1618 	env->head = elem;
1619 	env->stack_size++;
1620 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1621 		verbose(env,
1622 			"The sequence of %d jumps is too complex for async cb.\n",
1623 			env->stack_size);
1624 		goto err;
1625 	}
1626 	/* Unlike push_stack() do not copy_verifier_state().
1627 	 * The caller state doesn't matter.
1628 	 * This is async callback. It starts in a fresh stack.
1629 	 * Initialize it similar to do_check_common().
1630 	 */
1631 	elem->st.branches = 1;
1632 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1633 	if (!frame)
1634 		goto err;
1635 	init_func_state(env, frame,
1636 			BPF_MAIN_FUNC /* callsite */,
1637 			0 /* frameno within this callchain */,
1638 			subprog /* subprog number within this prog */);
1639 	elem->st.frame[0] = frame;
1640 	return &elem->st;
1641 err:
1642 	free_verifier_state(env->cur_state, true);
1643 	env->cur_state = NULL;
1644 	/* pop all elements and return */
1645 	while (!pop_stack(env, NULL, NULL, false));
1646 	return NULL;
1647 }
1648 
1649 
1650 enum reg_arg_type {
1651 	SRC_OP,		/* register is used as source operand */
1652 	DST_OP,		/* register is used as destination operand */
1653 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1654 };
1655 
1656 static int cmp_subprogs(const void *a, const void *b)
1657 {
1658 	return ((struct bpf_subprog_info *)a)->start -
1659 	       ((struct bpf_subprog_info *)b)->start;
1660 }
1661 
1662 static int find_subprog(struct bpf_verifier_env *env, int off)
1663 {
1664 	struct bpf_subprog_info *p;
1665 
1666 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1667 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1668 	if (!p)
1669 		return -ENOENT;
1670 	return p - env->subprog_info;
1671 
1672 }
1673 
1674 static int add_subprog(struct bpf_verifier_env *env, int off)
1675 {
1676 	int insn_cnt = env->prog->len;
1677 	int ret;
1678 
1679 	if (off >= insn_cnt || off < 0) {
1680 		verbose(env, "call to invalid destination\n");
1681 		return -EINVAL;
1682 	}
1683 	ret = find_subprog(env, off);
1684 	if (ret >= 0)
1685 		return ret;
1686 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1687 		verbose(env, "too many subprograms\n");
1688 		return -E2BIG;
1689 	}
1690 	/* determine subprog starts. The end is one before the next starts */
1691 	env->subprog_info[env->subprog_cnt++].start = off;
1692 	sort(env->subprog_info, env->subprog_cnt,
1693 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1694 	return env->subprog_cnt - 1;
1695 }
1696 
1697 #define MAX_KFUNC_DESCS 256
1698 #define MAX_KFUNC_BTFS	256
1699 
1700 struct bpf_kfunc_desc {
1701 	struct btf_func_model func_model;
1702 	u32 func_id;
1703 	s32 imm;
1704 	u16 offset;
1705 };
1706 
1707 struct bpf_kfunc_btf {
1708 	struct btf *btf;
1709 	struct module *module;
1710 	u16 offset;
1711 };
1712 
1713 struct bpf_kfunc_desc_tab {
1714 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1715 	u32 nr_descs;
1716 };
1717 
1718 struct bpf_kfunc_btf_tab {
1719 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1720 	u32 nr_descs;
1721 };
1722 
1723 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1724 {
1725 	const struct bpf_kfunc_desc *d0 = a;
1726 	const struct bpf_kfunc_desc *d1 = b;
1727 
1728 	/* func_id is not greater than BTF_MAX_TYPE */
1729 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1730 }
1731 
1732 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1733 {
1734 	const struct bpf_kfunc_btf *d0 = a;
1735 	const struct bpf_kfunc_btf *d1 = b;
1736 
1737 	return d0->offset - d1->offset;
1738 }
1739 
1740 static const struct bpf_kfunc_desc *
1741 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1742 {
1743 	struct bpf_kfunc_desc desc = {
1744 		.func_id = func_id,
1745 		.offset = offset,
1746 	};
1747 	struct bpf_kfunc_desc_tab *tab;
1748 
1749 	tab = prog->aux->kfunc_tab;
1750 	return bsearch(&desc, tab->descs, tab->nr_descs,
1751 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1752 }
1753 
1754 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1755 					 s16 offset)
1756 {
1757 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1758 	struct bpf_kfunc_btf_tab *tab;
1759 	struct bpf_kfunc_btf *b;
1760 	struct module *mod;
1761 	struct btf *btf;
1762 	int btf_fd;
1763 
1764 	tab = env->prog->aux->kfunc_btf_tab;
1765 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1766 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1767 	if (!b) {
1768 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1769 			verbose(env, "too many different module BTFs\n");
1770 			return ERR_PTR(-E2BIG);
1771 		}
1772 
1773 		if (bpfptr_is_null(env->fd_array)) {
1774 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1775 			return ERR_PTR(-EPROTO);
1776 		}
1777 
1778 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1779 					    offset * sizeof(btf_fd),
1780 					    sizeof(btf_fd)))
1781 			return ERR_PTR(-EFAULT);
1782 
1783 		btf = btf_get_by_fd(btf_fd);
1784 		if (IS_ERR(btf)) {
1785 			verbose(env, "invalid module BTF fd specified\n");
1786 			return btf;
1787 		}
1788 
1789 		if (!btf_is_module(btf)) {
1790 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1791 			btf_put(btf);
1792 			return ERR_PTR(-EINVAL);
1793 		}
1794 
1795 		mod = btf_try_get_module(btf);
1796 		if (!mod) {
1797 			btf_put(btf);
1798 			return ERR_PTR(-ENXIO);
1799 		}
1800 
1801 		b = &tab->descs[tab->nr_descs++];
1802 		b->btf = btf;
1803 		b->module = mod;
1804 		b->offset = offset;
1805 
1806 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1807 		     kfunc_btf_cmp_by_off, NULL);
1808 	}
1809 	return b->btf;
1810 }
1811 
1812 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1813 {
1814 	if (!tab)
1815 		return;
1816 
1817 	while (tab->nr_descs--) {
1818 		module_put(tab->descs[tab->nr_descs].module);
1819 		btf_put(tab->descs[tab->nr_descs].btf);
1820 	}
1821 	kfree(tab);
1822 }
1823 
1824 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1825 				       u32 func_id, s16 offset)
1826 {
1827 	if (offset) {
1828 		if (offset < 0) {
1829 			/* In the future, this can be allowed to increase limit
1830 			 * of fd index into fd_array, interpreted as u16.
1831 			 */
1832 			verbose(env, "negative offset disallowed for kernel module function call\n");
1833 			return ERR_PTR(-EINVAL);
1834 		}
1835 
1836 		return __find_kfunc_desc_btf(env, offset);
1837 	}
1838 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1839 }
1840 
1841 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1842 {
1843 	const struct btf_type *func, *func_proto;
1844 	struct bpf_kfunc_btf_tab *btf_tab;
1845 	struct bpf_kfunc_desc_tab *tab;
1846 	struct bpf_prog_aux *prog_aux;
1847 	struct bpf_kfunc_desc *desc;
1848 	const char *func_name;
1849 	struct btf *desc_btf;
1850 	unsigned long call_imm;
1851 	unsigned long addr;
1852 	int err;
1853 
1854 	prog_aux = env->prog->aux;
1855 	tab = prog_aux->kfunc_tab;
1856 	btf_tab = prog_aux->kfunc_btf_tab;
1857 	if (!tab) {
1858 		if (!btf_vmlinux) {
1859 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1860 			return -ENOTSUPP;
1861 		}
1862 
1863 		if (!env->prog->jit_requested) {
1864 			verbose(env, "JIT is required for calling kernel function\n");
1865 			return -ENOTSUPP;
1866 		}
1867 
1868 		if (!bpf_jit_supports_kfunc_call()) {
1869 			verbose(env, "JIT does not support calling kernel function\n");
1870 			return -ENOTSUPP;
1871 		}
1872 
1873 		if (!env->prog->gpl_compatible) {
1874 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1875 			return -EINVAL;
1876 		}
1877 
1878 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1879 		if (!tab)
1880 			return -ENOMEM;
1881 		prog_aux->kfunc_tab = tab;
1882 	}
1883 
1884 	/* func_id == 0 is always invalid, but instead of returning an error, be
1885 	 * conservative and wait until the code elimination pass before returning
1886 	 * error, so that invalid calls that get pruned out can be in BPF programs
1887 	 * loaded from userspace.  It is also required that offset be untouched
1888 	 * for such calls.
1889 	 */
1890 	if (!func_id && !offset)
1891 		return 0;
1892 
1893 	if (!btf_tab && offset) {
1894 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1895 		if (!btf_tab)
1896 			return -ENOMEM;
1897 		prog_aux->kfunc_btf_tab = btf_tab;
1898 	}
1899 
1900 	desc_btf = find_kfunc_desc_btf(env, func_id, offset);
1901 	if (IS_ERR(desc_btf)) {
1902 		verbose(env, "failed to find BTF for kernel function\n");
1903 		return PTR_ERR(desc_btf);
1904 	}
1905 
1906 	if (find_kfunc_desc(env->prog, func_id, offset))
1907 		return 0;
1908 
1909 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1910 		verbose(env, "too many different kernel function calls\n");
1911 		return -E2BIG;
1912 	}
1913 
1914 	func = btf_type_by_id(desc_btf, func_id);
1915 	if (!func || !btf_type_is_func(func)) {
1916 		verbose(env, "kernel btf_id %u is not a function\n",
1917 			func_id);
1918 		return -EINVAL;
1919 	}
1920 	func_proto = btf_type_by_id(desc_btf, func->type);
1921 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1922 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1923 			func_id);
1924 		return -EINVAL;
1925 	}
1926 
1927 	func_name = btf_name_by_offset(desc_btf, func->name_off);
1928 	addr = kallsyms_lookup_name(func_name);
1929 	if (!addr) {
1930 		verbose(env, "cannot find address for kernel function %s\n",
1931 			func_name);
1932 		return -EINVAL;
1933 	}
1934 
1935 	call_imm = BPF_CALL_IMM(addr);
1936 	/* Check whether or not the relative offset overflows desc->imm */
1937 	if ((unsigned long)(s32)call_imm != call_imm) {
1938 		verbose(env, "address of kernel function %s is out of range\n",
1939 			func_name);
1940 		return -EINVAL;
1941 	}
1942 
1943 	desc = &tab->descs[tab->nr_descs++];
1944 	desc->func_id = func_id;
1945 	desc->imm = call_imm;
1946 	desc->offset = offset;
1947 	err = btf_distill_func_proto(&env->log, desc_btf,
1948 				     func_proto, func_name,
1949 				     &desc->func_model);
1950 	if (!err)
1951 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1952 		     kfunc_desc_cmp_by_id_off, NULL);
1953 	return err;
1954 }
1955 
1956 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1957 {
1958 	const struct bpf_kfunc_desc *d0 = a;
1959 	const struct bpf_kfunc_desc *d1 = b;
1960 
1961 	if (d0->imm > d1->imm)
1962 		return 1;
1963 	else if (d0->imm < d1->imm)
1964 		return -1;
1965 	return 0;
1966 }
1967 
1968 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1969 {
1970 	struct bpf_kfunc_desc_tab *tab;
1971 
1972 	tab = prog->aux->kfunc_tab;
1973 	if (!tab)
1974 		return;
1975 
1976 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1977 	     kfunc_desc_cmp_by_imm, NULL);
1978 }
1979 
1980 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1981 {
1982 	return !!prog->aux->kfunc_tab;
1983 }
1984 
1985 const struct btf_func_model *
1986 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1987 			 const struct bpf_insn *insn)
1988 {
1989 	const struct bpf_kfunc_desc desc = {
1990 		.imm = insn->imm,
1991 	};
1992 	const struct bpf_kfunc_desc *res;
1993 	struct bpf_kfunc_desc_tab *tab;
1994 
1995 	tab = prog->aux->kfunc_tab;
1996 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1997 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1998 
1999 	return res ? &res->func_model : NULL;
2000 }
2001 
2002 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2003 {
2004 	struct bpf_subprog_info *subprog = env->subprog_info;
2005 	struct bpf_insn *insn = env->prog->insnsi;
2006 	int i, ret, insn_cnt = env->prog->len;
2007 
2008 	/* Add entry function. */
2009 	ret = add_subprog(env, 0);
2010 	if (ret)
2011 		return ret;
2012 
2013 	for (i = 0; i < insn_cnt; i++, insn++) {
2014 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2015 		    !bpf_pseudo_kfunc_call(insn))
2016 			continue;
2017 
2018 		if (!env->bpf_capable) {
2019 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2020 			return -EPERM;
2021 		}
2022 
2023 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2024 			ret = add_subprog(env, i + insn->imm + 1);
2025 		else
2026 			ret = add_kfunc_call(env, insn->imm, insn->off);
2027 
2028 		if (ret < 0)
2029 			return ret;
2030 	}
2031 
2032 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2033 	 * logic. 'subprog_cnt' should not be increased.
2034 	 */
2035 	subprog[env->subprog_cnt].start = insn_cnt;
2036 
2037 	if (env->log.level & BPF_LOG_LEVEL2)
2038 		for (i = 0; i < env->subprog_cnt; i++)
2039 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2040 
2041 	return 0;
2042 }
2043 
2044 static int check_subprogs(struct bpf_verifier_env *env)
2045 {
2046 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2047 	struct bpf_subprog_info *subprog = env->subprog_info;
2048 	struct bpf_insn *insn = env->prog->insnsi;
2049 	int insn_cnt = env->prog->len;
2050 
2051 	/* now check that all jumps are within the same subprog */
2052 	subprog_start = subprog[cur_subprog].start;
2053 	subprog_end = subprog[cur_subprog + 1].start;
2054 	for (i = 0; i < insn_cnt; i++) {
2055 		u8 code = insn[i].code;
2056 
2057 		if (code == (BPF_JMP | BPF_CALL) &&
2058 		    insn[i].imm == BPF_FUNC_tail_call &&
2059 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2060 			subprog[cur_subprog].has_tail_call = true;
2061 		if (BPF_CLASS(code) == BPF_LD &&
2062 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2063 			subprog[cur_subprog].has_ld_abs = true;
2064 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2065 			goto next;
2066 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2067 			goto next;
2068 		off = i + insn[i].off + 1;
2069 		if (off < subprog_start || off >= subprog_end) {
2070 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2071 			return -EINVAL;
2072 		}
2073 next:
2074 		if (i == subprog_end - 1) {
2075 			/* to avoid fall-through from one subprog into another
2076 			 * the last insn of the subprog should be either exit
2077 			 * or unconditional jump back
2078 			 */
2079 			if (code != (BPF_JMP | BPF_EXIT) &&
2080 			    code != (BPF_JMP | BPF_JA)) {
2081 				verbose(env, "last insn is not an exit or jmp\n");
2082 				return -EINVAL;
2083 			}
2084 			subprog_start = subprog_end;
2085 			cur_subprog++;
2086 			if (cur_subprog < env->subprog_cnt)
2087 				subprog_end = subprog[cur_subprog + 1].start;
2088 		}
2089 	}
2090 	return 0;
2091 }
2092 
2093 /* Parentage chain of this register (or stack slot) should take care of all
2094  * issues like callee-saved registers, stack slot allocation time, etc.
2095  */
2096 static int mark_reg_read(struct bpf_verifier_env *env,
2097 			 const struct bpf_reg_state *state,
2098 			 struct bpf_reg_state *parent, u8 flag)
2099 {
2100 	bool writes = parent == state->parent; /* Observe write marks */
2101 	int cnt = 0;
2102 
2103 	while (parent) {
2104 		/* if read wasn't screened by an earlier write ... */
2105 		if (writes && state->live & REG_LIVE_WRITTEN)
2106 			break;
2107 		if (parent->live & REG_LIVE_DONE) {
2108 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2109 				reg_type_str(env, parent->type),
2110 				parent->var_off.value, parent->off);
2111 			return -EFAULT;
2112 		}
2113 		/* The first condition is more likely to be true than the
2114 		 * second, checked it first.
2115 		 */
2116 		if ((parent->live & REG_LIVE_READ) == flag ||
2117 		    parent->live & REG_LIVE_READ64)
2118 			/* The parentage chain never changes and
2119 			 * this parent was already marked as LIVE_READ.
2120 			 * There is no need to keep walking the chain again and
2121 			 * keep re-marking all parents as LIVE_READ.
2122 			 * This case happens when the same register is read
2123 			 * multiple times without writes into it in-between.
2124 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2125 			 * then no need to set the weak REG_LIVE_READ32.
2126 			 */
2127 			break;
2128 		/* ... then we depend on parent's value */
2129 		parent->live |= flag;
2130 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2131 		if (flag == REG_LIVE_READ64)
2132 			parent->live &= ~REG_LIVE_READ32;
2133 		state = parent;
2134 		parent = state->parent;
2135 		writes = true;
2136 		cnt++;
2137 	}
2138 
2139 	if (env->longest_mark_read_walk < cnt)
2140 		env->longest_mark_read_walk = cnt;
2141 	return 0;
2142 }
2143 
2144 /* This function is supposed to be used by the following 32-bit optimization
2145  * code only. It returns TRUE if the source or destination register operates
2146  * on 64-bit, otherwise return FALSE.
2147  */
2148 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2149 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2150 {
2151 	u8 code, class, op;
2152 
2153 	code = insn->code;
2154 	class = BPF_CLASS(code);
2155 	op = BPF_OP(code);
2156 	if (class == BPF_JMP) {
2157 		/* BPF_EXIT for "main" will reach here. Return TRUE
2158 		 * conservatively.
2159 		 */
2160 		if (op == BPF_EXIT)
2161 			return true;
2162 		if (op == BPF_CALL) {
2163 			/* BPF to BPF call will reach here because of marking
2164 			 * caller saved clobber with DST_OP_NO_MARK for which we
2165 			 * don't care the register def because they are anyway
2166 			 * marked as NOT_INIT already.
2167 			 */
2168 			if (insn->src_reg == BPF_PSEUDO_CALL)
2169 				return false;
2170 			/* Helper call will reach here because of arg type
2171 			 * check, conservatively return TRUE.
2172 			 */
2173 			if (t == SRC_OP)
2174 				return true;
2175 
2176 			return false;
2177 		}
2178 	}
2179 
2180 	if (class == BPF_ALU64 || class == BPF_JMP ||
2181 	    /* BPF_END always use BPF_ALU class. */
2182 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2183 		return true;
2184 
2185 	if (class == BPF_ALU || class == BPF_JMP32)
2186 		return false;
2187 
2188 	if (class == BPF_LDX) {
2189 		if (t != SRC_OP)
2190 			return BPF_SIZE(code) == BPF_DW;
2191 		/* LDX source must be ptr. */
2192 		return true;
2193 	}
2194 
2195 	if (class == BPF_STX) {
2196 		/* BPF_STX (including atomic variants) has multiple source
2197 		 * operands, one of which is a ptr. Check whether the caller is
2198 		 * asking about it.
2199 		 */
2200 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2201 			return true;
2202 		return BPF_SIZE(code) == BPF_DW;
2203 	}
2204 
2205 	if (class == BPF_LD) {
2206 		u8 mode = BPF_MODE(code);
2207 
2208 		/* LD_IMM64 */
2209 		if (mode == BPF_IMM)
2210 			return true;
2211 
2212 		/* Both LD_IND and LD_ABS return 32-bit data. */
2213 		if (t != SRC_OP)
2214 			return  false;
2215 
2216 		/* Implicit ctx ptr. */
2217 		if (regno == BPF_REG_6)
2218 			return true;
2219 
2220 		/* Explicit source could be any width. */
2221 		return true;
2222 	}
2223 
2224 	if (class == BPF_ST)
2225 		/* The only source register for BPF_ST is a ptr. */
2226 		return true;
2227 
2228 	/* Conservatively return true at default. */
2229 	return true;
2230 }
2231 
2232 /* Return the regno defined by the insn, or -1. */
2233 static int insn_def_regno(const struct bpf_insn *insn)
2234 {
2235 	switch (BPF_CLASS(insn->code)) {
2236 	case BPF_JMP:
2237 	case BPF_JMP32:
2238 	case BPF_ST:
2239 		return -1;
2240 	case BPF_STX:
2241 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2242 		    (insn->imm & BPF_FETCH)) {
2243 			if (insn->imm == BPF_CMPXCHG)
2244 				return BPF_REG_0;
2245 			else
2246 				return insn->src_reg;
2247 		} else {
2248 			return -1;
2249 		}
2250 	default:
2251 		return insn->dst_reg;
2252 	}
2253 }
2254 
2255 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2256 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2257 {
2258 	int dst_reg = insn_def_regno(insn);
2259 
2260 	if (dst_reg == -1)
2261 		return false;
2262 
2263 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2264 }
2265 
2266 static void mark_insn_zext(struct bpf_verifier_env *env,
2267 			   struct bpf_reg_state *reg)
2268 {
2269 	s32 def_idx = reg->subreg_def;
2270 
2271 	if (def_idx == DEF_NOT_SUBREG)
2272 		return;
2273 
2274 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2275 	/* The dst will be zero extended, so won't be sub-register anymore. */
2276 	reg->subreg_def = DEF_NOT_SUBREG;
2277 }
2278 
2279 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2280 			 enum reg_arg_type t)
2281 {
2282 	struct bpf_verifier_state *vstate = env->cur_state;
2283 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2284 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2285 	struct bpf_reg_state *reg, *regs = state->regs;
2286 	bool rw64;
2287 
2288 	if (regno >= MAX_BPF_REG) {
2289 		verbose(env, "R%d is invalid\n", regno);
2290 		return -EINVAL;
2291 	}
2292 
2293 	mark_reg_scratched(env, regno);
2294 
2295 	reg = &regs[regno];
2296 	rw64 = is_reg64(env, insn, regno, reg, t);
2297 	if (t == SRC_OP) {
2298 		/* check whether register used as source operand can be read */
2299 		if (reg->type == NOT_INIT) {
2300 			verbose(env, "R%d !read_ok\n", regno);
2301 			return -EACCES;
2302 		}
2303 		/* We don't need to worry about FP liveness because it's read-only */
2304 		if (regno == BPF_REG_FP)
2305 			return 0;
2306 
2307 		if (rw64)
2308 			mark_insn_zext(env, reg);
2309 
2310 		return mark_reg_read(env, reg, reg->parent,
2311 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2312 	} else {
2313 		/* check whether register used as dest operand can be written to */
2314 		if (regno == BPF_REG_FP) {
2315 			verbose(env, "frame pointer is read only\n");
2316 			return -EACCES;
2317 		}
2318 		reg->live |= REG_LIVE_WRITTEN;
2319 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2320 		if (t == DST_OP)
2321 			mark_reg_unknown(env, regs, regno);
2322 	}
2323 	return 0;
2324 }
2325 
2326 /* for any branch, call, exit record the history of jmps in the given state */
2327 static int push_jmp_history(struct bpf_verifier_env *env,
2328 			    struct bpf_verifier_state *cur)
2329 {
2330 	u32 cnt = cur->jmp_history_cnt;
2331 	struct bpf_idx_pair *p;
2332 
2333 	cnt++;
2334 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2335 	if (!p)
2336 		return -ENOMEM;
2337 	p[cnt - 1].idx = env->insn_idx;
2338 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2339 	cur->jmp_history = p;
2340 	cur->jmp_history_cnt = cnt;
2341 	return 0;
2342 }
2343 
2344 /* Backtrack one insn at a time. If idx is not at the top of recorded
2345  * history then previous instruction came from straight line execution.
2346  */
2347 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2348 			     u32 *history)
2349 {
2350 	u32 cnt = *history;
2351 
2352 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2353 		i = st->jmp_history[cnt - 1].prev_idx;
2354 		(*history)--;
2355 	} else {
2356 		i--;
2357 	}
2358 	return i;
2359 }
2360 
2361 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2362 {
2363 	const struct btf_type *func;
2364 	struct btf *desc_btf;
2365 
2366 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2367 		return NULL;
2368 
2369 	desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off);
2370 	if (IS_ERR(desc_btf))
2371 		return "<error>";
2372 
2373 	func = btf_type_by_id(desc_btf, insn->imm);
2374 	return btf_name_by_offset(desc_btf, func->name_off);
2375 }
2376 
2377 /* For given verifier state backtrack_insn() is called from the last insn to
2378  * the first insn. Its purpose is to compute a bitmask of registers and
2379  * stack slots that needs precision in the parent verifier state.
2380  */
2381 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2382 			  u32 *reg_mask, u64 *stack_mask)
2383 {
2384 	const struct bpf_insn_cbs cbs = {
2385 		.cb_call	= disasm_kfunc_name,
2386 		.cb_print	= verbose,
2387 		.private_data	= env,
2388 	};
2389 	struct bpf_insn *insn = env->prog->insnsi + idx;
2390 	u8 class = BPF_CLASS(insn->code);
2391 	u8 opcode = BPF_OP(insn->code);
2392 	u8 mode = BPF_MODE(insn->code);
2393 	u32 dreg = 1u << insn->dst_reg;
2394 	u32 sreg = 1u << insn->src_reg;
2395 	u32 spi;
2396 
2397 	if (insn->code == 0)
2398 		return 0;
2399 	if (env->log.level & BPF_LOG_LEVEL2) {
2400 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2401 		verbose(env, "%d: ", idx);
2402 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2403 	}
2404 
2405 	if (class == BPF_ALU || class == BPF_ALU64) {
2406 		if (!(*reg_mask & dreg))
2407 			return 0;
2408 		if (opcode == BPF_MOV) {
2409 			if (BPF_SRC(insn->code) == BPF_X) {
2410 				/* dreg = sreg
2411 				 * dreg needs precision after this insn
2412 				 * sreg needs precision before this insn
2413 				 */
2414 				*reg_mask &= ~dreg;
2415 				*reg_mask |= sreg;
2416 			} else {
2417 				/* dreg = K
2418 				 * dreg needs precision after this insn.
2419 				 * Corresponding register is already marked
2420 				 * as precise=true in this verifier state.
2421 				 * No further markings in parent are necessary
2422 				 */
2423 				*reg_mask &= ~dreg;
2424 			}
2425 		} else {
2426 			if (BPF_SRC(insn->code) == BPF_X) {
2427 				/* dreg += sreg
2428 				 * both dreg and sreg need precision
2429 				 * before this insn
2430 				 */
2431 				*reg_mask |= sreg;
2432 			} /* else dreg += K
2433 			   * dreg still needs precision before this insn
2434 			   */
2435 		}
2436 	} else if (class == BPF_LDX) {
2437 		if (!(*reg_mask & dreg))
2438 			return 0;
2439 		*reg_mask &= ~dreg;
2440 
2441 		/* scalars can only be spilled into stack w/o losing precision.
2442 		 * Load from any other memory can be zero extended.
2443 		 * The desire to keep that precision is already indicated
2444 		 * by 'precise' mark in corresponding register of this state.
2445 		 * No further tracking necessary.
2446 		 */
2447 		if (insn->src_reg != BPF_REG_FP)
2448 			return 0;
2449 
2450 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2451 		 * that [fp - off] slot contains scalar that needs to be
2452 		 * tracked with precision
2453 		 */
2454 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2455 		if (spi >= 64) {
2456 			verbose(env, "BUG spi %d\n", spi);
2457 			WARN_ONCE(1, "verifier backtracking bug");
2458 			return -EFAULT;
2459 		}
2460 		*stack_mask |= 1ull << spi;
2461 	} else if (class == BPF_STX || class == BPF_ST) {
2462 		if (*reg_mask & dreg)
2463 			/* stx & st shouldn't be using _scalar_ dst_reg
2464 			 * to access memory. It means backtracking
2465 			 * encountered a case of pointer subtraction.
2466 			 */
2467 			return -ENOTSUPP;
2468 		/* scalars can only be spilled into stack */
2469 		if (insn->dst_reg != BPF_REG_FP)
2470 			return 0;
2471 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2472 		if (spi >= 64) {
2473 			verbose(env, "BUG spi %d\n", spi);
2474 			WARN_ONCE(1, "verifier backtracking bug");
2475 			return -EFAULT;
2476 		}
2477 		if (!(*stack_mask & (1ull << spi)))
2478 			return 0;
2479 		*stack_mask &= ~(1ull << spi);
2480 		if (class == BPF_STX)
2481 			*reg_mask |= sreg;
2482 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2483 		if (opcode == BPF_CALL) {
2484 			if (insn->src_reg == BPF_PSEUDO_CALL)
2485 				return -ENOTSUPP;
2486 			/* regular helper call sets R0 */
2487 			*reg_mask &= ~1;
2488 			if (*reg_mask & 0x3f) {
2489 				/* if backtracing was looking for registers R1-R5
2490 				 * they should have been found already.
2491 				 */
2492 				verbose(env, "BUG regs %x\n", *reg_mask);
2493 				WARN_ONCE(1, "verifier backtracking bug");
2494 				return -EFAULT;
2495 			}
2496 		} else if (opcode == BPF_EXIT) {
2497 			return -ENOTSUPP;
2498 		}
2499 	} else if (class == BPF_LD) {
2500 		if (!(*reg_mask & dreg))
2501 			return 0;
2502 		*reg_mask &= ~dreg;
2503 		/* It's ld_imm64 or ld_abs or ld_ind.
2504 		 * For ld_imm64 no further tracking of precision
2505 		 * into parent is necessary
2506 		 */
2507 		if (mode == BPF_IND || mode == BPF_ABS)
2508 			/* to be analyzed */
2509 			return -ENOTSUPP;
2510 	}
2511 	return 0;
2512 }
2513 
2514 /* the scalar precision tracking algorithm:
2515  * . at the start all registers have precise=false.
2516  * . scalar ranges are tracked as normal through alu and jmp insns.
2517  * . once precise value of the scalar register is used in:
2518  *   .  ptr + scalar alu
2519  *   . if (scalar cond K|scalar)
2520  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2521  *   backtrack through the verifier states and mark all registers and
2522  *   stack slots with spilled constants that these scalar regisers
2523  *   should be precise.
2524  * . during state pruning two registers (or spilled stack slots)
2525  *   are equivalent if both are not precise.
2526  *
2527  * Note the verifier cannot simply walk register parentage chain,
2528  * since many different registers and stack slots could have been
2529  * used to compute single precise scalar.
2530  *
2531  * The approach of starting with precise=true for all registers and then
2532  * backtrack to mark a register as not precise when the verifier detects
2533  * that program doesn't care about specific value (e.g., when helper
2534  * takes register as ARG_ANYTHING parameter) is not safe.
2535  *
2536  * It's ok to walk single parentage chain of the verifier states.
2537  * It's possible that this backtracking will go all the way till 1st insn.
2538  * All other branches will be explored for needing precision later.
2539  *
2540  * The backtracking needs to deal with cases like:
2541  *   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)
2542  * r9 -= r8
2543  * r5 = r9
2544  * if r5 > 0x79f goto pc+7
2545  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2546  * r5 += 1
2547  * ...
2548  * call bpf_perf_event_output#25
2549  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2550  *
2551  * and this case:
2552  * r6 = 1
2553  * call foo // uses callee's r6 inside to compute r0
2554  * r0 += r6
2555  * if r0 == 0 goto
2556  *
2557  * to track above reg_mask/stack_mask needs to be independent for each frame.
2558  *
2559  * Also if parent's curframe > frame where backtracking started,
2560  * the verifier need to mark registers in both frames, otherwise callees
2561  * may incorrectly prune callers. This is similar to
2562  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2563  *
2564  * For now backtracking falls back into conservative marking.
2565  */
2566 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2567 				     struct bpf_verifier_state *st)
2568 {
2569 	struct bpf_func_state *func;
2570 	struct bpf_reg_state *reg;
2571 	int i, j;
2572 
2573 	/* big hammer: mark all scalars precise in this path.
2574 	 * pop_stack may still get !precise scalars.
2575 	 */
2576 	for (; st; st = st->parent)
2577 		for (i = 0; i <= st->curframe; i++) {
2578 			func = st->frame[i];
2579 			for (j = 0; j < BPF_REG_FP; j++) {
2580 				reg = &func->regs[j];
2581 				if (reg->type != SCALAR_VALUE)
2582 					continue;
2583 				reg->precise = true;
2584 			}
2585 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2586 				if (!is_spilled_reg(&func->stack[j]))
2587 					continue;
2588 				reg = &func->stack[j].spilled_ptr;
2589 				if (reg->type != SCALAR_VALUE)
2590 					continue;
2591 				reg->precise = true;
2592 			}
2593 		}
2594 }
2595 
2596 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2597 				  int spi)
2598 {
2599 	struct bpf_verifier_state *st = env->cur_state;
2600 	int first_idx = st->first_insn_idx;
2601 	int last_idx = env->insn_idx;
2602 	struct bpf_func_state *func;
2603 	struct bpf_reg_state *reg;
2604 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2605 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2606 	bool skip_first = true;
2607 	bool new_marks = false;
2608 	int i, err;
2609 
2610 	if (!env->bpf_capable)
2611 		return 0;
2612 
2613 	func = st->frame[st->curframe];
2614 	if (regno >= 0) {
2615 		reg = &func->regs[regno];
2616 		if (reg->type != SCALAR_VALUE) {
2617 			WARN_ONCE(1, "backtracing misuse");
2618 			return -EFAULT;
2619 		}
2620 		if (!reg->precise)
2621 			new_marks = true;
2622 		else
2623 			reg_mask = 0;
2624 		reg->precise = true;
2625 	}
2626 
2627 	while (spi >= 0) {
2628 		if (!is_spilled_reg(&func->stack[spi])) {
2629 			stack_mask = 0;
2630 			break;
2631 		}
2632 		reg = &func->stack[spi].spilled_ptr;
2633 		if (reg->type != SCALAR_VALUE) {
2634 			stack_mask = 0;
2635 			break;
2636 		}
2637 		if (!reg->precise)
2638 			new_marks = true;
2639 		else
2640 			stack_mask = 0;
2641 		reg->precise = true;
2642 		break;
2643 	}
2644 
2645 	if (!new_marks)
2646 		return 0;
2647 	if (!reg_mask && !stack_mask)
2648 		return 0;
2649 	for (;;) {
2650 		DECLARE_BITMAP(mask, 64);
2651 		u32 history = st->jmp_history_cnt;
2652 
2653 		if (env->log.level & BPF_LOG_LEVEL2)
2654 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2655 		for (i = last_idx;;) {
2656 			if (skip_first) {
2657 				err = 0;
2658 				skip_first = false;
2659 			} else {
2660 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2661 			}
2662 			if (err == -ENOTSUPP) {
2663 				mark_all_scalars_precise(env, st);
2664 				return 0;
2665 			} else if (err) {
2666 				return err;
2667 			}
2668 			if (!reg_mask && !stack_mask)
2669 				/* Found assignment(s) into tracked register in this state.
2670 				 * Since this state is already marked, just return.
2671 				 * Nothing to be tracked further in the parent state.
2672 				 */
2673 				return 0;
2674 			if (i == first_idx)
2675 				break;
2676 			i = get_prev_insn_idx(st, i, &history);
2677 			if (i >= env->prog->len) {
2678 				/* This can happen if backtracking reached insn 0
2679 				 * and there are still reg_mask or stack_mask
2680 				 * to backtrack.
2681 				 * It means the backtracking missed the spot where
2682 				 * particular register was initialized with a constant.
2683 				 */
2684 				verbose(env, "BUG backtracking idx %d\n", i);
2685 				WARN_ONCE(1, "verifier backtracking bug");
2686 				return -EFAULT;
2687 			}
2688 		}
2689 		st = st->parent;
2690 		if (!st)
2691 			break;
2692 
2693 		new_marks = false;
2694 		func = st->frame[st->curframe];
2695 		bitmap_from_u64(mask, reg_mask);
2696 		for_each_set_bit(i, mask, 32) {
2697 			reg = &func->regs[i];
2698 			if (reg->type != SCALAR_VALUE) {
2699 				reg_mask &= ~(1u << i);
2700 				continue;
2701 			}
2702 			if (!reg->precise)
2703 				new_marks = true;
2704 			reg->precise = true;
2705 		}
2706 
2707 		bitmap_from_u64(mask, stack_mask);
2708 		for_each_set_bit(i, mask, 64) {
2709 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2710 				/* the sequence of instructions:
2711 				 * 2: (bf) r3 = r10
2712 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2713 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2714 				 * doesn't contain jmps. It's backtracked
2715 				 * as a single block.
2716 				 * During backtracking insn 3 is not recognized as
2717 				 * stack access, so at the end of backtracking
2718 				 * stack slot fp-8 is still marked in stack_mask.
2719 				 * However the parent state may not have accessed
2720 				 * fp-8 and it's "unallocated" stack space.
2721 				 * In such case fallback to conservative.
2722 				 */
2723 				mark_all_scalars_precise(env, st);
2724 				return 0;
2725 			}
2726 
2727 			if (!is_spilled_reg(&func->stack[i])) {
2728 				stack_mask &= ~(1ull << i);
2729 				continue;
2730 			}
2731 			reg = &func->stack[i].spilled_ptr;
2732 			if (reg->type != SCALAR_VALUE) {
2733 				stack_mask &= ~(1ull << i);
2734 				continue;
2735 			}
2736 			if (!reg->precise)
2737 				new_marks = true;
2738 			reg->precise = true;
2739 		}
2740 		if (env->log.level & BPF_LOG_LEVEL2) {
2741 			verbose(env, "parent %s regs=%x stack=%llx marks:",
2742 				new_marks ? "didn't have" : "already had",
2743 				reg_mask, stack_mask);
2744 			print_verifier_state(env, func, true);
2745 		}
2746 
2747 		if (!reg_mask && !stack_mask)
2748 			break;
2749 		if (!new_marks)
2750 			break;
2751 
2752 		last_idx = st->last_insn_idx;
2753 		first_idx = st->first_insn_idx;
2754 	}
2755 	return 0;
2756 }
2757 
2758 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2759 {
2760 	return __mark_chain_precision(env, regno, -1);
2761 }
2762 
2763 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2764 {
2765 	return __mark_chain_precision(env, -1, spi);
2766 }
2767 
2768 static bool is_spillable_regtype(enum bpf_reg_type type)
2769 {
2770 	switch (base_type(type)) {
2771 	case PTR_TO_MAP_VALUE:
2772 	case PTR_TO_STACK:
2773 	case PTR_TO_CTX:
2774 	case PTR_TO_PACKET:
2775 	case PTR_TO_PACKET_META:
2776 	case PTR_TO_PACKET_END:
2777 	case PTR_TO_FLOW_KEYS:
2778 	case CONST_PTR_TO_MAP:
2779 	case PTR_TO_SOCKET:
2780 	case PTR_TO_SOCK_COMMON:
2781 	case PTR_TO_TCP_SOCK:
2782 	case PTR_TO_XDP_SOCK:
2783 	case PTR_TO_BTF_ID:
2784 	case PTR_TO_BUF:
2785 	case PTR_TO_MEM:
2786 	case PTR_TO_FUNC:
2787 	case PTR_TO_MAP_KEY:
2788 		return true;
2789 	default:
2790 		return false;
2791 	}
2792 }
2793 
2794 /* Does this register contain a constant zero? */
2795 static bool register_is_null(struct bpf_reg_state *reg)
2796 {
2797 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2798 }
2799 
2800 static bool register_is_const(struct bpf_reg_state *reg)
2801 {
2802 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2803 }
2804 
2805 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2806 {
2807 	return tnum_is_unknown(reg->var_off) &&
2808 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2809 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2810 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2811 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2812 }
2813 
2814 static bool register_is_bounded(struct bpf_reg_state *reg)
2815 {
2816 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2817 }
2818 
2819 static bool __is_pointer_value(bool allow_ptr_leaks,
2820 			       const struct bpf_reg_state *reg)
2821 {
2822 	if (allow_ptr_leaks)
2823 		return false;
2824 
2825 	return reg->type != SCALAR_VALUE;
2826 }
2827 
2828 static void save_register_state(struct bpf_func_state *state,
2829 				int spi, struct bpf_reg_state *reg,
2830 				int size)
2831 {
2832 	int i;
2833 
2834 	state->stack[spi].spilled_ptr = *reg;
2835 	if (size == BPF_REG_SIZE)
2836 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2837 
2838 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2839 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2840 
2841 	/* size < 8 bytes spill */
2842 	for (; i; i--)
2843 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2844 }
2845 
2846 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2847  * stack boundary and alignment are checked in check_mem_access()
2848  */
2849 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2850 				       /* stack frame we're writing to */
2851 				       struct bpf_func_state *state,
2852 				       int off, int size, int value_regno,
2853 				       int insn_idx)
2854 {
2855 	struct bpf_func_state *cur; /* state of the current function */
2856 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2857 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2858 	struct bpf_reg_state *reg = NULL;
2859 
2860 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2861 	if (err)
2862 		return err;
2863 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2864 	 * so it's aligned access and [off, off + size) are within stack limits
2865 	 */
2866 	if (!env->allow_ptr_leaks &&
2867 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2868 	    size != BPF_REG_SIZE) {
2869 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2870 		return -EACCES;
2871 	}
2872 
2873 	cur = env->cur_state->frame[env->cur_state->curframe];
2874 	if (value_regno >= 0)
2875 		reg = &cur->regs[value_regno];
2876 	if (!env->bypass_spec_v4) {
2877 		bool sanitize = reg && is_spillable_regtype(reg->type);
2878 
2879 		for (i = 0; i < size; i++) {
2880 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2881 				sanitize = true;
2882 				break;
2883 			}
2884 		}
2885 
2886 		if (sanitize)
2887 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2888 	}
2889 
2890 	mark_stack_slot_scratched(env, spi);
2891 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2892 	    !register_is_null(reg) && env->bpf_capable) {
2893 		if (dst_reg != BPF_REG_FP) {
2894 			/* The backtracking logic can only recognize explicit
2895 			 * stack slot address like [fp - 8]. Other spill of
2896 			 * scalar via different register has to be conservative.
2897 			 * Backtrack from here and mark all registers as precise
2898 			 * that contributed into 'reg' being a constant.
2899 			 */
2900 			err = mark_chain_precision(env, value_regno);
2901 			if (err)
2902 				return err;
2903 		}
2904 		save_register_state(state, spi, reg, size);
2905 	} else if (reg && is_spillable_regtype(reg->type)) {
2906 		/* register containing pointer is being spilled into stack */
2907 		if (size != BPF_REG_SIZE) {
2908 			verbose_linfo(env, insn_idx, "; ");
2909 			verbose(env, "invalid size of register spill\n");
2910 			return -EACCES;
2911 		}
2912 		if (state != cur && reg->type == PTR_TO_STACK) {
2913 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2914 			return -EINVAL;
2915 		}
2916 		save_register_state(state, spi, reg, size);
2917 	} else {
2918 		u8 type = STACK_MISC;
2919 
2920 		/* regular write of data into stack destroys any spilled ptr */
2921 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2922 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2923 		if (is_spilled_reg(&state->stack[spi]))
2924 			for (i = 0; i < BPF_REG_SIZE; i++)
2925 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2926 
2927 		/* only mark the slot as written if all 8 bytes were written
2928 		 * otherwise read propagation may incorrectly stop too soon
2929 		 * when stack slots are partially written.
2930 		 * This heuristic means that read propagation will be
2931 		 * conservative, since it will add reg_live_read marks
2932 		 * to stack slots all the way to first state when programs
2933 		 * writes+reads less than 8 bytes
2934 		 */
2935 		if (size == BPF_REG_SIZE)
2936 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2937 
2938 		/* when we zero initialize stack slots mark them as such */
2939 		if (reg && register_is_null(reg)) {
2940 			/* backtracking doesn't work for STACK_ZERO yet. */
2941 			err = mark_chain_precision(env, value_regno);
2942 			if (err)
2943 				return err;
2944 			type = STACK_ZERO;
2945 		}
2946 
2947 		/* Mark slots affected by this stack write. */
2948 		for (i = 0; i < size; i++)
2949 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2950 				type;
2951 	}
2952 	return 0;
2953 }
2954 
2955 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2956  * known to contain a variable offset.
2957  * This function checks whether the write is permitted and conservatively
2958  * tracks the effects of the write, considering that each stack slot in the
2959  * dynamic range is potentially written to.
2960  *
2961  * 'off' includes 'regno->off'.
2962  * 'value_regno' can be -1, meaning that an unknown value is being written to
2963  * the stack.
2964  *
2965  * Spilled pointers in range are not marked as written because we don't know
2966  * what's going to be actually written. This means that read propagation for
2967  * future reads cannot be terminated by this write.
2968  *
2969  * For privileged programs, uninitialized stack slots are considered
2970  * initialized by this write (even though we don't know exactly what offsets
2971  * are going to be written to). The idea is that we don't want the verifier to
2972  * reject future reads that access slots written to through variable offsets.
2973  */
2974 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2975 				     /* func where register points to */
2976 				     struct bpf_func_state *state,
2977 				     int ptr_regno, int off, int size,
2978 				     int value_regno, int insn_idx)
2979 {
2980 	struct bpf_func_state *cur; /* state of the current function */
2981 	int min_off, max_off;
2982 	int i, err;
2983 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2984 	bool writing_zero = false;
2985 	/* set if the fact that we're writing a zero is used to let any
2986 	 * stack slots remain STACK_ZERO
2987 	 */
2988 	bool zero_used = false;
2989 
2990 	cur = env->cur_state->frame[env->cur_state->curframe];
2991 	ptr_reg = &cur->regs[ptr_regno];
2992 	min_off = ptr_reg->smin_value + off;
2993 	max_off = ptr_reg->smax_value + off + size;
2994 	if (value_regno >= 0)
2995 		value_reg = &cur->regs[value_regno];
2996 	if (value_reg && register_is_null(value_reg))
2997 		writing_zero = true;
2998 
2999 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3000 	if (err)
3001 		return err;
3002 
3003 
3004 	/* Variable offset writes destroy any spilled pointers in range. */
3005 	for (i = min_off; i < max_off; i++) {
3006 		u8 new_type, *stype;
3007 		int slot, spi;
3008 
3009 		slot = -i - 1;
3010 		spi = slot / BPF_REG_SIZE;
3011 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3012 		mark_stack_slot_scratched(env, spi);
3013 
3014 		if (!env->allow_ptr_leaks
3015 				&& *stype != NOT_INIT
3016 				&& *stype != SCALAR_VALUE) {
3017 			/* Reject the write if there's are spilled pointers in
3018 			 * range. If we didn't reject here, the ptr status
3019 			 * would be erased below (even though not all slots are
3020 			 * actually overwritten), possibly opening the door to
3021 			 * leaks.
3022 			 */
3023 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3024 				insn_idx, i);
3025 			return -EINVAL;
3026 		}
3027 
3028 		/* Erase all spilled pointers. */
3029 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3030 
3031 		/* Update the slot type. */
3032 		new_type = STACK_MISC;
3033 		if (writing_zero && *stype == STACK_ZERO) {
3034 			new_type = STACK_ZERO;
3035 			zero_used = true;
3036 		}
3037 		/* If the slot is STACK_INVALID, we check whether it's OK to
3038 		 * pretend that it will be initialized by this write. The slot
3039 		 * might not actually be written to, and so if we mark it as
3040 		 * initialized future reads might leak uninitialized memory.
3041 		 * For privileged programs, we will accept such reads to slots
3042 		 * that may or may not be written because, if we're reject
3043 		 * them, the error would be too confusing.
3044 		 */
3045 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3046 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3047 					insn_idx, i);
3048 			return -EINVAL;
3049 		}
3050 		*stype = new_type;
3051 	}
3052 	if (zero_used) {
3053 		/* backtracking doesn't work for STACK_ZERO yet. */
3054 		err = mark_chain_precision(env, value_regno);
3055 		if (err)
3056 			return err;
3057 	}
3058 	return 0;
3059 }
3060 
3061 /* When register 'dst_regno' is assigned some values from stack[min_off,
3062  * max_off), we set the register's type according to the types of the
3063  * respective stack slots. If all the stack values are known to be zeros, then
3064  * so is the destination reg. Otherwise, the register is considered to be
3065  * SCALAR. This function does not deal with register filling; the caller must
3066  * ensure that all spilled registers in the stack range have been marked as
3067  * read.
3068  */
3069 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3070 				/* func where src register points to */
3071 				struct bpf_func_state *ptr_state,
3072 				int min_off, int max_off, int dst_regno)
3073 {
3074 	struct bpf_verifier_state *vstate = env->cur_state;
3075 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3076 	int i, slot, spi;
3077 	u8 *stype;
3078 	int zeros = 0;
3079 
3080 	for (i = min_off; i < max_off; i++) {
3081 		slot = -i - 1;
3082 		spi = slot / BPF_REG_SIZE;
3083 		stype = ptr_state->stack[spi].slot_type;
3084 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3085 			break;
3086 		zeros++;
3087 	}
3088 	if (zeros == max_off - min_off) {
3089 		/* any access_size read into register is zero extended,
3090 		 * so the whole register == const_zero
3091 		 */
3092 		__mark_reg_const_zero(&state->regs[dst_regno]);
3093 		/* backtracking doesn't support STACK_ZERO yet,
3094 		 * so mark it precise here, so that later
3095 		 * backtracking can stop here.
3096 		 * Backtracking may not need this if this register
3097 		 * doesn't participate in pointer adjustment.
3098 		 * Forward propagation of precise flag is not
3099 		 * necessary either. This mark is only to stop
3100 		 * backtracking. Any register that contributed
3101 		 * to const 0 was marked precise before spill.
3102 		 */
3103 		state->regs[dst_regno].precise = true;
3104 	} else {
3105 		/* have read misc data from the stack */
3106 		mark_reg_unknown(env, state->regs, dst_regno);
3107 	}
3108 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3109 }
3110 
3111 /* Read the stack at 'off' and put the results into the register indicated by
3112  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3113  * spilled reg.
3114  *
3115  * 'dst_regno' can be -1, meaning that the read value is not going to a
3116  * register.
3117  *
3118  * The access is assumed to be within the current stack bounds.
3119  */
3120 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3121 				      /* func where src register points to */
3122 				      struct bpf_func_state *reg_state,
3123 				      int off, int size, int dst_regno)
3124 {
3125 	struct bpf_verifier_state *vstate = env->cur_state;
3126 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3127 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3128 	struct bpf_reg_state *reg;
3129 	u8 *stype, type;
3130 
3131 	stype = reg_state->stack[spi].slot_type;
3132 	reg = &reg_state->stack[spi].spilled_ptr;
3133 
3134 	if (is_spilled_reg(&reg_state->stack[spi])) {
3135 		u8 spill_size = 1;
3136 
3137 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3138 			spill_size++;
3139 
3140 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3141 			if (reg->type != SCALAR_VALUE) {
3142 				verbose_linfo(env, env->insn_idx, "; ");
3143 				verbose(env, "invalid size of register fill\n");
3144 				return -EACCES;
3145 			}
3146 
3147 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3148 			if (dst_regno < 0)
3149 				return 0;
3150 
3151 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3152 				/* The earlier check_reg_arg() has decided the
3153 				 * subreg_def for this insn.  Save it first.
3154 				 */
3155 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3156 
3157 				state->regs[dst_regno] = *reg;
3158 				state->regs[dst_regno].subreg_def = subreg_def;
3159 			} else {
3160 				for (i = 0; i < size; i++) {
3161 					type = stype[(slot - i) % BPF_REG_SIZE];
3162 					if (type == STACK_SPILL)
3163 						continue;
3164 					if (type == STACK_MISC)
3165 						continue;
3166 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3167 						off, i, size);
3168 					return -EACCES;
3169 				}
3170 				mark_reg_unknown(env, state->regs, dst_regno);
3171 			}
3172 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3173 			return 0;
3174 		}
3175 
3176 		if (dst_regno >= 0) {
3177 			/* restore register state from stack */
3178 			state->regs[dst_regno] = *reg;
3179 			/* mark reg as written since spilled pointer state likely
3180 			 * has its liveness marks cleared by is_state_visited()
3181 			 * which resets stack/reg liveness for state transitions
3182 			 */
3183 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3184 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3185 			/* If dst_regno==-1, the caller is asking us whether
3186 			 * it is acceptable to use this value as a SCALAR_VALUE
3187 			 * (e.g. for XADD).
3188 			 * We must not allow unprivileged callers to do that
3189 			 * with spilled pointers.
3190 			 */
3191 			verbose(env, "leaking pointer from stack off %d\n",
3192 				off);
3193 			return -EACCES;
3194 		}
3195 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3196 	} else {
3197 		for (i = 0; i < size; i++) {
3198 			type = stype[(slot - i) % BPF_REG_SIZE];
3199 			if (type == STACK_MISC)
3200 				continue;
3201 			if (type == STACK_ZERO)
3202 				continue;
3203 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3204 				off, i, size);
3205 			return -EACCES;
3206 		}
3207 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3208 		if (dst_regno >= 0)
3209 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3210 	}
3211 	return 0;
3212 }
3213 
3214 enum stack_access_src {
3215 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3216 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3217 };
3218 
3219 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3220 					 int regno, int off, int access_size,
3221 					 bool zero_size_allowed,
3222 					 enum stack_access_src type,
3223 					 struct bpf_call_arg_meta *meta);
3224 
3225 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3226 {
3227 	return cur_regs(env) + regno;
3228 }
3229 
3230 /* Read the stack at 'ptr_regno + off' and put the result into the register
3231  * 'dst_regno'.
3232  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3233  * but not its variable offset.
3234  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3235  *
3236  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3237  * filling registers (i.e. reads of spilled register cannot be detected when
3238  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3239  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3240  * offset; for a fixed offset check_stack_read_fixed_off should be used
3241  * instead.
3242  */
3243 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3244 				    int ptr_regno, int off, int size, int dst_regno)
3245 {
3246 	/* The state of the source register. */
3247 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3248 	struct bpf_func_state *ptr_state = func(env, reg);
3249 	int err;
3250 	int min_off, max_off;
3251 
3252 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3253 	 */
3254 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3255 					    false, ACCESS_DIRECT, NULL);
3256 	if (err)
3257 		return err;
3258 
3259 	min_off = reg->smin_value + off;
3260 	max_off = reg->smax_value + off;
3261 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3262 	return 0;
3263 }
3264 
3265 /* check_stack_read dispatches to check_stack_read_fixed_off or
3266  * check_stack_read_var_off.
3267  *
3268  * The caller must ensure that the offset falls within the allocated stack
3269  * bounds.
3270  *
3271  * 'dst_regno' is a register which will receive the value from the stack. It
3272  * can be -1, meaning that the read value is not going to a register.
3273  */
3274 static int check_stack_read(struct bpf_verifier_env *env,
3275 			    int ptr_regno, int off, int size,
3276 			    int dst_regno)
3277 {
3278 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3279 	struct bpf_func_state *state = func(env, reg);
3280 	int err;
3281 	/* Some accesses are only permitted with a static offset. */
3282 	bool var_off = !tnum_is_const(reg->var_off);
3283 
3284 	/* The offset is required to be static when reads don't go to a
3285 	 * register, in order to not leak pointers (see
3286 	 * check_stack_read_fixed_off).
3287 	 */
3288 	if (dst_regno < 0 && var_off) {
3289 		char tn_buf[48];
3290 
3291 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3292 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3293 			tn_buf, off, size);
3294 		return -EACCES;
3295 	}
3296 	/* Variable offset is prohibited for unprivileged mode for simplicity
3297 	 * since it requires corresponding support in Spectre masking for stack
3298 	 * ALU. See also retrieve_ptr_limit().
3299 	 */
3300 	if (!env->bypass_spec_v1 && var_off) {
3301 		char tn_buf[48];
3302 
3303 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3304 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3305 				ptr_regno, tn_buf);
3306 		return -EACCES;
3307 	}
3308 
3309 	if (!var_off) {
3310 		off += reg->var_off.value;
3311 		err = check_stack_read_fixed_off(env, state, off, size,
3312 						 dst_regno);
3313 	} else {
3314 		/* Variable offset stack reads need more conservative handling
3315 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3316 		 * branch.
3317 		 */
3318 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3319 					       dst_regno);
3320 	}
3321 	return err;
3322 }
3323 
3324 
3325 /* check_stack_write dispatches to check_stack_write_fixed_off or
3326  * check_stack_write_var_off.
3327  *
3328  * 'ptr_regno' is the register used as a pointer into the stack.
3329  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3330  * 'value_regno' is the register whose value we're writing to the stack. It can
3331  * be -1, meaning that we're not writing from a register.
3332  *
3333  * The caller must ensure that the offset falls within the maximum stack size.
3334  */
3335 static int check_stack_write(struct bpf_verifier_env *env,
3336 			     int ptr_regno, int off, int size,
3337 			     int value_regno, int insn_idx)
3338 {
3339 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3340 	struct bpf_func_state *state = func(env, reg);
3341 	int err;
3342 
3343 	if (tnum_is_const(reg->var_off)) {
3344 		off += reg->var_off.value;
3345 		err = check_stack_write_fixed_off(env, state, off, size,
3346 						  value_regno, insn_idx);
3347 	} else {
3348 		/* Variable offset stack reads need more conservative handling
3349 		 * than fixed offset ones.
3350 		 */
3351 		err = check_stack_write_var_off(env, state,
3352 						ptr_regno, off, size,
3353 						value_regno, insn_idx);
3354 	}
3355 	return err;
3356 }
3357 
3358 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3359 				 int off, int size, enum bpf_access_type type)
3360 {
3361 	struct bpf_reg_state *regs = cur_regs(env);
3362 	struct bpf_map *map = regs[regno].map_ptr;
3363 	u32 cap = bpf_map_flags_to_cap(map);
3364 
3365 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3366 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3367 			map->value_size, off, size);
3368 		return -EACCES;
3369 	}
3370 
3371 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3372 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3373 			map->value_size, off, size);
3374 		return -EACCES;
3375 	}
3376 
3377 	return 0;
3378 }
3379 
3380 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3381 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3382 			      int off, int size, u32 mem_size,
3383 			      bool zero_size_allowed)
3384 {
3385 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3386 	struct bpf_reg_state *reg;
3387 
3388 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3389 		return 0;
3390 
3391 	reg = &cur_regs(env)[regno];
3392 	switch (reg->type) {
3393 	case PTR_TO_MAP_KEY:
3394 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3395 			mem_size, off, size);
3396 		break;
3397 	case PTR_TO_MAP_VALUE:
3398 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3399 			mem_size, off, size);
3400 		break;
3401 	case PTR_TO_PACKET:
3402 	case PTR_TO_PACKET_META:
3403 	case PTR_TO_PACKET_END:
3404 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3405 			off, size, regno, reg->id, off, mem_size);
3406 		break;
3407 	case PTR_TO_MEM:
3408 	default:
3409 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3410 			mem_size, off, size);
3411 	}
3412 
3413 	return -EACCES;
3414 }
3415 
3416 /* check read/write into a memory region with possible variable offset */
3417 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3418 				   int off, int size, u32 mem_size,
3419 				   bool zero_size_allowed)
3420 {
3421 	struct bpf_verifier_state *vstate = env->cur_state;
3422 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3423 	struct bpf_reg_state *reg = &state->regs[regno];
3424 	int err;
3425 
3426 	/* We may have adjusted the register pointing to memory region, so we
3427 	 * need to try adding each of min_value and max_value to off
3428 	 * to make sure our theoretical access will be safe.
3429 	 *
3430 	 * The minimum value is only important with signed
3431 	 * comparisons where we can't assume the floor of a
3432 	 * value is 0.  If we are using signed variables for our
3433 	 * index'es we need to make sure that whatever we use
3434 	 * will have a set floor within our range.
3435 	 */
3436 	if (reg->smin_value < 0 &&
3437 	    (reg->smin_value == S64_MIN ||
3438 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3439 	      reg->smin_value + off < 0)) {
3440 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3441 			regno);
3442 		return -EACCES;
3443 	}
3444 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3445 				 mem_size, zero_size_allowed);
3446 	if (err) {
3447 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3448 			regno);
3449 		return err;
3450 	}
3451 
3452 	/* If we haven't set a max value then we need to bail since we can't be
3453 	 * sure we won't do bad things.
3454 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3455 	 */
3456 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3457 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3458 			regno);
3459 		return -EACCES;
3460 	}
3461 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3462 				 mem_size, zero_size_allowed);
3463 	if (err) {
3464 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3465 			regno);
3466 		return err;
3467 	}
3468 
3469 	return 0;
3470 }
3471 
3472 /* check read/write into a map element with possible variable offset */
3473 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3474 			    int off, int size, bool zero_size_allowed)
3475 {
3476 	struct bpf_verifier_state *vstate = env->cur_state;
3477 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3478 	struct bpf_reg_state *reg = &state->regs[regno];
3479 	struct bpf_map *map = reg->map_ptr;
3480 	int err;
3481 
3482 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3483 				      zero_size_allowed);
3484 	if (err)
3485 		return err;
3486 
3487 	if (map_value_has_spin_lock(map)) {
3488 		u32 lock = map->spin_lock_off;
3489 
3490 		/* if any part of struct bpf_spin_lock can be touched by
3491 		 * load/store reject this program.
3492 		 * To check that [x1, x2) overlaps with [y1, y2)
3493 		 * it is sufficient to check x1 < y2 && y1 < x2.
3494 		 */
3495 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3496 		     lock < reg->umax_value + off + size) {
3497 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3498 			return -EACCES;
3499 		}
3500 	}
3501 	if (map_value_has_timer(map)) {
3502 		u32 t = map->timer_off;
3503 
3504 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3505 		     t < reg->umax_value + off + size) {
3506 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3507 			return -EACCES;
3508 		}
3509 	}
3510 	return err;
3511 }
3512 
3513 #define MAX_PACKET_OFF 0xffff
3514 
3515 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3516 				       const struct bpf_call_arg_meta *meta,
3517 				       enum bpf_access_type t)
3518 {
3519 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3520 
3521 	switch (prog_type) {
3522 	/* Program types only with direct read access go here! */
3523 	case BPF_PROG_TYPE_LWT_IN:
3524 	case BPF_PROG_TYPE_LWT_OUT:
3525 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3526 	case BPF_PROG_TYPE_SK_REUSEPORT:
3527 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3528 	case BPF_PROG_TYPE_CGROUP_SKB:
3529 		if (t == BPF_WRITE)
3530 			return false;
3531 		fallthrough;
3532 
3533 	/* Program types with direct read + write access go here! */
3534 	case BPF_PROG_TYPE_SCHED_CLS:
3535 	case BPF_PROG_TYPE_SCHED_ACT:
3536 	case BPF_PROG_TYPE_XDP:
3537 	case BPF_PROG_TYPE_LWT_XMIT:
3538 	case BPF_PROG_TYPE_SK_SKB:
3539 	case BPF_PROG_TYPE_SK_MSG:
3540 		if (meta)
3541 			return meta->pkt_access;
3542 
3543 		env->seen_direct_write = true;
3544 		return true;
3545 
3546 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3547 		if (t == BPF_WRITE)
3548 			env->seen_direct_write = true;
3549 
3550 		return true;
3551 
3552 	default:
3553 		return false;
3554 	}
3555 }
3556 
3557 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3558 			       int size, bool zero_size_allowed)
3559 {
3560 	struct bpf_reg_state *regs = cur_regs(env);
3561 	struct bpf_reg_state *reg = &regs[regno];
3562 	int err;
3563 
3564 	/* We may have added a variable offset to the packet pointer; but any
3565 	 * reg->range we have comes after that.  We are only checking the fixed
3566 	 * offset.
3567 	 */
3568 
3569 	/* We don't allow negative numbers, because we aren't tracking enough
3570 	 * detail to prove they're safe.
3571 	 */
3572 	if (reg->smin_value < 0) {
3573 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3574 			regno);
3575 		return -EACCES;
3576 	}
3577 
3578 	err = reg->range < 0 ? -EINVAL :
3579 	      __check_mem_access(env, regno, off, size, reg->range,
3580 				 zero_size_allowed);
3581 	if (err) {
3582 		verbose(env, "R%d offset is outside of the packet\n", regno);
3583 		return err;
3584 	}
3585 
3586 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3587 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3588 	 * otherwise find_good_pkt_pointers would have refused to set range info
3589 	 * that __check_mem_access would have rejected this pkt access.
3590 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3591 	 */
3592 	env->prog->aux->max_pkt_offset =
3593 		max_t(u32, env->prog->aux->max_pkt_offset,
3594 		      off + reg->umax_value + size - 1);
3595 
3596 	return err;
3597 }
3598 
3599 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3600 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3601 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3602 			    struct btf **btf, u32 *btf_id)
3603 {
3604 	struct bpf_insn_access_aux info = {
3605 		.reg_type = *reg_type,
3606 		.log = &env->log,
3607 	};
3608 
3609 	if (env->ops->is_valid_access &&
3610 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3611 		/* A non zero info.ctx_field_size indicates that this field is a
3612 		 * candidate for later verifier transformation to load the whole
3613 		 * field and then apply a mask when accessed with a narrower
3614 		 * access than actual ctx access size. A zero info.ctx_field_size
3615 		 * will only allow for whole field access and rejects any other
3616 		 * type of narrower access.
3617 		 */
3618 		*reg_type = info.reg_type;
3619 
3620 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3621 			*btf = info.btf;
3622 			*btf_id = info.btf_id;
3623 		} else {
3624 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3625 		}
3626 		/* remember the offset of last byte accessed in ctx */
3627 		if (env->prog->aux->max_ctx_offset < off + size)
3628 			env->prog->aux->max_ctx_offset = off + size;
3629 		return 0;
3630 	}
3631 
3632 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3633 	return -EACCES;
3634 }
3635 
3636 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3637 				  int size)
3638 {
3639 	if (size < 0 || off < 0 ||
3640 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3641 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3642 			off, size);
3643 		return -EACCES;
3644 	}
3645 	return 0;
3646 }
3647 
3648 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3649 			     u32 regno, int off, int size,
3650 			     enum bpf_access_type t)
3651 {
3652 	struct bpf_reg_state *regs = cur_regs(env);
3653 	struct bpf_reg_state *reg = &regs[regno];
3654 	struct bpf_insn_access_aux info = {};
3655 	bool valid;
3656 
3657 	if (reg->smin_value < 0) {
3658 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3659 			regno);
3660 		return -EACCES;
3661 	}
3662 
3663 	switch (reg->type) {
3664 	case PTR_TO_SOCK_COMMON:
3665 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3666 		break;
3667 	case PTR_TO_SOCKET:
3668 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3669 		break;
3670 	case PTR_TO_TCP_SOCK:
3671 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3672 		break;
3673 	case PTR_TO_XDP_SOCK:
3674 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3675 		break;
3676 	default:
3677 		valid = false;
3678 	}
3679 
3680 
3681 	if (valid) {
3682 		env->insn_aux_data[insn_idx].ctx_field_size =
3683 			info.ctx_field_size;
3684 		return 0;
3685 	}
3686 
3687 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3688 		regno, reg_type_str(env, reg->type), off, size);
3689 
3690 	return -EACCES;
3691 }
3692 
3693 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3694 {
3695 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3696 }
3697 
3698 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3699 {
3700 	const struct bpf_reg_state *reg = reg_state(env, regno);
3701 
3702 	return reg->type == PTR_TO_CTX;
3703 }
3704 
3705 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3706 {
3707 	const struct bpf_reg_state *reg = reg_state(env, regno);
3708 
3709 	return type_is_sk_pointer(reg->type);
3710 }
3711 
3712 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3713 {
3714 	const struct bpf_reg_state *reg = reg_state(env, regno);
3715 
3716 	return type_is_pkt_pointer(reg->type);
3717 }
3718 
3719 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3720 {
3721 	const struct bpf_reg_state *reg = reg_state(env, regno);
3722 
3723 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3724 	return reg->type == PTR_TO_FLOW_KEYS;
3725 }
3726 
3727 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3728 				   const struct bpf_reg_state *reg,
3729 				   int off, int size, bool strict)
3730 {
3731 	struct tnum reg_off;
3732 	int ip_align;
3733 
3734 	/* Byte size accesses are always allowed. */
3735 	if (!strict || size == 1)
3736 		return 0;
3737 
3738 	/* For platforms that do not have a Kconfig enabling
3739 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3740 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3741 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3742 	 * to this code only in strict mode where we want to emulate
3743 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3744 	 * unconditional IP align value of '2'.
3745 	 */
3746 	ip_align = 2;
3747 
3748 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3749 	if (!tnum_is_aligned(reg_off, size)) {
3750 		char tn_buf[48];
3751 
3752 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3753 		verbose(env,
3754 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3755 			ip_align, tn_buf, reg->off, off, size);
3756 		return -EACCES;
3757 	}
3758 
3759 	return 0;
3760 }
3761 
3762 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3763 				       const struct bpf_reg_state *reg,
3764 				       const char *pointer_desc,
3765 				       int off, int size, bool strict)
3766 {
3767 	struct tnum reg_off;
3768 
3769 	/* Byte size accesses are always allowed. */
3770 	if (!strict || size == 1)
3771 		return 0;
3772 
3773 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3774 	if (!tnum_is_aligned(reg_off, size)) {
3775 		char tn_buf[48];
3776 
3777 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3778 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3779 			pointer_desc, tn_buf, reg->off, off, size);
3780 		return -EACCES;
3781 	}
3782 
3783 	return 0;
3784 }
3785 
3786 static int check_ptr_alignment(struct bpf_verifier_env *env,
3787 			       const struct bpf_reg_state *reg, int off,
3788 			       int size, bool strict_alignment_once)
3789 {
3790 	bool strict = env->strict_alignment || strict_alignment_once;
3791 	const char *pointer_desc = "";
3792 
3793 	switch (reg->type) {
3794 	case PTR_TO_PACKET:
3795 	case PTR_TO_PACKET_META:
3796 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3797 		 * right in front, treat it the very same way.
3798 		 */
3799 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3800 	case PTR_TO_FLOW_KEYS:
3801 		pointer_desc = "flow keys ";
3802 		break;
3803 	case PTR_TO_MAP_KEY:
3804 		pointer_desc = "key ";
3805 		break;
3806 	case PTR_TO_MAP_VALUE:
3807 		pointer_desc = "value ";
3808 		break;
3809 	case PTR_TO_CTX:
3810 		pointer_desc = "context ";
3811 		break;
3812 	case PTR_TO_STACK:
3813 		pointer_desc = "stack ";
3814 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3815 		 * and check_stack_read_fixed_off() relies on stack accesses being
3816 		 * aligned.
3817 		 */
3818 		strict = true;
3819 		break;
3820 	case PTR_TO_SOCKET:
3821 		pointer_desc = "sock ";
3822 		break;
3823 	case PTR_TO_SOCK_COMMON:
3824 		pointer_desc = "sock_common ";
3825 		break;
3826 	case PTR_TO_TCP_SOCK:
3827 		pointer_desc = "tcp_sock ";
3828 		break;
3829 	case PTR_TO_XDP_SOCK:
3830 		pointer_desc = "xdp_sock ";
3831 		break;
3832 	default:
3833 		break;
3834 	}
3835 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3836 					   strict);
3837 }
3838 
3839 static int update_stack_depth(struct bpf_verifier_env *env,
3840 			      const struct bpf_func_state *func,
3841 			      int off)
3842 {
3843 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3844 
3845 	if (stack >= -off)
3846 		return 0;
3847 
3848 	/* update known max for given subprogram */
3849 	env->subprog_info[func->subprogno].stack_depth = -off;
3850 	return 0;
3851 }
3852 
3853 /* starting from main bpf function walk all instructions of the function
3854  * and recursively walk all callees that given function can call.
3855  * Ignore jump and exit insns.
3856  * Since recursion is prevented by check_cfg() this algorithm
3857  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3858  */
3859 static int check_max_stack_depth(struct bpf_verifier_env *env)
3860 {
3861 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3862 	struct bpf_subprog_info *subprog = env->subprog_info;
3863 	struct bpf_insn *insn = env->prog->insnsi;
3864 	bool tail_call_reachable = false;
3865 	int ret_insn[MAX_CALL_FRAMES];
3866 	int ret_prog[MAX_CALL_FRAMES];
3867 	int j;
3868 
3869 process_func:
3870 	/* protect against potential stack overflow that might happen when
3871 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3872 	 * depth for such case down to 256 so that the worst case scenario
3873 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3874 	 * 8k).
3875 	 *
3876 	 * To get the idea what might happen, see an example:
3877 	 * func1 -> sub rsp, 128
3878 	 *  subfunc1 -> sub rsp, 256
3879 	 *  tailcall1 -> add rsp, 256
3880 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3881 	 *   subfunc2 -> sub rsp, 64
3882 	 *   subfunc22 -> sub rsp, 128
3883 	 *   tailcall2 -> add rsp, 128
3884 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3885 	 *
3886 	 * tailcall will unwind the current stack frame but it will not get rid
3887 	 * of caller's stack as shown on the example above.
3888 	 */
3889 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3890 		verbose(env,
3891 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3892 			depth);
3893 		return -EACCES;
3894 	}
3895 	/* round up to 32-bytes, since this is granularity
3896 	 * of interpreter stack size
3897 	 */
3898 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3899 	if (depth > MAX_BPF_STACK) {
3900 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3901 			frame + 1, depth);
3902 		return -EACCES;
3903 	}
3904 continue_func:
3905 	subprog_end = subprog[idx + 1].start;
3906 	for (; i < subprog_end; i++) {
3907 		int next_insn;
3908 
3909 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3910 			continue;
3911 		/* remember insn and function to return to */
3912 		ret_insn[frame] = i + 1;
3913 		ret_prog[frame] = idx;
3914 
3915 		/* find the callee */
3916 		next_insn = i + insn[i].imm + 1;
3917 		idx = find_subprog(env, next_insn);
3918 		if (idx < 0) {
3919 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3920 				  next_insn);
3921 			return -EFAULT;
3922 		}
3923 		if (subprog[idx].is_async_cb) {
3924 			if (subprog[idx].has_tail_call) {
3925 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3926 				return -EFAULT;
3927 			}
3928 			 /* async callbacks don't increase bpf prog stack size */
3929 			continue;
3930 		}
3931 		i = next_insn;
3932 
3933 		if (subprog[idx].has_tail_call)
3934 			tail_call_reachable = true;
3935 
3936 		frame++;
3937 		if (frame >= MAX_CALL_FRAMES) {
3938 			verbose(env, "the call stack of %d frames is too deep !\n",
3939 				frame);
3940 			return -E2BIG;
3941 		}
3942 		goto process_func;
3943 	}
3944 	/* if tail call got detected across bpf2bpf calls then mark each of the
3945 	 * currently present subprog frames as tail call reachable subprogs;
3946 	 * this info will be utilized by JIT so that we will be preserving the
3947 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3948 	 */
3949 	if (tail_call_reachable)
3950 		for (j = 0; j < frame; j++)
3951 			subprog[ret_prog[j]].tail_call_reachable = true;
3952 	if (subprog[0].tail_call_reachable)
3953 		env->prog->aux->tail_call_reachable = true;
3954 
3955 	/* end of for() loop means the last insn of the 'subprog'
3956 	 * was reached. Doesn't matter whether it was JA or EXIT
3957 	 */
3958 	if (frame == 0)
3959 		return 0;
3960 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3961 	frame--;
3962 	i = ret_insn[frame];
3963 	idx = ret_prog[frame];
3964 	goto continue_func;
3965 }
3966 
3967 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3968 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3969 				  const struct bpf_insn *insn, int idx)
3970 {
3971 	int start = idx + insn->imm + 1, subprog;
3972 
3973 	subprog = find_subprog(env, start);
3974 	if (subprog < 0) {
3975 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3976 			  start);
3977 		return -EFAULT;
3978 	}
3979 	return env->subprog_info[subprog].stack_depth;
3980 }
3981 #endif
3982 
3983 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3984 			       const struct bpf_reg_state *reg, int regno,
3985 			       bool fixed_off_ok)
3986 {
3987 	/* Access to this pointer-typed register or passing it to a helper
3988 	 * is only allowed in its original, unmodified form.
3989 	 */
3990 
3991 	if (reg->off < 0) {
3992 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3993 			reg_type_str(env, reg->type), regno, reg->off);
3994 		return -EACCES;
3995 	}
3996 
3997 	if (!fixed_off_ok && reg->off) {
3998 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3999 			reg_type_str(env, reg->type), regno, reg->off);
4000 		return -EACCES;
4001 	}
4002 
4003 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4004 		char tn_buf[48];
4005 
4006 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4007 		verbose(env, "variable %s access var_off=%s disallowed\n",
4008 			reg_type_str(env, reg->type), tn_buf);
4009 		return -EACCES;
4010 	}
4011 
4012 	return 0;
4013 }
4014 
4015 int check_ptr_off_reg(struct bpf_verifier_env *env,
4016 		      const struct bpf_reg_state *reg, int regno)
4017 {
4018 	return __check_ptr_off_reg(env, reg, regno, false);
4019 }
4020 
4021 static int __check_buffer_access(struct bpf_verifier_env *env,
4022 				 const char *buf_info,
4023 				 const struct bpf_reg_state *reg,
4024 				 int regno, int off, int size)
4025 {
4026 	if (off < 0) {
4027 		verbose(env,
4028 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4029 			regno, buf_info, off, size);
4030 		return -EACCES;
4031 	}
4032 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4033 		char tn_buf[48];
4034 
4035 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4036 		verbose(env,
4037 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4038 			regno, off, tn_buf);
4039 		return -EACCES;
4040 	}
4041 
4042 	return 0;
4043 }
4044 
4045 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4046 				  const struct bpf_reg_state *reg,
4047 				  int regno, int off, int size)
4048 {
4049 	int err;
4050 
4051 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4052 	if (err)
4053 		return err;
4054 
4055 	if (off + size > env->prog->aux->max_tp_access)
4056 		env->prog->aux->max_tp_access = off + size;
4057 
4058 	return 0;
4059 }
4060 
4061 static int check_buffer_access(struct bpf_verifier_env *env,
4062 			       const struct bpf_reg_state *reg,
4063 			       int regno, int off, int size,
4064 			       bool zero_size_allowed,
4065 			       u32 *max_access)
4066 {
4067 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4068 	int err;
4069 
4070 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4071 	if (err)
4072 		return err;
4073 
4074 	if (off + size > *max_access)
4075 		*max_access = off + size;
4076 
4077 	return 0;
4078 }
4079 
4080 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4081 static void zext_32_to_64(struct bpf_reg_state *reg)
4082 {
4083 	reg->var_off = tnum_subreg(reg->var_off);
4084 	__reg_assign_32_into_64(reg);
4085 }
4086 
4087 /* truncate register to smaller size (in bytes)
4088  * must be called with size < BPF_REG_SIZE
4089  */
4090 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4091 {
4092 	u64 mask;
4093 
4094 	/* clear high bits in bit representation */
4095 	reg->var_off = tnum_cast(reg->var_off, size);
4096 
4097 	/* fix arithmetic bounds */
4098 	mask = ((u64)1 << (size * 8)) - 1;
4099 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4100 		reg->umin_value &= mask;
4101 		reg->umax_value &= mask;
4102 	} else {
4103 		reg->umin_value = 0;
4104 		reg->umax_value = mask;
4105 	}
4106 	reg->smin_value = reg->umin_value;
4107 	reg->smax_value = reg->umax_value;
4108 
4109 	/* If size is smaller than 32bit register the 32bit register
4110 	 * values are also truncated so we push 64-bit bounds into
4111 	 * 32-bit bounds. Above were truncated < 32-bits already.
4112 	 */
4113 	if (size >= 4)
4114 		return;
4115 	__reg_combine_64_into_32(reg);
4116 }
4117 
4118 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4119 {
4120 	/* A map is considered read-only if the following condition are true:
4121 	 *
4122 	 * 1) BPF program side cannot change any of the map content. The
4123 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4124 	 *    and was set at map creation time.
4125 	 * 2) The map value(s) have been initialized from user space by a
4126 	 *    loader and then "frozen", such that no new map update/delete
4127 	 *    operations from syscall side are possible for the rest of
4128 	 *    the map's lifetime from that point onwards.
4129 	 * 3) Any parallel/pending map update/delete operations from syscall
4130 	 *    side have been completed. Only after that point, it's safe to
4131 	 *    assume that map value(s) are immutable.
4132 	 */
4133 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4134 	       READ_ONCE(map->frozen) &&
4135 	       !bpf_map_write_active(map);
4136 }
4137 
4138 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4139 {
4140 	void *ptr;
4141 	u64 addr;
4142 	int err;
4143 
4144 	err = map->ops->map_direct_value_addr(map, &addr, off);
4145 	if (err)
4146 		return err;
4147 	ptr = (void *)(long)addr + off;
4148 
4149 	switch (size) {
4150 	case sizeof(u8):
4151 		*val = (u64)*(u8 *)ptr;
4152 		break;
4153 	case sizeof(u16):
4154 		*val = (u64)*(u16 *)ptr;
4155 		break;
4156 	case sizeof(u32):
4157 		*val = (u64)*(u32 *)ptr;
4158 		break;
4159 	case sizeof(u64):
4160 		*val = *(u64 *)ptr;
4161 		break;
4162 	default:
4163 		return -EINVAL;
4164 	}
4165 	return 0;
4166 }
4167 
4168 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4169 				   struct bpf_reg_state *regs,
4170 				   int regno, int off, int size,
4171 				   enum bpf_access_type atype,
4172 				   int value_regno)
4173 {
4174 	struct bpf_reg_state *reg = regs + regno;
4175 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4176 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4177 	enum bpf_type_flag flag = 0;
4178 	u32 btf_id;
4179 	int ret;
4180 
4181 	if (off < 0) {
4182 		verbose(env,
4183 			"R%d is ptr_%s invalid negative access: off=%d\n",
4184 			regno, tname, off);
4185 		return -EACCES;
4186 	}
4187 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4188 		char tn_buf[48];
4189 
4190 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4191 		verbose(env,
4192 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4193 			regno, tname, off, tn_buf);
4194 		return -EACCES;
4195 	}
4196 
4197 	if (reg->type & MEM_USER) {
4198 		verbose(env,
4199 			"R%d is ptr_%s access user memory: off=%d\n",
4200 			regno, tname, off);
4201 		return -EACCES;
4202 	}
4203 
4204 	if (reg->type & MEM_PERCPU) {
4205 		verbose(env,
4206 			"R%d is ptr_%s access percpu memory: off=%d\n",
4207 			regno, tname, off);
4208 		return -EACCES;
4209 	}
4210 
4211 	if (env->ops->btf_struct_access) {
4212 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4213 						  off, size, atype, &btf_id, &flag);
4214 	} else {
4215 		if (atype != BPF_READ) {
4216 			verbose(env, "only read is supported\n");
4217 			return -EACCES;
4218 		}
4219 
4220 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4221 					atype, &btf_id, &flag);
4222 	}
4223 
4224 	if (ret < 0)
4225 		return ret;
4226 
4227 	if (atype == BPF_READ && value_regno >= 0)
4228 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4229 
4230 	return 0;
4231 }
4232 
4233 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4234 				   struct bpf_reg_state *regs,
4235 				   int regno, int off, int size,
4236 				   enum bpf_access_type atype,
4237 				   int value_regno)
4238 {
4239 	struct bpf_reg_state *reg = regs + regno;
4240 	struct bpf_map *map = reg->map_ptr;
4241 	enum bpf_type_flag flag = 0;
4242 	const struct btf_type *t;
4243 	const char *tname;
4244 	u32 btf_id;
4245 	int ret;
4246 
4247 	if (!btf_vmlinux) {
4248 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4249 		return -ENOTSUPP;
4250 	}
4251 
4252 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4253 		verbose(env, "map_ptr access not supported for map type %d\n",
4254 			map->map_type);
4255 		return -ENOTSUPP;
4256 	}
4257 
4258 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4259 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4260 
4261 	if (!env->allow_ptr_to_map_access) {
4262 		verbose(env,
4263 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4264 			tname);
4265 		return -EPERM;
4266 	}
4267 
4268 	if (off < 0) {
4269 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4270 			regno, tname, off);
4271 		return -EACCES;
4272 	}
4273 
4274 	if (atype != BPF_READ) {
4275 		verbose(env, "only read from %s is supported\n", tname);
4276 		return -EACCES;
4277 	}
4278 
4279 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4280 	if (ret < 0)
4281 		return ret;
4282 
4283 	if (value_regno >= 0)
4284 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4285 
4286 	return 0;
4287 }
4288 
4289 /* Check that the stack access at the given offset is within bounds. The
4290  * maximum valid offset is -1.
4291  *
4292  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4293  * -state->allocated_stack for reads.
4294  */
4295 static int check_stack_slot_within_bounds(int off,
4296 					  struct bpf_func_state *state,
4297 					  enum bpf_access_type t)
4298 {
4299 	int min_valid_off;
4300 
4301 	if (t == BPF_WRITE)
4302 		min_valid_off = -MAX_BPF_STACK;
4303 	else
4304 		min_valid_off = -state->allocated_stack;
4305 
4306 	if (off < min_valid_off || off > -1)
4307 		return -EACCES;
4308 	return 0;
4309 }
4310 
4311 /* Check that the stack access at 'regno + off' falls within the maximum stack
4312  * bounds.
4313  *
4314  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4315  */
4316 static int check_stack_access_within_bounds(
4317 		struct bpf_verifier_env *env,
4318 		int regno, int off, int access_size,
4319 		enum stack_access_src src, enum bpf_access_type type)
4320 {
4321 	struct bpf_reg_state *regs = cur_regs(env);
4322 	struct bpf_reg_state *reg = regs + regno;
4323 	struct bpf_func_state *state = func(env, reg);
4324 	int min_off, max_off;
4325 	int err;
4326 	char *err_extra;
4327 
4328 	if (src == ACCESS_HELPER)
4329 		/* We don't know if helpers are reading or writing (or both). */
4330 		err_extra = " indirect access to";
4331 	else if (type == BPF_READ)
4332 		err_extra = " read from";
4333 	else
4334 		err_extra = " write to";
4335 
4336 	if (tnum_is_const(reg->var_off)) {
4337 		min_off = reg->var_off.value + off;
4338 		if (access_size > 0)
4339 			max_off = min_off + access_size - 1;
4340 		else
4341 			max_off = min_off;
4342 	} else {
4343 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4344 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4345 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4346 				err_extra, regno);
4347 			return -EACCES;
4348 		}
4349 		min_off = reg->smin_value + off;
4350 		if (access_size > 0)
4351 			max_off = reg->smax_value + off + access_size - 1;
4352 		else
4353 			max_off = min_off;
4354 	}
4355 
4356 	err = check_stack_slot_within_bounds(min_off, state, type);
4357 	if (!err)
4358 		err = check_stack_slot_within_bounds(max_off, state, type);
4359 
4360 	if (err) {
4361 		if (tnum_is_const(reg->var_off)) {
4362 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4363 				err_extra, regno, off, access_size);
4364 		} else {
4365 			char tn_buf[48];
4366 
4367 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4368 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4369 				err_extra, regno, tn_buf, access_size);
4370 		}
4371 	}
4372 	return err;
4373 }
4374 
4375 /* check whether memory at (regno + off) is accessible for t = (read | write)
4376  * if t==write, value_regno is a register which value is stored into memory
4377  * if t==read, value_regno is a register which will receive the value from memory
4378  * if t==write && value_regno==-1, some unknown value is stored into memory
4379  * if t==read && value_regno==-1, don't care what we read from memory
4380  */
4381 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4382 			    int off, int bpf_size, enum bpf_access_type t,
4383 			    int value_regno, bool strict_alignment_once)
4384 {
4385 	struct bpf_reg_state *regs = cur_regs(env);
4386 	struct bpf_reg_state *reg = regs + regno;
4387 	struct bpf_func_state *state;
4388 	int size, err = 0;
4389 
4390 	size = bpf_size_to_bytes(bpf_size);
4391 	if (size < 0)
4392 		return size;
4393 
4394 	/* alignment checks will add in reg->off themselves */
4395 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4396 	if (err)
4397 		return err;
4398 
4399 	/* for access checks, reg->off is just part of off */
4400 	off += reg->off;
4401 
4402 	if (reg->type == PTR_TO_MAP_KEY) {
4403 		if (t == BPF_WRITE) {
4404 			verbose(env, "write to change key R%d not allowed\n", regno);
4405 			return -EACCES;
4406 		}
4407 
4408 		err = check_mem_region_access(env, regno, off, size,
4409 					      reg->map_ptr->key_size, false);
4410 		if (err)
4411 			return err;
4412 		if (value_regno >= 0)
4413 			mark_reg_unknown(env, regs, value_regno);
4414 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4415 		if (t == BPF_WRITE && value_regno >= 0 &&
4416 		    is_pointer_value(env, value_regno)) {
4417 			verbose(env, "R%d leaks addr into map\n", value_regno);
4418 			return -EACCES;
4419 		}
4420 		err = check_map_access_type(env, regno, off, size, t);
4421 		if (err)
4422 			return err;
4423 		err = check_map_access(env, regno, off, size, false);
4424 		if (!err && t == BPF_READ && value_regno >= 0) {
4425 			struct bpf_map *map = reg->map_ptr;
4426 
4427 			/* if map is read-only, track its contents as scalars */
4428 			if (tnum_is_const(reg->var_off) &&
4429 			    bpf_map_is_rdonly(map) &&
4430 			    map->ops->map_direct_value_addr) {
4431 				int map_off = off + reg->var_off.value;
4432 				u64 val = 0;
4433 
4434 				err = bpf_map_direct_read(map, map_off, size,
4435 							  &val);
4436 				if (err)
4437 					return err;
4438 
4439 				regs[value_regno].type = SCALAR_VALUE;
4440 				__mark_reg_known(&regs[value_regno], val);
4441 			} else {
4442 				mark_reg_unknown(env, regs, value_regno);
4443 			}
4444 		}
4445 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4446 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4447 
4448 		if (type_may_be_null(reg->type)) {
4449 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4450 				reg_type_str(env, reg->type));
4451 			return -EACCES;
4452 		}
4453 
4454 		if (t == BPF_WRITE && rdonly_mem) {
4455 			verbose(env, "R%d cannot write into %s\n",
4456 				regno, reg_type_str(env, reg->type));
4457 			return -EACCES;
4458 		}
4459 
4460 		if (t == BPF_WRITE && value_regno >= 0 &&
4461 		    is_pointer_value(env, value_regno)) {
4462 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4463 			return -EACCES;
4464 		}
4465 
4466 		err = check_mem_region_access(env, regno, off, size,
4467 					      reg->mem_size, false);
4468 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4469 			mark_reg_unknown(env, regs, value_regno);
4470 	} else if (reg->type == PTR_TO_CTX) {
4471 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4472 		struct btf *btf = NULL;
4473 		u32 btf_id = 0;
4474 
4475 		if (t == BPF_WRITE && value_regno >= 0 &&
4476 		    is_pointer_value(env, value_regno)) {
4477 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4478 			return -EACCES;
4479 		}
4480 
4481 		err = check_ptr_off_reg(env, reg, regno);
4482 		if (err < 0)
4483 			return err;
4484 
4485 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4486 				       &btf_id);
4487 		if (err)
4488 			verbose_linfo(env, insn_idx, "; ");
4489 		if (!err && t == BPF_READ && value_regno >= 0) {
4490 			/* ctx access returns either a scalar, or a
4491 			 * PTR_TO_PACKET[_META,_END]. In the latter
4492 			 * case, we know the offset is zero.
4493 			 */
4494 			if (reg_type == SCALAR_VALUE) {
4495 				mark_reg_unknown(env, regs, value_regno);
4496 			} else {
4497 				mark_reg_known_zero(env, regs,
4498 						    value_regno);
4499 				if (type_may_be_null(reg_type))
4500 					regs[value_regno].id = ++env->id_gen;
4501 				/* A load of ctx field could have different
4502 				 * actual load size with the one encoded in the
4503 				 * insn. When the dst is PTR, it is for sure not
4504 				 * a sub-register.
4505 				 */
4506 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4507 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4508 					regs[value_regno].btf = btf;
4509 					regs[value_regno].btf_id = btf_id;
4510 				}
4511 			}
4512 			regs[value_regno].type = reg_type;
4513 		}
4514 
4515 	} else if (reg->type == PTR_TO_STACK) {
4516 		/* Basic bounds checks. */
4517 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4518 		if (err)
4519 			return err;
4520 
4521 		state = func(env, reg);
4522 		err = update_stack_depth(env, state, off);
4523 		if (err)
4524 			return err;
4525 
4526 		if (t == BPF_READ)
4527 			err = check_stack_read(env, regno, off, size,
4528 					       value_regno);
4529 		else
4530 			err = check_stack_write(env, regno, off, size,
4531 						value_regno, insn_idx);
4532 	} else if (reg_is_pkt_pointer(reg)) {
4533 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4534 			verbose(env, "cannot write into packet\n");
4535 			return -EACCES;
4536 		}
4537 		if (t == BPF_WRITE && value_regno >= 0 &&
4538 		    is_pointer_value(env, value_regno)) {
4539 			verbose(env, "R%d leaks addr into packet\n",
4540 				value_regno);
4541 			return -EACCES;
4542 		}
4543 		err = check_packet_access(env, regno, off, size, false);
4544 		if (!err && t == BPF_READ && value_regno >= 0)
4545 			mark_reg_unknown(env, regs, value_regno);
4546 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4547 		if (t == BPF_WRITE && value_regno >= 0 &&
4548 		    is_pointer_value(env, value_regno)) {
4549 			verbose(env, "R%d leaks addr into flow keys\n",
4550 				value_regno);
4551 			return -EACCES;
4552 		}
4553 
4554 		err = check_flow_keys_access(env, off, size);
4555 		if (!err && t == BPF_READ && value_regno >= 0)
4556 			mark_reg_unknown(env, regs, value_regno);
4557 	} else if (type_is_sk_pointer(reg->type)) {
4558 		if (t == BPF_WRITE) {
4559 			verbose(env, "R%d cannot write into %s\n",
4560 				regno, reg_type_str(env, reg->type));
4561 			return -EACCES;
4562 		}
4563 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4564 		if (!err && value_regno >= 0)
4565 			mark_reg_unknown(env, regs, value_regno);
4566 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4567 		err = check_tp_buffer_access(env, reg, regno, off, size);
4568 		if (!err && t == BPF_READ && value_regno >= 0)
4569 			mark_reg_unknown(env, regs, value_regno);
4570 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4571 		   !type_may_be_null(reg->type)) {
4572 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4573 					      value_regno);
4574 	} else if (reg->type == CONST_PTR_TO_MAP) {
4575 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4576 					      value_regno);
4577 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4578 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4579 		u32 *max_access;
4580 
4581 		if (rdonly_mem) {
4582 			if (t == BPF_WRITE) {
4583 				verbose(env, "R%d cannot write into %s\n",
4584 					regno, reg_type_str(env, reg->type));
4585 				return -EACCES;
4586 			}
4587 			max_access = &env->prog->aux->max_rdonly_access;
4588 		} else {
4589 			max_access = &env->prog->aux->max_rdwr_access;
4590 		}
4591 
4592 		err = check_buffer_access(env, reg, regno, off, size, false,
4593 					  max_access);
4594 
4595 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4596 			mark_reg_unknown(env, regs, value_regno);
4597 	} else {
4598 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4599 			reg_type_str(env, reg->type));
4600 		return -EACCES;
4601 	}
4602 
4603 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4604 	    regs[value_regno].type == SCALAR_VALUE) {
4605 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4606 		coerce_reg_to_size(&regs[value_regno], size);
4607 	}
4608 	return err;
4609 }
4610 
4611 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4612 {
4613 	int load_reg;
4614 	int err;
4615 
4616 	switch (insn->imm) {
4617 	case BPF_ADD:
4618 	case BPF_ADD | BPF_FETCH:
4619 	case BPF_AND:
4620 	case BPF_AND | BPF_FETCH:
4621 	case BPF_OR:
4622 	case BPF_OR | BPF_FETCH:
4623 	case BPF_XOR:
4624 	case BPF_XOR | BPF_FETCH:
4625 	case BPF_XCHG:
4626 	case BPF_CMPXCHG:
4627 		break;
4628 	default:
4629 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4630 		return -EINVAL;
4631 	}
4632 
4633 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4634 		verbose(env, "invalid atomic operand size\n");
4635 		return -EINVAL;
4636 	}
4637 
4638 	/* check src1 operand */
4639 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4640 	if (err)
4641 		return err;
4642 
4643 	/* check src2 operand */
4644 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4645 	if (err)
4646 		return err;
4647 
4648 	if (insn->imm == BPF_CMPXCHG) {
4649 		/* Check comparison of R0 with memory location */
4650 		const u32 aux_reg = BPF_REG_0;
4651 
4652 		err = check_reg_arg(env, aux_reg, SRC_OP);
4653 		if (err)
4654 			return err;
4655 
4656 		if (is_pointer_value(env, aux_reg)) {
4657 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4658 			return -EACCES;
4659 		}
4660 	}
4661 
4662 	if (is_pointer_value(env, insn->src_reg)) {
4663 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4664 		return -EACCES;
4665 	}
4666 
4667 	if (is_ctx_reg(env, insn->dst_reg) ||
4668 	    is_pkt_reg(env, insn->dst_reg) ||
4669 	    is_flow_key_reg(env, insn->dst_reg) ||
4670 	    is_sk_reg(env, insn->dst_reg)) {
4671 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4672 			insn->dst_reg,
4673 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4674 		return -EACCES;
4675 	}
4676 
4677 	if (insn->imm & BPF_FETCH) {
4678 		if (insn->imm == BPF_CMPXCHG)
4679 			load_reg = BPF_REG_0;
4680 		else
4681 			load_reg = insn->src_reg;
4682 
4683 		/* check and record load of old value */
4684 		err = check_reg_arg(env, load_reg, DST_OP);
4685 		if (err)
4686 			return err;
4687 	} else {
4688 		/* This instruction accesses a memory location but doesn't
4689 		 * actually load it into a register.
4690 		 */
4691 		load_reg = -1;
4692 	}
4693 
4694 	/* Check whether we can read the memory, with second call for fetch
4695 	 * case to simulate the register fill.
4696 	 */
4697 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4698 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4699 	if (!err && load_reg >= 0)
4700 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4701 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
4702 				       true);
4703 	if (err)
4704 		return err;
4705 
4706 	/* Check whether we can write into the same memory. */
4707 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4708 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4709 	if (err)
4710 		return err;
4711 
4712 	return 0;
4713 }
4714 
4715 /* When register 'regno' is used to read the stack (either directly or through
4716  * a helper function) make sure that it's within stack boundary and, depending
4717  * on the access type, that all elements of the stack are initialized.
4718  *
4719  * 'off' includes 'regno->off', but not its dynamic part (if any).
4720  *
4721  * All registers that have been spilled on the stack in the slots within the
4722  * read offsets are marked as read.
4723  */
4724 static int check_stack_range_initialized(
4725 		struct bpf_verifier_env *env, int regno, int off,
4726 		int access_size, bool zero_size_allowed,
4727 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4728 {
4729 	struct bpf_reg_state *reg = reg_state(env, regno);
4730 	struct bpf_func_state *state = func(env, reg);
4731 	int err, min_off, max_off, i, j, slot, spi;
4732 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4733 	enum bpf_access_type bounds_check_type;
4734 	/* Some accesses can write anything into the stack, others are
4735 	 * read-only.
4736 	 */
4737 	bool clobber = false;
4738 
4739 	if (access_size == 0 && !zero_size_allowed) {
4740 		verbose(env, "invalid zero-sized read\n");
4741 		return -EACCES;
4742 	}
4743 
4744 	if (type == ACCESS_HELPER) {
4745 		/* The bounds checks for writes are more permissive than for
4746 		 * reads. However, if raw_mode is not set, we'll do extra
4747 		 * checks below.
4748 		 */
4749 		bounds_check_type = BPF_WRITE;
4750 		clobber = true;
4751 	} else {
4752 		bounds_check_type = BPF_READ;
4753 	}
4754 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4755 					       type, bounds_check_type);
4756 	if (err)
4757 		return err;
4758 
4759 
4760 	if (tnum_is_const(reg->var_off)) {
4761 		min_off = max_off = reg->var_off.value + off;
4762 	} else {
4763 		/* Variable offset is prohibited for unprivileged mode for
4764 		 * simplicity since it requires corresponding support in
4765 		 * Spectre masking for stack ALU.
4766 		 * See also retrieve_ptr_limit().
4767 		 */
4768 		if (!env->bypass_spec_v1) {
4769 			char tn_buf[48];
4770 
4771 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4772 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4773 				regno, err_extra, tn_buf);
4774 			return -EACCES;
4775 		}
4776 		/* Only initialized buffer on stack is allowed to be accessed
4777 		 * with variable offset. With uninitialized buffer it's hard to
4778 		 * guarantee that whole memory is marked as initialized on
4779 		 * helper return since specific bounds are unknown what may
4780 		 * cause uninitialized stack leaking.
4781 		 */
4782 		if (meta && meta->raw_mode)
4783 			meta = NULL;
4784 
4785 		min_off = reg->smin_value + off;
4786 		max_off = reg->smax_value + off;
4787 	}
4788 
4789 	if (meta && meta->raw_mode) {
4790 		meta->access_size = access_size;
4791 		meta->regno = regno;
4792 		return 0;
4793 	}
4794 
4795 	for (i = min_off; i < max_off + access_size; i++) {
4796 		u8 *stype;
4797 
4798 		slot = -i - 1;
4799 		spi = slot / BPF_REG_SIZE;
4800 		if (state->allocated_stack <= slot)
4801 			goto err;
4802 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4803 		if (*stype == STACK_MISC)
4804 			goto mark;
4805 		if (*stype == STACK_ZERO) {
4806 			if (clobber) {
4807 				/* helper can write anything into the stack */
4808 				*stype = STACK_MISC;
4809 			}
4810 			goto mark;
4811 		}
4812 
4813 		if (is_spilled_reg(&state->stack[spi]) &&
4814 		    base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
4815 			goto mark;
4816 
4817 		if (is_spilled_reg(&state->stack[spi]) &&
4818 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4819 		     env->allow_ptr_leaks)) {
4820 			if (clobber) {
4821 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4822 				for (j = 0; j < BPF_REG_SIZE; j++)
4823 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4824 			}
4825 			goto mark;
4826 		}
4827 
4828 err:
4829 		if (tnum_is_const(reg->var_off)) {
4830 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4831 				err_extra, regno, min_off, i - min_off, access_size);
4832 		} else {
4833 			char tn_buf[48];
4834 
4835 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4836 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4837 				err_extra, regno, tn_buf, i - min_off, access_size);
4838 		}
4839 		return -EACCES;
4840 mark:
4841 		/* reading any byte out of 8-byte 'spill_slot' will cause
4842 		 * the whole slot to be marked as 'read'
4843 		 */
4844 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4845 			      state->stack[spi].spilled_ptr.parent,
4846 			      REG_LIVE_READ64);
4847 	}
4848 	return update_stack_depth(env, state, min_off);
4849 }
4850 
4851 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4852 				   int access_size, bool zero_size_allowed,
4853 				   struct bpf_call_arg_meta *meta)
4854 {
4855 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4856 	u32 *max_access;
4857 
4858 	switch (base_type(reg->type)) {
4859 	case PTR_TO_PACKET:
4860 	case PTR_TO_PACKET_META:
4861 		return check_packet_access(env, regno, reg->off, access_size,
4862 					   zero_size_allowed);
4863 	case PTR_TO_MAP_KEY:
4864 		return check_mem_region_access(env, regno, reg->off, access_size,
4865 					       reg->map_ptr->key_size, false);
4866 	case PTR_TO_MAP_VALUE:
4867 		if (check_map_access_type(env, regno, reg->off, access_size,
4868 					  meta && meta->raw_mode ? BPF_WRITE :
4869 					  BPF_READ))
4870 			return -EACCES;
4871 		return check_map_access(env, regno, reg->off, access_size,
4872 					zero_size_allowed);
4873 	case PTR_TO_MEM:
4874 		return check_mem_region_access(env, regno, reg->off,
4875 					       access_size, reg->mem_size,
4876 					       zero_size_allowed);
4877 	case PTR_TO_BUF:
4878 		if (type_is_rdonly_mem(reg->type)) {
4879 			if (meta && meta->raw_mode)
4880 				return -EACCES;
4881 
4882 			max_access = &env->prog->aux->max_rdonly_access;
4883 		} else {
4884 			max_access = &env->prog->aux->max_rdwr_access;
4885 		}
4886 		return check_buffer_access(env, reg, regno, reg->off,
4887 					   access_size, zero_size_allowed,
4888 					   max_access);
4889 	case PTR_TO_STACK:
4890 		return check_stack_range_initialized(
4891 				env,
4892 				regno, reg->off, access_size,
4893 				zero_size_allowed, ACCESS_HELPER, meta);
4894 	default: /* scalar_value or invalid ptr */
4895 		/* Allow zero-byte read from NULL, regardless of pointer type */
4896 		if (zero_size_allowed && access_size == 0 &&
4897 		    register_is_null(reg))
4898 			return 0;
4899 
4900 		verbose(env, "R%d type=%s ", regno,
4901 			reg_type_str(env, reg->type));
4902 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4903 		return -EACCES;
4904 	}
4905 }
4906 
4907 static int check_mem_size_reg(struct bpf_verifier_env *env,
4908 			      struct bpf_reg_state *reg, u32 regno,
4909 			      bool zero_size_allowed,
4910 			      struct bpf_call_arg_meta *meta)
4911 {
4912 	int err;
4913 
4914 	/* This is used to refine r0 return value bounds for helpers
4915 	 * that enforce this value as an upper bound on return values.
4916 	 * See do_refine_retval_range() for helpers that can refine
4917 	 * the return value. C type of helper is u32 so we pull register
4918 	 * bound from umax_value however, if negative verifier errors
4919 	 * out. Only upper bounds can be learned because retval is an
4920 	 * int type and negative retvals are allowed.
4921 	 */
4922 	if (meta)
4923 		meta->msize_max_value = reg->umax_value;
4924 
4925 	/* The register is SCALAR_VALUE; the access check
4926 	 * happens using its boundaries.
4927 	 */
4928 	if (!tnum_is_const(reg->var_off))
4929 		/* For unprivileged variable accesses, disable raw
4930 		 * mode so that the program is required to
4931 		 * initialize all the memory that the helper could
4932 		 * just partially fill up.
4933 		 */
4934 		meta = NULL;
4935 
4936 	if (reg->smin_value < 0) {
4937 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4938 			regno);
4939 		return -EACCES;
4940 	}
4941 
4942 	if (reg->umin_value == 0) {
4943 		err = check_helper_mem_access(env, regno - 1, 0,
4944 					      zero_size_allowed,
4945 					      meta);
4946 		if (err)
4947 			return err;
4948 	}
4949 
4950 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4951 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4952 			regno);
4953 		return -EACCES;
4954 	}
4955 	err = check_helper_mem_access(env, regno - 1,
4956 				      reg->umax_value,
4957 				      zero_size_allowed, meta);
4958 	if (!err)
4959 		err = mark_chain_precision(env, regno);
4960 	return err;
4961 }
4962 
4963 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4964 		   u32 regno, u32 mem_size)
4965 {
4966 	if (register_is_null(reg))
4967 		return 0;
4968 
4969 	if (type_may_be_null(reg->type)) {
4970 		/* Assuming that the register contains a value check if the memory
4971 		 * access is safe. Temporarily save and restore the register's state as
4972 		 * the conversion shouldn't be visible to a caller.
4973 		 */
4974 		const struct bpf_reg_state saved_reg = *reg;
4975 		int rv;
4976 
4977 		mark_ptr_not_null_reg(reg);
4978 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4979 		*reg = saved_reg;
4980 		return rv;
4981 	}
4982 
4983 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4984 }
4985 
4986 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4987 			     u32 regno)
4988 {
4989 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
4990 	bool may_be_null = type_may_be_null(mem_reg->type);
4991 	struct bpf_reg_state saved_reg;
4992 	int err;
4993 
4994 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
4995 
4996 	if (may_be_null) {
4997 		saved_reg = *mem_reg;
4998 		mark_ptr_not_null_reg(mem_reg);
4999 	}
5000 
5001 	err = check_mem_size_reg(env, reg, regno, true, NULL);
5002 
5003 	if (may_be_null)
5004 		*mem_reg = saved_reg;
5005 	return err;
5006 }
5007 
5008 /* Implementation details:
5009  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5010  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5011  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5012  * value_or_null->value transition, since the verifier only cares about
5013  * the range of access to valid map value pointer and doesn't care about actual
5014  * address of the map element.
5015  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5016  * reg->id > 0 after value_or_null->value transition. By doing so
5017  * two bpf_map_lookups will be considered two different pointers that
5018  * point to different bpf_spin_locks.
5019  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5020  * dead-locks.
5021  * Since only one bpf_spin_lock is allowed the checks are simpler than
5022  * reg_is_refcounted() logic. The verifier needs to remember only
5023  * one spin_lock instead of array of acquired_refs.
5024  * cur_state->active_spin_lock remembers which map value element got locked
5025  * and clears it after bpf_spin_unlock.
5026  */
5027 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5028 			     bool is_lock)
5029 {
5030 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5031 	struct bpf_verifier_state *cur = env->cur_state;
5032 	bool is_const = tnum_is_const(reg->var_off);
5033 	struct bpf_map *map = reg->map_ptr;
5034 	u64 val = reg->var_off.value;
5035 
5036 	if (!is_const) {
5037 		verbose(env,
5038 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5039 			regno);
5040 		return -EINVAL;
5041 	}
5042 	if (!map->btf) {
5043 		verbose(env,
5044 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5045 			map->name);
5046 		return -EINVAL;
5047 	}
5048 	if (!map_value_has_spin_lock(map)) {
5049 		if (map->spin_lock_off == -E2BIG)
5050 			verbose(env,
5051 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
5052 				map->name);
5053 		else if (map->spin_lock_off == -ENOENT)
5054 			verbose(env,
5055 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
5056 				map->name);
5057 		else
5058 			verbose(env,
5059 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5060 				map->name);
5061 		return -EINVAL;
5062 	}
5063 	if (map->spin_lock_off != val + reg->off) {
5064 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5065 			val + reg->off);
5066 		return -EINVAL;
5067 	}
5068 	if (is_lock) {
5069 		if (cur->active_spin_lock) {
5070 			verbose(env,
5071 				"Locking two bpf_spin_locks are not allowed\n");
5072 			return -EINVAL;
5073 		}
5074 		cur->active_spin_lock = reg->id;
5075 	} else {
5076 		if (!cur->active_spin_lock) {
5077 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5078 			return -EINVAL;
5079 		}
5080 		if (cur->active_spin_lock != reg->id) {
5081 			verbose(env, "bpf_spin_unlock of different lock\n");
5082 			return -EINVAL;
5083 		}
5084 		cur->active_spin_lock = 0;
5085 	}
5086 	return 0;
5087 }
5088 
5089 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5090 			      struct bpf_call_arg_meta *meta)
5091 {
5092 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5093 	bool is_const = tnum_is_const(reg->var_off);
5094 	struct bpf_map *map = reg->map_ptr;
5095 	u64 val = reg->var_off.value;
5096 
5097 	if (!is_const) {
5098 		verbose(env,
5099 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5100 			regno);
5101 		return -EINVAL;
5102 	}
5103 	if (!map->btf) {
5104 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5105 			map->name);
5106 		return -EINVAL;
5107 	}
5108 	if (!map_value_has_timer(map)) {
5109 		if (map->timer_off == -E2BIG)
5110 			verbose(env,
5111 				"map '%s' has more than one 'struct bpf_timer'\n",
5112 				map->name);
5113 		else if (map->timer_off == -ENOENT)
5114 			verbose(env,
5115 				"map '%s' doesn't have 'struct bpf_timer'\n",
5116 				map->name);
5117 		else
5118 			verbose(env,
5119 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5120 				map->name);
5121 		return -EINVAL;
5122 	}
5123 	if (map->timer_off != val + reg->off) {
5124 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5125 			val + reg->off, map->timer_off);
5126 		return -EINVAL;
5127 	}
5128 	if (meta->map_ptr) {
5129 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5130 		return -EFAULT;
5131 	}
5132 	meta->map_uid = reg->map_uid;
5133 	meta->map_ptr = map;
5134 	return 0;
5135 }
5136 
5137 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5138 {
5139 	return base_type(type) == ARG_PTR_TO_MEM ||
5140 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
5141 }
5142 
5143 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5144 {
5145 	return type == ARG_CONST_SIZE ||
5146 	       type == ARG_CONST_SIZE_OR_ZERO;
5147 }
5148 
5149 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5150 {
5151 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5152 }
5153 
5154 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5155 {
5156 	return type == ARG_PTR_TO_INT ||
5157 	       type == ARG_PTR_TO_LONG;
5158 }
5159 
5160 static int int_ptr_type_to_size(enum bpf_arg_type type)
5161 {
5162 	if (type == ARG_PTR_TO_INT)
5163 		return sizeof(u32);
5164 	else if (type == ARG_PTR_TO_LONG)
5165 		return sizeof(u64);
5166 
5167 	return -EINVAL;
5168 }
5169 
5170 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5171 				 const struct bpf_call_arg_meta *meta,
5172 				 enum bpf_arg_type *arg_type)
5173 {
5174 	if (!meta->map_ptr) {
5175 		/* kernel subsystem misconfigured verifier */
5176 		verbose(env, "invalid map_ptr to access map->type\n");
5177 		return -EACCES;
5178 	}
5179 
5180 	switch (meta->map_ptr->map_type) {
5181 	case BPF_MAP_TYPE_SOCKMAP:
5182 	case BPF_MAP_TYPE_SOCKHASH:
5183 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5184 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5185 		} else {
5186 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5187 			return -EINVAL;
5188 		}
5189 		break;
5190 	case BPF_MAP_TYPE_BLOOM_FILTER:
5191 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5192 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5193 		break;
5194 	default:
5195 		break;
5196 	}
5197 	return 0;
5198 }
5199 
5200 struct bpf_reg_types {
5201 	const enum bpf_reg_type types[10];
5202 	u32 *btf_id;
5203 };
5204 
5205 static const struct bpf_reg_types map_key_value_types = {
5206 	.types = {
5207 		PTR_TO_STACK,
5208 		PTR_TO_PACKET,
5209 		PTR_TO_PACKET_META,
5210 		PTR_TO_MAP_KEY,
5211 		PTR_TO_MAP_VALUE,
5212 	},
5213 };
5214 
5215 static const struct bpf_reg_types sock_types = {
5216 	.types = {
5217 		PTR_TO_SOCK_COMMON,
5218 		PTR_TO_SOCKET,
5219 		PTR_TO_TCP_SOCK,
5220 		PTR_TO_XDP_SOCK,
5221 	},
5222 };
5223 
5224 #ifdef CONFIG_NET
5225 static const struct bpf_reg_types btf_id_sock_common_types = {
5226 	.types = {
5227 		PTR_TO_SOCK_COMMON,
5228 		PTR_TO_SOCKET,
5229 		PTR_TO_TCP_SOCK,
5230 		PTR_TO_XDP_SOCK,
5231 		PTR_TO_BTF_ID,
5232 	},
5233 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5234 };
5235 #endif
5236 
5237 static const struct bpf_reg_types mem_types = {
5238 	.types = {
5239 		PTR_TO_STACK,
5240 		PTR_TO_PACKET,
5241 		PTR_TO_PACKET_META,
5242 		PTR_TO_MAP_KEY,
5243 		PTR_TO_MAP_VALUE,
5244 		PTR_TO_MEM,
5245 		PTR_TO_MEM | MEM_ALLOC,
5246 		PTR_TO_BUF,
5247 	},
5248 };
5249 
5250 static const struct bpf_reg_types int_ptr_types = {
5251 	.types = {
5252 		PTR_TO_STACK,
5253 		PTR_TO_PACKET,
5254 		PTR_TO_PACKET_META,
5255 		PTR_TO_MAP_KEY,
5256 		PTR_TO_MAP_VALUE,
5257 	},
5258 };
5259 
5260 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5261 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5262 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5263 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5264 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5265 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5266 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5267 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5268 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5269 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5270 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5271 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5272 
5273 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5274 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5275 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5276 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5277 	[ARG_CONST_SIZE]		= &scalar_types,
5278 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5279 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5280 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5281 	[ARG_PTR_TO_CTX]		= &context_types,
5282 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5283 #ifdef CONFIG_NET
5284 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5285 #endif
5286 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5287 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5288 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5289 	[ARG_PTR_TO_MEM]		= &mem_types,
5290 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5291 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5292 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5293 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5294 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5295 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5296 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5297 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5298 	[ARG_PTR_TO_TIMER]		= &timer_types,
5299 };
5300 
5301 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5302 			  enum bpf_arg_type arg_type,
5303 			  const u32 *arg_btf_id)
5304 {
5305 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5306 	enum bpf_reg_type expected, type = reg->type;
5307 	const struct bpf_reg_types *compatible;
5308 	int i, j;
5309 
5310 	compatible = compatible_reg_types[base_type(arg_type)];
5311 	if (!compatible) {
5312 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5313 		return -EFAULT;
5314 	}
5315 
5316 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5317 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5318 	 *
5319 	 * Same for MAYBE_NULL:
5320 	 *
5321 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5322 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5323 	 *
5324 	 * Therefore we fold these flags depending on the arg_type before comparison.
5325 	 */
5326 	if (arg_type & MEM_RDONLY)
5327 		type &= ~MEM_RDONLY;
5328 	if (arg_type & PTR_MAYBE_NULL)
5329 		type &= ~PTR_MAYBE_NULL;
5330 
5331 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5332 		expected = compatible->types[i];
5333 		if (expected == NOT_INIT)
5334 			break;
5335 
5336 		if (type == expected)
5337 			goto found;
5338 	}
5339 
5340 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5341 	for (j = 0; j + 1 < i; j++)
5342 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5343 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5344 	return -EACCES;
5345 
5346 found:
5347 	if (reg->type == PTR_TO_BTF_ID) {
5348 		if (!arg_btf_id) {
5349 			if (!compatible->btf_id) {
5350 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5351 				return -EFAULT;
5352 			}
5353 			arg_btf_id = compatible->btf_id;
5354 		}
5355 
5356 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5357 					  btf_vmlinux, *arg_btf_id)) {
5358 			verbose(env, "R%d is of type %s but %s is expected\n",
5359 				regno, kernel_type_name(reg->btf, reg->btf_id),
5360 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5361 			return -EACCES;
5362 		}
5363 	}
5364 
5365 	return 0;
5366 }
5367 
5368 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5369 			   const struct bpf_reg_state *reg, int regno,
5370 			   enum bpf_arg_type arg_type,
5371 			   bool is_release_func)
5372 {
5373 	bool fixed_off_ok = false, release_reg;
5374 	enum bpf_reg_type type = reg->type;
5375 
5376 	switch ((u32)type) {
5377 	case SCALAR_VALUE:
5378 	/* Pointer types where reg offset is explicitly allowed: */
5379 	case PTR_TO_PACKET:
5380 	case PTR_TO_PACKET_META:
5381 	case PTR_TO_MAP_KEY:
5382 	case PTR_TO_MAP_VALUE:
5383 	case PTR_TO_MEM:
5384 	case PTR_TO_MEM | MEM_RDONLY:
5385 	case PTR_TO_MEM | MEM_ALLOC:
5386 	case PTR_TO_BUF:
5387 	case PTR_TO_BUF | MEM_RDONLY:
5388 	case PTR_TO_STACK:
5389 		/* Some of the argument types nevertheless require a
5390 		 * zero register offset.
5391 		 */
5392 		if (arg_type != ARG_PTR_TO_ALLOC_MEM)
5393 			return 0;
5394 		break;
5395 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5396 	 * fixed offset.
5397 	 */
5398 	case PTR_TO_BTF_ID:
5399 		/* When referenced PTR_TO_BTF_ID is passed to release function,
5400 		 * it's fixed offset must be 0. We rely on the property that
5401 		 * only one referenced register can be passed to BPF helpers and
5402 		 * kfuncs. In the other cases, fixed offset can be non-zero.
5403 		 */
5404 		release_reg = is_release_func && reg->ref_obj_id;
5405 		if (release_reg && reg->off) {
5406 			verbose(env, "R%d must have zero offset when passed to release func\n",
5407 				regno);
5408 			return -EINVAL;
5409 		}
5410 		/* For release_reg == true, fixed_off_ok must be false, but we
5411 		 * already checked and rejected reg->off != 0 above, so set to
5412 		 * true to allow fixed offset for all other cases.
5413 		 */
5414 		fixed_off_ok = true;
5415 		break;
5416 	default:
5417 		break;
5418 	}
5419 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5420 }
5421 
5422 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5423 			  struct bpf_call_arg_meta *meta,
5424 			  const struct bpf_func_proto *fn)
5425 {
5426 	u32 regno = BPF_REG_1 + arg;
5427 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5428 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5429 	enum bpf_reg_type type = reg->type;
5430 	int err = 0;
5431 
5432 	if (arg_type == ARG_DONTCARE)
5433 		return 0;
5434 
5435 	err = check_reg_arg(env, regno, SRC_OP);
5436 	if (err)
5437 		return err;
5438 
5439 	if (arg_type == ARG_ANYTHING) {
5440 		if (is_pointer_value(env, regno)) {
5441 			verbose(env, "R%d leaks addr into helper function\n",
5442 				regno);
5443 			return -EACCES;
5444 		}
5445 		return 0;
5446 	}
5447 
5448 	if (type_is_pkt_pointer(type) &&
5449 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5450 		verbose(env, "helper access to the packet is not allowed\n");
5451 		return -EACCES;
5452 	}
5453 
5454 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5455 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5456 		err = resolve_map_arg_type(env, meta, &arg_type);
5457 		if (err)
5458 			return err;
5459 	}
5460 
5461 	if (register_is_null(reg) && type_may_be_null(arg_type))
5462 		/* A NULL register has a SCALAR_VALUE type, so skip
5463 		 * type checking.
5464 		 */
5465 		goto skip_type_check;
5466 
5467 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5468 	if (err)
5469 		return err;
5470 
5471 	err = check_func_arg_reg_off(env, reg, regno, arg_type, is_release_function(meta->func_id));
5472 	if (err)
5473 		return err;
5474 
5475 skip_type_check:
5476 	/* check_func_arg_reg_off relies on only one referenced register being
5477 	 * allowed for BPF helpers.
5478 	 */
5479 	if (reg->ref_obj_id) {
5480 		if (meta->ref_obj_id) {
5481 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5482 				regno, reg->ref_obj_id,
5483 				meta->ref_obj_id);
5484 			return -EFAULT;
5485 		}
5486 		meta->ref_obj_id = reg->ref_obj_id;
5487 	}
5488 
5489 	if (arg_type == ARG_CONST_MAP_PTR) {
5490 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5491 		if (meta->map_ptr) {
5492 			/* Use map_uid (which is unique id of inner map) to reject:
5493 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5494 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5495 			 * if (inner_map1 && inner_map2) {
5496 			 *     timer = bpf_map_lookup_elem(inner_map1);
5497 			 *     if (timer)
5498 			 *         // mismatch would have been allowed
5499 			 *         bpf_timer_init(timer, inner_map2);
5500 			 * }
5501 			 *
5502 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5503 			 */
5504 			if (meta->map_ptr != reg->map_ptr ||
5505 			    meta->map_uid != reg->map_uid) {
5506 				verbose(env,
5507 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5508 					meta->map_uid, reg->map_uid);
5509 				return -EINVAL;
5510 			}
5511 		}
5512 		meta->map_ptr = reg->map_ptr;
5513 		meta->map_uid = reg->map_uid;
5514 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5515 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5516 		 * check that [key, key + map->key_size) are within
5517 		 * stack limits and initialized
5518 		 */
5519 		if (!meta->map_ptr) {
5520 			/* in function declaration map_ptr must come before
5521 			 * map_key, so that it's verified and known before
5522 			 * we have to check map_key here. Otherwise it means
5523 			 * that kernel subsystem misconfigured verifier
5524 			 */
5525 			verbose(env, "invalid map_ptr to access map->key\n");
5526 			return -EACCES;
5527 		}
5528 		err = check_helper_mem_access(env, regno,
5529 					      meta->map_ptr->key_size, false,
5530 					      NULL);
5531 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5532 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5533 		if (type_may_be_null(arg_type) && register_is_null(reg))
5534 			return 0;
5535 
5536 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5537 		 * check [value, value + map->value_size) validity
5538 		 */
5539 		if (!meta->map_ptr) {
5540 			/* kernel subsystem misconfigured verifier */
5541 			verbose(env, "invalid map_ptr to access map->value\n");
5542 			return -EACCES;
5543 		}
5544 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5545 		err = check_helper_mem_access(env, regno,
5546 					      meta->map_ptr->value_size, false,
5547 					      meta);
5548 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5549 		if (!reg->btf_id) {
5550 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5551 			return -EACCES;
5552 		}
5553 		meta->ret_btf = reg->btf;
5554 		meta->ret_btf_id = reg->btf_id;
5555 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5556 		if (meta->func_id == BPF_FUNC_spin_lock) {
5557 			if (process_spin_lock(env, regno, true))
5558 				return -EACCES;
5559 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5560 			if (process_spin_lock(env, regno, false))
5561 				return -EACCES;
5562 		} else {
5563 			verbose(env, "verifier internal error\n");
5564 			return -EFAULT;
5565 		}
5566 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5567 		if (process_timer_func(env, regno, meta))
5568 			return -EACCES;
5569 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5570 		meta->subprogno = reg->subprogno;
5571 	} else if (arg_type_is_mem_ptr(arg_type)) {
5572 		/* The access to this pointer is only checked when we hit the
5573 		 * next is_mem_size argument below.
5574 		 */
5575 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5576 	} else if (arg_type_is_mem_size(arg_type)) {
5577 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5578 
5579 		err = check_mem_size_reg(env, reg, regno, zero_size_allowed, meta);
5580 	} else if (arg_type_is_alloc_size(arg_type)) {
5581 		if (!tnum_is_const(reg->var_off)) {
5582 			verbose(env, "R%d is not a known constant'\n",
5583 				regno);
5584 			return -EACCES;
5585 		}
5586 		meta->mem_size = reg->var_off.value;
5587 	} else if (arg_type_is_int_ptr(arg_type)) {
5588 		int size = int_ptr_type_to_size(arg_type);
5589 
5590 		err = check_helper_mem_access(env, regno, size, false, meta);
5591 		if (err)
5592 			return err;
5593 		err = check_ptr_alignment(env, reg, 0, size, true);
5594 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5595 		struct bpf_map *map = reg->map_ptr;
5596 		int map_off;
5597 		u64 map_addr;
5598 		char *str_ptr;
5599 
5600 		if (!bpf_map_is_rdonly(map)) {
5601 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5602 			return -EACCES;
5603 		}
5604 
5605 		if (!tnum_is_const(reg->var_off)) {
5606 			verbose(env, "R%d is not a constant address'\n", regno);
5607 			return -EACCES;
5608 		}
5609 
5610 		if (!map->ops->map_direct_value_addr) {
5611 			verbose(env, "no direct value access support for this map type\n");
5612 			return -EACCES;
5613 		}
5614 
5615 		err = check_map_access(env, regno, reg->off,
5616 				       map->value_size - reg->off, false);
5617 		if (err)
5618 			return err;
5619 
5620 		map_off = reg->off + reg->var_off.value;
5621 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5622 		if (err) {
5623 			verbose(env, "direct value access on string failed\n");
5624 			return err;
5625 		}
5626 
5627 		str_ptr = (char *)(long)(map_addr);
5628 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5629 			verbose(env, "string is not zero-terminated\n");
5630 			return -EINVAL;
5631 		}
5632 	}
5633 
5634 	return err;
5635 }
5636 
5637 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5638 {
5639 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5640 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5641 
5642 	if (func_id != BPF_FUNC_map_update_elem)
5643 		return false;
5644 
5645 	/* It's not possible to get access to a locked struct sock in these
5646 	 * contexts, so updating is safe.
5647 	 */
5648 	switch (type) {
5649 	case BPF_PROG_TYPE_TRACING:
5650 		if (eatype == BPF_TRACE_ITER)
5651 			return true;
5652 		break;
5653 	case BPF_PROG_TYPE_SOCKET_FILTER:
5654 	case BPF_PROG_TYPE_SCHED_CLS:
5655 	case BPF_PROG_TYPE_SCHED_ACT:
5656 	case BPF_PROG_TYPE_XDP:
5657 	case BPF_PROG_TYPE_SK_REUSEPORT:
5658 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5659 	case BPF_PROG_TYPE_SK_LOOKUP:
5660 		return true;
5661 	default:
5662 		break;
5663 	}
5664 
5665 	verbose(env, "cannot update sockmap in this context\n");
5666 	return false;
5667 }
5668 
5669 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5670 {
5671 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5672 }
5673 
5674 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5675 					struct bpf_map *map, int func_id)
5676 {
5677 	if (!map)
5678 		return 0;
5679 
5680 	/* We need a two way check, first is from map perspective ... */
5681 	switch (map->map_type) {
5682 	case BPF_MAP_TYPE_PROG_ARRAY:
5683 		if (func_id != BPF_FUNC_tail_call)
5684 			goto error;
5685 		break;
5686 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5687 		if (func_id != BPF_FUNC_perf_event_read &&
5688 		    func_id != BPF_FUNC_perf_event_output &&
5689 		    func_id != BPF_FUNC_skb_output &&
5690 		    func_id != BPF_FUNC_perf_event_read_value &&
5691 		    func_id != BPF_FUNC_xdp_output)
5692 			goto error;
5693 		break;
5694 	case BPF_MAP_TYPE_RINGBUF:
5695 		if (func_id != BPF_FUNC_ringbuf_output &&
5696 		    func_id != BPF_FUNC_ringbuf_reserve &&
5697 		    func_id != BPF_FUNC_ringbuf_query)
5698 			goto error;
5699 		break;
5700 	case BPF_MAP_TYPE_STACK_TRACE:
5701 		if (func_id != BPF_FUNC_get_stackid)
5702 			goto error;
5703 		break;
5704 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5705 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5706 		    func_id != BPF_FUNC_current_task_under_cgroup)
5707 			goto error;
5708 		break;
5709 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5710 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5711 		if (func_id != BPF_FUNC_get_local_storage)
5712 			goto error;
5713 		break;
5714 	case BPF_MAP_TYPE_DEVMAP:
5715 	case BPF_MAP_TYPE_DEVMAP_HASH:
5716 		if (func_id != BPF_FUNC_redirect_map &&
5717 		    func_id != BPF_FUNC_map_lookup_elem)
5718 			goto error;
5719 		break;
5720 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5721 	 * appear.
5722 	 */
5723 	case BPF_MAP_TYPE_CPUMAP:
5724 		if (func_id != BPF_FUNC_redirect_map)
5725 			goto error;
5726 		break;
5727 	case BPF_MAP_TYPE_XSKMAP:
5728 		if (func_id != BPF_FUNC_redirect_map &&
5729 		    func_id != BPF_FUNC_map_lookup_elem)
5730 			goto error;
5731 		break;
5732 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5733 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5734 		if (func_id != BPF_FUNC_map_lookup_elem)
5735 			goto error;
5736 		break;
5737 	case BPF_MAP_TYPE_SOCKMAP:
5738 		if (func_id != BPF_FUNC_sk_redirect_map &&
5739 		    func_id != BPF_FUNC_sock_map_update &&
5740 		    func_id != BPF_FUNC_map_delete_elem &&
5741 		    func_id != BPF_FUNC_msg_redirect_map &&
5742 		    func_id != BPF_FUNC_sk_select_reuseport &&
5743 		    func_id != BPF_FUNC_map_lookup_elem &&
5744 		    !may_update_sockmap(env, func_id))
5745 			goto error;
5746 		break;
5747 	case BPF_MAP_TYPE_SOCKHASH:
5748 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5749 		    func_id != BPF_FUNC_sock_hash_update &&
5750 		    func_id != BPF_FUNC_map_delete_elem &&
5751 		    func_id != BPF_FUNC_msg_redirect_hash &&
5752 		    func_id != BPF_FUNC_sk_select_reuseport &&
5753 		    func_id != BPF_FUNC_map_lookup_elem &&
5754 		    !may_update_sockmap(env, func_id))
5755 			goto error;
5756 		break;
5757 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5758 		if (func_id != BPF_FUNC_sk_select_reuseport)
5759 			goto error;
5760 		break;
5761 	case BPF_MAP_TYPE_QUEUE:
5762 	case BPF_MAP_TYPE_STACK:
5763 		if (func_id != BPF_FUNC_map_peek_elem &&
5764 		    func_id != BPF_FUNC_map_pop_elem &&
5765 		    func_id != BPF_FUNC_map_push_elem)
5766 			goto error;
5767 		break;
5768 	case BPF_MAP_TYPE_SK_STORAGE:
5769 		if (func_id != BPF_FUNC_sk_storage_get &&
5770 		    func_id != BPF_FUNC_sk_storage_delete)
5771 			goto error;
5772 		break;
5773 	case BPF_MAP_TYPE_INODE_STORAGE:
5774 		if (func_id != BPF_FUNC_inode_storage_get &&
5775 		    func_id != BPF_FUNC_inode_storage_delete)
5776 			goto error;
5777 		break;
5778 	case BPF_MAP_TYPE_TASK_STORAGE:
5779 		if (func_id != BPF_FUNC_task_storage_get &&
5780 		    func_id != BPF_FUNC_task_storage_delete)
5781 			goto error;
5782 		break;
5783 	case BPF_MAP_TYPE_BLOOM_FILTER:
5784 		if (func_id != BPF_FUNC_map_peek_elem &&
5785 		    func_id != BPF_FUNC_map_push_elem)
5786 			goto error;
5787 		break;
5788 	default:
5789 		break;
5790 	}
5791 
5792 	/* ... and second from the function itself. */
5793 	switch (func_id) {
5794 	case BPF_FUNC_tail_call:
5795 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5796 			goto error;
5797 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5798 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5799 			return -EINVAL;
5800 		}
5801 		break;
5802 	case BPF_FUNC_perf_event_read:
5803 	case BPF_FUNC_perf_event_output:
5804 	case BPF_FUNC_perf_event_read_value:
5805 	case BPF_FUNC_skb_output:
5806 	case BPF_FUNC_xdp_output:
5807 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5808 			goto error;
5809 		break;
5810 	case BPF_FUNC_ringbuf_output:
5811 	case BPF_FUNC_ringbuf_reserve:
5812 	case BPF_FUNC_ringbuf_query:
5813 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5814 			goto error;
5815 		break;
5816 	case BPF_FUNC_get_stackid:
5817 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5818 			goto error;
5819 		break;
5820 	case BPF_FUNC_current_task_under_cgroup:
5821 	case BPF_FUNC_skb_under_cgroup:
5822 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5823 			goto error;
5824 		break;
5825 	case BPF_FUNC_redirect_map:
5826 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5827 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5828 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5829 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5830 			goto error;
5831 		break;
5832 	case BPF_FUNC_sk_redirect_map:
5833 	case BPF_FUNC_msg_redirect_map:
5834 	case BPF_FUNC_sock_map_update:
5835 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5836 			goto error;
5837 		break;
5838 	case BPF_FUNC_sk_redirect_hash:
5839 	case BPF_FUNC_msg_redirect_hash:
5840 	case BPF_FUNC_sock_hash_update:
5841 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5842 			goto error;
5843 		break;
5844 	case BPF_FUNC_get_local_storage:
5845 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5846 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5847 			goto error;
5848 		break;
5849 	case BPF_FUNC_sk_select_reuseport:
5850 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5851 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5852 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5853 			goto error;
5854 		break;
5855 	case BPF_FUNC_map_pop_elem:
5856 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5857 		    map->map_type != BPF_MAP_TYPE_STACK)
5858 			goto error;
5859 		break;
5860 	case BPF_FUNC_map_peek_elem:
5861 	case BPF_FUNC_map_push_elem:
5862 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5863 		    map->map_type != BPF_MAP_TYPE_STACK &&
5864 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5865 			goto error;
5866 		break;
5867 	case BPF_FUNC_sk_storage_get:
5868 	case BPF_FUNC_sk_storage_delete:
5869 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5870 			goto error;
5871 		break;
5872 	case BPF_FUNC_inode_storage_get:
5873 	case BPF_FUNC_inode_storage_delete:
5874 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5875 			goto error;
5876 		break;
5877 	case BPF_FUNC_task_storage_get:
5878 	case BPF_FUNC_task_storage_delete:
5879 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5880 			goto error;
5881 		break;
5882 	default:
5883 		break;
5884 	}
5885 
5886 	return 0;
5887 error:
5888 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5889 		map->map_type, func_id_name(func_id), func_id);
5890 	return -EINVAL;
5891 }
5892 
5893 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5894 {
5895 	int count = 0;
5896 
5897 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5898 		count++;
5899 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5900 		count++;
5901 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5902 		count++;
5903 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5904 		count++;
5905 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5906 		count++;
5907 
5908 	/* We only support one arg being in raw mode at the moment,
5909 	 * which is sufficient for the helper functions we have
5910 	 * right now.
5911 	 */
5912 	return count <= 1;
5913 }
5914 
5915 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5916 				    enum bpf_arg_type arg_next)
5917 {
5918 	return (arg_type_is_mem_ptr(arg_curr) &&
5919 	        !arg_type_is_mem_size(arg_next)) ||
5920 	       (!arg_type_is_mem_ptr(arg_curr) &&
5921 		arg_type_is_mem_size(arg_next));
5922 }
5923 
5924 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5925 {
5926 	/* bpf_xxx(..., buf, len) call will access 'len'
5927 	 * bytes from memory 'buf'. Both arg types need
5928 	 * to be paired, so make sure there's no buggy
5929 	 * helper function specification.
5930 	 */
5931 	if (arg_type_is_mem_size(fn->arg1_type) ||
5932 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5933 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5934 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5935 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5936 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5937 		return false;
5938 
5939 	return true;
5940 }
5941 
5942 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5943 {
5944 	int count = 0;
5945 
5946 	if (arg_type_may_be_refcounted(fn->arg1_type))
5947 		count++;
5948 	if (arg_type_may_be_refcounted(fn->arg2_type))
5949 		count++;
5950 	if (arg_type_may_be_refcounted(fn->arg3_type))
5951 		count++;
5952 	if (arg_type_may_be_refcounted(fn->arg4_type))
5953 		count++;
5954 	if (arg_type_may_be_refcounted(fn->arg5_type))
5955 		count++;
5956 
5957 	/* A reference acquiring function cannot acquire
5958 	 * another refcounted ptr.
5959 	 */
5960 	if (may_be_acquire_function(func_id) && count)
5961 		return false;
5962 
5963 	/* We only support one arg being unreferenced at the moment,
5964 	 * which is sufficient for the helper functions we have right now.
5965 	 */
5966 	return count <= 1;
5967 }
5968 
5969 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5970 {
5971 	int i;
5972 
5973 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5974 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5975 			return false;
5976 
5977 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5978 			return false;
5979 	}
5980 
5981 	return true;
5982 }
5983 
5984 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5985 {
5986 	return check_raw_mode_ok(fn) &&
5987 	       check_arg_pair_ok(fn) &&
5988 	       check_btf_id_ok(fn) &&
5989 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5990 }
5991 
5992 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5993  * are now invalid, so turn them into unknown SCALAR_VALUE.
5994  */
5995 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5996 				     struct bpf_func_state *state)
5997 {
5998 	struct bpf_reg_state *regs = state->regs, *reg;
5999 	int i;
6000 
6001 	for (i = 0; i < MAX_BPF_REG; i++)
6002 		if (reg_is_pkt_pointer_any(&regs[i]))
6003 			mark_reg_unknown(env, regs, i);
6004 
6005 	bpf_for_each_spilled_reg(i, state, reg) {
6006 		if (!reg)
6007 			continue;
6008 		if (reg_is_pkt_pointer_any(reg))
6009 			__mark_reg_unknown(env, reg);
6010 	}
6011 }
6012 
6013 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6014 {
6015 	struct bpf_verifier_state *vstate = env->cur_state;
6016 	int i;
6017 
6018 	for (i = 0; i <= vstate->curframe; i++)
6019 		__clear_all_pkt_pointers(env, vstate->frame[i]);
6020 }
6021 
6022 enum {
6023 	AT_PKT_END = -1,
6024 	BEYOND_PKT_END = -2,
6025 };
6026 
6027 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6028 {
6029 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6030 	struct bpf_reg_state *reg = &state->regs[regn];
6031 
6032 	if (reg->type != PTR_TO_PACKET)
6033 		/* PTR_TO_PACKET_META is not supported yet */
6034 		return;
6035 
6036 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6037 	 * How far beyond pkt_end it goes is unknown.
6038 	 * if (!range_open) it's the case of pkt >= pkt_end
6039 	 * if (range_open) it's the case of pkt > pkt_end
6040 	 * hence this pointer is at least 1 byte bigger than pkt_end
6041 	 */
6042 	if (range_open)
6043 		reg->range = BEYOND_PKT_END;
6044 	else
6045 		reg->range = AT_PKT_END;
6046 }
6047 
6048 static void release_reg_references(struct bpf_verifier_env *env,
6049 				   struct bpf_func_state *state,
6050 				   int ref_obj_id)
6051 {
6052 	struct bpf_reg_state *regs = state->regs, *reg;
6053 	int i;
6054 
6055 	for (i = 0; i < MAX_BPF_REG; i++)
6056 		if (regs[i].ref_obj_id == ref_obj_id)
6057 			mark_reg_unknown(env, regs, i);
6058 
6059 	bpf_for_each_spilled_reg(i, state, reg) {
6060 		if (!reg)
6061 			continue;
6062 		if (reg->ref_obj_id == ref_obj_id)
6063 			__mark_reg_unknown(env, reg);
6064 	}
6065 }
6066 
6067 /* The pointer with the specified id has released its reference to kernel
6068  * resources. Identify all copies of the same pointer and clear the reference.
6069  */
6070 static int release_reference(struct bpf_verifier_env *env,
6071 			     int ref_obj_id)
6072 {
6073 	struct bpf_verifier_state *vstate = env->cur_state;
6074 	int err;
6075 	int i;
6076 
6077 	err = release_reference_state(cur_func(env), ref_obj_id);
6078 	if (err)
6079 		return err;
6080 
6081 	for (i = 0; i <= vstate->curframe; i++)
6082 		release_reg_references(env, vstate->frame[i], ref_obj_id);
6083 
6084 	return 0;
6085 }
6086 
6087 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6088 				    struct bpf_reg_state *regs)
6089 {
6090 	int i;
6091 
6092 	/* after the call registers r0 - r5 were scratched */
6093 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6094 		mark_reg_not_init(env, regs, caller_saved[i]);
6095 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6096 	}
6097 }
6098 
6099 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6100 				   struct bpf_func_state *caller,
6101 				   struct bpf_func_state *callee,
6102 				   int insn_idx);
6103 
6104 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6105 			     int *insn_idx, int subprog,
6106 			     set_callee_state_fn set_callee_state_cb)
6107 {
6108 	struct bpf_verifier_state *state = env->cur_state;
6109 	struct bpf_func_info_aux *func_info_aux;
6110 	struct bpf_func_state *caller, *callee;
6111 	int err;
6112 	bool is_global = false;
6113 
6114 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6115 		verbose(env, "the call stack of %d frames is too deep\n",
6116 			state->curframe + 2);
6117 		return -E2BIG;
6118 	}
6119 
6120 	caller = state->frame[state->curframe];
6121 	if (state->frame[state->curframe + 1]) {
6122 		verbose(env, "verifier bug. Frame %d already allocated\n",
6123 			state->curframe + 1);
6124 		return -EFAULT;
6125 	}
6126 
6127 	func_info_aux = env->prog->aux->func_info_aux;
6128 	if (func_info_aux)
6129 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6130 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6131 	if (err == -EFAULT)
6132 		return err;
6133 	if (is_global) {
6134 		if (err) {
6135 			verbose(env, "Caller passes invalid args into func#%d\n",
6136 				subprog);
6137 			return err;
6138 		} else {
6139 			if (env->log.level & BPF_LOG_LEVEL)
6140 				verbose(env,
6141 					"Func#%d is global and valid. Skipping.\n",
6142 					subprog);
6143 			clear_caller_saved_regs(env, caller->regs);
6144 
6145 			/* All global functions return a 64-bit SCALAR_VALUE */
6146 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6147 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6148 
6149 			/* continue with next insn after call */
6150 			return 0;
6151 		}
6152 	}
6153 
6154 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6155 	    insn->src_reg == 0 &&
6156 	    insn->imm == BPF_FUNC_timer_set_callback) {
6157 		struct bpf_verifier_state *async_cb;
6158 
6159 		/* there is no real recursion here. timer callbacks are async */
6160 		env->subprog_info[subprog].is_async_cb = true;
6161 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6162 					 *insn_idx, subprog);
6163 		if (!async_cb)
6164 			return -EFAULT;
6165 		callee = async_cb->frame[0];
6166 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6167 
6168 		/* Convert bpf_timer_set_callback() args into timer callback args */
6169 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6170 		if (err)
6171 			return err;
6172 
6173 		clear_caller_saved_regs(env, caller->regs);
6174 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6175 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6176 		/* continue with next insn after call */
6177 		return 0;
6178 	}
6179 
6180 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6181 	if (!callee)
6182 		return -ENOMEM;
6183 	state->frame[state->curframe + 1] = callee;
6184 
6185 	/* callee cannot access r0, r6 - r9 for reading and has to write
6186 	 * into its own stack before reading from it.
6187 	 * callee can read/write into caller's stack
6188 	 */
6189 	init_func_state(env, callee,
6190 			/* remember the callsite, it will be used by bpf_exit */
6191 			*insn_idx /* callsite */,
6192 			state->curframe + 1 /* frameno within this callchain */,
6193 			subprog /* subprog number within this prog */);
6194 
6195 	/* Transfer references to the callee */
6196 	err = copy_reference_state(callee, caller);
6197 	if (err)
6198 		return err;
6199 
6200 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6201 	if (err)
6202 		return err;
6203 
6204 	clear_caller_saved_regs(env, caller->regs);
6205 
6206 	/* only increment it after check_reg_arg() finished */
6207 	state->curframe++;
6208 
6209 	/* and go analyze first insn of the callee */
6210 	*insn_idx = env->subprog_info[subprog].start - 1;
6211 
6212 	if (env->log.level & BPF_LOG_LEVEL) {
6213 		verbose(env, "caller:\n");
6214 		print_verifier_state(env, caller, true);
6215 		verbose(env, "callee:\n");
6216 		print_verifier_state(env, callee, true);
6217 	}
6218 	return 0;
6219 }
6220 
6221 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6222 				   struct bpf_func_state *caller,
6223 				   struct bpf_func_state *callee)
6224 {
6225 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6226 	 *      void *callback_ctx, u64 flags);
6227 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6228 	 *      void *callback_ctx);
6229 	 */
6230 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6231 
6232 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6233 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6234 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6235 
6236 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6237 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6238 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6239 
6240 	/* pointer to stack or null */
6241 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6242 
6243 	/* unused */
6244 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6245 	return 0;
6246 }
6247 
6248 static int set_callee_state(struct bpf_verifier_env *env,
6249 			    struct bpf_func_state *caller,
6250 			    struct bpf_func_state *callee, int insn_idx)
6251 {
6252 	int i;
6253 
6254 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6255 	 * pointers, which connects us up to the liveness chain
6256 	 */
6257 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6258 		callee->regs[i] = caller->regs[i];
6259 	return 0;
6260 }
6261 
6262 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6263 			   int *insn_idx)
6264 {
6265 	int subprog, target_insn;
6266 
6267 	target_insn = *insn_idx + insn->imm + 1;
6268 	subprog = find_subprog(env, target_insn);
6269 	if (subprog < 0) {
6270 		verbose(env, "verifier bug. No program starts at insn %d\n",
6271 			target_insn);
6272 		return -EFAULT;
6273 	}
6274 
6275 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6276 }
6277 
6278 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6279 				       struct bpf_func_state *caller,
6280 				       struct bpf_func_state *callee,
6281 				       int insn_idx)
6282 {
6283 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6284 	struct bpf_map *map;
6285 	int err;
6286 
6287 	if (bpf_map_ptr_poisoned(insn_aux)) {
6288 		verbose(env, "tail_call abusing map_ptr\n");
6289 		return -EINVAL;
6290 	}
6291 
6292 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6293 	if (!map->ops->map_set_for_each_callback_args ||
6294 	    !map->ops->map_for_each_callback) {
6295 		verbose(env, "callback function not allowed for map\n");
6296 		return -ENOTSUPP;
6297 	}
6298 
6299 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6300 	if (err)
6301 		return err;
6302 
6303 	callee->in_callback_fn = true;
6304 	return 0;
6305 }
6306 
6307 static int set_loop_callback_state(struct bpf_verifier_env *env,
6308 				   struct bpf_func_state *caller,
6309 				   struct bpf_func_state *callee,
6310 				   int insn_idx)
6311 {
6312 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6313 	 *	    u64 flags);
6314 	 * callback_fn(u32 index, void *callback_ctx);
6315 	 */
6316 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6317 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6318 
6319 	/* unused */
6320 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6321 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6322 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6323 
6324 	callee->in_callback_fn = true;
6325 	return 0;
6326 }
6327 
6328 static int set_timer_callback_state(struct bpf_verifier_env *env,
6329 				    struct bpf_func_state *caller,
6330 				    struct bpf_func_state *callee,
6331 				    int insn_idx)
6332 {
6333 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6334 
6335 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6336 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6337 	 */
6338 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6339 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6340 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6341 
6342 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6343 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6344 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6345 
6346 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6347 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6348 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6349 
6350 	/* unused */
6351 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6352 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6353 	callee->in_async_callback_fn = true;
6354 	return 0;
6355 }
6356 
6357 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6358 				       struct bpf_func_state *caller,
6359 				       struct bpf_func_state *callee,
6360 				       int insn_idx)
6361 {
6362 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6363 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6364 	 * (callback_fn)(struct task_struct *task,
6365 	 *               struct vm_area_struct *vma, void *callback_ctx);
6366 	 */
6367 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6368 
6369 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6370 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6371 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6372 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6373 
6374 	/* pointer to stack or null */
6375 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6376 
6377 	/* unused */
6378 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6379 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6380 	callee->in_callback_fn = true;
6381 	return 0;
6382 }
6383 
6384 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6385 {
6386 	struct bpf_verifier_state *state = env->cur_state;
6387 	struct bpf_func_state *caller, *callee;
6388 	struct bpf_reg_state *r0;
6389 	int err;
6390 
6391 	callee = state->frame[state->curframe];
6392 	r0 = &callee->regs[BPF_REG_0];
6393 	if (r0->type == PTR_TO_STACK) {
6394 		/* technically it's ok to return caller's stack pointer
6395 		 * (or caller's caller's pointer) back to the caller,
6396 		 * since these pointers are valid. Only current stack
6397 		 * pointer will be invalid as soon as function exits,
6398 		 * but let's be conservative
6399 		 */
6400 		verbose(env, "cannot return stack pointer to the caller\n");
6401 		return -EINVAL;
6402 	}
6403 
6404 	state->curframe--;
6405 	caller = state->frame[state->curframe];
6406 	if (callee->in_callback_fn) {
6407 		/* enforce R0 return value range [0, 1]. */
6408 		struct tnum range = tnum_range(0, 1);
6409 
6410 		if (r0->type != SCALAR_VALUE) {
6411 			verbose(env, "R0 not a scalar value\n");
6412 			return -EACCES;
6413 		}
6414 		if (!tnum_in(range, r0->var_off)) {
6415 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6416 			return -EINVAL;
6417 		}
6418 	} else {
6419 		/* return to the caller whatever r0 had in the callee */
6420 		caller->regs[BPF_REG_0] = *r0;
6421 	}
6422 
6423 	/* Transfer references to the caller */
6424 	err = copy_reference_state(caller, callee);
6425 	if (err)
6426 		return err;
6427 
6428 	*insn_idx = callee->callsite + 1;
6429 	if (env->log.level & BPF_LOG_LEVEL) {
6430 		verbose(env, "returning from callee:\n");
6431 		print_verifier_state(env, callee, true);
6432 		verbose(env, "to caller at %d:\n", *insn_idx);
6433 		print_verifier_state(env, caller, true);
6434 	}
6435 	/* clear everything in the callee */
6436 	free_func_state(callee);
6437 	state->frame[state->curframe + 1] = NULL;
6438 	return 0;
6439 }
6440 
6441 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6442 				   int func_id,
6443 				   struct bpf_call_arg_meta *meta)
6444 {
6445 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6446 
6447 	if (ret_type != RET_INTEGER ||
6448 	    (func_id != BPF_FUNC_get_stack &&
6449 	     func_id != BPF_FUNC_get_task_stack &&
6450 	     func_id != BPF_FUNC_probe_read_str &&
6451 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6452 	     func_id != BPF_FUNC_probe_read_user_str))
6453 		return;
6454 
6455 	ret_reg->smax_value = meta->msize_max_value;
6456 	ret_reg->s32_max_value = meta->msize_max_value;
6457 	ret_reg->smin_value = -MAX_ERRNO;
6458 	ret_reg->s32_min_value = -MAX_ERRNO;
6459 	__reg_deduce_bounds(ret_reg);
6460 	__reg_bound_offset(ret_reg);
6461 	__update_reg_bounds(ret_reg);
6462 }
6463 
6464 static int
6465 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6466 		int func_id, int insn_idx)
6467 {
6468 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6469 	struct bpf_map *map = meta->map_ptr;
6470 
6471 	if (func_id != BPF_FUNC_tail_call &&
6472 	    func_id != BPF_FUNC_map_lookup_elem &&
6473 	    func_id != BPF_FUNC_map_update_elem &&
6474 	    func_id != BPF_FUNC_map_delete_elem &&
6475 	    func_id != BPF_FUNC_map_push_elem &&
6476 	    func_id != BPF_FUNC_map_pop_elem &&
6477 	    func_id != BPF_FUNC_map_peek_elem &&
6478 	    func_id != BPF_FUNC_for_each_map_elem &&
6479 	    func_id != BPF_FUNC_redirect_map)
6480 		return 0;
6481 
6482 	if (map == NULL) {
6483 		verbose(env, "kernel subsystem misconfigured verifier\n");
6484 		return -EINVAL;
6485 	}
6486 
6487 	/* In case of read-only, some additional restrictions
6488 	 * need to be applied in order to prevent altering the
6489 	 * state of the map from program side.
6490 	 */
6491 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6492 	    (func_id == BPF_FUNC_map_delete_elem ||
6493 	     func_id == BPF_FUNC_map_update_elem ||
6494 	     func_id == BPF_FUNC_map_push_elem ||
6495 	     func_id == BPF_FUNC_map_pop_elem)) {
6496 		verbose(env, "write into map forbidden\n");
6497 		return -EACCES;
6498 	}
6499 
6500 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6501 		bpf_map_ptr_store(aux, meta->map_ptr,
6502 				  !meta->map_ptr->bypass_spec_v1);
6503 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6504 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6505 				  !meta->map_ptr->bypass_spec_v1);
6506 	return 0;
6507 }
6508 
6509 static int
6510 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6511 		int func_id, int insn_idx)
6512 {
6513 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6514 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6515 	struct bpf_map *map = meta->map_ptr;
6516 	struct tnum range;
6517 	u64 val;
6518 	int err;
6519 
6520 	if (func_id != BPF_FUNC_tail_call)
6521 		return 0;
6522 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6523 		verbose(env, "kernel subsystem misconfigured verifier\n");
6524 		return -EINVAL;
6525 	}
6526 
6527 	range = tnum_range(0, map->max_entries - 1);
6528 	reg = &regs[BPF_REG_3];
6529 
6530 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6531 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6532 		return 0;
6533 	}
6534 
6535 	err = mark_chain_precision(env, BPF_REG_3);
6536 	if (err)
6537 		return err;
6538 
6539 	val = reg->var_off.value;
6540 	if (bpf_map_key_unseen(aux))
6541 		bpf_map_key_store(aux, val);
6542 	else if (!bpf_map_key_poisoned(aux) &&
6543 		  bpf_map_key_immediate(aux) != val)
6544 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6545 	return 0;
6546 }
6547 
6548 static int check_reference_leak(struct bpf_verifier_env *env)
6549 {
6550 	struct bpf_func_state *state = cur_func(env);
6551 	int i;
6552 
6553 	for (i = 0; i < state->acquired_refs; i++) {
6554 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6555 			state->refs[i].id, state->refs[i].insn_idx);
6556 	}
6557 	return state->acquired_refs ? -EINVAL : 0;
6558 }
6559 
6560 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6561 				   struct bpf_reg_state *regs)
6562 {
6563 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6564 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6565 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6566 	int err, fmt_map_off, num_args;
6567 	u64 fmt_addr;
6568 	char *fmt;
6569 
6570 	/* data must be an array of u64 */
6571 	if (data_len_reg->var_off.value % 8)
6572 		return -EINVAL;
6573 	num_args = data_len_reg->var_off.value / 8;
6574 
6575 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6576 	 * and map_direct_value_addr is set.
6577 	 */
6578 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6579 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6580 						  fmt_map_off);
6581 	if (err) {
6582 		verbose(env, "verifier bug\n");
6583 		return -EFAULT;
6584 	}
6585 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6586 
6587 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6588 	 * can focus on validating the format specifiers.
6589 	 */
6590 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6591 	if (err < 0)
6592 		verbose(env, "Invalid format string\n");
6593 
6594 	return err;
6595 }
6596 
6597 static int check_get_func_ip(struct bpf_verifier_env *env)
6598 {
6599 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6600 	int func_id = BPF_FUNC_get_func_ip;
6601 
6602 	if (type == BPF_PROG_TYPE_TRACING) {
6603 		if (!bpf_prog_has_trampoline(env->prog)) {
6604 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6605 				func_id_name(func_id), func_id);
6606 			return -ENOTSUPP;
6607 		}
6608 		return 0;
6609 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6610 		return 0;
6611 	}
6612 
6613 	verbose(env, "func %s#%d not supported for program type %d\n",
6614 		func_id_name(func_id), func_id, type);
6615 	return -ENOTSUPP;
6616 }
6617 
6618 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6619 			     int *insn_idx_p)
6620 {
6621 	const struct bpf_func_proto *fn = NULL;
6622 	enum bpf_return_type ret_type;
6623 	enum bpf_type_flag ret_flag;
6624 	struct bpf_reg_state *regs;
6625 	struct bpf_call_arg_meta meta;
6626 	int insn_idx = *insn_idx_p;
6627 	bool changes_data;
6628 	int i, err, func_id;
6629 
6630 	/* find function prototype */
6631 	func_id = insn->imm;
6632 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6633 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6634 			func_id);
6635 		return -EINVAL;
6636 	}
6637 
6638 	if (env->ops->get_func_proto)
6639 		fn = env->ops->get_func_proto(func_id, env->prog);
6640 	if (!fn) {
6641 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6642 			func_id);
6643 		return -EINVAL;
6644 	}
6645 
6646 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6647 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6648 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6649 		return -EINVAL;
6650 	}
6651 
6652 	if (fn->allowed && !fn->allowed(env->prog)) {
6653 		verbose(env, "helper call is not allowed in probe\n");
6654 		return -EINVAL;
6655 	}
6656 
6657 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6658 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6659 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6660 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6661 			func_id_name(func_id), func_id);
6662 		return -EINVAL;
6663 	}
6664 
6665 	memset(&meta, 0, sizeof(meta));
6666 	meta.pkt_access = fn->pkt_access;
6667 
6668 	err = check_func_proto(fn, func_id);
6669 	if (err) {
6670 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6671 			func_id_name(func_id), func_id);
6672 		return err;
6673 	}
6674 
6675 	meta.func_id = func_id;
6676 	/* check args */
6677 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6678 		err = check_func_arg(env, i, &meta, fn);
6679 		if (err)
6680 			return err;
6681 	}
6682 
6683 	err = record_func_map(env, &meta, func_id, insn_idx);
6684 	if (err)
6685 		return err;
6686 
6687 	err = record_func_key(env, &meta, func_id, insn_idx);
6688 	if (err)
6689 		return err;
6690 
6691 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6692 	 * is inferred from register state.
6693 	 */
6694 	for (i = 0; i < meta.access_size; i++) {
6695 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6696 				       BPF_WRITE, -1, false);
6697 		if (err)
6698 			return err;
6699 	}
6700 
6701 	if (is_release_function(func_id)) {
6702 		err = release_reference(env, meta.ref_obj_id);
6703 		if (err) {
6704 			verbose(env, "func %s#%d reference has not been acquired before\n",
6705 				func_id_name(func_id), func_id);
6706 			return err;
6707 		}
6708 	}
6709 
6710 	regs = cur_regs(env);
6711 
6712 	switch (func_id) {
6713 	case BPF_FUNC_tail_call:
6714 		err = check_reference_leak(env);
6715 		if (err) {
6716 			verbose(env, "tail_call would lead to reference leak\n");
6717 			return err;
6718 		}
6719 		break;
6720 	case BPF_FUNC_get_local_storage:
6721 		/* check that flags argument in get_local_storage(map, flags) is 0,
6722 		 * this is required because get_local_storage() can't return an error.
6723 		 */
6724 		if (!register_is_null(&regs[BPF_REG_2])) {
6725 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6726 			return -EINVAL;
6727 		}
6728 		break;
6729 	case BPF_FUNC_for_each_map_elem:
6730 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6731 					set_map_elem_callback_state);
6732 		break;
6733 	case BPF_FUNC_timer_set_callback:
6734 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6735 					set_timer_callback_state);
6736 		break;
6737 	case BPF_FUNC_find_vma:
6738 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6739 					set_find_vma_callback_state);
6740 		break;
6741 	case BPF_FUNC_snprintf:
6742 		err = check_bpf_snprintf_call(env, regs);
6743 		break;
6744 	case BPF_FUNC_loop:
6745 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6746 					set_loop_callback_state);
6747 		break;
6748 	}
6749 
6750 	if (err)
6751 		return err;
6752 
6753 	/* reset caller saved regs */
6754 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6755 		mark_reg_not_init(env, regs, caller_saved[i]);
6756 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6757 	}
6758 
6759 	/* helper call returns 64-bit value. */
6760 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6761 
6762 	/* update return register (already marked as written above) */
6763 	ret_type = fn->ret_type;
6764 	ret_flag = type_flag(fn->ret_type);
6765 	if (ret_type == RET_INTEGER) {
6766 		/* sets type to SCALAR_VALUE */
6767 		mark_reg_unknown(env, regs, BPF_REG_0);
6768 	} else if (ret_type == RET_VOID) {
6769 		regs[BPF_REG_0].type = NOT_INIT;
6770 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6771 		/* There is no offset yet applied, variable or fixed */
6772 		mark_reg_known_zero(env, regs, BPF_REG_0);
6773 		/* remember map_ptr, so that check_map_access()
6774 		 * can check 'value_size' boundary of memory access
6775 		 * to map element returned from bpf_map_lookup_elem()
6776 		 */
6777 		if (meta.map_ptr == NULL) {
6778 			verbose(env,
6779 				"kernel subsystem misconfigured verifier\n");
6780 			return -EINVAL;
6781 		}
6782 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6783 		regs[BPF_REG_0].map_uid = meta.map_uid;
6784 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6785 		if (!type_may_be_null(ret_type) &&
6786 		    map_value_has_spin_lock(meta.map_ptr)) {
6787 			regs[BPF_REG_0].id = ++env->id_gen;
6788 		}
6789 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6790 		mark_reg_known_zero(env, regs, BPF_REG_0);
6791 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6792 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6793 		mark_reg_known_zero(env, regs, BPF_REG_0);
6794 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6795 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6796 		mark_reg_known_zero(env, regs, BPF_REG_0);
6797 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6798 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6799 		mark_reg_known_zero(env, regs, BPF_REG_0);
6800 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6801 		regs[BPF_REG_0].mem_size = meta.mem_size;
6802 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6803 		const struct btf_type *t;
6804 
6805 		mark_reg_known_zero(env, regs, BPF_REG_0);
6806 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6807 		if (!btf_type_is_struct(t)) {
6808 			u32 tsize;
6809 			const struct btf_type *ret;
6810 			const char *tname;
6811 
6812 			/* resolve the type size of ksym. */
6813 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6814 			if (IS_ERR(ret)) {
6815 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6816 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6817 					tname, PTR_ERR(ret));
6818 				return -EINVAL;
6819 			}
6820 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6821 			regs[BPF_REG_0].mem_size = tsize;
6822 		} else {
6823 			/* MEM_RDONLY may be carried from ret_flag, but it
6824 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6825 			 * it will confuse the check of PTR_TO_BTF_ID in
6826 			 * check_mem_access().
6827 			 */
6828 			ret_flag &= ~MEM_RDONLY;
6829 
6830 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6831 			regs[BPF_REG_0].btf = meta.ret_btf;
6832 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6833 		}
6834 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6835 		int ret_btf_id;
6836 
6837 		mark_reg_known_zero(env, regs, BPF_REG_0);
6838 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6839 		ret_btf_id = *fn->ret_btf_id;
6840 		if (ret_btf_id == 0) {
6841 			verbose(env, "invalid return type %u of func %s#%d\n",
6842 				base_type(ret_type), func_id_name(func_id),
6843 				func_id);
6844 			return -EINVAL;
6845 		}
6846 		/* current BPF helper definitions are only coming from
6847 		 * built-in code with type IDs from  vmlinux BTF
6848 		 */
6849 		regs[BPF_REG_0].btf = btf_vmlinux;
6850 		regs[BPF_REG_0].btf_id = ret_btf_id;
6851 	} else {
6852 		verbose(env, "unknown return type %u of func %s#%d\n",
6853 			base_type(ret_type), func_id_name(func_id), func_id);
6854 		return -EINVAL;
6855 	}
6856 
6857 	if (type_may_be_null(regs[BPF_REG_0].type))
6858 		regs[BPF_REG_0].id = ++env->id_gen;
6859 
6860 	if (is_ptr_cast_function(func_id)) {
6861 		/* For release_reference() */
6862 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6863 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6864 		int id = acquire_reference_state(env, insn_idx);
6865 
6866 		if (id < 0)
6867 			return id;
6868 		/* For mark_ptr_or_null_reg() */
6869 		regs[BPF_REG_0].id = id;
6870 		/* For release_reference() */
6871 		regs[BPF_REG_0].ref_obj_id = id;
6872 	}
6873 
6874 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6875 
6876 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6877 	if (err)
6878 		return err;
6879 
6880 	if ((func_id == BPF_FUNC_get_stack ||
6881 	     func_id == BPF_FUNC_get_task_stack) &&
6882 	    !env->prog->has_callchain_buf) {
6883 		const char *err_str;
6884 
6885 #ifdef CONFIG_PERF_EVENTS
6886 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6887 		err_str = "cannot get callchain buffer for func %s#%d\n";
6888 #else
6889 		err = -ENOTSUPP;
6890 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6891 #endif
6892 		if (err) {
6893 			verbose(env, err_str, func_id_name(func_id), func_id);
6894 			return err;
6895 		}
6896 
6897 		env->prog->has_callchain_buf = true;
6898 	}
6899 
6900 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6901 		env->prog->call_get_stack = true;
6902 
6903 	if (func_id == BPF_FUNC_get_func_ip) {
6904 		if (check_get_func_ip(env))
6905 			return -ENOTSUPP;
6906 		env->prog->call_get_func_ip = true;
6907 	}
6908 
6909 	if (changes_data)
6910 		clear_all_pkt_pointers(env);
6911 	return 0;
6912 }
6913 
6914 /* mark_btf_func_reg_size() is used when the reg size is determined by
6915  * the BTF func_proto's return value size and argument.
6916  */
6917 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6918 				   size_t reg_size)
6919 {
6920 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6921 
6922 	if (regno == BPF_REG_0) {
6923 		/* Function return value */
6924 		reg->live |= REG_LIVE_WRITTEN;
6925 		reg->subreg_def = reg_size == sizeof(u64) ?
6926 			DEF_NOT_SUBREG : env->insn_idx + 1;
6927 	} else {
6928 		/* Function argument */
6929 		if (reg_size == sizeof(u64)) {
6930 			mark_insn_zext(env, reg);
6931 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6932 		} else {
6933 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6934 		}
6935 	}
6936 }
6937 
6938 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6939 			    int *insn_idx_p)
6940 {
6941 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6942 	struct bpf_reg_state *regs = cur_regs(env);
6943 	const char *func_name, *ptr_type_name;
6944 	u32 i, nargs, func_id, ptr_type_id;
6945 	int err, insn_idx = *insn_idx_p;
6946 	const struct btf_param *args;
6947 	struct btf *desc_btf;
6948 	bool acq;
6949 
6950 	/* skip for now, but return error when we find this in fixup_kfunc_call */
6951 	if (!insn->imm)
6952 		return 0;
6953 
6954 	desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off);
6955 	if (IS_ERR(desc_btf))
6956 		return PTR_ERR(desc_btf);
6957 
6958 	func_id = insn->imm;
6959 	func = btf_type_by_id(desc_btf, func_id);
6960 	func_name = btf_name_by_offset(desc_btf, func->name_off);
6961 	func_proto = btf_type_by_id(desc_btf, func->type);
6962 
6963 	if (!btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
6964 				      BTF_KFUNC_TYPE_CHECK, func_id)) {
6965 		verbose(env, "calling kernel function %s is not allowed\n",
6966 			func_name);
6967 		return -EACCES;
6968 	}
6969 
6970 	acq = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
6971 					BTF_KFUNC_TYPE_ACQUIRE, func_id);
6972 
6973 	/* Check the arguments */
6974 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6975 	if (err < 0)
6976 		return err;
6977 	/* In case of release function, we get register number of refcounted
6978 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
6979 	 */
6980 	if (err) {
6981 		err = release_reference(env, regs[err].ref_obj_id);
6982 		if (err) {
6983 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
6984 				func_name, func_id);
6985 			return err;
6986 		}
6987 	}
6988 
6989 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6990 		mark_reg_not_init(env, regs, caller_saved[i]);
6991 
6992 	/* Check return type */
6993 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6994 
6995 	if (acq && !btf_type_is_ptr(t)) {
6996 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
6997 		return -EINVAL;
6998 	}
6999 
7000 	if (btf_type_is_scalar(t)) {
7001 		mark_reg_unknown(env, regs, BPF_REG_0);
7002 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7003 	} else if (btf_type_is_ptr(t)) {
7004 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7005 						   &ptr_type_id);
7006 		if (!btf_type_is_struct(ptr_type)) {
7007 			ptr_type_name = btf_name_by_offset(desc_btf,
7008 							   ptr_type->name_off);
7009 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7010 				func_name, btf_type_str(ptr_type),
7011 				ptr_type_name);
7012 			return -EINVAL;
7013 		}
7014 		mark_reg_known_zero(env, regs, BPF_REG_0);
7015 		regs[BPF_REG_0].btf = desc_btf;
7016 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7017 		regs[BPF_REG_0].btf_id = ptr_type_id;
7018 		if (btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7019 					      BTF_KFUNC_TYPE_RET_NULL, func_id)) {
7020 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7021 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7022 			regs[BPF_REG_0].id = ++env->id_gen;
7023 		}
7024 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7025 		if (acq) {
7026 			int id = acquire_reference_state(env, insn_idx);
7027 
7028 			if (id < 0)
7029 				return id;
7030 			regs[BPF_REG_0].id = id;
7031 			regs[BPF_REG_0].ref_obj_id = id;
7032 		}
7033 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7034 
7035 	nargs = btf_type_vlen(func_proto);
7036 	args = (const struct btf_param *)(func_proto + 1);
7037 	for (i = 0; i < nargs; i++) {
7038 		u32 regno = i + 1;
7039 
7040 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7041 		if (btf_type_is_ptr(t))
7042 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7043 		else
7044 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7045 			mark_btf_func_reg_size(env, regno, t->size);
7046 	}
7047 
7048 	return 0;
7049 }
7050 
7051 static bool signed_add_overflows(s64 a, s64 b)
7052 {
7053 	/* Do the add in u64, where overflow is well-defined */
7054 	s64 res = (s64)((u64)a + (u64)b);
7055 
7056 	if (b < 0)
7057 		return res > a;
7058 	return res < a;
7059 }
7060 
7061 static bool signed_add32_overflows(s32 a, s32 b)
7062 {
7063 	/* Do the add in u32, where overflow is well-defined */
7064 	s32 res = (s32)((u32)a + (u32)b);
7065 
7066 	if (b < 0)
7067 		return res > a;
7068 	return res < a;
7069 }
7070 
7071 static bool signed_sub_overflows(s64 a, s64 b)
7072 {
7073 	/* Do the sub in u64, where overflow is well-defined */
7074 	s64 res = (s64)((u64)a - (u64)b);
7075 
7076 	if (b < 0)
7077 		return res < a;
7078 	return res > a;
7079 }
7080 
7081 static bool signed_sub32_overflows(s32 a, s32 b)
7082 {
7083 	/* Do the sub in u32, where overflow is well-defined */
7084 	s32 res = (s32)((u32)a - (u32)b);
7085 
7086 	if (b < 0)
7087 		return res < a;
7088 	return res > a;
7089 }
7090 
7091 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7092 				  const struct bpf_reg_state *reg,
7093 				  enum bpf_reg_type type)
7094 {
7095 	bool known = tnum_is_const(reg->var_off);
7096 	s64 val = reg->var_off.value;
7097 	s64 smin = reg->smin_value;
7098 
7099 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7100 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7101 			reg_type_str(env, type), val);
7102 		return false;
7103 	}
7104 
7105 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7106 		verbose(env, "%s pointer offset %d is not allowed\n",
7107 			reg_type_str(env, type), reg->off);
7108 		return false;
7109 	}
7110 
7111 	if (smin == S64_MIN) {
7112 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7113 			reg_type_str(env, type));
7114 		return false;
7115 	}
7116 
7117 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7118 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7119 			smin, reg_type_str(env, type));
7120 		return false;
7121 	}
7122 
7123 	return true;
7124 }
7125 
7126 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7127 {
7128 	return &env->insn_aux_data[env->insn_idx];
7129 }
7130 
7131 enum {
7132 	REASON_BOUNDS	= -1,
7133 	REASON_TYPE	= -2,
7134 	REASON_PATHS	= -3,
7135 	REASON_LIMIT	= -4,
7136 	REASON_STACK	= -5,
7137 };
7138 
7139 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7140 			      u32 *alu_limit, bool mask_to_left)
7141 {
7142 	u32 max = 0, ptr_limit = 0;
7143 
7144 	switch (ptr_reg->type) {
7145 	case PTR_TO_STACK:
7146 		/* Offset 0 is out-of-bounds, but acceptable start for the
7147 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7148 		 * offset where we would need to deal with min/max bounds is
7149 		 * currently prohibited for unprivileged.
7150 		 */
7151 		max = MAX_BPF_STACK + mask_to_left;
7152 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7153 		break;
7154 	case PTR_TO_MAP_VALUE:
7155 		max = ptr_reg->map_ptr->value_size;
7156 		ptr_limit = (mask_to_left ?
7157 			     ptr_reg->smin_value :
7158 			     ptr_reg->umax_value) + ptr_reg->off;
7159 		break;
7160 	default:
7161 		return REASON_TYPE;
7162 	}
7163 
7164 	if (ptr_limit >= max)
7165 		return REASON_LIMIT;
7166 	*alu_limit = ptr_limit;
7167 	return 0;
7168 }
7169 
7170 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7171 				    const struct bpf_insn *insn)
7172 {
7173 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7174 }
7175 
7176 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7177 				       u32 alu_state, u32 alu_limit)
7178 {
7179 	/* If we arrived here from different branches with different
7180 	 * state or limits to sanitize, then this won't work.
7181 	 */
7182 	if (aux->alu_state &&
7183 	    (aux->alu_state != alu_state ||
7184 	     aux->alu_limit != alu_limit))
7185 		return REASON_PATHS;
7186 
7187 	/* Corresponding fixup done in do_misc_fixups(). */
7188 	aux->alu_state = alu_state;
7189 	aux->alu_limit = alu_limit;
7190 	return 0;
7191 }
7192 
7193 static int sanitize_val_alu(struct bpf_verifier_env *env,
7194 			    struct bpf_insn *insn)
7195 {
7196 	struct bpf_insn_aux_data *aux = cur_aux(env);
7197 
7198 	if (can_skip_alu_sanitation(env, insn))
7199 		return 0;
7200 
7201 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7202 }
7203 
7204 static bool sanitize_needed(u8 opcode)
7205 {
7206 	return opcode == BPF_ADD || opcode == BPF_SUB;
7207 }
7208 
7209 struct bpf_sanitize_info {
7210 	struct bpf_insn_aux_data aux;
7211 	bool mask_to_left;
7212 };
7213 
7214 static struct bpf_verifier_state *
7215 sanitize_speculative_path(struct bpf_verifier_env *env,
7216 			  const struct bpf_insn *insn,
7217 			  u32 next_idx, u32 curr_idx)
7218 {
7219 	struct bpf_verifier_state *branch;
7220 	struct bpf_reg_state *regs;
7221 
7222 	branch = push_stack(env, next_idx, curr_idx, true);
7223 	if (branch && insn) {
7224 		regs = branch->frame[branch->curframe]->regs;
7225 		if (BPF_SRC(insn->code) == BPF_K) {
7226 			mark_reg_unknown(env, regs, insn->dst_reg);
7227 		} else if (BPF_SRC(insn->code) == BPF_X) {
7228 			mark_reg_unknown(env, regs, insn->dst_reg);
7229 			mark_reg_unknown(env, regs, insn->src_reg);
7230 		}
7231 	}
7232 	return branch;
7233 }
7234 
7235 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7236 			    struct bpf_insn *insn,
7237 			    const struct bpf_reg_state *ptr_reg,
7238 			    const struct bpf_reg_state *off_reg,
7239 			    struct bpf_reg_state *dst_reg,
7240 			    struct bpf_sanitize_info *info,
7241 			    const bool commit_window)
7242 {
7243 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7244 	struct bpf_verifier_state *vstate = env->cur_state;
7245 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7246 	bool off_is_neg = off_reg->smin_value < 0;
7247 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7248 	u8 opcode = BPF_OP(insn->code);
7249 	u32 alu_state, alu_limit;
7250 	struct bpf_reg_state tmp;
7251 	bool ret;
7252 	int err;
7253 
7254 	if (can_skip_alu_sanitation(env, insn))
7255 		return 0;
7256 
7257 	/* We already marked aux for masking from non-speculative
7258 	 * paths, thus we got here in the first place. We only care
7259 	 * to explore bad access from here.
7260 	 */
7261 	if (vstate->speculative)
7262 		goto do_sim;
7263 
7264 	if (!commit_window) {
7265 		if (!tnum_is_const(off_reg->var_off) &&
7266 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7267 			return REASON_BOUNDS;
7268 
7269 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7270 				     (opcode == BPF_SUB && !off_is_neg);
7271 	}
7272 
7273 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7274 	if (err < 0)
7275 		return err;
7276 
7277 	if (commit_window) {
7278 		/* In commit phase we narrow the masking window based on
7279 		 * the observed pointer move after the simulated operation.
7280 		 */
7281 		alu_state = info->aux.alu_state;
7282 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7283 	} else {
7284 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7285 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7286 		alu_state |= ptr_is_dst_reg ?
7287 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7288 
7289 		/* Limit pruning on unknown scalars to enable deep search for
7290 		 * potential masking differences from other program paths.
7291 		 */
7292 		if (!off_is_imm)
7293 			env->explore_alu_limits = true;
7294 	}
7295 
7296 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7297 	if (err < 0)
7298 		return err;
7299 do_sim:
7300 	/* If we're in commit phase, we're done here given we already
7301 	 * pushed the truncated dst_reg into the speculative verification
7302 	 * stack.
7303 	 *
7304 	 * Also, when register is a known constant, we rewrite register-based
7305 	 * operation to immediate-based, and thus do not need masking (and as
7306 	 * a consequence, do not need to simulate the zero-truncation either).
7307 	 */
7308 	if (commit_window || off_is_imm)
7309 		return 0;
7310 
7311 	/* Simulate and find potential out-of-bounds access under
7312 	 * speculative execution from truncation as a result of
7313 	 * masking when off was not within expected range. If off
7314 	 * sits in dst, then we temporarily need to move ptr there
7315 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7316 	 * for cases where we use K-based arithmetic in one direction
7317 	 * and truncated reg-based in the other in order to explore
7318 	 * bad access.
7319 	 */
7320 	if (!ptr_is_dst_reg) {
7321 		tmp = *dst_reg;
7322 		*dst_reg = *ptr_reg;
7323 	}
7324 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7325 					env->insn_idx);
7326 	if (!ptr_is_dst_reg && ret)
7327 		*dst_reg = tmp;
7328 	return !ret ? REASON_STACK : 0;
7329 }
7330 
7331 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7332 {
7333 	struct bpf_verifier_state *vstate = env->cur_state;
7334 
7335 	/* If we simulate paths under speculation, we don't update the
7336 	 * insn as 'seen' such that when we verify unreachable paths in
7337 	 * the non-speculative domain, sanitize_dead_code() can still
7338 	 * rewrite/sanitize them.
7339 	 */
7340 	if (!vstate->speculative)
7341 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7342 }
7343 
7344 static int sanitize_err(struct bpf_verifier_env *env,
7345 			const struct bpf_insn *insn, int reason,
7346 			const struct bpf_reg_state *off_reg,
7347 			const struct bpf_reg_state *dst_reg)
7348 {
7349 	static const char *err = "pointer arithmetic with it prohibited for !root";
7350 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7351 	u32 dst = insn->dst_reg, src = insn->src_reg;
7352 
7353 	switch (reason) {
7354 	case REASON_BOUNDS:
7355 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7356 			off_reg == dst_reg ? dst : src, err);
7357 		break;
7358 	case REASON_TYPE:
7359 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7360 			off_reg == dst_reg ? src : dst, err);
7361 		break;
7362 	case REASON_PATHS:
7363 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7364 			dst, op, err);
7365 		break;
7366 	case REASON_LIMIT:
7367 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7368 			dst, op, err);
7369 		break;
7370 	case REASON_STACK:
7371 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7372 			dst, err);
7373 		break;
7374 	default:
7375 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7376 			reason);
7377 		break;
7378 	}
7379 
7380 	return -EACCES;
7381 }
7382 
7383 /* check that stack access falls within stack limits and that 'reg' doesn't
7384  * have a variable offset.
7385  *
7386  * Variable offset is prohibited for unprivileged mode for simplicity since it
7387  * requires corresponding support in Spectre masking for stack ALU.  See also
7388  * retrieve_ptr_limit().
7389  *
7390  *
7391  * 'off' includes 'reg->off'.
7392  */
7393 static int check_stack_access_for_ptr_arithmetic(
7394 				struct bpf_verifier_env *env,
7395 				int regno,
7396 				const struct bpf_reg_state *reg,
7397 				int off)
7398 {
7399 	if (!tnum_is_const(reg->var_off)) {
7400 		char tn_buf[48];
7401 
7402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7403 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7404 			regno, tn_buf, off);
7405 		return -EACCES;
7406 	}
7407 
7408 	if (off >= 0 || off < -MAX_BPF_STACK) {
7409 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7410 			"prohibited for !root; off=%d\n", regno, off);
7411 		return -EACCES;
7412 	}
7413 
7414 	return 0;
7415 }
7416 
7417 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7418 				 const struct bpf_insn *insn,
7419 				 const struct bpf_reg_state *dst_reg)
7420 {
7421 	u32 dst = insn->dst_reg;
7422 
7423 	/* For unprivileged we require that resulting offset must be in bounds
7424 	 * in order to be able to sanitize access later on.
7425 	 */
7426 	if (env->bypass_spec_v1)
7427 		return 0;
7428 
7429 	switch (dst_reg->type) {
7430 	case PTR_TO_STACK:
7431 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7432 					dst_reg->off + dst_reg->var_off.value))
7433 			return -EACCES;
7434 		break;
7435 	case PTR_TO_MAP_VALUE:
7436 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7437 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7438 				"prohibited for !root\n", dst);
7439 			return -EACCES;
7440 		}
7441 		break;
7442 	default:
7443 		break;
7444 	}
7445 
7446 	return 0;
7447 }
7448 
7449 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7450  * Caller should also handle BPF_MOV case separately.
7451  * If we return -EACCES, caller may want to try again treating pointer as a
7452  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7453  */
7454 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7455 				   struct bpf_insn *insn,
7456 				   const struct bpf_reg_state *ptr_reg,
7457 				   const struct bpf_reg_state *off_reg)
7458 {
7459 	struct bpf_verifier_state *vstate = env->cur_state;
7460 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7461 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7462 	bool known = tnum_is_const(off_reg->var_off);
7463 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7464 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7465 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7466 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7467 	struct bpf_sanitize_info info = {};
7468 	u8 opcode = BPF_OP(insn->code);
7469 	u32 dst = insn->dst_reg;
7470 	int ret;
7471 
7472 	dst_reg = &regs[dst];
7473 
7474 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7475 	    smin_val > smax_val || umin_val > umax_val) {
7476 		/* Taint dst register if offset had invalid bounds derived from
7477 		 * e.g. dead branches.
7478 		 */
7479 		__mark_reg_unknown(env, dst_reg);
7480 		return 0;
7481 	}
7482 
7483 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7484 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7485 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7486 			__mark_reg_unknown(env, dst_reg);
7487 			return 0;
7488 		}
7489 
7490 		verbose(env,
7491 			"R%d 32-bit pointer arithmetic prohibited\n",
7492 			dst);
7493 		return -EACCES;
7494 	}
7495 
7496 	if (ptr_reg->type & PTR_MAYBE_NULL) {
7497 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7498 			dst, reg_type_str(env, ptr_reg->type));
7499 		return -EACCES;
7500 	}
7501 
7502 	switch (base_type(ptr_reg->type)) {
7503 	case CONST_PTR_TO_MAP:
7504 		/* smin_val represents the known value */
7505 		if (known && smin_val == 0 && opcode == BPF_ADD)
7506 			break;
7507 		fallthrough;
7508 	case PTR_TO_PACKET_END:
7509 	case PTR_TO_SOCKET:
7510 	case PTR_TO_SOCK_COMMON:
7511 	case PTR_TO_TCP_SOCK:
7512 	case PTR_TO_XDP_SOCK:
7513 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7514 			dst, reg_type_str(env, ptr_reg->type));
7515 		return -EACCES;
7516 	default:
7517 		break;
7518 	}
7519 
7520 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7521 	 * The id may be overwritten later if we create a new variable offset.
7522 	 */
7523 	dst_reg->type = ptr_reg->type;
7524 	dst_reg->id = ptr_reg->id;
7525 
7526 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7527 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7528 		return -EINVAL;
7529 
7530 	/* pointer types do not carry 32-bit bounds at the moment. */
7531 	__mark_reg32_unbounded(dst_reg);
7532 
7533 	if (sanitize_needed(opcode)) {
7534 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7535 				       &info, false);
7536 		if (ret < 0)
7537 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7538 	}
7539 
7540 	switch (opcode) {
7541 	case BPF_ADD:
7542 		/* We can take a fixed offset as long as it doesn't overflow
7543 		 * the s32 'off' field
7544 		 */
7545 		if (known && (ptr_reg->off + smin_val ==
7546 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7547 			/* pointer += K.  Accumulate it into fixed offset */
7548 			dst_reg->smin_value = smin_ptr;
7549 			dst_reg->smax_value = smax_ptr;
7550 			dst_reg->umin_value = umin_ptr;
7551 			dst_reg->umax_value = umax_ptr;
7552 			dst_reg->var_off = ptr_reg->var_off;
7553 			dst_reg->off = ptr_reg->off + smin_val;
7554 			dst_reg->raw = ptr_reg->raw;
7555 			break;
7556 		}
7557 		/* A new variable offset is created.  Note that off_reg->off
7558 		 * == 0, since it's a scalar.
7559 		 * dst_reg gets the pointer type and since some positive
7560 		 * integer value was added to the pointer, give it a new 'id'
7561 		 * if it's a PTR_TO_PACKET.
7562 		 * this creates a new 'base' pointer, off_reg (variable) gets
7563 		 * added into the variable offset, and we copy the fixed offset
7564 		 * from ptr_reg.
7565 		 */
7566 		if (signed_add_overflows(smin_ptr, smin_val) ||
7567 		    signed_add_overflows(smax_ptr, smax_val)) {
7568 			dst_reg->smin_value = S64_MIN;
7569 			dst_reg->smax_value = S64_MAX;
7570 		} else {
7571 			dst_reg->smin_value = smin_ptr + smin_val;
7572 			dst_reg->smax_value = smax_ptr + smax_val;
7573 		}
7574 		if (umin_ptr + umin_val < umin_ptr ||
7575 		    umax_ptr + umax_val < umax_ptr) {
7576 			dst_reg->umin_value = 0;
7577 			dst_reg->umax_value = U64_MAX;
7578 		} else {
7579 			dst_reg->umin_value = umin_ptr + umin_val;
7580 			dst_reg->umax_value = umax_ptr + umax_val;
7581 		}
7582 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7583 		dst_reg->off = ptr_reg->off;
7584 		dst_reg->raw = ptr_reg->raw;
7585 		if (reg_is_pkt_pointer(ptr_reg)) {
7586 			dst_reg->id = ++env->id_gen;
7587 			/* something was added to pkt_ptr, set range to zero */
7588 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7589 		}
7590 		break;
7591 	case BPF_SUB:
7592 		if (dst_reg == off_reg) {
7593 			/* scalar -= pointer.  Creates an unknown scalar */
7594 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7595 				dst);
7596 			return -EACCES;
7597 		}
7598 		/* We don't allow subtraction from FP, because (according to
7599 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7600 		 * be able to deal with it.
7601 		 */
7602 		if (ptr_reg->type == PTR_TO_STACK) {
7603 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7604 				dst);
7605 			return -EACCES;
7606 		}
7607 		if (known && (ptr_reg->off - smin_val ==
7608 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7609 			/* pointer -= K.  Subtract it from fixed offset */
7610 			dst_reg->smin_value = smin_ptr;
7611 			dst_reg->smax_value = smax_ptr;
7612 			dst_reg->umin_value = umin_ptr;
7613 			dst_reg->umax_value = umax_ptr;
7614 			dst_reg->var_off = ptr_reg->var_off;
7615 			dst_reg->id = ptr_reg->id;
7616 			dst_reg->off = ptr_reg->off - smin_val;
7617 			dst_reg->raw = ptr_reg->raw;
7618 			break;
7619 		}
7620 		/* A new variable offset is created.  If the subtrahend is known
7621 		 * nonnegative, then any reg->range we had before is still good.
7622 		 */
7623 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7624 		    signed_sub_overflows(smax_ptr, smin_val)) {
7625 			/* Overflow possible, we know nothing */
7626 			dst_reg->smin_value = S64_MIN;
7627 			dst_reg->smax_value = S64_MAX;
7628 		} else {
7629 			dst_reg->smin_value = smin_ptr - smax_val;
7630 			dst_reg->smax_value = smax_ptr - smin_val;
7631 		}
7632 		if (umin_ptr < umax_val) {
7633 			/* Overflow possible, we know nothing */
7634 			dst_reg->umin_value = 0;
7635 			dst_reg->umax_value = U64_MAX;
7636 		} else {
7637 			/* Cannot overflow (as long as bounds are consistent) */
7638 			dst_reg->umin_value = umin_ptr - umax_val;
7639 			dst_reg->umax_value = umax_ptr - umin_val;
7640 		}
7641 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7642 		dst_reg->off = ptr_reg->off;
7643 		dst_reg->raw = ptr_reg->raw;
7644 		if (reg_is_pkt_pointer(ptr_reg)) {
7645 			dst_reg->id = ++env->id_gen;
7646 			/* something was added to pkt_ptr, set range to zero */
7647 			if (smin_val < 0)
7648 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7649 		}
7650 		break;
7651 	case BPF_AND:
7652 	case BPF_OR:
7653 	case BPF_XOR:
7654 		/* bitwise ops on pointers are troublesome, prohibit. */
7655 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7656 			dst, bpf_alu_string[opcode >> 4]);
7657 		return -EACCES;
7658 	default:
7659 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7660 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7661 			dst, bpf_alu_string[opcode >> 4]);
7662 		return -EACCES;
7663 	}
7664 
7665 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7666 		return -EINVAL;
7667 
7668 	__update_reg_bounds(dst_reg);
7669 	__reg_deduce_bounds(dst_reg);
7670 	__reg_bound_offset(dst_reg);
7671 
7672 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7673 		return -EACCES;
7674 	if (sanitize_needed(opcode)) {
7675 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7676 				       &info, true);
7677 		if (ret < 0)
7678 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7679 	}
7680 
7681 	return 0;
7682 }
7683 
7684 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7685 				 struct bpf_reg_state *src_reg)
7686 {
7687 	s32 smin_val = src_reg->s32_min_value;
7688 	s32 smax_val = src_reg->s32_max_value;
7689 	u32 umin_val = src_reg->u32_min_value;
7690 	u32 umax_val = src_reg->u32_max_value;
7691 
7692 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7693 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7694 		dst_reg->s32_min_value = S32_MIN;
7695 		dst_reg->s32_max_value = S32_MAX;
7696 	} else {
7697 		dst_reg->s32_min_value += smin_val;
7698 		dst_reg->s32_max_value += smax_val;
7699 	}
7700 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7701 	    dst_reg->u32_max_value + umax_val < umax_val) {
7702 		dst_reg->u32_min_value = 0;
7703 		dst_reg->u32_max_value = U32_MAX;
7704 	} else {
7705 		dst_reg->u32_min_value += umin_val;
7706 		dst_reg->u32_max_value += umax_val;
7707 	}
7708 }
7709 
7710 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7711 			       struct bpf_reg_state *src_reg)
7712 {
7713 	s64 smin_val = src_reg->smin_value;
7714 	s64 smax_val = src_reg->smax_value;
7715 	u64 umin_val = src_reg->umin_value;
7716 	u64 umax_val = src_reg->umax_value;
7717 
7718 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7719 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7720 		dst_reg->smin_value = S64_MIN;
7721 		dst_reg->smax_value = S64_MAX;
7722 	} else {
7723 		dst_reg->smin_value += smin_val;
7724 		dst_reg->smax_value += smax_val;
7725 	}
7726 	if (dst_reg->umin_value + umin_val < umin_val ||
7727 	    dst_reg->umax_value + umax_val < umax_val) {
7728 		dst_reg->umin_value = 0;
7729 		dst_reg->umax_value = U64_MAX;
7730 	} else {
7731 		dst_reg->umin_value += umin_val;
7732 		dst_reg->umax_value += umax_val;
7733 	}
7734 }
7735 
7736 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7737 				 struct bpf_reg_state *src_reg)
7738 {
7739 	s32 smin_val = src_reg->s32_min_value;
7740 	s32 smax_val = src_reg->s32_max_value;
7741 	u32 umin_val = src_reg->u32_min_value;
7742 	u32 umax_val = src_reg->u32_max_value;
7743 
7744 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7745 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7746 		/* Overflow possible, we know nothing */
7747 		dst_reg->s32_min_value = S32_MIN;
7748 		dst_reg->s32_max_value = S32_MAX;
7749 	} else {
7750 		dst_reg->s32_min_value -= smax_val;
7751 		dst_reg->s32_max_value -= smin_val;
7752 	}
7753 	if (dst_reg->u32_min_value < umax_val) {
7754 		/* Overflow possible, we know nothing */
7755 		dst_reg->u32_min_value = 0;
7756 		dst_reg->u32_max_value = U32_MAX;
7757 	} else {
7758 		/* Cannot overflow (as long as bounds are consistent) */
7759 		dst_reg->u32_min_value -= umax_val;
7760 		dst_reg->u32_max_value -= umin_val;
7761 	}
7762 }
7763 
7764 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7765 			       struct bpf_reg_state *src_reg)
7766 {
7767 	s64 smin_val = src_reg->smin_value;
7768 	s64 smax_val = src_reg->smax_value;
7769 	u64 umin_val = src_reg->umin_value;
7770 	u64 umax_val = src_reg->umax_value;
7771 
7772 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7773 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7774 		/* Overflow possible, we know nothing */
7775 		dst_reg->smin_value = S64_MIN;
7776 		dst_reg->smax_value = S64_MAX;
7777 	} else {
7778 		dst_reg->smin_value -= smax_val;
7779 		dst_reg->smax_value -= smin_val;
7780 	}
7781 	if (dst_reg->umin_value < umax_val) {
7782 		/* Overflow possible, we know nothing */
7783 		dst_reg->umin_value = 0;
7784 		dst_reg->umax_value = U64_MAX;
7785 	} else {
7786 		/* Cannot overflow (as long as bounds are consistent) */
7787 		dst_reg->umin_value -= umax_val;
7788 		dst_reg->umax_value -= umin_val;
7789 	}
7790 }
7791 
7792 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7793 				 struct bpf_reg_state *src_reg)
7794 {
7795 	s32 smin_val = src_reg->s32_min_value;
7796 	u32 umin_val = src_reg->u32_min_value;
7797 	u32 umax_val = src_reg->u32_max_value;
7798 
7799 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7800 		/* Ain't nobody got time to multiply that sign */
7801 		__mark_reg32_unbounded(dst_reg);
7802 		return;
7803 	}
7804 	/* Both values are positive, so we can work with unsigned and
7805 	 * copy the result to signed (unless it exceeds S32_MAX).
7806 	 */
7807 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7808 		/* Potential overflow, we know nothing */
7809 		__mark_reg32_unbounded(dst_reg);
7810 		return;
7811 	}
7812 	dst_reg->u32_min_value *= umin_val;
7813 	dst_reg->u32_max_value *= umax_val;
7814 	if (dst_reg->u32_max_value > S32_MAX) {
7815 		/* Overflow possible, we know nothing */
7816 		dst_reg->s32_min_value = S32_MIN;
7817 		dst_reg->s32_max_value = S32_MAX;
7818 	} else {
7819 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7820 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7821 	}
7822 }
7823 
7824 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7825 			       struct bpf_reg_state *src_reg)
7826 {
7827 	s64 smin_val = src_reg->smin_value;
7828 	u64 umin_val = src_reg->umin_value;
7829 	u64 umax_val = src_reg->umax_value;
7830 
7831 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7832 		/* Ain't nobody got time to multiply that sign */
7833 		__mark_reg64_unbounded(dst_reg);
7834 		return;
7835 	}
7836 	/* Both values are positive, so we can work with unsigned and
7837 	 * copy the result to signed (unless it exceeds S64_MAX).
7838 	 */
7839 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7840 		/* Potential overflow, we know nothing */
7841 		__mark_reg64_unbounded(dst_reg);
7842 		return;
7843 	}
7844 	dst_reg->umin_value *= umin_val;
7845 	dst_reg->umax_value *= umax_val;
7846 	if (dst_reg->umax_value > S64_MAX) {
7847 		/* Overflow possible, we know nothing */
7848 		dst_reg->smin_value = S64_MIN;
7849 		dst_reg->smax_value = S64_MAX;
7850 	} else {
7851 		dst_reg->smin_value = dst_reg->umin_value;
7852 		dst_reg->smax_value = dst_reg->umax_value;
7853 	}
7854 }
7855 
7856 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7857 				 struct bpf_reg_state *src_reg)
7858 {
7859 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7860 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7861 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7862 	s32 smin_val = src_reg->s32_min_value;
7863 	u32 umax_val = src_reg->u32_max_value;
7864 
7865 	if (src_known && dst_known) {
7866 		__mark_reg32_known(dst_reg, var32_off.value);
7867 		return;
7868 	}
7869 
7870 	/* We get our minimum from the var_off, since that's inherently
7871 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7872 	 */
7873 	dst_reg->u32_min_value = var32_off.value;
7874 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7875 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7876 		/* Lose signed bounds when ANDing negative numbers,
7877 		 * ain't nobody got time for that.
7878 		 */
7879 		dst_reg->s32_min_value = S32_MIN;
7880 		dst_reg->s32_max_value = S32_MAX;
7881 	} else {
7882 		/* ANDing two positives gives a positive, so safe to
7883 		 * cast result into s64.
7884 		 */
7885 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7886 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7887 	}
7888 }
7889 
7890 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7891 			       struct bpf_reg_state *src_reg)
7892 {
7893 	bool src_known = tnum_is_const(src_reg->var_off);
7894 	bool dst_known = tnum_is_const(dst_reg->var_off);
7895 	s64 smin_val = src_reg->smin_value;
7896 	u64 umax_val = src_reg->umax_value;
7897 
7898 	if (src_known && dst_known) {
7899 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7900 		return;
7901 	}
7902 
7903 	/* We get our minimum from the var_off, since that's inherently
7904 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7905 	 */
7906 	dst_reg->umin_value = dst_reg->var_off.value;
7907 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7908 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7909 		/* Lose signed bounds when ANDing negative numbers,
7910 		 * ain't nobody got time for that.
7911 		 */
7912 		dst_reg->smin_value = S64_MIN;
7913 		dst_reg->smax_value = S64_MAX;
7914 	} else {
7915 		/* ANDing two positives gives a positive, so safe to
7916 		 * cast result into s64.
7917 		 */
7918 		dst_reg->smin_value = dst_reg->umin_value;
7919 		dst_reg->smax_value = dst_reg->umax_value;
7920 	}
7921 	/* We may learn something more from the var_off */
7922 	__update_reg_bounds(dst_reg);
7923 }
7924 
7925 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7926 				struct bpf_reg_state *src_reg)
7927 {
7928 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7929 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7930 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7931 	s32 smin_val = src_reg->s32_min_value;
7932 	u32 umin_val = src_reg->u32_min_value;
7933 
7934 	if (src_known && dst_known) {
7935 		__mark_reg32_known(dst_reg, var32_off.value);
7936 		return;
7937 	}
7938 
7939 	/* We get our maximum from the var_off, and our minimum is the
7940 	 * maximum of the operands' minima
7941 	 */
7942 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7943 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7944 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7945 		/* Lose signed bounds when ORing negative numbers,
7946 		 * ain't nobody got time for that.
7947 		 */
7948 		dst_reg->s32_min_value = S32_MIN;
7949 		dst_reg->s32_max_value = S32_MAX;
7950 	} else {
7951 		/* ORing two positives gives a positive, so safe to
7952 		 * cast result into s64.
7953 		 */
7954 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7955 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7956 	}
7957 }
7958 
7959 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7960 			      struct bpf_reg_state *src_reg)
7961 {
7962 	bool src_known = tnum_is_const(src_reg->var_off);
7963 	bool dst_known = tnum_is_const(dst_reg->var_off);
7964 	s64 smin_val = src_reg->smin_value;
7965 	u64 umin_val = src_reg->umin_value;
7966 
7967 	if (src_known && dst_known) {
7968 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7969 		return;
7970 	}
7971 
7972 	/* We get our maximum from the var_off, and our minimum is the
7973 	 * maximum of the operands' minima
7974 	 */
7975 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7976 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7977 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7978 		/* Lose signed bounds when ORing negative numbers,
7979 		 * ain't nobody got time for that.
7980 		 */
7981 		dst_reg->smin_value = S64_MIN;
7982 		dst_reg->smax_value = S64_MAX;
7983 	} else {
7984 		/* ORing two positives gives a positive, so safe to
7985 		 * cast result into s64.
7986 		 */
7987 		dst_reg->smin_value = dst_reg->umin_value;
7988 		dst_reg->smax_value = dst_reg->umax_value;
7989 	}
7990 	/* We may learn something more from the var_off */
7991 	__update_reg_bounds(dst_reg);
7992 }
7993 
7994 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7995 				 struct bpf_reg_state *src_reg)
7996 {
7997 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7998 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7999 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8000 	s32 smin_val = src_reg->s32_min_value;
8001 
8002 	if (src_known && dst_known) {
8003 		__mark_reg32_known(dst_reg, var32_off.value);
8004 		return;
8005 	}
8006 
8007 	/* We get both minimum and maximum from the var32_off. */
8008 	dst_reg->u32_min_value = var32_off.value;
8009 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8010 
8011 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8012 		/* XORing two positive sign numbers gives a positive,
8013 		 * so safe to cast u32 result into s32.
8014 		 */
8015 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8016 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8017 	} else {
8018 		dst_reg->s32_min_value = S32_MIN;
8019 		dst_reg->s32_max_value = S32_MAX;
8020 	}
8021 }
8022 
8023 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8024 			       struct bpf_reg_state *src_reg)
8025 {
8026 	bool src_known = tnum_is_const(src_reg->var_off);
8027 	bool dst_known = tnum_is_const(dst_reg->var_off);
8028 	s64 smin_val = src_reg->smin_value;
8029 
8030 	if (src_known && dst_known) {
8031 		/* dst_reg->var_off.value has been updated earlier */
8032 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8033 		return;
8034 	}
8035 
8036 	/* We get both minimum and maximum from the var_off. */
8037 	dst_reg->umin_value = dst_reg->var_off.value;
8038 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8039 
8040 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8041 		/* XORing two positive sign numbers gives a positive,
8042 		 * so safe to cast u64 result into s64.
8043 		 */
8044 		dst_reg->smin_value = dst_reg->umin_value;
8045 		dst_reg->smax_value = dst_reg->umax_value;
8046 	} else {
8047 		dst_reg->smin_value = S64_MIN;
8048 		dst_reg->smax_value = S64_MAX;
8049 	}
8050 
8051 	__update_reg_bounds(dst_reg);
8052 }
8053 
8054 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8055 				   u64 umin_val, u64 umax_val)
8056 {
8057 	/* We lose all sign bit information (except what we can pick
8058 	 * up from var_off)
8059 	 */
8060 	dst_reg->s32_min_value = S32_MIN;
8061 	dst_reg->s32_max_value = S32_MAX;
8062 	/* If we might shift our top bit out, then we know nothing */
8063 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8064 		dst_reg->u32_min_value = 0;
8065 		dst_reg->u32_max_value = U32_MAX;
8066 	} else {
8067 		dst_reg->u32_min_value <<= umin_val;
8068 		dst_reg->u32_max_value <<= umax_val;
8069 	}
8070 }
8071 
8072 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8073 				 struct bpf_reg_state *src_reg)
8074 {
8075 	u32 umax_val = src_reg->u32_max_value;
8076 	u32 umin_val = src_reg->u32_min_value;
8077 	/* u32 alu operation will zext upper bits */
8078 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8079 
8080 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8081 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8082 	/* Not required but being careful mark reg64 bounds as unknown so
8083 	 * that we are forced to pick them up from tnum and zext later and
8084 	 * if some path skips this step we are still safe.
8085 	 */
8086 	__mark_reg64_unbounded(dst_reg);
8087 	__update_reg32_bounds(dst_reg);
8088 }
8089 
8090 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8091 				   u64 umin_val, u64 umax_val)
8092 {
8093 	/* Special case <<32 because it is a common compiler pattern to sign
8094 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8095 	 * positive we know this shift will also be positive so we can track
8096 	 * bounds correctly. Otherwise we lose all sign bit information except
8097 	 * what we can pick up from var_off. Perhaps we can generalize this
8098 	 * later to shifts of any length.
8099 	 */
8100 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8101 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8102 	else
8103 		dst_reg->smax_value = S64_MAX;
8104 
8105 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8106 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8107 	else
8108 		dst_reg->smin_value = S64_MIN;
8109 
8110 	/* If we might shift our top bit out, then we know nothing */
8111 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8112 		dst_reg->umin_value = 0;
8113 		dst_reg->umax_value = U64_MAX;
8114 	} else {
8115 		dst_reg->umin_value <<= umin_val;
8116 		dst_reg->umax_value <<= umax_val;
8117 	}
8118 }
8119 
8120 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8121 			       struct bpf_reg_state *src_reg)
8122 {
8123 	u64 umax_val = src_reg->umax_value;
8124 	u64 umin_val = src_reg->umin_value;
8125 
8126 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8127 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8128 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8129 
8130 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8131 	/* We may learn something more from the var_off */
8132 	__update_reg_bounds(dst_reg);
8133 }
8134 
8135 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8136 				 struct bpf_reg_state *src_reg)
8137 {
8138 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8139 	u32 umax_val = src_reg->u32_max_value;
8140 	u32 umin_val = src_reg->u32_min_value;
8141 
8142 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8143 	 * be negative, then either:
8144 	 * 1) src_reg might be zero, so the sign bit of the result is
8145 	 *    unknown, so we lose our signed bounds
8146 	 * 2) it's known negative, thus the unsigned bounds capture the
8147 	 *    signed bounds
8148 	 * 3) the signed bounds cross zero, so they tell us nothing
8149 	 *    about the result
8150 	 * If the value in dst_reg is known nonnegative, then again the
8151 	 * unsigned bounds capture the signed bounds.
8152 	 * Thus, in all cases it suffices to blow away our signed bounds
8153 	 * and rely on inferring new ones from the unsigned bounds and
8154 	 * var_off of the result.
8155 	 */
8156 	dst_reg->s32_min_value = S32_MIN;
8157 	dst_reg->s32_max_value = S32_MAX;
8158 
8159 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8160 	dst_reg->u32_min_value >>= umax_val;
8161 	dst_reg->u32_max_value >>= umin_val;
8162 
8163 	__mark_reg64_unbounded(dst_reg);
8164 	__update_reg32_bounds(dst_reg);
8165 }
8166 
8167 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8168 			       struct bpf_reg_state *src_reg)
8169 {
8170 	u64 umax_val = src_reg->umax_value;
8171 	u64 umin_val = src_reg->umin_value;
8172 
8173 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8174 	 * be negative, then either:
8175 	 * 1) src_reg might be zero, so the sign bit of the result is
8176 	 *    unknown, so we lose our signed bounds
8177 	 * 2) it's known negative, thus the unsigned bounds capture the
8178 	 *    signed bounds
8179 	 * 3) the signed bounds cross zero, so they tell us nothing
8180 	 *    about the result
8181 	 * If the value in dst_reg is known nonnegative, then again the
8182 	 * unsigned bounds capture the signed bounds.
8183 	 * Thus, in all cases it suffices to blow away our signed bounds
8184 	 * and rely on inferring new ones from the unsigned bounds and
8185 	 * var_off of the result.
8186 	 */
8187 	dst_reg->smin_value = S64_MIN;
8188 	dst_reg->smax_value = S64_MAX;
8189 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8190 	dst_reg->umin_value >>= umax_val;
8191 	dst_reg->umax_value >>= umin_val;
8192 
8193 	/* Its not easy to operate on alu32 bounds here because it depends
8194 	 * on bits being shifted in. Take easy way out and mark unbounded
8195 	 * so we can recalculate later from tnum.
8196 	 */
8197 	__mark_reg32_unbounded(dst_reg);
8198 	__update_reg_bounds(dst_reg);
8199 }
8200 
8201 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8202 				  struct bpf_reg_state *src_reg)
8203 {
8204 	u64 umin_val = src_reg->u32_min_value;
8205 
8206 	/* Upon reaching here, src_known is true and
8207 	 * umax_val is equal to umin_val.
8208 	 */
8209 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8210 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8211 
8212 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8213 
8214 	/* blow away the dst_reg umin_value/umax_value and rely on
8215 	 * dst_reg var_off to refine the result.
8216 	 */
8217 	dst_reg->u32_min_value = 0;
8218 	dst_reg->u32_max_value = U32_MAX;
8219 
8220 	__mark_reg64_unbounded(dst_reg);
8221 	__update_reg32_bounds(dst_reg);
8222 }
8223 
8224 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8225 				struct bpf_reg_state *src_reg)
8226 {
8227 	u64 umin_val = src_reg->umin_value;
8228 
8229 	/* Upon reaching here, src_known is true and umax_val is equal
8230 	 * to umin_val.
8231 	 */
8232 	dst_reg->smin_value >>= umin_val;
8233 	dst_reg->smax_value >>= umin_val;
8234 
8235 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8236 
8237 	/* blow away the dst_reg umin_value/umax_value and rely on
8238 	 * dst_reg var_off to refine the result.
8239 	 */
8240 	dst_reg->umin_value = 0;
8241 	dst_reg->umax_value = U64_MAX;
8242 
8243 	/* Its not easy to operate on alu32 bounds here because it depends
8244 	 * on bits being shifted in from upper 32-bits. Take easy way out
8245 	 * and mark unbounded so we can recalculate later from tnum.
8246 	 */
8247 	__mark_reg32_unbounded(dst_reg);
8248 	__update_reg_bounds(dst_reg);
8249 }
8250 
8251 /* WARNING: This function does calculations on 64-bit values, but the actual
8252  * execution may occur on 32-bit values. Therefore, things like bitshifts
8253  * need extra checks in the 32-bit case.
8254  */
8255 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8256 				      struct bpf_insn *insn,
8257 				      struct bpf_reg_state *dst_reg,
8258 				      struct bpf_reg_state src_reg)
8259 {
8260 	struct bpf_reg_state *regs = cur_regs(env);
8261 	u8 opcode = BPF_OP(insn->code);
8262 	bool src_known;
8263 	s64 smin_val, smax_val;
8264 	u64 umin_val, umax_val;
8265 	s32 s32_min_val, s32_max_val;
8266 	u32 u32_min_val, u32_max_val;
8267 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8268 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8269 	int ret;
8270 
8271 	smin_val = src_reg.smin_value;
8272 	smax_val = src_reg.smax_value;
8273 	umin_val = src_reg.umin_value;
8274 	umax_val = src_reg.umax_value;
8275 
8276 	s32_min_val = src_reg.s32_min_value;
8277 	s32_max_val = src_reg.s32_max_value;
8278 	u32_min_val = src_reg.u32_min_value;
8279 	u32_max_val = src_reg.u32_max_value;
8280 
8281 	if (alu32) {
8282 		src_known = tnum_subreg_is_const(src_reg.var_off);
8283 		if ((src_known &&
8284 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8285 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8286 			/* Taint dst register if offset had invalid bounds
8287 			 * derived from e.g. dead branches.
8288 			 */
8289 			__mark_reg_unknown(env, dst_reg);
8290 			return 0;
8291 		}
8292 	} else {
8293 		src_known = tnum_is_const(src_reg.var_off);
8294 		if ((src_known &&
8295 		     (smin_val != smax_val || umin_val != umax_val)) ||
8296 		    smin_val > smax_val || umin_val > umax_val) {
8297 			/* Taint dst register if offset had invalid bounds
8298 			 * derived from e.g. dead branches.
8299 			 */
8300 			__mark_reg_unknown(env, dst_reg);
8301 			return 0;
8302 		}
8303 	}
8304 
8305 	if (!src_known &&
8306 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8307 		__mark_reg_unknown(env, dst_reg);
8308 		return 0;
8309 	}
8310 
8311 	if (sanitize_needed(opcode)) {
8312 		ret = sanitize_val_alu(env, insn);
8313 		if (ret < 0)
8314 			return sanitize_err(env, insn, ret, NULL, NULL);
8315 	}
8316 
8317 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8318 	 * There are two classes of instructions: The first class we track both
8319 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8320 	 * greatest amount of precision when alu operations are mixed with jmp32
8321 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8322 	 * and BPF_OR. This is possible because these ops have fairly easy to
8323 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8324 	 * See alu32 verifier tests for examples. The second class of
8325 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8326 	 * with regards to tracking sign/unsigned bounds because the bits may
8327 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8328 	 * the reg unbounded in the subreg bound space and use the resulting
8329 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8330 	 */
8331 	switch (opcode) {
8332 	case BPF_ADD:
8333 		scalar32_min_max_add(dst_reg, &src_reg);
8334 		scalar_min_max_add(dst_reg, &src_reg);
8335 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8336 		break;
8337 	case BPF_SUB:
8338 		scalar32_min_max_sub(dst_reg, &src_reg);
8339 		scalar_min_max_sub(dst_reg, &src_reg);
8340 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8341 		break;
8342 	case BPF_MUL:
8343 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8344 		scalar32_min_max_mul(dst_reg, &src_reg);
8345 		scalar_min_max_mul(dst_reg, &src_reg);
8346 		break;
8347 	case BPF_AND:
8348 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8349 		scalar32_min_max_and(dst_reg, &src_reg);
8350 		scalar_min_max_and(dst_reg, &src_reg);
8351 		break;
8352 	case BPF_OR:
8353 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8354 		scalar32_min_max_or(dst_reg, &src_reg);
8355 		scalar_min_max_or(dst_reg, &src_reg);
8356 		break;
8357 	case BPF_XOR:
8358 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8359 		scalar32_min_max_xor(dst_reg, &src_reg);
8360 		scalar_min_max_xor(dst_reg, &src_reg);
8361 		break;
8362 	case BPF_LSH:
8363 		if (umax_val >= insn_bitness) {
8364 			/* Shifts greater than 31 or 63 are undefined.
8365 			 * This includes shifts by a negative number.
8366 			 */
8367 			mark_reg_unknown(env, regs, insn->dst_reg);
8368 			break;
8369 		}
8370 		if (alu32)
8371 			scalar32_min_max_lsh(dst_reg, &src_reg);
8372 		else
8373 			scalar_min_max_lsh(dst_reg, &src_reg);
8374 		break;
8375 	case BPF_RSH:
8376 		if (umax_val >= insn_bitness) {
8377 			/* Shifts greater than 31 or 63 are undefined.
8378 			 * This includes shifts by a negative number.
8379 			 */
8380 			mark_reg_unknown(env, regs, insn->dst_reg);
8381 			break;
8382 		}
8383 		if (alu32)
8384 			scalar32_min_max_rsh(dst_reg, &src_reg);
8385 		else
8386 			scalar_min_max_rsh(dst_reg, &src_reg);
8387 		break;
8388 	case BPF_ARSH:
8389 		if (umax_val >= insn_bitness) {
8390 			/* Shifts greater than 31 or 63 are undefined.
8391 			 * This includes shifts by a negative number.
8392 			 */
8393 			mark_reg_unknown(env, regs, insn->dst_reg);
8394 			break;
8395 		}
8396 		if (alu32)
8397 			scalar32_min_max_arsh(dst_reg, &src_reg);
8398 		else
8399 			scalar_min_max_arsh(dst_reg, &src_reg);
8400 		break;
8401 	default:
8402 		mark_reg_unknown(env, regs, insn->dst_reg);
8403 		break;
8404 	}
8405 
8406 	/* ALU32 ops are zero extended into 64bit register */
8407 	if (alu32)
8408 		zext_32_to_64(dst_reg);
8409 
8410 	__update_reg_bounds(dst_reg);
8411 	__reg_deduce_bounds(dst_reg);
8412 	__reg_bound_offset(dst_reg);
8413 	return 0;
8414 }
8415 
8416 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8417  * and var_off.
8418  */
8419 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8420 				   struct bpf_insn *insn)
8421 {
8422 	struct bpf_verifier_state *vstate = env->cur_state;
8423 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8424 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8425 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8426 	u8 opcode = BPF_OP(insn->code);
8427 	int err;
8428 
8429 	dst_reg = &regs[insn->dst_reg];
8430 	src_reg = NULL;
8431 	if (dst_reg->type != SCALAR_VALUE)
8432 		ptr_reg = dst_reg;
8433 	else
8434 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8435 		 * incorrectly propagated into other registers by find_equal_scalars()
8436 		 */
8437 		dst_reg->id = 0;
8438 	if (BPF_SRC(insn->code) == BPF_X) {
8439 		src_reg = &regs[insn->src_reg];
8440 		if (src_reg->type != SCALAR_VALUE) {
8441 			if (dst_reg->type != SCALAR_VALUE) {
8442 				/* Combining two pointers by any ALU op yields
8443 				 * an arbitrary scalar. Disallow all math except
8444 				 * pointer subtraction
8445 				 */
8446 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8447 					mark_reg_unknown(env, regs, insn->dst_reg);
8448 					return 0;
8449 				}
8450 				verbose(env, "R%d pointer %s pointer prohibited\n",
8451 					insn->dst_reg,
8452 					bpf_alu_string[opcode >> 4]);
8453 				return -EACCES;
8454 			} else {
8455 				/* scalar += pointer
8456 				 * This is legal, but we have to reverse our
8457 				 * src/dest handling in computing the range
8458 				 */
8459 				err = mark_chain_precision(env, insn->dst_reg);
8460 				if (err)
8461 					return err;
8462 				return adjust_ptr_min_max_vals(env, insn,
8463 							       src_reg, dst_reg);
8464 			}
8465 		} else if (ptr_reg) {
8466 			/* pointer += scalar */
8467 			err = mark_chain_precision(env, insn->src_reg);
8468 			if (err)
8469 				return err;
8470 			return adjust_ptr_min_max_vals(env, insn,
8471 						       dst_reg, src_reg);
8472 		}
8473 	} else {
8474 		/* Pretend the src is a reg with a known value, since we only
8475 		 * need to be able to read from this state.
8476 		 */
8477 		off_reg.type = SCALAR_VALUE;
8478 		__mark_reg_known(&off_reg, insn->imm);
8479 		src_reg = &off_reg;
8480 		if (ptr_reg) /* pointer += K */
8481 			return adjust_ptr_min_max_vals(env, insn,
8482 						       ptr_reg, src_reg);
8483 	}
8484 
8485 	/* Got here implies adding two SCALAR_VALUEs */
8486 	if (WARN_ON_ONCE(ptr_reg)) {
8487 		print_verifier_state(env, state, true);
8488 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8489 		return -EINVAL;
8490 	}
8491 	if (WARN_ON(!src_reg)) {
8492 		print_verifier_state(env, state, true);
8493 		verbose(env, "verifier internal error: no src_reg\n");
8494 		return -EINVAL;
8495 	}
8496 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8497 }
8498 
8499 /* check validity of 32-bit and 64-bit arithmetic operations */
8500 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8501 {
8502 	struct bpf_reg_state *regs = cur_regs(env);
8503 	u8 opcode = BPF_OP(insn->code);
8504 	int err;
8505 
8506 	if (opcode == BPF_END || opcode == BPF_NEG) {
8507 		if (opcode == BPF_NEG) {
8508 			if (BPF_SRC(insn->code) != 0 ||
8509 			    insn->src_reg != BPF_REG_0 ||
8510 			    insn->off != 0 || insn->imm != 0) {
8511 				verbose(env, "BPF_NEG uses reserved fields\n");
8512 				return -EINVAL;
8513 			}
8514 		} else {
8515 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8516 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8517 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8518 				verbose(env, "BPF_END uses reserved fields\n");
8519 				return -EINVAL;
8520 			}
8521 		}
8522 
8523 		/* check src operand */
8524 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8525 		if (err)
8526 			return err;
8527 
8528 		if (is_pointer_value(env, insn->dst_reg)) {
8529 			verbose(env, "R%d pointer arithmetic prohibited\n",
8530 				insn->dst_reg);
8531 			return -EACCES;
8532 		}
8533 
8534 		/* check dest operand */
8535 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8536 		if (err)
8537 			return err;
8538 
8539 	} else if (opcode == BPF_MOV) {
8540 
8541 		if (BPF_SRC(insn->code) == BPF_X) {
8542 			if (insn->imm != 0 || insn->off != 0) {
8543 				verbose(env, "BPF_MOV uses reserved fields\n");
8544 				return -EINVAL;
8545 			}
8546 
8547 			/* check src operand */
8548 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8549 			if (err)
8550 				return err;
8551 		} else {
8552 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8553 				verbose(env, "BPF_MOV uses reserved fields\n");
8554 				return -EINVAL;
8555 			}
8556 		}
8557 
8558 		/* check dest operand, mark as required later */
8559 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8560 		if (err)
8561 			return err;
8562 
8563 		if (BPF_SRC(insn->code) == BPF_X) {
8564 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8565 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8566 
8567 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8568 				/* case: R1 = R2
8569 				 * copy register state to dest reg
8570 				 */
8571 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8572 					/* Assign src and dst registers the same ID
8573 					 * that will be used by find_equal_scalars()
8574 					 * to propagate min/max range.
8575 					 */
8576 					src_reg->id = ++env->id_gen;
8577 				*dst_reg = *src_reg;
8578 				dst_reg->live |= REG_LIVE_WRITTEN;
8579 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8580 			} else {
8581 				/* R1 = (u32) R2 */
8582 				if (is_pointer_value(env, insn->src_reg)) {
8583 					verbose(env,
8584 						"R%d partial copy of pointer\n",
8585 						insn->src_reg);
8586 					return -EACCES;
8587 				} else if (src_reg->type == SCALAR_VALUE) {
8588 					*dst_reg = *src_reg;
8589 					/* Make sure ID is cleared otherwise
8590 					 * dst_reg min/max could be incorrectly
8591 					 * propagated into src_reg by find_equal_scalars()
8592 					 */
8593 					dst_reg->id = 0;
8594 					dst_reg->live |= REG_LIVE_WRITTEN;
8595 					dst_reg->subreg_def = env->insn_idx + 1;
8596 				} else {
8597 					mark_reg_unknown(env, regs,
8598 							 insn->dst_reg);
8599 				}
8600 				zext_32_to_64(dst_reg);
8601 
8602 				__update_reg_bounds(dst_reg);
8603 				__reg_deduce_bounds(dst_reg);
8604 				__reg_bound_offset(dst_reg);
8605 			}
8606 		} else {
8607 			/* case: R = imm
8608 			 * remember the value we stored into this reg
8609 			 */
8610 			/* clear any state __mark_reg_known doesn't set */
8611 			mark_reg_unknown(env, regs, insn->dst_reg);
8612 			regs[insn->dst_reg].type = SCALAR_VALUE;
8613 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8614 				__mark_reg_known(regs + insn->dst_reg,
8615 						 insn->imm);
8616 			} else {
8617 				__mark_reg_known(regs + insn->dst_reg,
8618 						 (u32)insn->imm);
8619 			}
8620 		}
8621 
8622 	} else if (opcode > BPF_END) {
8623 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8624 		return -EINVAL;
8625 
8626 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8627 
8628 		if (BPF_SRC(insn->code) == BPF_X) {
8629 			if (insn->imm != 0 || insn->off != 0) {
8630 				verbose(env, "BPF_ALU uses reserved fields\n");
8631 				return -EINVAL;
8632 			}
8633 			/* check src1 operand */
8634 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8635 			if (err)
8636 				return err;
8637 		} else {
8638 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8639 				verbose(env, "BPF_ALU uses reserved fields\n");
8640 				return -EINVAL;
8641 			}
8642 		}
8643 
8644 		/* check src2 operand */
8645 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8646 		if (err)
8647 			return err;
8648 
8649 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8650 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8651 			verbose(env, "div by zero\n");
8652 			return -EINVAL;
8653 		}
8654 
8655 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8656 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8657 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8658 
8659 			if (insn->imm < 0 || insn->imm >= size) {
8660 				verbose(env, "invalid shift %d\n", insn->imm);
8661 				return -EINVAL;
8662 			}
8663 		}
8664 
8665 		/* check dest operand */
8666 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8667 		if (err)
8668 			return err;
8669 
8670 		return adjust_reg_min_max_vals(env, insn);
8671 	}
8672 
8673 	return 0;
8674 }
8675 
8676 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8677 				     struct bpf_reg_state *dst_reg,
8678 				     enum bpf_reg_type type, int new_range)
8679 {
8680 	struct bpf_reg_state *reg;
8681 	int i;
8682 
8683 	for (i = 0; i < MAX_BPF_REG; i++) {
8684 		reg = &state->regs[i];
8685 		if (reg->type == type && reg->id == dst_reg->id)
8686 			/* keep the maximum range already checked */
8687 			reg->range = max(reg->range, new_range);
8688 	}
8689 
8690 	bpf_for_each_spilled_reg(i, state, reg) {
8691 		if (!reg)
8692 			continue;
8693 		if (reg->type == type && reg->id == dst_reg->id)
8694 			reg->range = max(reg->range, new_range);
8695 	}
8696 }
8697 
8698 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8699 				   struct bpf_reg_state *dst_reg,
8700 				   enum bpf_reg_type type,
8701 				   bool range_right_open)
8702 {
8703 	int new_range, i;
8704 
8705 	if (dst_reg->off < 0 ||
8706 	    (dst_reg->off == 0 && range_right_open))
8707 		/* This doesn't give us any range */
8708 		return;
8709 
8710 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8711 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8712 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8713 		 * than pkt_end, but that's because it's also less than pkt.
8714 		 */
8715 		return;
8716 
8717 	new_range = dst_reg->off;
8718 	if (range_right_open)
8719 		new_range++;
8720 
8721 	/* Examples for register markings:
8722 	 *
8723 	 * pkt_data in dst register:
8724 	 *
8725 	 *   r2 = r3;
8726 	 *   r2 += 8;
8727 	 *   if (r2 > pkt_end) goto <handle exception>
8728 	 *   <access okay>
8729 	 *
8730 	 *   r2 = r3;
8731 	 *   r2 += 8;
8732 	 *   if (r2 < pkt_end) goto <access okay>
8733 	 *   <handle exception>
8734 	 *
8735 	 *   Where:
8736 	 *     r2 == dst_reg, pkt_end == src_reg
8737 	 *     r2=pkt(id=n,off=8,r=0)
8738 	 *     r3=pkt(id=n,off=0,r=0)
8739 	 *
8740 	 * pkt_data in src register:
8741 	 *
8742 	 *   r2 = r3;
8743 	 *   r2 += 8;
8744 	 *   if (pkt_end >= r2) goto <access okay>
8745 	 *   <handle exception>
8746 	 *
8747 	 *   r2 = r3;
8748 	 *   r2 += 8;
8749 	 *   if (pkt_end <= r2) goto <handle exception>
8750 	 *   <access okay>
8751 	 *
8752 	 *   Where:
8753 	 *     pkt_end == dst_reg, r2 == src_reg
8754 	 *     r2=pkt(id=n,off=8,r=0)
8755 	 *     r3=pkt(id=n,off=0,r=0)
8756 	 *
8757 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8758 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8759 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8760 	 * the check.
8761 	 */
8762 
8763 	/* If our ids match, then we must have the same max_value.  And we
8764 	 * don't care about the other reg's fixed offset, since if it's too big
8765 	 * the range won't allow anything.
8766 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8767 	 */
8768 	for (i = 0; i <= vstate->curframe; i++)
8769 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8770 					 new_range);
8771 }
8772 
8773 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8774 {
8775 	struct tnum subreg = tnum_subreg(reg->var_off);
8776 	s32 sval = (s32)val;
8777 
8778 	switch (opcode) {
8779 	case BPF_JEQ:
8780 		if (tnum_is_const(subreg))
8781 			return !!tnum_equals_const(subreg, val);
8782 		break;
8783 	case BPF_JNE:
8784 		if (tnum_is_const(subreg))
8785 			return !tnum_equals_const(subreg, val);
8786 		break;
8787 	case BPF_JSET:
8788 		if ((~subreg.mask & subreg.value) & val)
8789 			return 1;
8790 		if (!((subreg.mask | subreg.value) & val))
8791 			return 0;
8792 		break;
8793 	case BPF_JGT:
8794 		if (reg->u32_min_value > val)
8795 			return 1;
8796 		else if (reg->u32_max_value <= val)
8797 			return 0;
8798 		break;
8799 	case BPF_JSGT:
8800 		if (reg->s32_min_value > sval)
8801 			return 1;
8802 		else if (reg->s32_max_value <= sval)
8803 			return 0;
8804 		break;
8805 	case BPF_JLT:
8806 		if (reg->u32_max_value < val)
8807 			return 1;
8808 		else if (reg->u32_min_value >= val)
8809 			return 0;
8810 		break;
8811 	case BPF_JSLT:
8812 		if (reg->s32_max_value < sval)
8813 			return 1;
8814 		else if (reg->s32_min_value >= sval)
8815 			return 0;
8816 		break;
8817 	case BPF_JGE:
8818 		if (reg->u32_min_value >= val)
8819 			return 1;
8820 		else if (reg->u32_max_value < val)
8821 			return 0;
8822 		break;
8823 	case BPF_JSGE:
8824 		if (reg->s32_min_value >= sval)
8825 			return 1;
8826 		else if (reg->s32_max_value < sval)
8827 			return 0;
8828 		break;
8829 	case BPF_JLE:
8830 		if (reg->u32_max_value <= val)
8831 			return 1;
8832 		else if (reg->u32_min_value > val)
8833 			return 0;
8834 		break;
8835 	case BPF_JSLE:
8836 		if (reg->s32_max_value <= sval)
8837 			return 1;
8838 		else if (reg->s32_min_value > sval)
8839 			return 0;
8840 		break;
8841 	}
8842 
8843 	return -1;
8844 }
8845 
8846 
8847 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8848 {
8849 	s64 sval = (s64)val;
8850 
8851 	switch (opcode) {
8852 	case BPF_JEQ:
8853 		if (tnum_is_const(reg->var_off))
8854 			return !!tnum_equals_const(reg->var_off, val);
8855 		break;
8856 	case BPF_JNE:
8857 		if (tnum_is_const(reg->var_off))
8858 			return !tnum_equals_const(reg->var_off, val);
8859 		break;
8860 	case BPF_JSET:
8861 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8862 			return 1;
8863 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8864 			return 0;
8865 		break;
8866 	case BPF_JGT:
8867 		if (reg->umin_value > val)
8868 			return 1;
8869 		else if (reg->umax_value <= val)
8870 			return 0;
8871 		break;
8872 	case BPF_JSGT:
8873 		if (reg->smin_value > sval)
8874 			return 1;
8875 		else if (reg->smax_value <= sval)
8876 			return 0;
8877 		break;
8878 	case BPF_JLT:
8879 		if (reg->umax_value < val)
8880 			return 1;
8881 		else if (reg->umin_value >= val)
8882 			return 0;
8883 		break;
8884 	case BPF_JSLT:
8885 		if (reg->smax_value < sval)
8886 			return 1;
8887 		else if (reg->smin_value >= sval)
8888 			return 0;
8889 		break;
8890 	case BPF_JGE:
8891 		if (reg->umin_value >= val)
8892 			return 1;
8893 		else if (reg->umax_value < val)
8894 			return 0;
8895 		break;
8896 	case BPF_JSGE:
8897 		if (reg->smin_value >= sval)
8898 			return 1;
8899 		else if (reg->smax_value < sval)
8900 			return 0;
8901 		break;
8902 	case BPF_JLE:
8903 		if (reg->umax_value <= val)
8904 			return 1;
8905 		else if (reg->umin_value > val)
8906 			return 0;
8907 		break;
8908 	case BPF_JSLE:
8909 		if (reg->smax_value <= sval)
8910 			return 1;
8911 		else if (reg->smin_value > sval)
8912 			return 0;
8913 		break;
8914 	}
8915 
8916 	return -1;
8917 }
8918 
8919 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8920  * and return:
8921  *  1 - branch will be taken and "goto target" will be executed
8922  *  0 - branch will not be taken and fall-through to next insn
8923  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8924  *      range [0,10]
8925  */
8926 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8927 			   bool is_jmp32)
8928 {
8929 	if (__is_pointer_value(false, reg)) {
8930 		if (!reg_type_not_null(reg->type))
8931 			return -1;
8932 
8933 		/* If pointer is valid tests against zero will fail so we can
8934 		 * use this to direct branch taken.
8935 		 */
8936 		if (val != 0)
8937 			return -1;
8938 
8939 		switch (opcode) {
8940 		case BPF_JEQ:
8941 			return 0;
8942 		case BPF_JNE:
8943 			return 1;
8944 		default:
8945 			return -1;
8946 		}
8947 	}
8948 
8949 	if (is_jmp32)
8950 		return is_branch32_taken(reg, val, opcode);
8951 	return is_branch64_taken(reg, val, opcode);
8952 }
8953 
8954 static int flip_opcode(u32 opcode)
8955 {
8956 	/* How can we transform "a <op> b" into "b <op> a"? */
8957 	static const u8 opcode_flip[16] = {
8958 		/* these stay the same */
8959 		[BPF_JEQ  >> 4] = BPF_JEQ,
8960 		[BPF_JNE  >> 4] = BPF_JNE,
8961 		[BPF_JSET >> 4] = BPF_JSET,
8962 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8963 		[BPF_JGE  >> 4] = BPF_JLE,
8964 		[BPF_JGT  >> 4] = BPF_JLT,
8965 		[BPF_JLE  >> 4] = BPF_JGE,
8966 		[BPF_JLT  >> 4] = BPF_JGT,
8967 		[BPF_JSGE >> 4] = BPF_JSLE,
8968 		[BPF_JSGT >> 4] = BPF_JSLT,
8969 		[BPF_JSLE >> 4] = BPF_JSGE,
8970 		[BPF_JSLT >> 4] = BPF_JSGT
8971 	};
8972 	return opcode_flip[opcode >> 4];
8973 }
8974 
8975 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8976 				   struct bpf_reg_state *src_reg,
8977 				   u8 opcode)
8978 {
8979 	struct bpf_reg_state *pkt;
8980 
8981 	if (src_reg->type == PTR_TO_PACKET_END) {
8982 		pkt = dst_reg;
8983 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8984 		pkt = src_reg;
8985 		opcode = flip_opcode(opcode);
8986 	} else {
8987 		return -1;
8988 	}
8989 
8990 	if (pkt->range >= 0)
8991 		return -1;
8992 
8993 	switch (opcode) {
8994 	case BPF_JLE:
8995 		/* pkt <= pkt_end */
8996 		fallthrough;
8997 	case BPF_JGT:
8998 		/* pkt > pkt_end */
8999 		if (pkt->range == BEYOND_PKT_END)
9000 			/* pkt has at last one extra byte beyond pkt_end */
9001 			return opcode == BPF_JGT;
9002 		break;
9003 	case BPF_JLT:
9004 		/* pkt < pkt_end */
9005 		fallthrough;
9006 	case BPF_JGE:
9007 		/* pkt >= pkt_end */
9008 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9009 			return opcode == BPF_JGE;
9010 		break;
9011 	}
9012 	return -1;
9013 }
9014 
9015 /* Adjusts the register min/max values in the case that the dst_reg is the
9016  * variable register that we are working on, and src_reg is a constant or we're
9017  * simply doing a BPF_K check.
9018  * In JEQ/JNE cases we also adjust the var_off values.
9019  */
9020 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9021 			    struct bpf_reg_state *false_reg,
9022 			    u64 val, u32 val32,
9023 			    u8 opcode, bool is_jmp32)
9024 {
9025 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9026 	struct tnum false_64off = false_reg->var_off;
9027 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9028 	struct tnum true_64off = true_reg->var_off;
9029 	s64 sval = (s64)val;
9030 	s32 sval32 = (s32)val32;
9031 
9032 	/* If the dst_reg is a pointer, we can't learn anything about its
9033 	 * variable offset from the compare (unless src_reg were a pointer into
9034 	 * the same object, but we don't bother with that.
9035 	 * Since false_reg and true_reg have the same type by construction, we
9036 	 * only need to check one of them for pointerness.
9037 	 */
9038 	if (__is_pointer_value(false, false_reg))
9039 		return;
9040 
9041 	switch (opcode) {
9042 	case BPF_JEQ:
9043 	case BPF_JNE:
9044 	{
9045 		struct bpf_reg_state *reg =
9046 			opcode == BPF_JEQ ? true_reg : false_reg;
9047 
9048 		/* JEQ/JNE comparison doesn't change the register equivalence.
9049 		 * r1 = r2;
9050 		 * if (r1 == 42) goto label;
9051 		 * ...
9052 		 * label: // here both r1 and r2 are known to be 42.
9053 		 *
9054 		 * Hence when marking register as known preserve it's ID.
9055 		 */
9056 		if (is_jmp32)
9057 			__mark_reg32_known(reg, val32);
9058 		else
9059 			___mark_reg_known(reg, val);
9060 		break;
9061 	}
9062 	case BPF_JSET:
9063 		if (is_jmp32) {
9064 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9065 			if (is_power_of_2(val32))
9066 				true_32off = tnum_or(true_32off,
9067 						     tnum_const(val32));
9068 		} else {
9069 			false_64off = tnum_and(false_64off, tnum_const(~val));
9070 			if (is_power_of_2(val))
9071 				true_64off = tnum_or(true_64off,
9072 						     tnum_const(val));
9073 		}
9074 		break;
9075 	case BPF_JGE:
9076 	case BPF_JGT:
9077 	{
9078 		if (is_jmp32) {
9079 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9080 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9081 
9082 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9083 						       false_umax);
9084 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9085 						      true_umin);
9086 		} else {
9087 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9088 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9089 
9090 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9091 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9092 		}
9093 		break;
9094 	}
9095 	case BPF_JSGE:
9096 	case BPF_JSGT:
9097 	{
9098 		if (is_jmp32) {
9099 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9100 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9101 
9102 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9103 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9104 		} else {
9105 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9106 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9107 
9108 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9109 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9110 		}
9111 		break;
9112 	}
9113 	case BPF_JLE:
9114 	case BPF_JLT:
9115 	{
9116 		if (is_jmp32) {
9117 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9118 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9119 
9120 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9121 						       false_umin);
9122 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9123 						      true_umax);
9124 		} else {
9125 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9126 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9127 
9128 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9129 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9130 		}
9131 		break;
9132 	}
9133 	case BPF_JSLE:
9134 	case BPF_JSLT:
9135 	{
9136 		if (is_jmp32) {
9137 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9138 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9139 
9140 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9141 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9142 		} else {
9143 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9144 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9145 
9146 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9147 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9148 		}
9149 		break;
9150 	}
9151 	default:
9152 		return;
9153 	}
9154 
9155 	if (is_jmp32) {
9156 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9157 					     tnum_subreg(false_32off));
9158 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9159 					    tnum_subreg(true_32off));
9160 		__reg_combine_32_into_64(false_reg);
9161 		__reg_combine_32_into_64(true_reg);
9162 	} else {
9163 		false_reg->var_off = false_64off;
9164 		true_reg->var_off = true_64off;
9165 		__reg_combine_64_into_32(false_reg);
9166 		__reg_combine_64_into_32(true_reg);
9167 	}
9168 }
9169 
9170 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9171  * the variable reg.
9172  */
9173 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9174 				struct bpf_reg_state *false_reg,
9175 				u64 val, u32 val32,
9176 				u8 opcode, bool is_jmp32)
9177 {
9178 	opcode = flip_opcode(opcode);
9179 	/* This uses zero as "not present in table"; luckily the zero opcode,
9180 	 * BPF_JA, can't get here.
9181 	 */
9182 	if (opcode)
9183 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9184 }
9185 
9186 /* Regs are known to be equal, so intersect their min/max/var_off */
9187 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9188 				  struct bpf_reg_state *dst_reg)
9189 {
9190 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9191 							dst_reg->umin_value);
9192 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9193 							dst_reg->umax_value);
9194 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9195 							dst_reg->smin_value);
9196 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9197 							dst_reg->smax_value);
9198 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9199 							     dst_reg->var_off);
9200 	/* We might have learned new bounds from the var_off. */
9201 	__update_reg_bounds(src_reg);
9202 	__update_reg_bounds(dst_reg);
9203 	/* We might have learned something about the sign bit. */
9204 	__reg_deduce_bounds(src_reg);
9205 	__reg_deduce_bounds(dst_reg);
9206 	/* We might have learned some bits from the bounds. */
9207 	__reg_bound_offset(src_reg);
9208 	__reg_bound_offset(dst_reg);
9209 	/* Intersecting with the old var_off might have improved our bounds
9210 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
9211 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
9212 	 */
9213 	__update_reg_bounds(src_reg);
9214 	__update_reg_bounds(dst_reg);
9215 }
9216 
9217 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9218 				struct bpf_reg_state *true_dst,
9219 				struct bpf_reg_state *false_src,
9220 				struct bpf_reg_state *false_dst,
9221 				u8 opcode)
9222 {
9223 	switch (opcode) {
9224 	case BPF_JEQ:
9225 		__reg_combine_min_max(true_src, true_dst);
9226 		break;
9227 	case BPF_JNE:
9228 		__reg_combine_min_max(false_src, false_dst);
9229 		break;
9230 	}
9231 }
9232 
9233 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9234 				 struct bpf_reg_state *reg, u32 id,
9235 				 bool is_null)
9236 {
9237 	if (type_may_be_null(reg->type) && reg->id == id &&
9238 	    !WARN_ON_ONCE(!reg->id)) {
9239 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9240 				 !tnum_equals_const(reg->var_off, 0) ||
9241 				 reg->off)) {
9242 			/* Old offset (both fixed and variable parts) should
9243 			 * have been known-zero, because we don't allow pointer
9244 			 * arithmetic on pointers that might be NULL. If we
9245 			 * see this happening, don't convert the register.
9246 			 */
9247 			return;
9248 		}
9249 		if (is_null) {
9250 			reg->type = SCALAR_VALUE;
9251 			/* We don't need id and ref_obj_id from this point
9252 			 * onwards anymore, thus we should better reset it,
9253 			 * so that state pruning has chances to take effect.
9254 			 */
9255 			reg->id = 0;
9256 			reg->ref_obj_id = 0;
9257 
9258 			return;
9259 		}
9260 
9261 		mark_ptr_not_null_reg(reg);
9262 
9263 		if (!reg_may_point_to_spin_lock(reg)) {
9264 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9265 			 * in release_reg_references().
9266 			 *
9267 			 * reg->id is still used by spin_lock ptr. Other
9268 			 * than spin_lock ptr type, reg->id can be reset.
9269 			 */
9270 			reg->id = 0;
9271 		}
9272 	}
9273 }
9274 
9275 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9276 				    bool is_null)
9277 {
9278 	struct bpf_reg_state *reg;
9279 	int i;
9280 
9281 	for (i = 0; i < MAX_BPF_REG; i++)
9282 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9283 
9284 	bpf_for_each_spilled_reg(i, state, reg) {
9285 		if (!reg)
9286 			continue;
9287 		mark_ptr_or_null_reg(state, reg, id, is_null);
9288 	}
9289 }
9290 
9291 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9292  * be folded together at some point.
9293  */
9294 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9295 				  bool is_null)
9296 {
9297 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9298 	struct bpf_reg_state *regs = state->regs;
9299 	u32 ref_obj_id = regs[regno].ref_obj_id;
9300 	u32 id = regs[regno].id;
9301 	int i;
9302 
9303 	if (ref_obj_id && ref_obj_id == id && is_null)
9304 		/* regs[regno] is in the " == NULL" branch.
9305 		 * No one could have freed the reference state before
9306 		 * doing the NULL check.
9307 		 */
9308 		WARN_ON_ONCE(release_reference_state(state, id));
9309 
9310 	for (i = 0; i <= vstate->curframe; i++)
9311 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9312 }
9313 
9314 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9315 				   struct bpf_reg_state *dst_reg,
9316 				   struct bpf_reg_state *src_reg,
9317 				   struct bpf_verifier_state *this_branch,
9318 				   struct bpf_verifier_state *other_branch)
9319 {
9320 	if (BPF_SRC(insn->code) != BPF_X)
9321 		return false;
9322 
9323 	/* Pointers are always 64-bit. */
9324 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9325 		return false;
9326 
9327 	switch (BPF_OP(insn->code)) {
9328 	case BPF_JGT:
9329 		if ((dst_reg->type == PTR_TO_PACKET &&
9330 		     src_reg->type == PTR_TO_PACKET_END) ||
9331 		    (dst_reg->type == PTR_TO_PACKET_META &&
9332 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9333 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9334 			find_good_pkt_pointers(this_branch, dst_reg,
9335 					       dst_reg->type, false);
9336 			mark_pkt_end(other_branch, insn->dst_reg, true);
9337 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9338 			    src_reg->type == PTR_TO_PACKET) ||
9339 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9340 			    src_reg->type == PTR_TO_PACKET_META)) {
9341 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9342 			find_good_pkt_pointers(other_branch, src_reg,
9343 					       src_reg->type, true);
9344 			mark_pkt_end(this_branch, insn->src_reg, false);
9345 		} else {
9346 			return false;
9347 		}
9348 		break;
9349 	case BPF_JLT:
9350 		if ((dst_reg->type == PTR_TO_PACKET &&
9351 		     src_reg->type == PTR_TO_PACKET_END) ||
9352 		    (dst_reg->type == PTR_TO_PACKET_META &&
9353 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9354 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9355 			find_good_pkt_pointers(other_branch, dst_reg,
9356 					       dst_reg->type, true);
9357 			mark_pkt_end(this_branch, insn->dst_reg, false);
9358 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9359 			    src_reg->type == PTR_TO_PACKET) ||
9360 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9361 			    src_reg->type == PTR_TO_PACKET_META)) {
9362 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9363 			find_good_pkt_pointers(this_branch, src_reg,
9364 					       src_reg->type, false);
9365 			mark_pkt_end(other_branch, insn->src_reg, true);
9366 		} else {
9367 			return false;
9368 		}
9369 		break;
9370 	case BPF_JGE:
9371 		if ((dst_reg->type == PTR_TO_PACKET &&
9372 		     src_reg->type == PTR_TO_PACKET_END) ||
9373 		    (dst_reg->type == PTR_TO_PACKET_META &&
9374 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9375 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9376 			find_good_pkt_pointers(this_branch, dst_reg,
9377 					       dst_reg->type, true);
9378 			mark_pkt_end(other_branch, insn->dst_reg, false);
9379 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9380 			    src_reg->type == PTR_TO_PACKET) ||
9381 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9382 			    src_reg->type == PTR_TO_PACKET_META)) {
9383 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9384 			find_good_pkt_pointers(other_branch, src_reg,
9385 					       src_reg->type, false);
9386 			mark_pkt_end(this_branch, insn->src_reg, true);
9387 		} else {
9388 			return false;
9389 		}
9390 		break;
9391 	case BPF_JLE:
9392 		if ((dst_reg->type == PTR_TO_PACKET &&
9393 		     src_reg->type == PTR_TO_PACKET_END) ||
9394 		    (dst_reg->type == PTR_TO_PACKET_META &&
9395 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9396 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9397 			find_good_pkt_pointers(other_branch, dst_reg,
9398 					       dst_reg->type, false);
9399 			mark_pkt_end(this_branch, insn->dst_reg, true);
9400 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9401 			    src_reg->type == PTR_TO_PACKET) ||
9402 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9403 			    src_reg->type == PTR_TO_PACKET_META)) {
9404 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9405 			find_good_pkt_pointers(this_branch, src_reg,
9406 					       src_reg->type, true);
9407 			mark_pkt_end(other_branch, insn->src_reg, false);
9408 		} else {
9409 			return false;
9410 		}
9411 		break;
9412 	default:
9413 		return false;
9414 	}
9415 
9416 	return true;
9417 }
9418 
9419 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9420 			       struct bpf_reg_state *known_reg)
9421 {
9422 	struct bpf_func_state *state;
9423 	struct bpf_reg_state *reg;
9424 	int i, j;
9425 
9426 	for (i = 0; i <= vstate->curframe; i++) {
9427 		state = vstate->frame[i];
9428 		for (j = 0; j < MAX_BPF_REG; j++) {
9429 			reg = &state->regs[j];
9430 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9431 				*reg = *known_reg;
9432 		}
9433 
9434 		bpf_for_each_spilled_reg(j, state, reg) {
9435 			if (!reg)
9436 				continue;
9437 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9438 				*reg = *known_reg;
9439 		}
9440 	}
9441 }
9442 
9443 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9444 			     struct bpf_insn *insn, int *insn_idx)
9445 {
9446 	struct bpf_verifier_state *this_branch = env->cur_state;
9447 	struct bpf_verifier_state *other_branch;
9448 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9449 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9450 	u8 opcode = BPF_OP(insn->code);
9451 	bool is_jmp32;
9452 	int pred = -1;
9453 	int err;
9454 
9455 	/* Only conditional jumps are expected to reach here. */
9456 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9457 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9458 		return -EINVAL;
9459 	}
9460 
9461 	if (BPF_SRC(insn->code) == BPF_X) {
9462 		if (insn->imm != 0) {
9463 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9464 			return -EINVAL;
9465 		}
9466 
9467 		/* check src1 operand */
9468 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9469 		if (err)
9470 			return err;
9471 
9472 		if (is_pointer_value(env, insn->src_reg)) {
9473 			verbose(env, "R%d pointer comparison prohibited\n",
9474 				insn->src_reg);
9475 			return -EACCES;
9476 		}
9477 		src_reg = &regs[insn->src_reg];
9478 	} else {
9479 		if (insn->src_reg != BPF_REG_0) {
9480 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9481 			return -EINVAL;
9482 		}
9483 	}
9484 
9485 	/* check src2 operand */
9486 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9487 	if (err)
9488 		return err;
9489 
9490 	dst_reg = &regs[insn->dst_reg];
9491 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9492 
9493 	if (BPF_SRC(insn->code) == BPF_K) {
9494 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9495 	} else if (src_reg->type == SCALAR_VALUE &&
9496 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9497 		pred = is_branch_taken(dst_reg,
9498 				       tnum_subreg(src_reg->var_off).value,
9499 				       opcode,
9500 				       is_jmp32);
9501 	} else if (src_reg->type == SCALAR_VALUE &&
9502 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9503 		pred = is_branch_taken(dst_reg,
9504 				       src_reg->var_off.value,
9505 				       opcode,
9506 				       is_jmp32);
9507 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9508 		   reg_is_pkt_pointer_any(src_reg) &&
9509 		   !is_jmp32) {
9510 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9511 	}
9512 
9513 	if (pred >= 0) {
9514 		/* If we get here with a dst_reg pointer type it is because
9515 		 * above is_branch_taken() special cased the 0 comparison.
9516 		 */
9517 		if (!__is_pointer_value(false, dst_reg))
9518 			err = mark_chain_precision(env, insn->dst_reg);
9519 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9520 		    !__is_pointer_value(false, src_reg))
9521 			err = mark_chain_precision(env, insn->src_reg);
9522 		if (err)
9523 			return err;
9524 	}
9525 
9526 	if (pred == 1) {
9527 		/* Only follow the goto, ignore fall-through. If needed, push
9528 		 * the fall-through branch for simulation under speculative
9529 		 * execution.
9530 		 */
9531 		if (!env->bypass_spec_v1 &&
9532 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9533 					       *insn_idx))
9534 			return -EFAULT;
9535 		*insn_idx += insn->off;
9536 		return 0;
9537 	} else if (pred == 0) {
9538 		/* Only follow the fall-through branch, since that's where the
9539 		 * program will go. If needed, push the goto branch for
9540 		 * simulation under speculative execution.
9541 		 */
9542 		if (!env->bypass_spec_v1 &&
9543 		    !sanitize_speculative_path(env, insn,
9544 					       *insn_idx + insn->off + 1,
9545 					       *insn_idx))
9546 			return -EFAULT;
9547 		return 0;
9548 	}
9549 
9550 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9551 				  false);
9552 	if (!other_branch)
9553 		return -EFAULT;
9554 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9555 
9556 	/* detect if we are comparing against a constant value so we can adjust
9557 	 * our min/max values for our dst register.
9558 	 * this is only legit if both are scalars (or pointers to the same
9559 	 * object, I suppose, but we don't support that right now), because
9560 	 * otherwise the different base pointers mean the offsets aren't
9561 	 * comparable.
9562 	 */
9563 	if (BPF_SRC(insn->code) == BPF_X) {
9564 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9565 
9566 		if (dst_reg->type == SCALAR_VALUE &&
9567 		    src_reg->type == SCALAR_VALUE) {
9568 			if (tnum_is_const(src_reg->var_off) ||
9569 			    (is_jmp32 &&
9570 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9571 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9572 						dst_reg,
9573 						src_reg->var_off.value,
9574 						tnum_subreg(src_reg->var_off).value,
9575 						opcode, is_jmp32);
9576 			else if (tnum_is_const(dst_reg->var_off) ||
9577 				 (is_jmp32 &&
9578 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9579 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9580 						    src_reg,
9581 						    dst_reg->var_off.value,
9582 						    tnum_subreg(dst_reg->var_off).value,
9583 						    opcode, is_jmp32);
9584 			else if (!is_jmp32 &&
9585 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9586 				/* Comparing for equality, we can combine knowledge */
9587 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9588 						    &other_branch_regs[insn->dst_reg],
9589 						    src_reg, dst_reg, opcode);
9590 			if (src_reg->id &&
9591 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9592 				find_equal_scalars(this_branch, src_reg);
9593 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9594 			}
9595 
9596 		}
9597 	} else if (dst_reg->type == SCALAR_VALUE) {
9598 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9599 					dst_reg, insn->imm, (u32)insn->imm,
9600 					opcode, is_jmp32);
9601 	}
9602 
9603 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9604 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9605 		find_equal_scalars(this_branch, dst_reg);
9606 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9607 	}
9608 
9609 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9610 	 * NOTE: these optimizations below are related with pointer comparison
9611 	 *       which will never be JMP32.
9612 	 */
9613 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9614 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9615 	    type_may_be_null(dst_reg->type)) {
9616 		/* Mark all identical registers in each branch as either
9617 		 * safe or unknown depending R == 0 or R != 0 conditional.
9618 		 */
9619 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9620 				      opcode == BPF_JNE);
9621 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9622 				      opcode == BPF_JEQ);
9623 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9624 					   this_branch, other_branch) &&
9625 		   is_pointer_value(env, insn->dst_reg)) {
9626 		verbose(env, "R%d pointer comparison prohibited\n",
9627 			insn->dst_reg);
9628 		return -EACCES;
9629 	}
9630 	if (env->log.level & BPF_LOG_LEVEL)
9631 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
9632 	return 0;
9633 }
9634 
9635 /* verify BPF_LD_IMM64 instruction */
9636 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9637 {
9638 	struct bpf_insn_aux_data *aux = cur_aux(env);
9639 	struct bpf_reg_state *regs = cur_regs(env);
9640 	struct bpf_reg_state *dst_reg;
9641 	struct bpf_map *map;
9642 	int err;
9643 
9644 	if (BPF_SIZE(insn->code) != BPF_DW) {
9645 		verbose(env, "invalid BPF_LD_IMM insn\n");
9646 		return -EINVAL;
9647 	}
9648 	if (insn->off != 0) {
9649 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9650 		return -EINVAL;
9651 	}
9652 
9653 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9654 	if (err)
9655 		return err;
9656 
9657 	dst_reg = &regs[insn->dst_reg];
9658 	if (insn->src_reg == 0) {
9659 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9660 
9661 		dst_reg->type = SCALAR_VALUE;
9662 		__mark_reg_known(&regs[insn->dst_reg], imm);
9663 		return 0;
9664 	}
9665 
9666 	/* All special src_reg cases are listed below. From this point onwards
9667 	 * we either succeed and assign a corresponding dst_reg->type after
9668 	 * zeroing the offset, or fail and reject the program.
9669 	 */
9670 	mark_reg_known_zero(env, regs, insn->dst_reg);
9671 
9672 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9673 		dst_reg->type = aux->btf_var.reg_type;
9674 		switch (base_type(dst_reg->type)) {
9675 		case PTR_TO_MEM:
9676 			dst_reg->mem_size = aux->btf_var.mem_size;
9677 			break;
9678 		case PTR_TO_BTF_ID:
9679 			dst_reg->btf = aux->btf_var.btf;
9680 			dst_reg->btf_id = aux->btf_var.btf_id;
9681 			break;
9682 		default:
9683 			verbose(env, "bpf verifier is misconfigured\n");
9684 			return -EFAULT;
9685 		}
9686 		return 0;
9687 	}
9688 
9689 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9690 		struct bpf_prog_aux *aux = env->prog->aux;
9691 		u32 subprogno = find_subprog(env,
9692 					     env->insn_idx + insn->imm + 1);
9693 
9694 		if (!aux->func_info) {
9695 			verbose(env, "missing btf func_info\n");
9696 			return -EINVAL;
9697 		}
9698 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9699 			verbose(env, "callback function not static\n");
9700 			return -EINVAL;
9701 		}
9702 
9703 		dst_reg->type = PTR_TO_FUNC;
9704 		dst_reg->subprogno = subprogno;
9705 		return 0;
9706 	}
9707 
9708 	map = env->used_maps[aux->map_index];
9709 	dst_reg->map_ptr = map;
9710 
9711 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9712 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9713 		dst_reg->type = PTR_TO_MAP_VALUE;
9714 		dst_reg->off = aux->map_off;
9715 		if (map_value_has_spin_lock(map))
9716 			dst_reg->id = ++env->id_gen;
9717 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9718 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9719 		dst_reg->type = CONST_PTR_TO_MAP;
9720 	} else {
9721 		verbose(env, "bpf verifier is misconfigured\n");
9722 		return -EINVAL;
9723 	}
9724 
9725 	return 0;
9726 }
9727 
9728 static bool may_access_skb(enum bpf_prog_type type)
9729 {
9730 	switch (type) {
9731 	case BPF_PROG_TYPE_SOCKET_FILTER:
9732 	case BPF_PROG_TYPE_SCHED_CLS:
9733 	case BPF_PROG_TYPE_SCHED_ACT:
9734 		return true;
9735 	default:
9736 		return false;
9737 	}
9738 }
9739 
9740 /* verify safety of LD_ABS|LD_IND instructions:
9741  * - they can only appear in the programs where ctx == skb
9742  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9743  *   preserve R6-R9, and store return value into R0
9744  *
9745  * Implicit input:
9746  *   ctx == skb == R6 == CTX
9747  *
9748  * Explicit input:
9749  *   SRC == any register
9750  *   IMM == 32-bit immediate
9751  *
9752  * Output:
9753  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9754  */
9755 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9756 {
9757 	struct bpf_reg_state *regs = cur_regs(env);
9758 	static const int ctx_reg = BPF_REG_6;
9759 	u8 mode = BPF_MODE(insn->code);
9760 	int i, err;
9761 
9762 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9763 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9764 		return -EINVAL;
9765 	}
9766 
9767 	if (!env->ops->gen_ld_abs) {
9768 		verbose(env, "bpf verifier is misconfigured\n");
9769 		return -EINVAL;
9770 	}
9771 
9772 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9773 	    BPF_SIZE(insn->code) == BPF_DW ||
9774 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9775 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9776 		return -EINVAL;
9777 	}
9778 
9779 	/* check whether implicit source operand (register R6) is readable */
9780 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9781 	if (err)
9782 		return err;
9783 
9784 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9785 	 * gen_ld_abs() may terminate the program at runtime, leading to
9786 	 * reference leak.
9787 	 */
9788 	err = check_reference_leak(env);
9789 	if (err) {
9790 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9791 		return err;
9792 	}
9793 
9794 	if (env->cur_state->active_spin_lock) {
9795 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9796 		return -EINVAL;
9797 	}
9798 
9799 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9800 		verbose(env,
9801 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9802 		return -EINVAL;
9803 	}
9804 
9805 	if (mode == BPF_IND) {
9806 		/* check explicit source operand */
9807 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9808 		if (err)
9809 			return err;
9810 	}
9811 
9812 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
9813 	if (err < 0)
9814 		return err;
9815 
9816 	/* reset caller saved regs to unreadable */
9817 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9818 		mark_reg_not_init(env, regs, caller_saved[i]);
9819 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9820 	}
9821 
9822 	/* mark destination R0 register as readable, since it contains
9823 	 * the value fetched from the packet.
9824 	 * Already marked as written above.
9825 	 */
9826 	mark_reg_unknown(env, regs, BPF_REG_0);
9827 	/* ld_abs load up to 32-bit skb data. */
9828 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9829 	return 0;
9830 }
9831 
9832 static int check_return_code(struct bpf_verifier_env *env)
9833 {
9834 	struct tnum enforce_attach_type_range = tnum_unknown;
9835 	const struct bpf_prog *prog = env->prog;
9836 	struct bpf_reg_state *reg;
9837 	struct tnum range = tnum_range(0, 1);
9838 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9839 	int err;
9840 	struct bpf_func_state *frame = env->cur_state->frame[0];
9841 	const bool is_subprog = frame->subprogno;
9842 
9843 	/* LSM and struct_ops func-ptr's return type could be "void" */
9844 	if (!is_subprog &&
9845 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9846 	     prog_type == BPF_PROG_TYPE_LSM) &&
9847 	    !prog->aux->attach_func_proto->type)
9848 		return 0;
9849 
9850 	/* eBPF calling convention is such that R0 is used
9851 	 * to return the value from eBPF program.
9852 	 * Make sure that it's readable at this time
9853 	 * of bpf_exit, which means that program wrote
9854 	 * something into it earlier
9855 	 */
9856 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9857 	if (err)
9858 		return err;
9859 
9860 	if (is_pointer_value(env, BPF_REG_0)) {
9861 		verbose(env, "R0 leaks addr as return value\n");
9862 		return -EACCES;
9863 	}
9864 
9865 	reg = cur_regs(env) + BPF_REG_0;
9866 
9867 	if (frame->in_async_callback_fn) {
9868 		/* enforce return zero from async callbacks like timer */
9869 		if (reg->type != SCALAR_VALUE) {
9870 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9871 				reg_type_str(env, reg->type));
9872 			return -EINVAL;
9873 		}
9874 
9875 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9876 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9877 			return -EINVAL;
9878 		}
9879 		return 0;
9880 	}
9881 
9882 	if (is_subprog) {
9883 		if (reg->type != SCALAR_VALUE) {
9884 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9885 				reg_type_str(env, reg->type));
9886 			return -EINVAL;
9887 		}
9888 		return 0;
9889 	}
9890 
9891 	switch (prog_type) {
9892 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9893 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9894 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9895 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9896 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9897 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9898 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9899 			range = tnum_range(1, 1);
9900 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9901 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9902 			range = tnum_range(0, 3);
9903 		break;
9904 	case BPF_PROG_TYPE_CGROUP_SKB:
9905 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9906 			range = tnum_range(0, 3);
9907 			enforce_attach_type_range = tnum_range(2, 3);
9908 		}
9909 		break;
9910 	case BPF_PROG_TYPE_CGROUP_SOCK:
9911 	case BPF_PROG_TYPE_SOCK_OPS:
9912 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9913 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9914 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9915 		break;
9916 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9917 		if (!env->prog->aux->attach_btf_id)
9918 			return 0;
9919 		range = tnum_const(0);
9920 		break;
9921 	case BPF_PROG_TYPE_TRACING:
9922 		switch (env->prog->expected_attach_type) {
9923 		case BPF_TRACE_FENTRY:
9924 		case BPF_TRACE_FEXIT:
9925 			range = tnum_const(0);
9926 			break;
9927 		case BPF_TRACE_RAW_TP:
9928 		case BPF_MODIFY_RETURN:
9929 			return 0;
9930 		case BPF_TRACE_ITER:
9931 			break;
9932 		default:
9933 			return -ENOTSUPP;
9934 		}
9935 		break;
9936 	case BPF_PROG_TYPE_SK_LOOKUP:
9937 		range = tnum_range(SK_DROP, SK_PASS);
9938 		break;
9939 	case BPF_PROG_TYPE_EXT:
9940 		/* freplace program can return anything as its return value
9941 		 * depends on the to-be-replaced kernel func or bpf program.
9942 		 */
9943 	default:
9944 		return 0;
9945 	}
9946 
9947 	if (reg->type != SCALAR_VALUE) {
9948 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9949 			reg_type_str(env, reg->type));
9950 		return -EINVAL;
9951 	}
9952 
9953 	if (!tnum_in(range, reg->var_off)) {
9954 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9955 		return -EINVAL;
9956 	}
9957 
9958 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9959 	    tnum_in(enforce_attach_type_range, reg->var_off))
9960 		env->prog->enforce_expected_attach_type = 1;
9961 	return 0;
9962 }
9963 
9964 /* non-recursive DFS pseudo code
9965  * 1  procedure DFS-iterative(G,v):
9966  * 2      label v as discovered
9967  * 3      let S be a stack
9968  * 4      S.push(v)
9969  * 5      while S is not empty
9970  * 6            t <- S.pop()
9971  * 7            if t is what we're looking for:
9972  * 8                return t
9973  * 9            for all edges e in G.adjacentEdges(t) do
9974  * 10               if edge e is already labelled
9975  * 11                   continue with the next edge
9976  * 12               w <- G.adjacentVertex(t,e)
9977  * 13               if vertex w is not discovered and not explored
9978  * 14                   label e as tree-edge
9979  * 15                   label w as discovered
9980  * 16                   S.push(w)
9981  * 17                   continue at 5
9982  * 18               else if vertex w is discovered
9983  * 19                   label e as back-edge
9984  * 20               else
9985  * 21                   // vertex w is explored
9986  * 22                   label e as forward- or cross-edge
9987  * 23           label t as explored
9988  * 24           S.pop()
9989  *
9990  * convention:
9991  * 0x10 - discovered
9992  * 0x11 - discovered and fall-through edge labelled
9993  * 0x12 - discovered and fall-through and branch edges labelled
9994  * 0x20 - explored
9995  */
9996 
9997 enum {
9998 	DISCOVERED = 0x10,
9999 	EXPLORED = 0x20,
10000 	FALLTHROUGH = 1,
10001 	BRANCH = 2,
10002 };
10003 
10004 static u32 state_htab_size(struct bpf_verifier_env *env)
10005 {
10006 	return env->prog->len;
10007 }
10008 
10009 static struct bpf_verifier_state_list **explored_state(
10010 					struct bpf_verifier_env *env,
10011 					int idx)
10012 {
10013 	struct bpf_verifier_state *cur = env->cur_state;
10014 	struct bpf_func_state *state = cur->frame[cur->curframe];
10015 
10016 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10017 }
10018 
10019 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10020 {
10021 	env->insn_aux_data[idx].prune_point = true;
10022 }
10023 
10024 enum {
10025 	DONE_EXPLORING = 0,
10026 	KEEP_EXPLORING = 1,
10027 };
10028 
10029 /* t, w, e - match pseudo-code above:
10030  * t - index of current instruction
10031  * w - next instruction
10032  * e - edge
10033  */
10034 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10035 		     bool loop_ok)
10036 {
10037 	int *insn_stack = env->cfg.insn_stack;
10038 	int *insn_state = env->cfg.insn_state;
10039 
10040 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10041 		return DONE_EXPLORING;
10042 
10043 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10044 		return DONE_EXPLORING;
10045 
10046 	if (w < 0 || w >= env->prog->len) {
10047 		verbose_linfo(env, t, "%d: ", t);
10048 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10049 		return -EINVAL;
10050 	}
10051 
10052 	if (e == BRANCH)
10053 		/* mark branch target for state pruning */
10054 		init_explored_state(env, w);
10055 
10056 	if (insn_state[w] == 0) {
10057 		/* tree-edge */
10058 		insn_state[t] = DISCOVERED | e;
10059 		insn_state[w] = DISCOVERED;
10060 		if (env->cfg.cur_stack >= env->prog->len)
10061 			return -E2BIG;
10062 		insn_stack[env->cfg.cur_stack++] = w;
10063 		return KEEP_EXPLORING;
10064 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10065 		if (loop_ok && env->bpf_capable)
10066 			return DONE_EXPLORING;
10067 		verbose_linfo(env, t, "%d: ", t);
10068 		verbose_linfo(env, w, "%d: ", w);
10069 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10070 		return -EINVAL;
10071 	} else if (insn_state[w] == EXPLORED) {
10072 		/* forward- or cross-edge */
10073 		insn_state[t] = DISCOVERED | e;
10074 	} else {
10075 		verbose(env, "insn state internal bug\n");
10076 		return -EFAULT;
10077 	}
10078 	return DONE_EXPLORING;
10079 }
10080 
10081 static int visit_func_call_insn(int t, int insn_cnt,
10082 				struct bpf_insn *insns,
10083 				struct bpf_verifier_env *env,
10084 				bool visit_callee)
10085 {
10086 	int ret;
10087 
10088 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10089 	if (ret)
10090 		return ret;
10091 
10092 	if (t + 1 < insn_cnt)
10093 		init_explored_state(env, t + 1);
10094 	if (visit_callee) {
10095 		init_explored_state(env, t);
10096 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10097 				/* It's ok to allow recursion from CFG point of
10098 				 * view. __check_func_call() will do the actual
10099 				 * check.
10100 				 */
10101 				bpf_pseudo_func(insns + t));
10102 	}
10103 	return ret;
10104 }
10105 
10106 /* Visits the instruction at index t and returns one of the following:
10107  *  < 0 - an error occurred
10108  *  DONE_EXPLORING - the instruction was fully explored
10109  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10110  */
10111 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10112 {
10113 	struct bpf_insn *insns = env->prog->insnsi;
10114 	int ret;
10115 
10116 	if (bpf_pseudo_func(insns + t))
10117 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10118 
10119 	/* All non-branch instructions have a single fall-through edge. */
10120 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10121 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10122 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10123 
10124 	switch (BPF_OP(insns[t].code)) {
10125 	case BPF_EXIT:
10126 		return DONE_EXPLORING;
10127 
10128 	case BPF_CALL:
10129 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10130 			/* Mark this call insn to trigger is_state_visited() check
10131 			 * before call itself is processed by __check_func_call().
10132 			 * Otherwise new async state will be pushed for further
10133 			 * exploration.
10134 			 */
10135 			init_explored_state(env, t);
10136 		return visit_func_call_insn(t, insn_cnt, insns, env,
10137 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10138 
10139 	case BPF_JA:
10140 		if (BPF_SRC(insns[t].code) != BPF_K)
10141 			return -EINVAL;
10142 
10143 		/* unconditional jump with single edge */
10144 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10145 				true);
10146 		if (ret)
10147 			return ret;
10148 
10149 		/* unconditional jmp is not a good pruning point,
10150 		 * but it's marked, since backtracking needs
10151 		 * to record jmp history in is_state_visited().
10152 		 */
10153 		init_explored_state(env, t + insns[t].off + 1);
10154 		/* tell verifier to check for equivalent states
10155 		 * after every call and jump
10156 		 */
10157 		if (t + 1 < insn_cnt)
10158 			init_explored_state(env, t + 1);
10159 
10160 		return ret;
10161 
10162 	default:
10163 		/* conditional jump with two edges */
10164 		init_explored_state(env, t);
10165 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10166 		if (ret)
10167 			return ret;
10168 
10169 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10170 	}
10171 }
10172 
10173 /* non-recursive depth-first-search to detect loops in BPF program
10174  * loop == back-edge in directed graph
10175  */
10176 static int check_cfg(struct bpf_verifier_env *env)
10177 {
10178 	int insn_cnt = env->prog->len;
10179 	int *insn_stack, *insn_state;
10180 	int ret = 0;
10181 	int i;
10182 
10183 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10184 	if (!insn_state)
10185 		return -ENOMEM;
10186 
10187 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10188 	if (!insn_stack) {
10189 		kvfree(insn_state);
10190 		return -ENOMEM;
10191 	}
10192 
10193 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10194 	insn_stack[0] = 0; /* 0 is the first instruction */
10195 	env->cfg.cur_stack = 1;
10196 
10197 	while (env->cfg.cur_stack > 0) {
10198 		int t = insn_stack[env->cfg.cur_stack - 1];
10199 
10200 		ret = visit_insn(t, insn_cnt, env);
10201 		switch (ret) {
10202 		case DONE_EXPLORING:
10203 			insn_state[t] = EXPLORED;
10204 			env->cfg.cur_stack--;
10205 			break;
10206 		case KEEP_EXPLORING:
10207 			break;
10208 		default:
10209 			if (ret > 0) {
10210 				verbose(env, "visit_insn internal bug\n");
10211 				ret = -EFAULT;
10212 			}
10213 			goto err_free;
10214 		}
10215 	}
10216 
10217 	if (env->cfg.cur_stack < 0) {
10218 		verbose(env, "pop stack internal bug\n");
10219 		ret = -EFAULT;
10220 		goto err_free;
10221 	}
10222 
10223 	for (i = 0; i < insn_cnt; i++) {
10224 		if (insn_state[i] != EXPLORED) {
10225 			verbose(env, "unreachable insn %d\n", i);
10226 			ret = -EINVAL;
10227 			goto err_free;
10228 		}
10229 	}
10230 	ret = 0; /* cfg looks good */
10231 
10232 err_free:
10233 	kvfree(insn_state);
10234 	kvfree(insn_stack);
10235 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10236 	return ret;
10237 }
10238 
10239 static int check_abnormal_return(struct bpf_verifier_env *env)
10240 {
10241 	int i;
10242 
10243 	for (i = 1; i < env->subprog_cnt; i++) {
10244 		if (env->subprog_info[i].has_ld_abs) {
10245 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10246 			return -EINVAL;
10247 		}
10248 		if (env->subprog_info[i].has_tail_call) {
10249 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10250 			return -EINVAL;
10251 		}
10252 	}
10253 	return 0;
10254 }
10255 
10256 /* The minimum supported BTF func info size */
10257 #define MIN_BPF_FUNCINFO_SIZE	8
10258 #define MAX_FUNCINFO_REC_SIZE	252
10259 
10260 static int check_btf_func(struct bpf_verifier_env *env,
10261 			  const union bpf_attr *attr,
10262 			  bpfptr_t uattr)
10263 {
10264 	const struct btf_type *type, *func_proto, *ret_type;
10265 	u32 i, nfuncs, urec_size, min_size;
10266 	u32 krec_size = sizeof(struct bpf_func_info);
10267 	struct bpf_func_info *krecord;
10268 	struct bpf_func_info_aux *info_aux = NULL;
10269 	struct bpf_prog *prog;
10270 	const struct btf *btf;
10271 	bpfptr_t urecord;
10272 	u32 prev_offset = 0;
10273 	bool scalar_return;
10274 	int ret = -ENOMEM;
10275 
10276 	nfuncs = attr->func_info_cnt;
10277 	if (!nfuncs) {
10278 		if (check_abnormal_return(env))
10279 			return -EINVAL;
10280 		return 0;
10281 	}
10282 
10283 	if (nfuncs != env->subprog_cnt) {
10284 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10285 		return -EINVAL;
10286 	}
10287 
10288 	urec_size = attr->func_info_rec_size;
10289 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10290 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10291 	    urec_size % sizeof(u32)) {
10292 		verbose(env, "invalid func info rec size %u\n", urec_size);
10293 		return -EINVAL;
10294 	}
10295 
10296 	prog = env->prog;
10297 	btf = prog->aux->btf;
10298 
10299 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10300 	min_size = min_t(u32, krec_size, urec_size);
10301 
10302 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10303 	if (!krecord)
10304 		return -ENOMEM;
10305 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10306 	if (!info_aux)
10307 		goto err_free;
10308 
10309 	for (i = 0; i < nfuncs; i++) {
10310 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10311 		if (ret) {
10312 			if (ret == -E2BIG) {
10313 				verbose(env, "nonzero tailing record in func info");
10314 				/* set the size kernel expects so loader can zero
10315 				 * out the rest of the record.
10316 				 */
10317 				if (copy_to_bpfptr_offset(uattr,
10318 							  offsetof(union bpf_attr, func_info_rec_size),
10319 							  &min_size, sizeof(min_size)))
10320 					ret = -EFAULT;
10321 			}
10322 			goto err_free;
10323 		}
10324 
10325 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10326 			ret = -EFAULT;
10327 			goto err_free;
10328 		}
10329 
10330 		/* check insn_off */
10331 		ret = -EINVAL;
10332 		if (i == 0) {
10333 			if (krecord[i].insn_off) {
10334 				verbose(env,
10335 					"nonzero insn_off %u for the first func info record",
10336 					krecord[i].insn_off);
10337 				goto err_free;
10338 			}
10339 		} else if (krecord[i].insn_off <= prev_offset) {
10340 			verbose(env,
10341 				"same or smaller insn offset (%u) than previous func info record (%u)",
10342 				krecord[i].insn_off, prev_offset);
10343 			goto err_free;
10344 		}
10345 
10346 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10347 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10348 			goto err_free;
10349 		}
10350 
10351 		/* check type_id */
10352 		type = btf_type_by_id(btf, krecord[i].type_id);
10353 		if (!type || !btf_type_is_func(type)) {
10354 			verbose(env, "invalid type id %d in func info",
10355 				krecord[i].type_id);
10356 			goto err_free;
10357 		}
10358 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10359 
10360 		func_proto = btf_type_by_id(btf, type->type);
10361 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10362 			/* btf_func_check() already verified it during BTF load */
10363 			goto err_free;
10364 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10365 		scalar_return =
10366 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10367 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10368 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10369 			goto err_free;
10370 		}
10371 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10372 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10373 			goto err_free;
10374 		}
10375 
10376 		prev_offset = krecord[i].insn_off;
10377 		bpfptr_add(&urecord, urec_size);
10378 	}
10379 
10380 	prog->aux->func_info = krecord;
10381 	prog->aux->func_info_cnt = nfuncs;
10382 	prog->aux->func_info_aux = info_aux;
10383 	return 0;
10384 
10385 err_free:
10386 	kvfree(krecord);
10387 	kfree(info_aux);
10388 	return ret;
10389 }
10390 
10391 static void adjust_btf_func(struct bpf_verifier_env *env)
10392 {
10393 	struct bpf_prog_aux *aux = env->prog->aux;
10394 	int i;
10395 
10396 	if (!aux->func_info)
10397 		return;
10398 
10399 	for (i = 0; i < env->subprog_cnt; i++)
10400 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10401 }
10402 
10403 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
10404 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10405 
10406 static int check_btf_line(struct bpf_verifier_env *env,
10407 			  const union bpf_attr *attr,
10408 			  bpfptr_t uattr)
10409 {
10410 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10411 	struct bpf_subprog_info *sub;
10412 	struct bpf_line_info *linfo;
10413 	struct bpf_prog *prog;
10414 	const struct btf *btf;
10415 	bpfptr_t ulinfo;
10416 	int err;
10417 
10418 	nr_linfo = attr->line_info_cnt;
10419 	if (!nr_linfo)
10420 		return 0;
10421 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10422 		return -EINVAL;
10423 
10424 	rec_size = attr->line_info_rec_size;
10425 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10426 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10427 	    rec_size & (sizeof(u32) - 1))
10428 		return -EINVAL;
10429 
10430 	/* Need to zero it in case the userspace may
10431 	 * pass in a smaller bpf_line_info object.
10432 	 */
10433 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10434 			 GFP_KERNEL | __GFP_NOWARN);
10435 	if (!linfo)
10436 		return -ENOMEM;
10437 
10438 	prog = env->prog;
10439 	btf = prog->aux->btf;
10440 
10441 	s = 0;
10442 	sub = env->subprog_info;
10443 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10444 	expected_size = sizeof(struct bpf_line_info);
10445 	ncopy = min_t(u32, expected_size, rec_size);
10446 	for (i = 0; i < nr_linfo; i++) {
10447 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10448 		if (err) {
10449 			if (err == -E2BIG) {
10450 				verbose(env, "nonzero tailing record in line_info");
10451 				if (copy_to_bpfptr_offset(uattr,
10452 							  offsetof(union bpf_attr, line_info_rec_size),
10453 							  &expected_size, sizeof(expected_size)))
10454 					err = -EFAULT;
10455 			}
10456 			goto err_free;
10457 		}
10458 
10459 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10460 			err = -EFAULT;
10461 			goto err_free;
10462 		}
10463 
10464 		/*
10465 		 * Check insn_off to ensure
10466 		 * 1) strictly increasing AND
10467 		 * 2) bounded by prog->len
10468 		 *
10469 		 * The linfo[0].insn_off == 0 check logically falls into
10470 		 * the later "missing bpf_line_info for func..." case
10471 		 * because the first linfo[0].insn_off must be the
10472 		 * first sub also and the first sub must have
10473 		 * subprog_info[0].start == 0.
10474 		 */
10475 		if ((i && linfo[i].insn_off <= prev_offset) ||
10476 		    linfo[i].insn_off >= prog->len) {
10477 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10478 				i, linfo[i].insn_off, prev_offset,
10479 				prog->len);
10480 			err = -EINVAL;
10481 			goto err_free;
10482 		}
10483 
10484 		if (!prog->insnsi[linfo[i].insn_off].code) {
10485 			verbose(env,
10486 				"Invalid insn code at line_info[%u].insn_off\n",
10487 				i);
10488 			err = -EINVAL;
10489 			goto err_free;
10490 		}
10491 
10492 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10493 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10494 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10495 			err = -EINVAL;
10496 			goto err_free;
10497 		}
10498 
10499 		if (s != env->subprog_cnt) {
10500 			if (linfo[i].insn_off == sub[s].start) {
10501 				sub[s].linfo_idx = i;
10502 				s++;
10503 			} else if (sub[s].start < linfo[i].insn_off) {
10504 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10505 				err = -EINVAL;
10506 				goto err_free;
10507 			}
10508 		}
10509 
10510 		prev_offset = linfo[i].insn_off;
10511 		bpfptr_add(&ulinfo, rec_size);
10512 	}
10513 
10514 	if (s != env->subprog_cnt) {
10515 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10516 			env->subprog_cnt - s, s);
10517 		err = -EINVAL;
10518 		goto err_free;
10519 	}
10520 
10521 	prog->aux->linfo = linfo;
10522 	prog->aux->nr_linfo = nr_linfo;
10523 
10524 	return 0;
10525 
10526 err_free:
10527 	kvfree(linfo);
10528 	return err;
10529 }
10530 
10531 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
10532 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
10533 
10534 static int check_core_relo(struct bpf_verifier_env *env,
10535 			   const union bpf_attr *attr,
10536 			   bpfptr_t uattr)
10537 {
10538 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
10539 	struct bpf_core_relo core_relo = {};
10540 	struct bpf_prog *prog = env->prog;
10541 	const struct btf *btf = prog->aux->btf;
10542 	struct bpf_core_ctx ctx = {
10543 		.log = &env->log,
10544 		.btf = btf,
10545 	};
10546 	bpfptr_t u_core_relo;
10547 	int err;
10548 
10549 	nr_core_relo = attr->core_relo_cnt;
10550 	if (!nr_core_relo)
10551 		return 0;
10552 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
10553 		return -EINVAL;
10554 
10555 	rec_size = attr->core_relo_rec_size;
10556 	if (rec_size < MIN_CORE_RELO_SIZE ||
10557 	    rec_size > MAX_CORE_RELO_SIZE ||
10558 	    rec_size % sizeof(u32))
10559 		return -EINVAL;
10560 
10561 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
10562 	expected_size = sizeof(struct bpf_core_relo);
10563 	ncopy = min_t(u32, expected_size, rec_size);
10564 
10565 	/* Unlike func_info and line_info, copy and apply each CO-RE
10566 	 * relocation record one at a time.
10567 	 */
10568 	for (i = 0; i < nr_core_relo; i++) {
10569 		/* future proofing when sizeof(bpf_core_relo) changes */
10570 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
10571 		if (err) {
10572 			if (err == -E2BIG) {
10573 				verbose(env, "nonzero tailing record in core_relo");
10574 				if (copy_to_bpfptr_offset(uattr,
10575 							  offsetof(union bpf_attr, core_relo_rec_size),
10576 							  &expected_size, sizeof(expected_size)))
10577 					err = -EFAULT;
10578 			}
10579 			break;
10580 		}
10581 
10582 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
10583 			err = -EFAULT;
10584 			break;
10585 		}
10586 
10587 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
10588 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
10589 				i, core_relo.insn_off, prog->len);
10590 			err = -EINVAL;
10591 			break;
10592 		}
10593 
10594 		err = bpf_core_apply(&ctx, &core_relo, i,
10595 				     &prog->insnsi[core_relo.insn_off / 8]);
10596 		if (err)
10597 			break;
10598 		bpfptr_add(&u_core_relo, rec_size);
10599 	}
10600 	return err;
10601 }
10602 
10603 static int check_btf_info(struct bpf_verifier_env *env,
10604 			  const union bpf_attr *attr,
10605 			  bpfptr_t uattr)
10606 {
10607 	struct btf *btf;
10608 	int err;
10609 
10610 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10611 		if (check_abnormal_return(env))
10612 			return -EINVAL;
10613 		return 0;
10614 	}
10615 
10616 	btf = btf_get_by_fd(attr->prog_btf_fd);
10617 	if (IS_ERR(btf))
10618 		return PTR_ERR(btf);
10619 	if (btf_is_kernel(btf)) {
10620 		btf_put(btf);
10621 		return -EACCES;
10622 	}
10623 	env->prog->aux->btf = btf;
10624 
10625 	err = check_btf_func(env, attr, uattr);
10626 	if (err)
10627 		return err;
10628 
10629 	err = check_btf_line(env, attr, uattr);
10630 	if (err)
10631 		return err;
10632 
10633 	err = check_core_relo(env, attr, uattr);
10634 	if (err)
10635 		return err;
10636 
10637 	return 0;
10638 }
10639 
10640 /* check %cur's range satisfies %old's */
10641 static bool range_within(struct bpf_reg_state *old,
10642 			 struct bpf_reg_state *cur)
10643 {
10644 	return old->umin_value <= cur->umin_value &&
10645 	       old->umax_value >= cur->umax_value &&
10646 	       old->smin_value <= cur->smin_value &&
10647 	       old->smax_value >= cur->smax_value &&
10648 	       old->u32_min_value <= cur->u32_min_value &&
10649 	       old->u32_max_value >= cur->u32_max_value &&
10650 	       old->s32_min_value <= cur->s32_min_value &&
10651 	       old->s32_max_value >= cur->s32_max_value;
10652 }
10653 
10654 /* If in the old state two registers had the same id, then they need to have
10655  * the same id in the new state as well.  But that id could be different from
10656  * the old state, so we need to track the mapping from old to new ids.
10657  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10658  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10659  * regs with a different old id could still have new id 9, we don't care about
10660  * that.
10661  * So we look through our idmap to see if this old id has been seen before.  If
10662  * so, we require the new id to match; otherwise, we add the id pair to the map.
10663  */
10664 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10665 {
10666 	unsigned int i;
10667 
10668 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10669 		if (!idmap[i].old) {
10670 			/* Reached an empty slot; haven't seen this id before */
10671 			idmap[i].old = old_id;
10672 			idmap[i].cur = cur_id;
10673 			return true;
10674 		}
10675 		if (idmap[i].old == old_id)
10676 			return idmap[i].cur == cur_id;
10677 	}
10678 	/* We ran out of idmap slots, which should be impossible */
10679 	WARN_ON_ONCE(1);
10680 	return false;
10681 }
10682 
10683 static void clean_func_state(struct bpf_verifier_env *env,
10684 			     struct bpf_func_state *st)
10685 {
10686 	enum bpf_reg_liveness live;
10687 	int i, j;
10688 
10689 	for (i = 0; i < BPF_REG_FP; i++) {
10690 		live = st->regs[i].live;
10691 		/* liveness must not touch this register anymore */
10692 		st->regs[i].live |= REG_LIVE_DONE;
10693 		if (!(live & REG_LIVE_READ))
10694 			/* since the register is unused, clear its state
10695 			 * to make further comparison simpler
10696 			 */
10697 			__mark_reg_not_init(env, &st->regs[i]);
10698 	}
10699 
10700 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10701 		live = st->stack[i].spilled_ptr.live;
10702 		/* liveness must not touch this stack slot anymore */
10703 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10704 		if (!(live & REG_LIVE_READ)) {
10705 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10706 			for (j = 0; j < BPF_REG_SIZE; j++)
10707 				st->stack[i].slot_type[j] = STACK_INVALID;
10708 		}
10709 	}
10710 }
10711 
10712 static void clean_verifier_state(struct bpf_verifier_env *env,
10713 				 struct bpf_verifier_state *st)
10714 {
10715 	int i;
10716 
10717 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10718 		/* all regs in this state in all frames were already marked */
10719 		return;
10720 
10721 	for (i = 0; i <= st->curframe; i++)
10722 		clean_func_state(env, st->frame[i]);
10723 }
10724 
10725 /* the parentage chains form a tree.
10726  * the verifier states are added to state lists at given insn and
10727  * pushed into state stack for future exploration.
10728  * when the verifier reaches bpf_exit insn some of the verifer states
10729  * stored in the state lists have their final liveness state already,
10730  * but a lot of states will get revised from liveness point of view when
10731  * the verifier explores other branches.
10732  * Example:
10733  * 1: r0 = 1
10734  * 2: if r1 == 100 goto pc+1
10735  * 3: r0 = 2
10736  * 4: exit
10737  * when the verifier reaches exit insn the register r0 in the state list of
10738  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10739  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10740  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10741  *
10742  * Since the verifier pushes the branch states as it sees them while exploring
10743  * the program the condition of walking the branch instruction for the second
10744  * time means that all states below this branch were already explored and
10745  * their final liveness marks are already propagated.
10746  * Hence when the verifier completes the search of state list in is_state_visited()
10747  * we can call this clean_live_states() function to mark all liveness states
10748  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10749  * will not be used.
10750  * This function also clears the registers and stack for states that !READ
10751  * to simplify state merging.
10752  *
10753  * Important note here that walking the same branch instruction in the callee
10754  * doesn't meant that the states are DONE. The verifier has to compare
10755  * the callsites
10756  */
10757 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10758 			      struct bpf_verifier_state *cur)
10759 {
10760 	struct bpf_verifier_state_list *sl;
10761 	int i;
10762 
10763 	sl = *explored_state(env, insn);
10764 	while (sl) {
10765 		if (sl->state.branches)
10766 			goto next;
10767 		if (sl->state.insn_idx != insn ||
10768 		    sl->state.curframe != cur->curframe)
10769 			goto next;
10770 		for (i = 0; i <= cur->curframe; i++)
10771 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10772 				goto next;
10773 		clean_verifier_state(env, &sl->state);
10774 next:
10775 		sl = sl->next;
10776 	}
10777 }
10778 
10779 /* Returns true if (rold safe implies rcur safe) */
10780 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10781 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10782 {
10783 	bool equal;
10784 
10785 	if (!(rold->live & REG_LIVE_READ))
10786 		/* explored state didn't use this */
10787 		return true;
10788 
10789 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10790 
10791 	if (rold->type == PTR_TO_STACK)
10792 		/* two stack pointers are equal only if they're pointing to
10793 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10794 		 */
10795 		return equal && rold->frameno == rcur->frameno;
10796 
10797 	if (equal)
10798 		return true;
10799 
10800 	if (rold->type == NOT_INIT)
10801 		/* explored state can't have used this */
10802 		return true;
10803 	if (rcur->type == NOT_INIT)
10804 		return false;
10805 	switch (base_type(rold->type)) {
10806 	case SCALAR_VALUE:
10807 		if (env->explore_alu_limits)
10808 			return false;
10809 		if (rcur->type == SCALAR_VALUE) {
10810 			if (!rold->precise && !rcur->precise)
10811 				return true;
10812 			/* new val must satisfy old val knowledge */
10813 			return range_within(rold, rcur) &&
10814 			       tnum_in(rold->var_off, rcur->var_off);
10815 		} else {
10816 			/* We're trying to use a pointer in place of a scalar.
10817 			 * Even if the scalar was unbounded, this could lead to
10818 			 * pointer leaks because scalars are allowed to leak
10819 			 * while pointers are not. We could make this safe in
10820 			 * special cases if root is calling us, but it's
10821 			 * probably not worth the hassle.
10822 			 */
10823 			return false;
10824 		}
10825 	case PTR_TO_MAP_KEY:
10826 	case PTR_TO_MAP_VALUE:
10827 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10828 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10829 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10830 		 * checked, doing so could have affected others with the same
10831 		 * id, and we can't check for that because we lost the id when
10832 		 * we converted to a PTR_TO_MAP_VALUE.
10833 		 */
10834 		if (type_may_be_null(rold->type)) {
10835 			if (!type_may_be_null(rcur->type))
10836 				return false;
10837 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10838 				return false;
10839 			/* Check our ids match any regs they're supposed to */
10840 			return check_ids(rold->id, rcur->id, idmap);
10841 		}
10842 
10843 		/* If the new min/max/var_off satisfy the old ones and
10844 		 * everything else matches, we are OK.
10845 		 * 'id' is not compared, since it's only used for maps with
10846 		 * bpf_spin_lock inside map element and in such cases if
10847 		 * the rest of the prog is valid for one map element then
10848 		 * it's valid for all map elements regardless of the key
10849 		 * used in bpf_map_lookup()
10850 		 */
10851 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10852 		       range_within(rold, rcur) &&
10853 		       tnum_in(rold->var_off, rcur->var_off);
10854 	case PTR_TO_PACKET_META:
10855 	case PTR_TO_PACKET:
10856 		if (rcur->type != rold->type)
10857 			return false;
10858 		/* We must have at least as much range as the old ptr
10859 		 * did, so that any accesses which were safe before are
10860 		 * still safe.  This is true even if old range < old off,
10861 		 * since someone could have accessed through (ptr - k), or
10862 		 * even done ptr -= k in a register, to get a safe access.
10863 		 */
10864 		if (rold->range > rcur->range)
10865 			return false;
10866 		/* If the offsets don't match, we can't trust our alignment;
10867 		 * nor can we be sure that we won't fall out of range.
10868 		 */
10869 		if (rold->off != rcur->off)
10870 			return false;
10871 		/* id relations must be preserved */
10872 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10873 			return false;
10874 		/* new val must satisfy old val knowledge */
10875 		return range_within(rold, rcur) &&
10876 		       tnum_in(rold->var_off, rcur->var_off);
10877 	case PTR_TO_CTX:
10878 	case CONST_PTR_TO_MAP:
10879 	case PTR_TO_PACKET_END:
10880 	case PTR_TO_FLOW_KEYS:
10881 	case PTR_TO_SOCKET:
10882 	case PTR_TO_SOCK_COMMON:
10883 	case PTR_TO_TCP_SOCK:
10884 	case PTR_TO_XDP_SOCK:
10885 		/* Only valid matches are exact, which memcmp() above
10886 		 * would have accepted
10887 		 */
10888 	default:
10889 		/* Don't know what's going on, just say it's not safe */
10890 		return false;
10891 	}
10892 
10893 	/* Shouldn't get here; if we do, say it's not safe */
10894 	WARN_ON_ONCE(1);
10895 	return false;
10896 }
10897 
10898 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10899 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10900 {
10901 	int i, spi;
10902 
10903 	/* walk slots of the explored stack and ignore any additional
10904 	 * slots in the current stack, since explored(safe) state
10905 	 * didn't use them
10906 	 */
10907 	for (i = 0; i < old->allocated_stack; i++) {
10908 		spi = i / BPF_REG_SIZE;
10909 
10910 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10911 			i += BPF_REG_SIZE - 1;
10912 			/* explored state didn't use this */
10913 			continue;
10914 		}
10915 
10916 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10917 			continue;
10918 
10919 		/* explored stack has more populated slots than current stack
10920 		 * and these slots were used
10921 		 */
10922 		if (i >= cur->allocated_stack)
10923 			return false;
10924 
10925 		/* if old state was safe with misc data in the stack
10926 		 * it will be safe with zero-initialized stack.
10927 		 * The opposite is not true
10928 		 */
10929 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10930 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10931 			continue;
10932 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10933 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10934 			/* Ex: old explored (safe) state has STACK_SPILL in
10935 			 * this stack slot, but current has STACK_MISC ->
10936 			 * this verifier states are not equivalent,
10937 			 * return false to continue verification of this path
10938 			 */
10939 			return false;
10940 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10941 			continue;
10942 		if (!is_spilled_reg(&old->stack[spi]))
10943 			continue;
10944 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10945 			     &cur->stack[spi].spilled_ptr, idmap))
10946 			/* when explored and current stack slot are both storing
10947 			 * spilled registers, check that stored pointers types
10948 			 * are the same as well.
10949 			 * Ex: explored safe path could have stored
10950 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10951 			 * but current path has stored:
10952 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10953 			 * such verifier states are not equivalent.
10954 			 * return false to continue verification of this path
10955 			 */
10956 			return false;
10957 	}
10958 	return true;
10959 }
10960 
10961 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10962 {
10963 	if (old->acquired_refs != cur->acquired_refs)
10964 		return false;
10965 	return !memcmp(old->refs, cur->refs,
10966 		       sizeof(*old->refs) * old->acquired_refs);
10967 }
10968 
10969 /* compare two verifier states
10970  *
10971  * all states stored in state_list are known to be valid, since
10972  * verifier reached 'bpf_exit' instruction through them
10973  *
10974  * this function is called when verifier exploring different branches of
10975  * execution popped from the state stack. If it sees an old state that has
10976  * more strict register state and more strict stack state then this execution
10977  * branch doesn't need to be explored further, since verifier already
10978  * concluded that more strict state leads to valid finish.
10979  *
10980  * Therefore two states are equivalent if register state is more conservative
10981  * and explored stack state is more conservative than the current one.
10982  * Example:
10983  *       explored                   current
10984  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10985  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10986  *
10987  * In other words if current stack state (one being explored) has more
10988  * valid slots than old one that already passed validation, it means
10989  * the verifier can stop exploring and conclude that current state is valid too
10990  *
10991  * Similarly with registers. If explored state has register type as invalid
10992  * whereas register type in current state is meaningful, it means that
10993  * the current state will reach 'bpf_exit' instruction safely
10994  */
10995 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10996 			      struct bpf_func_state *cur)
10997 {
10998 	int i;
10999 
11000 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11001 	for (i = 0; i < MAX_BPF_REG; i++)
11002 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11003 			     env->idmap_scratch))
11004 			return false;
11005 
11006 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11007 		return false;
11008 
11009 	if (!refsafe(old, cur))
11010 		return false;
11011 
11012 	return true;
11013 }
11014 
11015 static bool states_equal(struct bpf_verifier_env *env,
11016 			 struct bpf_verifier_state *old,
11017 			 struct bpf_verifier_state *cur)
11018 {
11019 	int i;
11020 
11021 	if (old->curframe != cur->curframe)
11022 		return false;
11023 
11024 	/* Verification state from speculative execution simulation
11025 	 * must never prune a non-speculative execution one.
11026 	 */
11027 	if (old->speculative && !cur->speculative)
11028 		return false;
11029 
11030 	if (old->active_spin_lock != cur->active_spin_lock)
11031 		return false;
11032 
11033 	/* for states to be equal callsites have to be the same
11034 	 * and all frame states need to be equivalent
11035 	 */
11036 	for (i = 0; i <= old->curframe; i++) {
11037 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11038 			return false;
11039 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11040 			return false;
11041 	}
11042 	return true;
11043 }
11044 
11045 /* Return 0 if no propagation happened. Return negative error code if error
11046  * happened. Otherwise, return the propagated bit.
11047  */
11048 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11049 				  struct bpf_reg_state *reg,
11050 				  struct bpf_reg_state *parent_reg)
11051 {
11052 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11053 	u8 flag = reg->live & REG_LIVE_READ;
11054 	int err;
11055 
11056 	/* When comes here, read flags of PARENT_REG or REG could be any of
11057 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11058 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11059 	 */
11060 	if (parent_flag == REG_LIVE_READ64 ||
11061 	    /* Or if there is no read flag from REG. */
11062 	    !flag ||
11063 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11064 	    parent_flag == flag)
11065 		return 0;
11066 
11067 	err = mark_reg_read(env, reg, parent_reg, flag);
11068 	if (err)
11069 		return err;
11070 
11071 	return flag;
11072 }
11073 
11074 /* A write screens off any subsequent reads; but write marks come from the
11075  * straight-line code between a state and its parent.  When we arrive at an
11076  * equivalent state (jump target or such) we didn't arrive by the straight-line
11077  * code, so read marks in the state must propagate to the parent regardless
11078  * of the state's write marks. That's what 'parent == state->parent' comparison
11079  * in mark_reg_read() is for.
11080  */
11081 static int propagate_liveness(struct bpf_verifier_env *env,
11082 			      const struct bpf_verifier_state *vstate,
11083 			      struct bpf_verifier_state *vparent)
11084 {
11085 	struct bpf_reg_state *state_reg, *parent_reg;
11086 	struct bpf_func_state *state, *parent;
11087 	int i, frame, err = 0;
11088 
11089 	if (vparent->curframe != vstate->curframe) {
11090 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11091 		     vparent->curframe, vstate->curframe);
11092 		return -EFAULT;
11093 	}
11094 	/* Propagate read liveness of registers... */
11095 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11096 	for (frame = 0; frame <= vstate->curframe; frame++) {
11097 		parent = vparent->frame[frame];
11098 		state = vstate->frame[frame];
11099 		parent_reg = parent->regs;
11100 		state_reg = state->regs;
11101 		/* We don't need to worry about FP liveness, it's read-only */
11102 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11103 			err = propagate_liveness_reg(env, &state_reg[i],
11104 						     &parent_reg[i]);
11105 			if (err < 0)
11106 				return err;
11107 			if (err == REG_LIVE_READ64)
11108 				mark_insn_zext(env, &parent_reg[i]);
11109 		}
11110 
11111 		/* Propagate stack slots. */
11112 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11113 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11114 			parent_reg = &parent->stack[i].spilled_ptr;
11115 			state_reg = &state->stack[i].spilled_ptr;
11116 			err = propagate_liveness_reg(env, state_reg,
11117 						     parent_reg);
11118 			if (err < 0)
11119 				return err;
11120 		}
11121 	}
11122 	return 0;
11123 }
11124 
11125 /* find precise scalars in the previous equivalent state and
11126  * propagate them into the current state
11127  */
11128 static int propagate_precision(struct bpf_verifier_env *env,
11129 			       const struct bpf_verifier_state *old)
11130 {
11131 	struct bpf_reg_state *state_reg;
11132 	struct bpf_func_state *state;
11133 	int i, err = 0;
11134 
11135 	state = old->frame[old->curframe];
11136 	state_reg = state->regs;
11137 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11138 		if (state_reg->type != SCALAR_VALUE ||
11139 		    !state_reg->precise)
11140 			continue;
11141 		if (env->log.level & BPF_LOG_LEVEL2)
11142 			verbose(env, "propagating r%d\n", i);
11143 		err = mark_chain_precision(env, i);
11144 		if (err < 0)
11145 			return err;
11146 	}
11147 
11148 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11149 		if (!is_spilled_reg(&state->stack[i]))
11150 			continue;
11151 		state_reg = &state->stack[i].spilled_ptr;
11152 		if (state_reg->type != SCALAR_VALUE ||
11153 		    !state_reg->precise)
11154 			continue;
11155 		if (env->log.level & BPF_LOG_LEVEL2)
11156 			verbose(env, "propagating fp%d\n",
11157 				(-i - 1) * BPF_REG_SIZE);
11158 		err = mark_chain_precision_stack(env, i);
11159 		if (err < 0)
11160 			return err;
11161 	}
11162 	return 0;
11163 }
11164 
11165 static bool states_maybe_looping(struct bpf_verifier_state *old,
11166 				 struct bpf_verifier_state *cur)
11167 {
11168 	struct bpf_func_state *fold, *fcur;
11169 	int i, fr = cur->curframe;
11170 
11171 	if (old->curframe != fr)
11172 		return false;
11173 
11174 	fold = old->frame[fr];
11175 	fcur = cur->frame[fr];
11176 	for (i = 0; i < MAX_BPF_REG; i++)
11177 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11178 			   offsetof(struct bpf_reg_state, parent)))
11179 			return false;
11180 	return true;
11181 }
11182 
11183 
11184 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11185 {
11186 	struct bpf_verifier_state_list *new_sl;
11187 	struct bpf_verifier_state_list *sl, **pprev;
11188 	struct bpf_verifier_state *cur = env->cur_state, *new;
11189 	int i, j, err, states_cnt = 0;
11190 	bool add_new_state = env->test_state_freq ? true : false;
11191 
11192 	cur->last_insn_idx = env->prev_insn_idx;
11193 	if (!env->insn_aux_data[insn_idx].prune_point)
11194 		/* this 'insn_idx' instruction wasn't marked, so we will not
11195 		 * be doing state search here
11196 		 */
11197 		return 0;
11198 
11199 	/* bpf progs typically have pruning point every 4 instructions
11200 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11201 	 * Do not add new state for future pruning if the verifier hasn't seen
11202 	 * at least 2 jumps and at least 8 instructions.
11203 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11204 	 * In tests that amounts to up to 50% reduction into total verifier
11205 	 * memory consumption and 20% verifier time speedup.
11206 	 */
11207 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11208 	    env->insn_processed - env->prev_insn_processed >= 8)
11209 		add_new_state = true;
11210 
11211 	pprev = explored_state(env, insn_idx);
11212 	sl = *pprev;
11213 
11214 	clean_live_states(env, insn_idx, cur);
11215 
11216 	while (sl) {
11217 		states_cnt++;
11218 		if (sl->state.insn_idx != insn_idx)
11219 			goto next;
11220 
11221 		if (sl->state.branches) {
11222 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11223 
11224 			if (frame->in_async_callback_fn &&
11225 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11226 				/* Different async_entry_cnt means that the verifier is
11227 				 * processing another entry into async callback.
11228 				 * Seeing the same state is not an indication of infinite
11229 				 * loop or infinite recursion.
11230 				 * But finding the same state doesn't mean that it's safe
11231 				 * to stop processing the current state. The previous state
11232 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11233 				 * Checking in_async_callback_fn alone is not enough either.
11234 				 * Since the verifier still needs to catch infinite loops
11235 				 * inside async callbacks.
11236 				 */
11237 			} else if (states_maybe_looping(&sl->state, cur) &&
11238 				   states_equal(env, &sl->state, cur)) {
11239 				verbose_linfo(env, insn_idx, "; ");
11240 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11241 				return -EINVAL;
11242 			}
11243 			/* if the verifier is processing a loop, avoid adding new state
11244 			 * too often, since different loop iterations have distinct
11245 			 * states and may not help future pruning.
11246 			 * This threshold shouldn't be too low to make sure that
11247 			 * a loop with large bound will be rejected quickly.
11248 			 * The most abusive loop will be:
11249 			 * r1 += 1
11250 			 * if r1 < 1000000 goto pc-2
11251 			 * 1M insn_procssed limit / 100 == 10k peak states.
11252 			 * This threshold shouldn't be too high either, since states
11253 			 * at the end of the loop are likely to be useful in pruning.
11254 			 */
11255 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11256 			    env->insn_processed - env->prev_insn_processed < 100)
11257 				add_new_state = false;
11258 			goto miss;
11259 		}
11260 		if (states_equal(env, &sl->state, cur)) {
11261 			sl->hit_cnt++;
11262 			/* reached equivalent register/stack state,
11263 			 * prune the search.
11264 			 * Registers read by the continuation are read by us.
11265 			 * If we have any write marks in env->cur_state, they
11266 			 * will prevent corresponding reads in the continuation
11267 			 * from reaching our parent (an explored_state).  Our
11268 			 * own state will get the read marks recorded, but
11269 			 * they'll be immediately forgotten as we're pruning
11270 			 * this state and will pop a new one.
11271 			 */
11272 			err = propagate_liveness(env, &sl->state, cur);
11273 
11274 			/* if previous state reached the exit with precision and
11275 			 * current state is equivalent to it (except precsion marks)
11276 			 * the precision needs to be propagated back in
11277 			 * the current state.
11278 			 */
11279 			err = err ? : push_jmp_history(env, cur);
11280 			err = err ? : propagate_precision(env, &sl->state);
11281 			if (err)
11282 				return err;
11283 			return 1;
11284 		}
11285 miss:
11286 		/* when new state is not going to be added do not increase miss count.
11287 		 * Otherwise several loop iterations will remove the state
11288 		 * recorded earlier. The goal of these heuristics is to have
11289 		 * states from some iterations of the loop (some in the beginning
11290 		 * and some at the end) to help pruning.
11291 		 */
11292 		if (add_new_state)
11293 			sl->miss_cnt++;
11294 		/* heuristic to determine whether this state is beneficial
11295 		 * to keep checking from state equivalence point of view.
11296 		 * Higher numbers increase max_states_per_insn and verification time,
11297 		 * but do not meaningfully decrease insn_processed.
11298 		 */
11299 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11300 			/* the state is unlikely to be useful. Remove it to
11301 			 * speed up verification
11302 			 */
11303 			*pprev = sl->next;
11304 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11305 				u32 br = sl->state.branches;
11306 
11307 				WARN_ONCE(br,
11308 					  "BUG live_done but branches_to_explore %d\n",
11309 					  br);
11310 				free_verifier_state(&sl->state, false);
11311 				kfree(sl);
11312 				env->peak_states--;
11313 			} else {
11314 				/* cannot free this state, since parentage chain may
11315 				 * walk it later. Add it for free_list instead to
11316 				 * be freed at the end of verification
11317 				 */
11318 				sl->next = env->free_list;
11319 				env->free_list = sl;
11320 			}
11321 			sl = *pprev;
11322 			continue;
11323 		}
11324 next:
11325 		pprev = &sl->next;
11326 		sl = *pprev;
11327 	}
11328 
11329 	if (env->max_states_per_insn < states_cnt)
11330 		env->max_states_per_insn = states_cnt;
11331 
11332 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11333 		return push_jmp_history(env, cur);
11334 
11335 	if (!add_new_state)
11336 		return push_jmp_history(env, cur);
11337 
11338 	/* There were no equivalent states, remember the current one.
11339 	 * Technically the current state is not proven to be safe yet,
11340 	 * but it will either reach outer most bpf_exit (which means it's safe)
11341 	 * or it will be rejected. When there are no loops the verifier won't be
11342 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11343 	 * again on the way to bpf_exit.
11344 	 * When looping the sl->state.branches will be > 0 and this state
11345 	 * will not be considered for equivalence until branches == 0.
11346 	 */
11347 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11348 	if (!new_sl)
11349 		return -ENOMEM;
11350 	env->total_states++;
11351 	env->peak_states++;
11352 	env->prev_jmps_processed = env->jmps_processed;
11353 	env->prev_insn_processed = env->insn_processed;
11354 
11355 	/* add new state to the head of linked list */
11356 	new = &new_sl->state;
11357 	err = copy_verifier_state(new, cur);
11358 	if (err) {
11359 		free_verifier_state(new, false);
11360 		kfree(new_sl);
11361 		return err;
11362 	}
11363 	new->insn_idx = insn_idx;
11364 	WARN_ONCE(new->branches != 1,
11365 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11366 
11367 	cur->parent = new;
11368 	cur->first_insn_idx = insn_idx;
11369 	clear_jmp_history(cur);
11370 	new_sl->next = *explored_state(env, insn_idx);
11371 	*explored_state(env, insn_idx) = new_sl;
11372 	/* connect new state to parentage chain. Current frame needs all
11373 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11374 	 * to the stack implicitly by JITs) so in callers' frames connect just
11375 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11376 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11377 	 * from callee with its full parentage chain, anyway.
11378 	 */
11379 	/* clear write marks in current state: the writes we did are not writes
11380 	 * our child did, so they don't screen off its reads from us.
11381 	 * (There are no read marks in current state, because reads always mark
11382 	 * their parent and current state never has children yet.  Only
11383 	 * explored_states can get read marks.)
11384 	 */
11385 	for (j = 0; j <= cur->curframe; j++) {
11386 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11387 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11388 		for (i = 0; i < BPF_REG_FP; i++)
11389 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11390 	}
11391 
11392 	/* all stack frames are accessible from callee, clear them all */
11393 	for (j = 0; j <= cur->curframe; j++) {
11394 		struct bpf_func_state *frame = cur->frame[j];
11395 		struct bpf_func_state *newframe = new->frame[j];
11396 
11397 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11398 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11399 			frame->stack[i].spilled_ptr.parent =
11400 						&newframe->stack[i].spilled_ptr;
11401 		}
11402 	}
11403 	return 0;
11404 }
11405 
11406 /* Return true if it's OK to have the same insn return a different type. */
11407 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11408 {
11409 	switch (base_type(type)) {
11410 	case PTR_TO_CTX:
11411 	case PTR_TO_SOCKET:
11412 	case PTR_TO_SOCK_COMMON:
11413 	case PTR_TO_TCP_SOCK:
11414 	case PTR_TO_XDP_SOCK:
11415 	case PTR_TO_BTF_ID:
11416 		return false;
11417 	default:
11418 		return true;
11419 	}
11420 }
11421 
11422 /* If an instruction was previously used with particular pointer types, then we
11423  * need to be careful to avoid cases such as the below, where it may be ok
11424  * for one branch accessing the pointer, but not ok for the other branch:
11425  *
11426  * R1 = sock_ptr
11427  * goto X;
11428  * ...
11429  * R1 = some_other_valid_ptr;
11430  * goto X;
11431  * ...
11432  * R2 = *(u32 *)(R1 + 0);
11433  */
11434 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11435 {
11436 	return src != prev && (!reg_type_mismatch_ok(src) ||
11437 			       !reg_type_mismatch_ok(prev));
11438 }
11439 
11440 static int do_check(struct bpf_verifier_env *env)
11441 {
11442 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11443 	struct bpf_verifier_state *state = env->cur_state;
11444 	struct bpf_insn *insns = env->prog->insnsi;
11445 	struct bpf_reg_state *regs;
11446 	int insn_cnt = env->prog->len;
11447 	bool do_print_state = false;
11448 	int prev_insn_idx = -1;
11449 
11450 	for (;;) {
11451 		struct bpf_insn *insn;
11452 		u8 class;
11453 		int err;
11454 
11455 		env->prev_insn_idx = prev_insn_idx;
11456 		if (env->insn_idx >= insn_cnt) {
11457 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11458 				env->insn_idx, insn_cnt);
11459 			return -EFAULT;
11460 		}
11461 
11462 		insn = &insns[env->insn_idx];
11463 		class = BPF_CLASS(insn->code);
11464 
11465 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11466 			verbose(env,
11467 				"BPF program is too large. Processed %d insn\n",
11468 				env->insn_processed);
11469 			return -E2BIG;
11470 		}
11471 
11472 		err = is_state_visited(env, env->insn_idx);
11473 		if (err < 0)
11474 			return err;
11475 		if (err == 1) {
11476 			/* found equivalent state, can prune the search */
11477 			if (env->log.level & BPF_LOG_LEVEL) {
11478 				if (do_print_state)
11479 					verbose(env, "\nfrom %d to %d%s: safe\n",
11480 						env->prev_insn_idx, env->insn_idx,
11481 						env->cur_state->speculative ?
11482 						" (speculative execution)" : "");
11483 				else
11484 					verbose(env, "%d: safe\n", env->insn_idx);
11485 			}
11486 			goto process_bpf_exit;
11487 		}
11488 
11489 		if (signal_pending(current))
11490 			return -EAGAIN;
11491 
11492 		if (need_resched())
11493 			cond_resched();
11494 
11495 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
11496 			verbose(env, "\nfrom %d to %d%s:",
11497 				env->prev_insn_idx, env->insn_idx,
11498 				env->cur_state->speculative ?
11499 				" (speculative execution)" : "");
11500 			print_verifier_state(env, state->frame[state->curframe], true);
11501 			do_print_state = false;
11502 		}
11503 
11504 		if (env->log.level & BPF_LOG_LEVEL) {
11505 			const struct bpf_insn_cbs cbs = {
11506 				.cb_call	= disasm_kfunc_name,
11507 				.cb_print	= verbose,
11508 				.private_data	= env,
11509 			};
11510 
11511 			if (verifier_state_scratched(env))
11512 				print_insn_state(env, state->frame[state->curframe]);
11513 
11514 			verbose_linfo(env, env->insn_idx, "; ");
11515 			env->prev_log_len = env->log.len_used;
11516 			verbose(env, "%d: ", env->insn_idx);
11517 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11518 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
11519 			env->prev_log_len = env->log.len_used;
11520 		}
11521 
11522 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11523 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11524 							   env->prev_insn_idx);
11525 			if (err)
11526 				return err;
11527 		}
11528 
11529 		regs = cur_regs(env);
11530 		sanitize_mark_insn_seen(env);
11531 		prev_insn_idx = env->insn_idx;
11532 
11533 		if (class == BPF_ALU || class == BPF_ALU64) {
11534 			err = check_alu_op(env, insn);
11535 			if (err)
11536 				return err;
11537 
11538 		} else if (class == BPF_LDX) {
11539 			enum bpf_reg_type *prev_src_type, src_reg_type;
11540 
11541 			/* check for reserved fields is already done */
11542 
11543 			/* check src operand */
11544 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11545 			if (err)
11546 				return err;
11547 
11548 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11549 			if (err)
11550 				return err;
11551 
11552 			src_reg_type = regs[insn->src_reg].type;
11553 
11554 			/* check that memory (src_reg + off) is readable,
11555 			 * the state of dst_reg will be updated by this func
11556 			 */
11557 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11558 					       insn->off, BPF_SIZE(insn->code),
11559 					       BPF_READ, insn->dst_reg, false);
11560 			if (err)
11561 				return err;
11562 
11563 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11564 
11565 			if (*prev_src_type == NOT_INIT) {
11566 				/* saw a valid insn
11567 				 * dst_reg = *(u32 *)(src_reg + off)
11568 				 * save type to validate intersecting paths
11569 				 */
11570 				*prev_src_type = src_reg_type;
11571 
11572 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11573 				/* ABuser program is trying to use the same insn
11574 				 * dst_reg = *(u32*) (src_reg + off)
11575 				 * with different pointer types:
11576 				 * src_reg == ctx in one branch and
11577 				 * src_reg == stack|map in some other branch.
11578 				 * Reject it.
11579 				 */
11580 				verbose(env, "same insn cannot be used with different pointers\n");
11581 				return -EINVAL;
11582 			}
11583 
11584 		} else if (class == BPF_STX) {
11585 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11586 
11587 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11588 				err = check_atomic(env, env->insn_idx, insn);
11589 				if (err)
11590 					return err;
11591 				env->insn_idx++;
11592 				continue;
11593 			}
11594 
11595 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11596 				verbose(env, "BPF_STX uses reserved fields\n");
11597 				return -EINVAL;
11598 			}
11599 
11600 			/* check src1 operand */
11601 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11602 			if (err)
11603 				return err;
11604 			/* check src2 operand */
11605 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11606 			if (err)
11607 				return err;
11608 
11609 			dst_reg_type = regs[insn->dst_reg].type;
11610 
11611 			/* check that memory (dst_reg + off) is writeable */
11612 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11613 					       insn->off, BPF_SIZE(insn->code),
11614 					       BPF_WRITE, insn->src_reg, false);
11615 			if (err)
11616 				return err;
11617 
11618 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11619 
11620 			if (*prev_dst_type == NOT_INIT) {
11621 				*prev_dst_type = dst_reg_type;
11622 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11623 				verbose(env, "same insn cannot be used with different pointers\n");
11624 				return -EINVAL;
11625 			}
11626 
11627 		} else if (class == BPF_ST) {
11628 			if (BPF_MODE(insn->code) != BPF_MEM ||
11629 			    insn->src_reg != BPF_REG_0) {
11630 				verbose(env, "BPF_ST uses reserved fields\n");
11631 				return -EINVAL;
11632 			}
11633 			/* check src operand */
11634 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11635 			if (err)
11636 				return err;
11637 
11638 			if (is_ctx_reg(env, insn->dst_reg)) {
11639 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11640 					insn->dst_reg,
11641 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11642 				return -EACCES;
11643 			}
11644 
11645 			/* check that memory (dst_reg + off) is writeable */
11646 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11647 					       insn->off, BPF_SIZE(insn->code),
11648 					       BPF_WRITE, -1, false);
11649 			if (err)
11650 				return err;
11651 
11652 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11653 			u8 opcode = BPF_OP(insn->code);
11654 
11655 			env->jmps_processed++;
11656 			if (opcode == BPF_CALL) {
11657 				if (BPF_SRC(insn->code) != BPF_K ||
11658 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11659 				     && insn->off != 0) ||
11660 				    (insn->src_reg != BPF_REG_0 &&
11661 				     insn->src_reg != BPF_PSEUDO_CALL &&
11662 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11663 				    insn->dst_reg != BPF_REG_0 ||
11664 				    class == BPF_JMP32) {
11665 					verbose(env, "BPF_CALL uses reserved fields\n");
11666 					return -EINVAL;
11667 				}
11668 
11669 				if (env->cur_state->active_spin_lock &&
11670 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11671 				     insn->imm != BPF_FUNC_spin_unlock)) {
11672 					verbose(env, "function calls are not allowed while holding a lock\n");
11673 					return -EINVAL;
11674 				}
11675 				if (insn->src_reg == BPF_PSEUDO_CALL)
11676 					err = check_func_call(env, insn, &env->insn_idx);
11677 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11678 					err = check_kfunc_call(env, insn, &env->insn_idx);
11679 				else
11680 					err = check_helper_call(env, insn, &env->insn_idx);
11681 				if (err)
11682 					return err;
11683 			} else if (opcode == BPF_JA) {
11684 				if (BPF_SRC(insn->code) != BPF_K ||
11685 				    insn->imm != 0 ||
11686 				    insn->src_reg != BPF_REG_0 ||
11687 				    insn->dst_reg != BPF_REG_0 ||
11688 				    class == BPF_JMP32) {
11689 					verbose(env, "BPF_JA uses reserved fields\n");
11690 					return -EINVAL;
11691 				}
11692 
11693 				env->insn_idx += insn->off + 1;
11694 				continue;
11695 
11696 			} else if (opcode == BPF_EXIT) {
11697 				if (BPF_SRC(insn->code) != BPF_K ||
11698 				    insn->imm != 0 ||
11699 				    insn->src_reg != BPF_REG_0 ||
11700 				    insn->dst_reg != BPF_REG_0 ||
11701 				    class == BPF_JMP32) {
11702 					verbose(env, "BPF_EXIT uses reserved fields\n");
11703 					return -EINVAL;
11704 				}
11705 
11706 				if (env->cur_state->active_spin_lock) {
11707 					verbose(env, "bpf_spin_unlock is missing\n");
11708 					return -EINVAL;
11709 				}
11710 
11711 				if (state->curframe) {
11712 					/* exit from nested function */
11713 					err = prepare_func_exit(env, &env->insn_idx);
11714 					if (err)
11715 						return err;
11716 					do_print_state = true;
11717 					continue;
11718 				}
11719 
11720 				err = check_reference_leak(env);
11721 				if (err)
11722 					return err;
11723 
11724 				err = check_return_code(env);
11725 				if (err)
11726 					return err;
11727 process_bpf_exit:
11728 				mark_verifier_state_scratched(env);
11729 				update_branch_counts(env, env->cur_state);
11730 				err = pop_stack(env, &prev_insn_idx,
11731 						&env->insn_idx, pop_log);
11732 				if (err < 0) {
11733 					if (err != -ENOENT)
11734 						return err;
11735 					break;
11736 				} else {
11737 					do_print_state = true;
11738 					continue;
11739 				}
11740 			} else {
11741 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11742 				if (err)
11743 					return err;
11744 			}
11745 		} else if (class == BPF_LD) {
11746 			u8 mode = BPF_MODE(insn->code);
11747 
11748 			if (mode == BPF_ABS || mode == BPF_IND) {
11749 				err = check_ld_abs(env, insn);
11750 				if (err)
11751 					return err;
11752 
11753 			} else if (mode == BPF_IMM) {
11754 				err = check_ld_imm(env, insn);
11755 				if (err)
11756 					return err;
11757 
11758 				env->insn_idx++;
11759 				sanitize_mark_insn_seen(env);
11760 			} else {
11761 				verbose(env, "invalid BPF_LD mode\n");
11762 				return -EINVAL;
11763 			}
11764 		} else {
11765 			verbose(env, "unknown insn class %d\n", class);
11766 			return -EINVAL;
11767 		}
11768 
11769 		env->insn_idx++;
11770 	}
11771 
11772 	return 0;
11773 }
11774 
11775 static int find_btf_percpu_datasec(struct btf *btf)
11776 {
11777 	const struct btf_type *t;
11778 	const char *tname;
11779 	int i, n;
11780 
11781 	/*
11782 	 * Both vmlinux and module each have their own ".data..percpu"
11783 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11784 	 * types to look at only module's own BTF types.
11785 	 */
11786 	n = btf_nr_types(btf);
11787 	if (btf_is_module(btf))
11788 		i = btf_nr_types(btf_vmlinux);
11789 	else
11790 		i = 1;
11791 
11792 	for(; i < n; i++) {
11793 		t = btf_type_by_id(btf, i);
11794 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11795 			continue;
11796 
11797 		tname = btf_name_by_offset(btf, t->name_off);
11798 		if (!strcmp(tname, ".data..percpu"))
11799 			return i;
11800 	}
11801 
11802 	return -ENOENT;
11803 }
11804 
11805 /* replace pseudo btf_id with kernel symbol address */
11806 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11807 			       struct bpf_insn *insn,
11808 			       struct bpf_insn_aux_data *aux)
11809 {
11810 	const struct btf_var_secinfo *vsi;
11811 	const struct btf_type *datasec;
11812 	struct btf_mod_pair *btf_mod;
11813 	const struct btf_type *t;
11814 	const char *sym_name;
11815 	bool percpu = false;
11816 	u32 type, id = insn->imm;
11817 	struct btf *btf;
11818 	s32 datasec_id;
11819 	u64 addr;
11820 	int i, btf_fd, err;
11821 
11822 	btf_fd = insn[1].imm;
11823 	if (btf_fd) {
11824 		btf = btf_get_by_fd(btf_fd);
11825 		if (IS_ERR(btf)) {
11826 			verbose(env, "invalid module BTF object FD specified.\n");
11827 			return -EINVAL;
11828 		}
11829 	} else {
11830 		if (!btf_vmlinux) {
11831 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11832 			return -EINVAL;
11833 		}
11834 		btf = btf_vmlinux;
11835 		btf_get(btf);
11836 	}
11837 
11838 	t = btf_type_by_id(btf, id);
11839 	if (!t) {
11840 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11841 		err = -ENOENT;
11842 		goto err_put;
11843 	}
11844 
11845 	if (!btf_type_is_var(t)) {
11846 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11847 		err = -EINVAL;
11848 		goto err_put;
11849 	}
11850 
11851 	sym_name = btf_name_by_offset(btf, t->name_off);
11852 	addr = kallsyms_lookup_name(sym_name);
11853 	if (!addr) {
11854 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11855 			sym_name);
11856 		err = -ENOENT;
11857 		goto err_put;
11858 	}
11859 
11860 	datasec_id = find_btf_percpu_datasec(btf);
11861 	if (datasec_id > 0) {
11862 		datasec = btf_type_by_id(btf, datasec_id);
11863 		for_each_vsi(i, datasec, vsi) {
11864 			if (vsi->type == id) {
11865 				percpu = true;
11866 				break;
11867 			}
11868 		}
11869 	}
11870 
11871 	insn[0].imm = (u32)addr;
11872 	insn[1].imm = addr >> 32;
11873 
11874 	type = t->type;
11875 	t = btf_type_skip_modifiers(btf, type, NULL);
11876 	if (percpu) {
11877 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
11878 		aux->btf_var.btf = btf;
11879 		aux->btf_var.btf_id = type;
11880 	} else if (!btf_type_is_struct(t)) {
11881 		const struct btf_type *ret;
11882 		const char *tname;
11883 		u32 tsize;
11884 
11885 		/* resolve the type size of ksym. */
11886 		ret = btf_resolve_size(btf, t, &tsize);
11887 		if (IS_ERR(ret)) {
11888 			tname = btf_name_by_offset(btf, t->name_off);
11889 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11890 				tname, PTR_ERR(ret));
11891 			err = -EINVAL;
11892 			goto err_put;
11893 		}
11894 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11895 		aux->btf_var.mem_size = tsize;
11896 	} else {
11897 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11898 		aux->btf_var.btf = btf;
11899 		aux->btf_var.btf_id = type;
11900 	}
11901 
11902 	/* check whether we recorded this BTF (and maybe module) already */
11903 	for (i = 0; i < env->used_btf_cnt; i++) {
11904 		if (env->used_btfs[i].btf == btf) {
11905 			btf_put(btf);
11906 			return 0;
11907 		}
11908 	}
11909 
11910 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11911 		err = -E2BIG;
11912 		goto err_put;
11913 	}
11914 
11915 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11916 	btf_mod->btf = btf;
11917 	btf_mod->module = NULL;
11918 
11919 	/* if we reference variables from kernel module, bump its refcount */
11920 	if (btf_is_module(btf)) {
11921 		btf_mod->module = btf_try_get_module(btf);
11922 		if (!btf_mod->module) {
11923 			err = -ENXIO;
11924 			goto err_put;
11925 		}
11926 	}
11927 
11928 	env->used_btf_cnt++;
11929 
11930 	return 0;
11931 err_put:
11932 	btf_put(btf);
11933 	return err;
11934 }
11935 
11936 static int check_map_prealloc(struct bpf_map *map)
11937 {
11938 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11939 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11940 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11941 		!(map->map_flags & BPF_F_NO_PREALLOC);
11942 }
11943 
11944 static bool is_tracing_prog_type(enum bpf_prog_type type)
11945 {
11946 	switch (type) {
11947 	case BPF_PROG_TYPE_KPROBE:
11948 	case BPF_PROG_TYPE_TRACEPOINT:
11949 	case BPF_PROG_TYPE_PERF_EVENT:
11950 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11951 		return true;
11952 	default:
11953 		return false;
11954 	}
11955 }
11956 
11957 static bool is_preallocated_map(struct bpf_map *map)
11958 {
11959 	if (!check_map_prealloc(map))
11960 		return false;
11961 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11962 		return false;
11963 	return true;
11964 }
11965 
11966 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11967 					struct bpf_map *map,
11968 					struct bpf_prog *prog)
11969 
11970 {
11971 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11972 	/*
11973 	 * Validate that trace type programs use preallocated hash maps.
11974 	 *
11975 	 * For programs attached to PERF events this is mandatory as the
11976 	 * perf NMI can hit any arbitrary code sequence.
11977 	 *
11978 	 * All other trace types using preallocated hash maps are unsafe as
11979 	 * well because tracepoint or kprobes can be inside locked regions
11980 	 * of the memory allocator or at a place where a recursion into the
11981 	 * memory allocator would see inconsistent state.
11982 	 *
11983 	 * On RT enabled kernels run-time allocation of all trace type
11984 	 * programs is strictly prohibited due to lock type constraints. On
11985 	 * !RT kernels it is allowed for backwards compatibility reasons for
11986 	 * now, but warnings are emitted so developers are made aware of
11987 	 * the unsafety and can fix their programs before this is enforced.
11988 	 */
11989 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11990 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11991 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11992 			return -EINVAL;
11993 		}
11994 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11995 			verbose(env, "trace type programs can only use preallocated hash map\n");
11996 			return -EINVAL;
11997 		}
11998 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11999 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
12000 	}
12001 
12002 	if (map_value_has_spin_lock(map)) {
12003 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12004 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12005 			return -EINVAL;
12006 		}
12007 
12008 		if (is_tracing_prog_type(prog_type)) {
12009 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12010 			return -EINVAL;
12011 		}
12012 
12013 		if (prog->aux->sleepable) {
12014 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12015 			return -EINVAL;
12016 		}
12017 	}
12018 
12019 	if (map_value_has_timer(map)) {
12020 		if (is_tracing_prog_type(prog_type)) {
12021 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12022 			return -EINVAL;
12023 		}
12024 	}
12025 
12026 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12027 	    !bpf_offload_prog_map_match(prog, map)) {
12028 		verbose(env, "offload device mismatch between prog and map\n");
12029 		return -EINVAL;
12030 	}
12031 
12032 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12033 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12034 		return -EINVAL;
12035 	}
12036 
12037 	if (prog->aux->sleepable)
12038 		switch (map->map_type) {
12039 		case BPF_MAP_TYPE_HASH:
12040 		case BPF_MAP_TYPE_LRU_HASH:
12041 		case BPF_MAP_TYPE_ARRAY:
12042 		case BPF_MAP_TYPE_PERCPU_HASH:
12043 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12044 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12045 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12046 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12047 			if (!is_preallocated_map(map)) {
12048 				verbose(env,
12049 					"Sleepable programs can only use preallocated maps\n");
12050 				return -EINVAL;
12051 			}
12052 			break;
12053 		case BPF_MAP_TYPE_RINGBUF:
12054 		case BPF_MAP_TYPE_INODE_STORAGE:
12055 		case BPF_MAP_TYPE_SK_STORAGE:
12056 		case BPF_MAP_TYPE_TASK_STORAGE:
12057 			break;
12058 		default:
12059 			verbose(env,
12060 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12061 			return -EINVAL;
12062 		}
12063 
12064 	return 0;
12065 }
12066 
12067 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12068 {
12069 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12070 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12071 }
12072 
12073 /* find and rewrite pseudo imm in ld_imm64 instructions:
12074  *
12075  * 1. if it accesses map FD, replace it with actual map pointer.
12076  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12077  *
12078  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12079  */
12080 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12081 {
12082 	struct bpf_insn *insn = env->prog->insnsi;
12083 	int insn_cnt = env->prog->len;
12084 	int i, j, err;
12085 
12086 	err = bpf_prog_calc_tag(env->prog);
12087 	if (err)
12088 		return err;
12089 
12090 	for (i = 0; i < insn_cnt; i++, insn++) {
12091 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12092 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12093 			verbose(env, "BPF_LDX uses reserved fields\n");
12094 			return -EINVAL;
12095 		}
12096 
12097 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12098 			struct bpf_insn_aux_data *aux;
12099 			struct bpf_map *map;
12100 			struct fd f;
12101 			u64 addr;
12102 			u32 fd;
12103 
12104 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12105 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12106 			    insn[1].off != 0) {
12107 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12108 				return -EINVAL;
12109 			}
12110 
12111 			if (insn[0].src_reg == 0)
12112 				/* valid generic load 64-bit imm */
12113 				goto next_insn;
12114 
12115 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12116 				aux = &env->insn_aux_data[i];
12117 				err = check_pseudo_btf_id(env, insn, aux);
12118 				if (err)
12119 					return err;
12120 				goto next_insn;
12121 			}
12122 
12123 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12124 				aux = &env->insn_aux_data[i];
12125 				aux->ptr_type = PTR_TO_FUNC;
12126 				goto next_insn;
12127 			}
12128 
12129 			/* In final convert_pseudo_ld_imm64() step, this is
12130 			 * converted into regular 64-bit imm load insn.
12131 			 */
12132 			switch (insn[0].src_reg) {
12133 			case BPF_PSEUDO_MAP_VALUE:
12134 			case BPF_PSEUDO_MAP_IDX_VALUE:
12135 				break;
12136 			case BPF_PSEUDO_MAP_FD:
12137 			case BPF_PSEUDO_MAP_IDX:
12138 				if (insn[1].imm == 0)
12139 					break;
12140 				fallthrough;
12141 			default:
12142 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12143 				return -EINVAL;
12144 			}
12145 
12146 			switch (insn[0].src_reg) {
12147 			case BPF_PSEUDO_MAP_IDX_VALUE:
12148 			case BPF_PSEUDO_MAP_IDX:
12149 				if (bpfptr_is_null(env->fd_array)) {
12150 					verbose(env, "fd_idx without fd_array is invalid\n");
12151 					return -EPROTO;
12152 				}
12153 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12154 							    insn[0].imm * sizeof(fd),
12155 							    sizeof(fd)))
12156 					return -EFAULT;
12157 				break;
12158 			default:
12159 				fd = insn[0].imm;
12160 				break;
12161 			}
12162 
12163 			f = fdget(fd);
12164 			map = __bpf_map_get(f);
12165 			if (IS_ERR(map)) {
12166 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12167 					insn[0].imm);
12168 				return PTR_ERR(map);
12169 			}
12170 
12171 			err = check_map_prog_compatibility(env, map, env->prog);
12172 			if (err) {
12173 				fdput(f);
12174 				return err;
12175 			}
12176 
12177 			aux = &env->insn_aux_data[i];
12178 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12179 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12180 				addr = (unsigned long)map;
12181 			} else {
12182 				u32 off = insn[1].imm;
12183 
12184 				if (off >= BPF_MAX_VAR_OFF) {
12185 					verbose(env, "direct value offset of %u is not allowed\n", off);
12186 					fdput(f);
12187 					return -EINVAL;
12188 				}
12189 
12190 				if (!map->ops->map_direct_value_addr) {
12191 					verbose(env, "no direct value access support for this map type\n");
12192 					fdput(f);
12193 					return -EINVAL;
12194 				}
12195 
12196 				err = map->ops->map_direct_value_addr(map, &addr, off);
12197 				if (err) {
12198 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12199 						map->value_size, off);
12200 					fdput(f);
12201 					return err;
12202 				}
12203 
12204 				aux->map_off = off;
12205 				addr += off;
12206 			}
12207 
12208 			insn[0].imm = (u32)addr;
12209 			insn[1].imm = addr >> 32;
12210 
12211 			/* check whether we recorded this map already */
12212 			for (j = 0; j < env->used_map_cnt; j++) {
12213 				if (env->used_maps[j] == map) {
12214 					aux->map_index = j;
12215 					fdput(f);
12216 					goto next_insn;
12217 				}
12218 			}
12219 
12220 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12221 				fdput(f);
12222 				return -E2BIG;
12223 			}
12224 
12225 			/* hold the map. If the program is rejected by verifier,
12226 			 * the map will be released by release_maps() or it
12227 			 * will be used by the valid program until it's unloaded
12228 			 * and all maps are released in free_used_maps()
12229 			 */
12230 			bpf_map_inc(map);
12231 
12232 			aux->map_index = env->used_map_cnt;
12233 			env->used_maps[env->used_map_cnt++] = map;
12234 
12235 			if (bpf_map_is_cgroup_storage(map) &&
12236 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12237 				verbose(env, "only one cgroup storage of each type is allowed\n");
12238 				fdput(f);
12239 				return -EBUSY;
12240 			}
12241 
12242 			fdput(f);
12243 next_insn:
12244 			insn++;
12245 			i++;
12246 			continue;
12247 		}
12248 
12249 		/* Basic sanity check before we invest more work here. */
12250 		if (!bpf_opcode_in_insntable(insn->code)) {
12251 			verbose(env, "unknown opcode %02x\n", insn->code);
12252 			return -EINVAL;
12253 		}
12254 	}
12255 
12256 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12257 	 * 'struct bpf_map *' into a register instead of user map_fd.
12258 	 * These pointers will be used later by verifier to validate map access.
12259 	 */
12260 	return 0;
12261 }
12262 
12263 /* drop refcnt of maps used by the rejected program */
12264 static void release_maps(struct bpf_verifier_env *env)
12265 {
12266 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12267 			     env->used_map_cnt);
12268 }
12269 
12270 /* drop refcnt of maps used by the rejected program */
12271 static void release_btfs(struct bpf_verifier_env *env)
12272 {
12273 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12274 			     env->used_btf_cnt);
12275 }
12276 
12277 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12278 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12279 {
12280 	struct bpf_insn *insn = env->prog->insnsi;
12281 	int insn_cnt = env->prog->len;
12282 	int i;
12283 
12284 	for (i = 0; i < insn_cnt; i++, insn++) {
12285 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12286 			continue;
12287 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12288 			continue;
12289 		insn->src_reg = 0;
12290 	}
12291 }
12292 
12293 /* single env->prog->insni[off] instruction was replaced with the range
12294  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12295  * [0, off) and [off, end) to new locations, so the patched range stays zero
12296  */
12297 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12298 				 struct bpf_insn_aux_data *new_data,
12299 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12300 {
12301 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12302 	struct bpf_insn *insn = new_prog->insnsi;
12303 	u32 old_seen = old_data[off].seen;
12304 	u32 prog_len;
12305 	int i;
12306 
12307 	/* aux info at OFF always needs adjustment, no matter fast path
12308 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12309 	 * original insn at old prog.
12310 	 */
12311 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12312 
12313 	if (cnt == 1)
12314 		return;
12315 	prog_len = new_prog->len;
12316 
12317 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12318 	memcpy(new_data + off + cnt - 1, old_data + off,
12319 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12320 	for (i = off; i < off + cnt - 1; i++) {
12321 		/* Expand insni[off]'s seen count to the patched range. */
12322 		new_data[i].seen = old_seen;
12323 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12324 	}
12325 	env->insn_aux_data = new_data;
12326 	vfree(old_data);
12327 }
12328 
12329 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12330 {
12331 	int i;
12332 
12333 	if (len == 1)
12334 		return;
12335 	/* NOTE: fake 'exit' subprog should be updated as well. */
12336 	for (i = 0; i <= env->subprog_cnt; i++) {
12337 		if (env->subprog_info[i].start <= off)
12338 			continue;
12339 		env->subprog_info[i].start += len - 1;
12340 	}
12341 }
12342 
12343 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12344 {
12345 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12346 	int i, sz = prog->aux->size_poke_tab;
12347 	struct bpf_jit_poke_descriptor *desc;
12348 
12349 	for (i = 0; i < sz; i++) {
12350 		desc = &tab[i];
12351 		if (desc->insn_idx <= off)
12352 			continue;
12353 		desc->insn_idx += len - 1;
12354 	}
12355 }
12356 
12357 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12358 					    const struct bpf_insn *patch, u32 len)
12359 {
12360 	struct bpf_prog *new_prog;
12361 	struct bpf_insn_aux_data *new_data = NULL;
12362 
12363 	if (len > 1) {
12364 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12365 					      sizeof(struct bpf_insn_aux_data)));
12366 		if (!new_data)
12367 			return NULL;
12368 	}
12369 
12370 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12371 	if (IS_ERR(new_prog)) {
12372 		if (PTR_ERR(new_prog) == -ERANGE)
12373 			verbose(env,
12374 				"insn %d cannot be patched due to 16-bit range\n",
12375 				env->insn_aux_data[off].orig_idx);
12376 		vfree(new_data);
12377 		return NULL;
12378 	}
12379 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12380 	adjust_subprog_starts(env, off, len);
12381 	adjust_poke_descs(new_prog, off, len);
12382 	return new_prog;
12383 }
12384 
12385 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12386 					      u32 off, u32 cnt)
12387 {
12388 	int i, j;
12389 
12390 	/* find first prog starting at or after off (first to remove) */
12391 	for (i = 0; i < env->subprog_cnt; i++)
12392 		if (env->subprog_info[i].start >= off)
12393 			break;
12394 	/* find first prog starting at or after off + cnt (first to stay) */
12395 	for (j = i; j < env->subprog_cnt; j++)
12396 		if (env->subprog_info[j].start >= off + cnt)
12397 			break;
12398 	/* if j doesn't start exactly at off + cnt, we are just removing
12399 	 * the front of previous prog
12400 	 */
12401 	if (env->subprog_info[j].start != off + cnt)
12402 		j--;
12403 
12404 	if (j > i) {
12405 		struct bpf_prog_aux *aux = env->prog->aux;
12406 		int move;
12407 
12408 		/* move fake 'exit' subprog as well */
12409 		move = env->subprog_cnt + 1 - j;
12410 
12411 		memmove(env->subprog_info + i,
12412 			env->subprog_info + j,
12413 			sizeof(*env->subprog_info) * move);
12414 		env->subprog_cnt -= j - i;
12415 
12416 		/* remove func_info */
12417 		if (aux->func_info) {
12418 			move = aux->func_info_cnt - j;
12419 
12420 			memmove(aux->func_info + i,
12421 				aux->func_info + j,
12422 				sizeof(*aux->func_info) * move);
12423 			aux->func_info_cnt -= j - i;
12424 			/* func_info->insn_off is set after all code rewrites,
12425 			 * in adjust_btf_func() - no need to adjust
12426 			 */
12427 		}
12428 	} else {
12429 		/* convert i from "first prog to remove" to "first to adjust" */
12430 		if (env->subprog_info[i].start == off)
12431 			i++;
12432 	}
12433 
12434 	/* update fake 'exit' subprog as well */
12435 	for (; i <= env->subprog_cnt; i++)
12436 		env->subprog_info[i].start -= cnt;
12437 
12438 	return 0;
12439 }
12440 
12441 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12442 				      u32 cnt)
12443 {
12444 	struct bpf_prog *prog = env->prog;
12445 	u32 i, l_off, l_cnt, nr_linfo;
12446 	struct bpf_line_info *linfo;
12447 
12448 	nr_linfo = prog->aux->nr_linfo;
12449 	if (!nr_linfo)
12450 		return 0;
12451 
12452 	linfo = prog->aux->linfo;
12453 
12454 	/* find first line info to remove, count lines to be removed */
12455 	for (i = 0; i < nr_linfo; i++)
12456 		if (linfo[i].insn_off >= off)
12457 			break;
12458 
12459 	l_off = i;
12460 	l_cnt = 0;
12461 	for (; i < nr_linfo; i++)
12462 		if (linfo[i].insn_off < off + cnt)
12463 			l_cnt++;
12464 		else
12465 			break;
12466 
12467 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12468 	 * last removed linfo.  prog is already modified, so prog->len == off
12469 	 * means no live instructions after (tail of the program was removed).
12470 	 */
12471 	if (prog->len != off && l_cnt &&
12472 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12473 		l_cnt--;
12474 		linfo[--i].insn_off = off + cnt;
12475 	}
12476 
12477 	/* remove the line info which refer to the removed instructions */
12478 	if (l_cnt) {
12479 		memmove(linfo + l_off, linfo + i,
12480 			sizeof(*linfo) * (nr_linfo - i));
12481 
12482 		prog->aux->nr_linfo -= l_cnt;
12483 		nr_linfo = prog->aux->nr_linfo;
12484 	}
12485 
12486 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12487 	for (i = l_off; i < nr_linfo; i++)
12488 		linfo[i].insn_off -= cnt;
12489 
12490 	/* fix up all subprogs (incl. 'exit') which start >= off */
12491 	for (i = 0; i <= env->subprog_cnt; i++)
12492 		if (env->subprog_info[i].linfo_idx > l_off) {
12493 			/* program may have started in the removed region but
12494 			 * may not be fully removed
12495 			 */
12496 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12497 				env->subprog_info[i].linfo_idx -= l_cnt;
12498 			else
12499 				env->subprog_info[i].linfo_idx = l_off;
12500 		}
12501 
12502 	return 0;
12503 }
12504 
12505 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12506 {
12507 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12508 	unsigned int orig_prog_len = env->prog->len;
12509 	int err;
12510 
12511 	if (bpf_prog_is_dev_bound(env->prog->aux))
12512 		bpf_prog_offload_remove_insns(env, off, cnt);
12513 
12514 	err = bpf_remove_insns(env->prog, off, cnt);
12515 	if (err)
12516 		return err;
12517 
12518 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12519 	if (err)
12520 		return err;
12521 
12522 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12523 	if (err)
12524 		return err;
12525 
12526 	memmove(aux_data + off,	aux_data + off + cnt,
12527 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12528 
12529 	return 0;
12530 }
12531 
12532 /* The verifier does more data flow analysis than llvm and will not
12533  * explore branches that are dead at run time. Malicious programs can
12534  * have dead code too. Therefore replace all dead at-run-time code
12535  * with 'ja -1'.
12536  *
12537  * Just nops are not optimal, e.g. if they would sit at the end of the
12538  * program and through another bug we would manage to jump there, then
12539  * we'd execute beyond program memory otherwise. Returning exception
12540  * code also wouldn't work since we can have subprogs where the dead
12541  * code could be located.
12542  */
12543 static void sanitize_dead_code(struct bpf_verifier_env *env)
12544 {
12545 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12546 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12547 	struct bpf_insn *insn = env->prog->insnsi;
12548 	const int insn_cnt = env->prog->len;
12549 	int i;
12550 
12551 	for (i = 0; i < insn_cnt; i++) {
12552 		if (aux_data[i].seen)
12553 			continue;
12554 		memcpy(insn + i, &trap, sizeof(trap));
12555 		aux_data[i].zext_dst = false;
12556 	}
12557 }
12558 
12559 static bool insn_is_cond_jump(u8 code)
12560 {
12561 	u8 op;
12562 
12563 	if (BPF_CLASS(code) == BPF_JMP32)
12564 		return true;
12565 
12566 	if (BPF_CLASS(code) != BPF_JMP)
12567 		return false;
12568 
12569 	op = BPF_OP(code);
12570 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12571 }
12572 
12573 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12574 {
12575 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12576 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12577 	struct bpf_insn *insn = env->prog->insnsi;
12578 	const int insn_cnt = env->prog->len;
12579 	int i;
12580 
12581 	for (i = 0; i < insn_cnt; i++, insn++) {
12582 		if (!insn_is_cond_jump(insn->code))
12583 			continue;
12584 
12585 		if (!aux_data[i + 1].seen)
12586 			ja.off = insn->off;
12587 		else if (!aux_data[i + 1 + insn->off].seen)
12588 			ja.off = 0;
12589 		else
12590 			continue;
12591 
12592 		if (bpf_prog_is_dev_bound(env->prog->aux))
12593 			bpf_prog_offload_replace_insn(env, i, &ja);
12594 
12595 		memcpy(insn, &ja, sizeof(ja));
12596 	}
12597 }
12598 
12599 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12600 {
12601 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12602 	int insn_cnt = env->prog->len;
12603 	int i, err;
12604 
12605 	for (i = 0; i < insn_cnt; i++) {
12606 		int j;
12607 
12608 		j = 0;
12609 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12610 			j++;
12611 		if (!j)
12612 			continue;
12613 
12614 		err = verifier_remove_insns(env, i, j);
12615 		if (err)
12616 			return err;
12617 		insn_cnt = env->prog->len;
12618 	}
12619 
12620 	return 0;
12621 }
12622 
12623 static int opt_remove_nops(struct bpf_verifier_env *env)
12624 {
12625 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12626 	struct bpf_insn *insn = env->prog->insnsi;
12627 	int insn_cnt = env->prog->len;
12628 	int i, err;
12629 
12630 	for (i = 0; i < insn_cnt; i++) {
12631 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12632 			continue;
12633 
12634 		err = verifier_remove_insns(env, i, 1);
12635 		if (err)
12636 			return err;
12637 		insn_cnt--;
12638 		i--;
12639 	}
12640 
12641 	return 0;
12642 }
12643 
12644 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12645 					 const union bpf_attr *attr)
12646 {
12647 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12648 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12649 	int i, patch_len, delta = 0, len = env->prog->len;
12650 	struct bpf_insn *insns = env->prog->insnsi;
12651 	struct bpf_prog *new_prog;
12652 	bool rnd_hi32;
12653 
12654 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12655 	zext_patch[1] = BPF_ZEXT_REG(0);
12656 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12657 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12658 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12659 	for (i = 0; i < len; i++) {
12660 		int adj_idx = i + delta;
12661 		struct bpf_insn insn;
12662 		int load_reg;
12663 
12664 		insn = insns[adj_idx];
12665 		load_reg = insn_def_regno(&insn);
12666 		if (!aux[adj_idx].zext_dst) {
12667 			u8 code, class;
12668 			u32 imm_rnd;
12669 
12670 			if (!rnd_hi32)
12671 				continue;
12672 
12673 			code = insn.code;
12674 			class = BPF_CLASS(code);
12675 			if (load_reg == -1)
12676 				continue;
12677 
12678 			/* NOTE: arg "reg" (the fourth one) is only used for
12679 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12680 			 *       here.
12681 			 */
12682 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12683 				if (class == BPF_LD &&
12684 				    BPF_MODE(code) == BPF_IMM)
12685 					i++;
12686 				continue;
12687 			}
12688 
12689 			/* ctx load could be transformed into wider load. */
12690 			if (class == BPF_LDX &&
12691 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12692 				continue;
12693 
12694 			imm_rnd = get_random_int();
12695 			rnd_hi32_patch[0] = insn;
12696 			rnd_hi32_patch[1].imm = imm_rnd;
12697 			rnd_hi32_patch[3].dst_reg = load_reg;
12698 			patch = rnd_hi32_patch;
12699 			patch_len = 4;
12700 			goto apply_patch_buffer;
12701 		}
12702 
12703 		/* Add in an zero-extend instruction if a) the JIT has requested
12704 		 * it or b) it's a CMPXCHG.
12705 		 *
12706 		 * The latter is because: BPF_CMPXCHG always loads a value into
12707 		 * R0, therefore always zero-extends. However some archs'
12708 		 * equivalent instruction only does this load when the
12709 		 * comparison is successful. This detail of CMPXCHG is
12710 		 * orthogonal to the general zero-extension behaviour of the
12711 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12712 		 */
12713 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12714 			continue;
12715 
12716 		if (WARN_ON(load_reg == -1)) {
12717 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12718 			return -EFAULT;
12719 		}
12720 
12721 		zext_patch[0] = insn;
12722 		zext_patch[1].dst_reg = load_reg;
12723 		zext_patch[1].src_reg = load_reg;
12724 		patch = zext_patch;
12725 		patch_len = 2;
12726 apply_patch_buffer:
12727 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12728 		if (!new_prog)
12729 			return -ENOMEM;
12730 		env->prog = new_prog;
12731 		insns = new_prog->insnsi;
12732 		aux = env->insn_aux_data;
12733 		delta += patch_len - 1;
12734 	}
12735 
12736 	return 0;
12737 }
12738 
12739 /* convert load instructions that access fields of a context type into a
12740  * sequence of instructions that access fields of the underlying structure:
12741  *     struct __sk_buff    -> struct sk_buff
12742  *     struct bpf_sock_ops -> struct sock
12743  */
12744 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12745 {
12746 	const struct bpf_verifier_ops *ops = env->ops;
12747 	int i, cnt, size, ctx_field_size, delta = 0;
12748 	const int insn_cnt = env->prog->len;
12749 	struct bpf_insn insn_buf[16], *insn;
12750 	u32 target_size, size_default, off;
12751 	struct bpf_prog *new_prog;
12752 	enum bpf_access_type type;
12753 	bool is_narrower_load;
12754 
12755 	if (ops->gen_prologue || env->seen_direct_write) {
12756 		if (!ops->gen_prologue) {
12757 			verbose(env, "bpf verifier is misconfigured\n");
12758 			return -EINVAL;
12759 		}
12760 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12761 					env->prog);
12762 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12763 			verbose(env, "bpf verifier is misconfigured\n");
12764 			return -EINVAL;
12765 		} else if (cnt) {
12766 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12767 			if (!new_prog)
12768 				return -ENOMEM;
12769 
12770 			env->prog = new_prog;
12771 			delta += cnt - 1;
12772 		}
12773 	}
12774 
12775 	if (bpf_prog_is_dev_bound(env->prog->aux))
12776 		return 0;
12777 
12778 	insn = env->prog->insnsi + delta;
12779 
12780 	for (i = 0; i < insn_cnt; i++, insn++) {
12781 		bpf_convert_ctx_access_t convert_ctx_access;
12782 		bool ctx_access;
12783 
12784 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12785 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12786 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12787 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12788 			type = BPF_READ;
12789 			ctx_access = true;
12790 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12791 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12792 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12793 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12794 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12795 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12796 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12797 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12798 			type = BPF_WRITE;
12799 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12800 		} else {
12801 			continue;
12802 		}
12803 
12804 		if (type == BPF_WRITE &&
12805 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12806 			struct bpf_insn patch[] = {
12807 				*insn,
12808 				BPF_ST_NOSPEC(),
12809 			};
12810 
12811 			cnt = ARRAY_SIZE(patch);
12812 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12813 			if (!new_prog)
12814 				return -ENOMEM;
12815 
12816 			delta    += cnt - 1;
12817 			env->prog = new_prog;
12818 			insn      = new_prog->insnsi + i + delta;
12819 			continue;
12820 		}
12821 
12822 		if (!ctx_access)
12823 			continue;
12824 
12825 		switch (env->insn_aux_data[i + delta].ptr_type) {
12826 		case PTR_TO_CTX:
12827 			if (!ops->convert_ctx_access)
12828 				continue;
12829 			convert_ctx_access = ops->convert_ctx_access;
12830 			break;
12831 		case PTR_TO_SOCKET:
12832 		case PTR_TO_SOCK_COMMON:
12833 			convert_ctx_access = bpf_sock_convert_ctx_access;
12834 			break;
12835 		case PTR_TO_TCP_SOCK:
12836 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12837 			break;
12838 		case PTR_TO_XDP_SOCK:
12839 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12840 			break;
12841 		case PTR_TO_BTF_ID:
12842 			if (type == BPF_READ) {
12843 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12844 					BPF_SIZE((insn)->code);
12845 				env->prog->aux->num_exentries++;
12846 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12847 				verbose(env, "Writes through BTF pointers are not allowed\n");
12848 				return -EINVAL;
12849 			}
12850 			continue;
12851 		default:
12852 			continue;
12853 		}
12854 
12855 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12856 		size = BPF_LDST_BYTES(insn);
12857 
12858 		/* If the read access is a narrower load of the field,
12859 		 * convert to a 4/8-byte load, to minimum program type specific
12860 		 * convert_ctx_access changes. If conversion is successful,
12861 		 * we will apply proper mask to the result.
12862 		 */
12863 		is_narrower_load = size < ctx_field_size;
12864 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12865 		off = insn->off;
12866 		if (is_narrower_load) {
12867 			u8 size_code;
12868 
12869 			if (type == BPF_WRITE) {
12870 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12871 				return -EINVAL;
12872 			}
12873 
12874 			size_code = BPF_H;
12875 			if (ctx_field_size == 4)
12876 				size_code = BPF_W;
12877 			else if (ctx_field_size == 8)
12878 				size_code = BPF_DW;
12879 
12880 			insn->off = off & ~(size_default - 1);
12881 			insn->code = BPF_LDX | BPF_MEM | size_code;
12882 		}
12883 
12884 		target_size = 0;
12885 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12886 					 &target_size);
12887 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12888 		    (ctx_field_size && !target_size)) {
12889 			verbose(env, "bpf verifier is misconfigured\n");
12890 			return -EINVAL;
12891 		}
12892 
12893 		if (is_narrower_load && size < target_size) {
12894 			u8 shift = bpf_ctx_narrow_access_offset(
12895 				off, size, size_default) * 8;
12896 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12897 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12898 				return -EINVAL;
12899 			}
12900 			if (ctx_field_size <= 4) {
12901 				if (shift)
12902 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12903 									insn->dst_reg,
12904 									shift);
12905 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12906 								(1 << size * 8) - 1);
12907 			} else {
12908 				if (shift)
12909 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12910 									insn->dst_reg,
12911 									shift);
12912 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12913 								(1ULL << size * 8) - 1);
12914 			}
12915 		}
12916 
12917 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12918 		if (!new_prog)
12919 			return -ENOMEM;
12920 
12921 		delta += cnt - 1;
12922 
12923 		/* keep walking new program and skip insns we just inserted */
12924 		env->prog = new_prog;
12925 		insn      = new_prog->insnsi + i + delta;
12926 	}
12927 
12928 	return 0;
12929 }
12930 
12931 static int jit_subprogs(struct bpf_verifier_env *env)
12932 {
12933 	struct bpf_prog *prog = env->prog, **func, *tmp;
12934 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12935 	struct bpf_map *map_ptr;
12936 	struct bpf_insn *insn;
12937 	void *old_bpf_func;
12938 	int err, num_exentries;
12939 
12940 	if (env->subprog_cnt <= 1)
12941 		return 0;
12942 
12943 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12944 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12945 			continue;
12946 
12947 		/* Upon error here we cannot fall back to interpreter but
12948 		 * need a hard reject of the program. Thus -EFAULT is
12949 		 * propagated in any case.
12950 		 */
12951 		subprog = find_subprog(env, i + insn->imm + 1);
12952 		if (subprog < 0) {
12953 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12954 				  i + insn->imm + 1);
12955 			return -EFAULT;
12956 		}
12957 		/* temporarily remember subprog id inside insn instead of
12958 		 * aux_data, since next loop will split up all insns into funcs
12959 		 */
12960 		insn->off = subprog;
12961 		/* remember original imm in case JIT fails and fallback
12962 		 * to interpreter will be needed
12963 		 */
12964 		env->insn_aux_data[i].call_imm = insn->imm;
12965 		/* point imm to __bpf_call_base+1 from JITs point of view */
12966 		insn->imm = 1;
12967 		if (bpf_pseudo_func(insn))
12968 			/* jit (e.g. x86_64) may emit fewer instructions
12969 			 * if it learns a u32 imm is the same as a u64 imm.
12970 			 * Force a non zero here.
12971 			 */
12972 			insn[1].imm = 1;
12973 	}
12974 
12975 	err = bpf_prog_alloc_jited_linfo(prog);
12976 	if (err)
12977 		goto out_undo_insn;
12978 
12979 	err = -ENOMEM;
12980 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12981 	if (!func)
12982 		goto out_undo_insn;
12983 
12984 	for (i = 0; i < env->subprog_cnt; i++) {
12985 		subprog_start = subprog_end;
12986 		subprog_end = env->subprog_info[i + 1].start;
12987 
12988 		len = subprog_end - subprog_start;
12989 		/* bpf_prog_run() doesn't call subprogs directly,
12990 		 * hence main prog stats include the runtime of subprogs.
12991 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12992 		 * func[i]->stats will never be accessed and stays NULL
12993 		 */
12994 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12995 		if (!func[i])
12996 			goto out_free;
12997 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12998 		       len * sizeof(struct bpf_insn));
12999 		func[i]->type = prog->type;
13000 		func[i]->len = len;
13001 		if (bpf_prog_calc_tag(func[i]))
13002 			goto out_free;
13003 		func[i]->is_func = 1;
13004 		func[i]->aux->func_idx = i;
13005 		/* Below members will be freed only at prog->aux */
13006 		func[i]->aux->btf = prog->aux->btf;
13007 		func[i]->aux->func_info = prog->aux->func_info;
13008 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13009 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13010 
13011 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13012 			struct bpf_jit_poke_descriptor *poke;
13013 
13014 			poke = &prog->aux->poke_tab[j];
13015 			if (poke->insn_idx < subprog_end &&
13016 			    poke->insn_idx >= subprog_start)
13017 				poke->aux = func[i]->aux;
13018 		}
13019 
13020 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
13021 		 * Long term would need debug info to populate names
13022 		 */
13023 		func[i]->aux->name[0] = 'F';
13024 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13025 		func[i]->jit_requested = 1;
13026 		func[i]->blinding_requested = prog->blinding_requested;
13027 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13028 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13029 		func[i]->aux->linfo = prog->aux->linfo;
13030 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13031 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13032 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13033 		num_exentries = 0;
13034 		insn = func[i]->insnsi;
13035 		for (j = 0; j < func[i]->len; j++, insn++) {
13036 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13037 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13038 				num_exentries++;
13039 		}
13040 		func[i]->aux->num_exentries = num_exentries;
13041 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13042 		func[i] = bpf_int_jit_compile(func[i]);
13043 		if (!func[i]->jited) {
13044 			err = -ENOTSUPP;
13045 			goto out_free;
13046 		}
13047 		cond_resched();
13048 	}
13049 
13050 	/* at this point all bpf functions were successfully JITed
13051 	 * now populate all bpf_calls with correct addresses and
13052 	 * run last pass of JIT
13053 	 */
13054 	for (i = 0; i < env->subprog_cnt; i++) {
13055 		insn = func[i]->insnsi;
13056 		for (j = 0; j < func[i]->len; j++, insn++) {
13057 			if (bpf_pseudo_func(insn)) {
13058 				subprog = insn->off;
13059 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13060 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13061 				continue;
13062 			}
13063 			if (!bpf_pseudo_call(insn))
13064 				continue;
13065 			subprog = insn->off;
13066 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13067 		}
13068 
13069 		/* we use the aux data to keep a list of the start addresses
13070 		 * of the JITed images for each function in the program
13071 		 *
13072 		 * for some architectures, such as powerpc64, the imm field
13073 		 * might not be large enough to hold the offset of the start
13074 		 * address of the callee's JITed image from __bpf_call_base
13075 		 *
13076 		 * in such cases, we can lookup the start address of a callee
13077 		 * by using its subprog id, available from the off field of
13078 		 * the call instruction, as an index for this list
13079 		 */
13080 		func[i]->aux->func = func;
13081 		func[i]->aux->func_cnt = env->subprog_cnt;
13082 	}
13083 	for (i = 0; i < env->subprog_cnt; i++) {
13084 		old_bpf_func = func[i]->bpf_func;
13085 		tmp = bpf_int_jit_compile(func[i]);
13086 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13087 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13088 			err = -ENOTSUPP;
13089 			goto out_free;
13090 		}
13091 		cond_resched();
13092 	}
13093 
13094 	/* finally lock prog and jit images for all functions and
13095 	 * populate kallsysm
13096 	 */
13097 	for (i = 0; i < env->subprog_cnt; i++) {
13098 		bpf_prog_lock_ro(func[i]);
13099 		bpf_prog_kallsyms_add(func[i]);
13100 	}
13101 
13102 	/* Last step: make now unused interpreter insns from main
13103 	 * prog consistent for later dump requests, so they can
13104 	 * later look the same as if they were interpreted only.
13105 	 */
13106 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13107 		if (bpf_pseudo_func(insn)) {
13108 			insn[0].imm = env->insn_aux_data[i].call_imm;
13109 			insn[1].imm = insn->off;
13110 			insn->off = 0;
13111 			continue;
13112 		}
13113 		if (!bpf_pseudo_call(insn))
13114 			continue;
13115 		insn->off = env->insn_aux_data[i].call_imm;
13116 		subprog = find_subprog(env, i + insn->off + 1);
13117 		insn->imm = subprog;
13118 	}
13119 
13120 	prog->jited = 1;
13121 	prog->bpf_func = func[0]->bpf_func;
13122 	prog->jited_len = func[0]->jited_len;
13123 	prog->aux->func = func;
13124 	prog->aux->func_cnt = env->subprog_cnt;
13125 	bpf_prog_jit_attempt_done(prog);
13126 	return 0;
13127 out_free:
13128 	/* We failed JIT'ing, so at this point we need to unregister poke
13129 	 * descriptors from subprogs, so that kernel is not attempting to
13130 	 * patch it anymore as we're freeing the subprog JIT memory.
13131 	 */
13132 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13133 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13134 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13135 	}
13136 	/* At this point we're guaranteed that poke descriptors are not
13137 	 * live anymore. We can just unlink its descriptor table as it's
13138 	 * released with the main prog.
13139 	 */
13140 	for (i = 0; i < env->subprog_cnt; i++) {
13141 		if (!func[i])
13142 			continue;
13143 		func[i]->aux->poke_tab = NULL;
13144 		bpf_jit_free(func[i]);
13145 	}
13146 	kfree(func);
13147 out_undo_insn:
13148 	/* cleanup main prog to be interpreted */
13149 	prog->jit_requested = 0;
13150 	prog->blinding_requested = 0;
13151 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13152 		if (!bpf_pseudo_call(insn))
13153 			continue;
13154 		insn->off = 0;
13155 		insn->imm = env->insn_aux_data[i].call_imm;
13156 	}
13157 	bpf_prog_jit_attempt_done(prog);
13158 	return err;
13159 }
13160 
13161 static int fixup_call_args(struct bpf_verifier_env *env)
13162 {
13163 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13164 	struct bpf_prog *prog = env->prog;
13165 	struct bpf_insn *insn = prog->insnsi;
13166 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13167 	int i, depth;
13168 #endif
13169 	int err = 0;
13170 
13171 	if (env->prog->jit_requested &&
13172 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13173 		err = jit_subprogs(env);
13174 		if (err == 0)
13175 			return 0;
13176 		if (err == -EFAULT)
13177 			return err;
13178 	}
13179 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13180 	if (has_kfunc_call) {
13181 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13182 		return -EINVAL;
13183 	}
13184 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13185 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13186 		 * have to be rejected, since interpreter doesn't support them yet.
13187 		 */
13188 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13189 		return -EINVAL;
13190 	}
13191 	for (i = 0; i < prog->len; i++, insn++) {
13192 		if (bpf_pseudo_func(insn)) {
13193 			/* When JIT fails the progs with callback calls
13194 			 * have to be rejected, since interpreter doesn't support them yet.
13195 			 */
13196 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13197 			return -EINVAL;
13198 		}
13199 
13200 		if (!bpf_pseudo_call(insn))
13201 			continue;
13202 		depth = get_callee_stack_depth(env, insn, i);
13203 		if (depth < 0)
13204 			return depth;
13205 		bpf_patch_call_args(insn, depth);
13206 	}
13207 	err = 0;
13208 #endif
13209 	return err;
13210 }
13211 
13212 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13213 			    struct bpf_insn *insn)
13214 {
13215 	const struct bpf_kfunc_desc *desc;
13216 
13217 	if (!insn->imm) {
13218 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13219 		return -EINVAL;
13220 	}
13221 
13222 	/* insn->imm has the btf func_id. Replace it with
13223 	 * an address (relative to __bpf_base_call).
13224 	 */
13225 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13226 	if (!desc) {
13227 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13228 			insn->imm);
13229 		return -EFAULT;
13230 	}
13231 
13232 	insn->imm = desc->imm;
13233 
13234 	return 0;
13235 }
13236 
13237 /* Do various post-verification rewrites in a single program pass.
13238  * These rewrites simplify JIT and interpreter implementations.
13239  */
13240 static int do_misc_fixups(struct bpf_verifier_env *env)
13241 {
13242 	struct bpf_prog *prog = env->prog;
13243 	enum bpf_attach_type eatype = prog->expected_attach_type;
13244 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13245 	struct bpf_insn *insn = prog->insnsi;
13246 	const struct bpf_func_proto *fn;
13247 	const int insn_cnt = prog->len;
13248 	const struct bpf_map_ops *ops;
13249 	struct bpf_insn_aux_data *aux;
13250 	struct bpf_insn insn_buf[16];
13251 	struct bpf_prog *new_prog;
13252 	struct bpf_map *map_ptr;
13253 	int i, ret, cnt, delta = 0;
13254 
13255 	for (i = 0; i < insn_cnt; i++, insn++) {
13256 		/* Make divide-by-zero exceptions impossible. */
13257 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13258 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13259 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13260 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13261 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13262 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13263 			struct bpf_insn *patchlet;
13264 			struct bpf_insn chk_and_div[] = {
13265 				/* [R,W]x div 0 -> 0 */
13266 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13267 					     BPF_JNE | BPF_K, insn->src_reg,
13268 					     0, 2, 0),
13269 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13270 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13271 				*insn,
13272 			};
13273 			struct bpf_insn chk_and_mod[] = {
13274 				/* [R,W]x mod 0 -> [R,W]x */
13275 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13276 					     BPF_JEQ | BPF_K, insn->src_reg,
13277 					     0, 1 + (is64 ? 0 : 1), 0),
13278 				*insn,
13279 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13280 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13281 			};
13282 
13283 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13284 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13285 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13286 
13287 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13288 			if (!new_prog)
13289 				return -ENOMEM;
13290 
13291 			delta    += cnt - 1;
13292 			env->prog = prog = new_prog;
13293 			insn      = new_prog->insnsi + i + delta;
13294 			continue;
13295 		}
13296 
13297 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13298 		if (BPF_CLASS(insn->code) == BPF_LD &&
13299 		    (BPF_MODE(insn->code) == BPF_ABS ||
13300 		     BPF_MODE(insn->code) == BPF_IND)) {
13301 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13302 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13303 				verbose(env, "bpf verifier is misconfigured\n");
13304 				return -EINVAL;
13305 			}
13306 
13307 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13308 			if (!new_prog)
13309 				return -ENOMEM;
13310 
13311 			delta    += cnt - 1;
13312 			env->prog = prog = new_prog;
13313 			insn      = new_prog->insnsi + i + delta;
13314 			continue;
13315 		}
13316 
13317 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
13318 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13319 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13320 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13321 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13322 			struct bpf_insn *patch = &insn_buf[0];
13323 			bool issrc, isneg, isimm;
13324 			u32 off_reg;
13325 
13326 			aux = &env->insn_aux_data[i + delta];
13327 			if (!aux->alu_state ||
13328 			    aux->alu_state == BPF_ALU_NON_POINTER)
13329 				continue;
13330 
13331 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13332 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13333 				BPF_ALU_SANITIZE_SRC;
13334 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13335 
13336 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13337 			if (isimm) {
13338 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13339 			} else {
13340 				if (isneg)
13341 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13342 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13343 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13344 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13345 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13346 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13347 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13348 			}
13349 			if (!issrc)
13350 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13351 			insn->src_reg = BPF_REG_AX;
13352 			if (isneg)
13353 				insn->code = insn->code == code_add ?
13354 					     code_sub : code_add;
13355 			*patch++ = *insn;
13356 			if (issrc && isneg && !isimm)
13357 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13358 			cnt = patch - insn_buf;
13359 
13360 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13361 			if (!new_prog)
13362 				return -ENOMEM;
13363 
13364 			delta    += cnt - 1;
13365 			env->prog = prog = new_prog;
13366 			insn      = new_prog->insnsi + i + delta;
13367 			continue;
13368 		}
13369 
13370 		if (insn->code != (BPF_JMP | BPF_CALL))
13371 			continue;
13372 		if (insn->src_reg == BPF_PSEUDO_CALL)
13373 			continue;
13374 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13375 			ret = fixup_kfunc_call(env, insn);
13376 			if (ret)
13377 				return ret;
13378 			continue;
13379 		}
13380 
13381 		if (insn->imm == BPF_FUNC_get_route_realm)
13382 			prog->dst_needed = 1;
13383 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13384 			bpf_user_rnd_init_once();
13385 		if (insn->imm == BPF_FUNC_override_return)
13386 			prog->kprobe_override = 1;
13387 		if (insn->imm == BPF_FUNC_tail_call) {
13388 			/* If we tail call into other programs, we
13389 			 * cannot make any assumptions since they can
13390 			 * be replaced dynamically during runtime in
13391 			 * the program array.
13392 			 */
13393 			prog->cb_access = 1;
13394 			if (!allow_tail_call_in_subprogs(env))
13395 				prog->aux->stack_depth = MAX_BPF_STACK;
13396 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13397 
13398 			/* mark bpf_tail_call as different opcode to avoid
13399 			 * conditional branch in the interpreter for every normal
13400 			 * call and to prevent accidental JITing by JIT compiler
13401 			 * that doesn't support bpf_tail_call yet
13402 			 */
13403 			insn->imm = 0;
13404 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13405 
13406 			aux = &env->insn_aux_data[i + delta];
13407 			if (env->bpf_capable && !prog->blinding_requested &&
13408 			    prog->jit_requested &&
13409 			    !bpf_map_key_poisoned(aux) &&
13410 			    !bpf_map_ptr_poisoned(aux) &&
13411 			    !bpf_map_ptr_unpriv(aux)) {
13412 				struct bpf_jit_poke_descriptor desc = {
13413 					.reason = BPF_POKE_REASON_TAIL_CALL,
13414 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13415 					.tail_call.key = bpf_map_key_immediate(aux),
13416 					.insn_idx = i + delta,
13417 				};
13418 
13419 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13420 				if (ret < 0) {
13421 					verbose(env, "adding tail call poke descriptor failed\n");
13422 					return ret;
13423 				}
13424 
13425 				insn->imm = ret + 1;
13426 				continue;
13427 			}
13428 
13429 			if (!bpf_map_ptr_unpriv(aux))
13430 				continue;
13431 
13432 			/* instead of changing every JIT dealing with tail_call
13433 			 * emit two extra insns:
13434 			 * if (index >= max_entries) goto out;
13435 			 * index &= array->index_mask;
13436 			 * to avoid out-of-bounds cpu speculation
13437 			 */
13438 			if (bpf_map_ptr_poisoned(aux)) {
13439 				verbose(env, "tail_call abusing map_ptr\n");
13440 				return -EINVAL;
13441 			}
13442 
13443 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13444 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13445 						  map_ptr->max_entries, 2);
13446 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13447 						    container_of(map_ptr,
13448 								 struct bpf_array,
13449 								 map)->index_mask);
13450 			insn_buf[2] = *insn;
13451 			cnt = 3;
13452 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13453 			if (!new_prog)
13454 				return -ENOMEM;
13455 
13456 			delta    += cnt - 1;
13457 			env->prog = prog = new_prog;
13458 			insn      = new_prog->insnsi + i + delta;
13459 			continue;
13460 		}
13461 
13462 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13463 			/* The verifier will process callback_fn as many times as necessary
13464 			 * with different maps and the register states prepared by
13465 			 * set_timer_callback_state will be accurate.
13466 			 *
13467 			 * The following use case is valid:
13468 			 *   map1 is shared by prog1, prog2, prog3.
13469 			 *   prog1 calls bpf_timer_init for some map1 elements
13470 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13471 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13472 			 *   prog3 calls bpf_timer_start for some map1 elements.
13473 			 *     Those that were not both bpf_timer_init-ed and
13474 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13475 			 */
13476 			struct bpf_insn ld_addrs[2] = {
13477 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13478 			};
13479 
13480 			insn_buf[0] = ld_addrs[0];
13481 			insn_buf[1] = ld_addrs[1];
13482 			insn_buf[2] = *insn;
13483 			cnt = 3;
13484 
13485 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13486 			if (!new_prog)
13487 				return -ENOMEM;
13488 
13489 			delta    += cnt - 1;
13490 			env->prog = prog = new_prog;
13491 			insn      = new_prog->insnsi + i + delta;
13492 			goto patch_call_imm;
13493 		}
13494 
13495 		if (insn->imm == BPF_FUNC_task_storage_get ||
13496 		    insn->imm == BPF_FUNC_sk_storage_get ||
13497 		    insn->imm == BPF_FUNC_inode_storage_get) {
13498 			if (env->prog->aux->sleepable)
13499 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
13500 			else
13501 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
13502 			insn_buf[1] = *insn;
13503 			cnt = 2;
13504 
13505 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13506 			if (!new_prog)
13507 				return -ENOMEM;
13508 
13509 			delta += cnt - 1;
13510 			env->prog = prog = new_prog;
13511 			insn = new_prog->insnsi + i + delta;
13512 			goto patch_call_imm;
13513 		}
13514 
13515 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13516 		 * and other inlining handlers are currently limited to 64 bit
13517 		 * only.
13518 		 */
13519 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13520 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13521 		     insn->imm == BPF_FUNC_map_update_elem ||
13522 		     insn->imm == BPF_FUNC_map_delete_elem ||
13523 		     insn->imm == BPF_FUNC_map_push_elem   ||
13524 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13525 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13526 		     insn->imm == BPF_FUNC_redirect_map    ||
13527 		     insn->imm == BPF_FUNC_for_each_map_elem)) {
13528 			aux = &env->insn_aux_data[i + delta];
13529 			if (bpf_map_ptr_poisoned(aux))
13530 				goto patch_call_imm;
13531 
13532 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13533 			ops = map_ptr->ops;
13534 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13535 			    ops->map_gen_lookup) {
13536 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13537 				if (cnt == -EOPNOTSUPP)
13538 					goto patch_map_ops_generic;
13539 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13540 					verbose(env, "bpf verifier is misconfigured\n");
13541 					return -EINVAL;
13542 				}
13543 
13544 				new_prog = bpf_patch_insn_data(env, i + delta,
13545 							       insn_buf, cnt);
13546 				if (!new_prog)
13547 					return -ENOMEM;
13548 
13549 				delta    += cnt - 1;
13550 				env->prog = prog = new_prog;
13551 				insn      = new_prog->insnsi + i + delta;
13552 				continue;
13553 			}
13554 
13555 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13556 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13557 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13558 				     (int (*)(struct bpf_map *map, void *key))NULL));
13559 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13560 				     (int (*)(struct bpf_map *map, void *key, void *value,
13561 					      u64 flags))NULL));
13562 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13563 				     (int (*)(struct bpf_map *map, void *value,
13564 					      u64 flags))NULL));
13565 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13566 				     (int (*)(struct bpf_map *map, void *value))NULL));
13567 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13568 				     (int (*)(struct bpf_map *map, void *value))NULL));
13569 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13570 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13571 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13572 				     (int (*)(struct bpf_map *map,
13573 					      bpf_callback_t callback_fn,
13574 					      void *callback_ctx,
13575 					      u64 flags))NULL));
13576 
13577 patch_map_ops_generic:
13578 			switch (insn->imm) {
13579 			case BPF_FUNC_map_lookup_elem:
13580 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13581 				continue;
13582 			case BPF_FUNC_map_update_elem:
13583 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13584 				continue;
13585 			case BPF_FUNC_map_delete_elem:
13586 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13587 				continue;
13588 			case BPF_FUNC_map_push_elem:
13589 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13590 				continue;
13591 			case BPF_FUNC_map_pop_elem:
13592 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13593 				continue;
13594 			case BPF_FUNC_map_peek_elem:
13595 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13596 				continue;
13597 			case BPF_FUNC_redirect_map:
13598 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13599 				continue;
13600 			case BPF_FUNC_for_each_map_elem:
13601 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13602 				continue;
13603 			}
13604 
13605 			goto patch_call_imm;
13606 		}
13607 
13608 		/* Implement bpf_jiffies64 inline. */
13609 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13610 		    insn->imm == BPF_FUNC_jiffies64) {
13611 			struct bpf_insn ld_jiffies_addr[2] = {
13612 				BPF_LD_IMM64(BPF_REG_0,
13613 					     (unsigned long)&jiffies),
13614 			};
13615 
13616 			insn_buf[0] = ld_jiffies_addr[0];
13617 			insn_buf[1] = ld_jiffies_addr[1];
13618 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13619 						  BPF_REG_0, 0);
13620 			cnt = 3;
13621 
13622 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13623 						       cnt);
13624 			if (!new_prog)
13625 				return -ENOMEM;
13626 
13627 			delta    += cnt - 1;
13628 			env->prog = prog = new_prog;
13629 			insn      = new_prog->insnsi + i + delta;
13630 			continue;
13631 		}
13632 
13633 		/* Implement bpf_get_func_arg inline. */
13634 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13635 		    insn->imm == BPF_FUNC_get_func_arg) {
13636 			/* Load nr_args from ctx - 8 */
13637 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13638 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
13639 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
13640 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
13641 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
13642 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13643 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
13644 			insn_buf[7] = BPF_JMP_A(1);
13645 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
13646 			cnt = 9;
13647 
13648 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13649 			if (!new_prog)
13650 				return -ENOMEM;
13651 
13652 			delta    += cnt - 1;
13653 			env->prog = prog = new_prog;
13654 			insn      = new_prog->insnsi + i + delta;
13655 			continue;
13656 		}
13657 
13658 		/* Implement bpf_get_func_ret inline. */
13659 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13660 		    insn->imm == BPF_FUNC_get_func_ret) {
13661 			if (eatype == BPF_TRACE_FEXIT ||
13662 			    eatype == BPF_MODIFY_RETURN) {
13663 				/* Load nr_args from ctx - 8 */
13664 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13665 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
13666 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
13667 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13668 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
13669 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
13670 				cnt = 6;
13671 			} else {
13672 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
13673 				cnt = 1;
13674 			}
13675 
13676 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13677 			if (!new_prog)
13678 				return -ENOMEM;
13679 
13680 			delta    += cnt - 1;
13681 			env->prog = prog = new_prog;
13682 			insn      = new_prog->insnsi + i + delta;
13683 			continue;
13684 		}
13685 
13686 		/* Implement get_func_arg_cnt inline. */
13687 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13688 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
13689 			/* Load nr_args from ctx - 8 */
13690 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13691 
13692 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13693 			if (!new_prog)
13694 				return -ENOMEM;
13695 
13696 			env->prog = prog = new_prog;
13697 			insn      = new_prog->insnsi + i + delta;
13698 			continue;
13699 		}
13700 
13701 		/* Implement bpf_get_func_ip inline. */
13702 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13703 		    insn->imm == BPF_FUNC_get_func_ip) {
13704 			/* Load IP address from ctx - 16 */
13705 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
13706 
13707 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13708 			if (!new_prog)
13709 				return -ENOMEM;
13710 
13711 			env->prog = prog = new_prog;
13712 			insn      = new_prog->insnsi + i + delta;
13713 			continue;
13714 		}
13715 
13716 patch_call_imm:
13717 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13718 		/* all functions that have prototype and verifier allowed
13719 		 * programs to call them, must be real in-kernel functions
13720 		 */
13721 		if (!fn->func) {
13722 			verbose(env,
13723 				"kernel subsystem misconfigured func %s#%d\n",
13724 				func_id_name(insn->imm), insn->imm);
13725 			return -EFAULT;
13726 		}
13727 		insn->imm = fn->func - __bpf_call_base;
13728 	}
13729 
13730 	/* Since poke tab is now finalized, publish aux to tracker. */
13731 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13732 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13733 		if (!map_ptr->ops->map_poke_track ||
13734 		    !map_ptr->ops->map_poke_untrack ||
13735 		    !map_ptr->ops->map_poke_run) {
13736 			verbose(env, "bpf verifier is misconfigured\n");
13737 			return -EINVAL;
13738 		}
13739 
13740 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13741 		if (ret < 0) {
13742 			verbose(env, "tracking tail call prog failed\n");
13743 			return ret;
13744 		}
13745 	}
13746 
13747 	sort_kfunc_descs_by_imm(env->prog);
13748 
13749 	return 0;
13750 }
13751 
13752 static void free_states(struct bpf_verifier_env *env)
13753 {
13754 	struct bpf_verifier_state_list *sl, *sln;
13755 	int i;
13756 
13757 	sl = env->free_list;
13758 	while (sl) {
13759 		sln = sl->next;
13760 		free_verifier_state(&sl->state, false);
13761 		kfree(sl);
13762 		sl = sln;
13763 	}
13764 	env->free_list = NULL;
13765 
13766 	if (!env->explored_states)
13767 		return;
13768 
13769 	for (i = 0; i < state_htab_size(env); i++) {
13770 		sl = env->explored_states[i];
13771 
13772 		while (sl) {
13773 			sln = sl->next;
13774 			free_verifier_state(&sl->state, false);
13775 			kfree(sl);
13776 			sl = sln;
13777 		}
13778 		env->explored_states[i] = NULL;
13779 	}
13780 }
13781 
13782 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13783 {
13784 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13785 	struct bpf_verifier_state *state;
13786 	struct bpf_reg_state *regs;
13787 	int ret, i;
13788 
13789 	env->prev_linfo = NULL;
13790 	env->pass_cnt++;
13791 
13792 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13793 	if (!state)
13794 		return -ENOMEM;
13795 	state->curframe = 0;
13796 	state->speculative = false;
13797 	state->branches = 1;
13798 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13799 	if (!state->frame[0]) {
13800 		kfree(state);
13801 		return -ENOMEM;
13802 	}
13803 	env->cur_state = state;
13804 	init_func_state(env, state->frame[0],
13805 			BPF_MAIN_FUNC /* callsite */,
13806 			0 /* frameno */,
13807 			subprog);
13808 
13809 	regs = state->frame[state->curframe]->regs;
13810 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13811 		ret = btf_prepare_func_args(env, subprog, regs);
13812 		if (ret)
13813 			goto out;
13814 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13815 			if (regs[i].type == PTR_TO_CTX)
13816 				mark_reg_known_zero(env, regs, i);
13817 			else if (regs[i].type == SCALAR_VALUE)
13818 				mark_reg_unknown(env, regs, i);
13819 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
13820 				const u32 mem_size = regs[i].mem_size;
13821 
13822 				mark_reg_known_zero(env, regs, i);
13823 				regs[i].mem_size = mem_size;
13824 				regs[i].id = ++env->id_gen;
13825 			}
13826 		}
13827 	} else {
13828 		/* 1st arg to a function */
13829 		regs[BPF_REG_1].type = PTR_TO_CTX;
13830 		mark_reg_known_zero(env, regs, BPF_REG_1);
13831 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13832 		if (ret == -EFAULT)
13833 			/* unlikely verifier bug. abort.
13834 			 * ret == 0 and ret < 0 are sadly acceptable for
13835 			 * main() function due to backward compatibility.
13836 			 * Like socket filter program may be written as:
13837 			 * int bpf_prog(struct pt_regs *ctx)
13838 			 * and never dereference that ctx in the program.
13839 			 * 'struct pt_regs' is a type mismatch for socket
13840 			 * filter that should be using 'struct __sk_buff'.
13841 			 */
13842 			goto out;
13843 	}
13844 
13845 	ret = do_check(env);
13846 out:
13847 	/* check for NULL is necessary, since cur_state can be freed inside
13848 	 * do_check() under memory pressure.
13849 	 */
13850 	if (env->cur_state) {
13851 		free_verifier_state(env->cur_state, true);
13852 		env->cur_state = NULL;
13853 	}
13854 	while (!pop_stack(env, NULL, NULL, false));
13855 	if (!ret && pop_log)
13856 		bpf_vlog_reset(&env->log, 0);
13857 	free_states(env);
13858 	return ret;
13859 }
13860 
13861 /* Verify all global functions in a BPF program one by one based on their BTF.
13862  * All global functions must pass verification. Otherwise the whole program is rejected.
13863  * Consider:
13864  * int bar(int);
13865  * int foo(int f)
13866  * {
13867  *    return bar(f);
13868  * }
13869  * int bar(int b)
13870  * {
13871  *    ...
13872  * }
13873  * foo() will be verified first for R1=any_scalar_value. During verification it
13874  * will be assumed that bar() already verified successfully and call to bar()
13875  * from foo() will be checked for type match only. Later bar() will be verified
13876  * independently to check that it's safe for R1=any_scalar_value.
13877  */
13878 static int do_check_subprogs(struct bpf_verifier_env *env)
13879 {
13880 	struct bpf_prog_aux *aux = env->prog->aux;
13881 	int i, ret;
13882 
13883 	if (!aux->func_info)
13884 		return 0;
13885 
13886 	for (i = 1; i < env->subprog_cnt; i++) {
13887 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13888 			continue;
13889 		env->insn_idx = env->subprog_info[i].start;
13890 		WARN_ON_ONCE(env->insn_idx == 0);
13891 		ret = do_check_common(env, i);
13892 		if (ret) {
13893 			return ret;
13894 		} else if (env->log.level & BPF_LOG_LEVEL) {
13895 			verbose(env,
13896 				"Func#%d is safe for any args that match its prototype\n",
13897 				i);
13898 		}
13899 	}
13900 	return 0;
13901 }
13902 
13903 static int do_check_main(struct bpf_verifier_env *env)
13904 {
13905 	int ret;
13906 
13907 	env->insn_idx = 0;
13908 	ret = do_check_common(env, 0);
13909 	if (!ret)
13910 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13911 	return ret;
13912 }
13913 
13914 
13915 static void print_verification_stats(struct bpf_verifier_env *env)
13916 {
13917 	int i;
13918 
13919 	if (env->log.level & BPF_LOG_STATS) {
13920 		verbose(env, "verification time %lld usec\n",
13921 			div_u64(env->verification_time, 1000));
13922 		verbose(env, "stack depth ");
13923 		for (i = 0; i < env->subprog_cnt; i++) {
13924 			u32 depth = env->subprog_info[i].stack_depth;
13925 
13926 			verbose(env, "%d", depth);
13927 			if (i + 1 < env->subprog_cnt)
13928 				verbose(env, "+");
13929 		}
13930 		verbose(env, "\n");
13931 	}
13932 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13933 		"total_states %d peak_states %d mark_read %d\n",
13934 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13935 		env->max_states_per_insn, env->total_states,
13936 		env->peak_states, env->longest_mark_read_walk);
13937 }
13938 
13939 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13940 {
13941 	const struct btf_type *t, *func_proto;
13942 	const struct bpf_struct_ops *st_ops;
13943 	const struct btf_member *member;
13944 	struct bpf_prog *prog = env->prog;
13945 	u32 btf_id, member_idx;
13946 	const char *mname;
13947 
13948 	if (!prog->gpl_compatible) {
13949 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13950 		return -EINVAL;
13951 	}
13952 
13953 	btf_id = prog->aux->attach_btf_id;
13954 	st_ops = bpf_struct_ops_find(btf_id);
13955 	if (!st_ops) {
13956 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13957 			btf_id);
13958 		return -ENOTSUPP;
13959 	}
13960 
13961 	t = st_ops->type;
13962 	member_idx = prog->expected_attach_type;
13963 	if (member_idx >= btf_type_vlen(t)) {
13964 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13965 			member_idx, st_ops->name);
13966 		return -EINVAL;
13967 	}
13968 
13969 	member = &btf_type_member(t)[member_idx];
13970 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13971 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13972 					       NULL);
13973 	if (!func_proto) {
13974 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13975 			mname, member_idx, st_ops->name);
13976 		return -EINVAL;
13977 	}
13978 
13979 	if (st_ops->check_member) {
13980 		int err = st_ops->check_member(t, member);
13981 
13982 		if (err) {
13983 			verbose(env, "attach to unsupported member %s of struct %s\n",
13984 				mname, st_ops->name);
13985 			return err;
13986 		}
13987 	}
13988 
13989 	prog->aux->attach_func_proto = func_proto;
13990 	prog->aux->attach_func_name = mname;
13991 	env->ops = st_ops->verifier_ops;
13992 
13993 	return 0;
13994 }
13995 #define SECURITY_PREFIX "security_"
13996 
13997 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13998 {
13999 	if (within_error_injection_list(addr) ||
14000 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14001 		return 0;
14002 
14003 	return -EINVAL;
14004 }
14005 
14006 /* list of non-sleepable functions that are otherwise on
14007  * ALLOW_ERROR_INJECTION list
14008  */
14009 BTF_SET_START(btf_non_sleepable_error_inject)
14010 /* Three functions below can be called from sleepable and non-sleepable context.
14011  * Assume non-sleepable from bpf safety point of view.
14012  */
14013 BTF_ID(func, __filemap_add_folio)
14014 BTF_ID(func, should_fail_alloc_page)
14015 BTF_ID(func, should_failslab)
14016 BTF_SET_END(btf_non_sleepable_error_inject)
14017 
14018 static int check_non_sleepable_error_inject(u32 btf_id)
14019 {
14020 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14021 }
14022 
14023 int bpf_check_attach_target(struct bpf_verifier_log *log,
14024 			    const struct bpf_prog *prog,
14025 			    const struct bpf_prog *tgt_prog,
14026 			    u32 btf_id,
14027 			    struct bpf_attach_target_info *tgt_info)
14028 {
14029 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14030 	const char prefix[] = "btf_trace_";
14031 	int ret = 0, subprog = -1, i;
14032 	const struct btf_type *t;
14033 	bool conservative = true;
14034 	const char *tname;
14035 	struct btf *btf;
14036 	long addr = 0;
14037 
14038 	if (!btf_id) {
14039 		bpf_log(log, "Tracing programs must provide btf_id\n");
14040 		return -EINVAL;
14041 	}
14042 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14043 	if (!btf) {
14044 		bpf_log(log,
14045 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14046 		return -EINVAL;
14047 	}
14048 	t = btf_type_by_id(btf, btf_id);
14049 	if (!t) {
14050 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14051 		return -EINVAL;
14052 	}
14053 	tname = btf_name_by_offset(btf, t->name_off);
14054 	if (!tname) {
14055 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14056 		return -EINVAL;
14057 	}
14058 	if (tgt_prog) {
14059 		struct bpf_prog_aux *aux = tgt_prog->aux;
14060 
14061 		for (i = 0; i < aux->func_info_cnt; i++)
14062 			if (aux->func_info[i].type_id == btf_id) {
14063 				subprog = i;
14064 				break;
14065 			}
14066 		if (subprog == -1) {
14067 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
14068 			return -EINVAL;
14069 		}
14070 		conservative = aux->func_info_aux[subprog].unreliable;
14071 		if (prog_extension) {
14072 			if (conservative) {
14073 				bpf_log(log,
14074 					"Cannot replace static functions\n");
14075 				return -EINVAL;
14076 			}
14077 			if (!prog->jit_requested) {
14078 				bpf_log(log,
14079 					"Extension programs should be JITed\n");
14080 				return -EINVAL;
14081 			}
14082 		}
14083 		if (!tgt_prog->jited) {
14084 			bpf_log(log, "Can attach to only JITed progs\n");
14085 			return -EINVAL;
14086 		}
14087 		if (tgt_prog->type == prog->type) {
14088 			/* Cannot fentry/fexit another fentry/fexit program.
14089 			 * Cannot attach program extension to another extension.
14090 			 * It's ok to attach fentry/fexit to extension program.
14091 			 */
14092 			bpf_log(log, "Cannot recursively attach\n");
14093 			return -EINVAL;
14094 		}
14095 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14096 		    prog_extension &&
14097 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14098 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14099 			/* Program extensions can extend all program types
14100 			 * except fentry/fexit. The reason is the following.
14101 			 * The fentry/fexit programs are used for performance
14102 			 * analysis, stats and can be attached to any program
14103 			 * type except themselves. When extension program is
14104 			 * replacing XDP function it is necessary to allow
14105 			 * performance analysis of all functions. Both original
14106 			 * XDP program and its program extension. Hence
14107 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14108 			 * allowed. If extending of fentry/fexit was allowed it
14109 			 * would be possible to create long call chain
14110 			 * fentry->extension->fentry->extension beyond
14111 			 * reasonable stack size. Hence extending fentry is not
14112 			 * allowed.
14113 			 */
14114 			bpf_log(log, "Cannot extend fentry/fexit\n");
14115 			return -EINVAL;
14116 		}
14117 	} else {
14118 		if (prog_extension) {
14119 			bpf_log(log, "Cannot replace kernel functions\n");
14120 			return -EINVAL;
14121 		}
14122 	}
14123 
14124 	switch (prog->expected_attach_type) {
14125 	case BPF_TRACE_RAW_TP:
14126 		if (tgt_prog) {
14127 			bpf_log(log,
14128 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14129 			return -EINVAL;
14130 		}
14131 		if (!btf_type_is_typedef(t)) {
14132 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
14133 				btf_id);
14134 			return -EINVAL;
14135 		}
14136 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14137 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14138 				btf_id, tname);
14139 			return -EINVAL;
14140 		}
14141 		tname += sizeof(prefix) - 1;
14142 		t = btf_type_by_id(btf, t->type);
14143 		if (!btf_type_is_ptr(t))
14144 			/* should never happen in valid vmlinux build */
14145 			return -EINVAL;
14146 		t = btf_type_by_id(btf, t->type);
14147 		if (!btf_type_is_func_proto(t))
14148 			/* should never happen in valid vmlinux build */
14149 			return -EINVAL;
14150 
14151 		break;
14152 	case BPF_TRACE_ITER:
14153 		if (!btf_type_is_func(t)) {
14154 			bpf_log(log, "attach_btf_id %u is not a function\n",
14155 				btf_id);
14156 			return -EINVAL;
14157 		}
14158 		t = btf_type_by_id(btf, t->type);
14159 		if (!btf_type_is_func_proto(t))
14160 			return -EINVAL;
14161 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14162 		if (ret)
14163 			return ret;
14164 		break;
14165 	default:
14166 		if (!prog_extension)
14167 			return -EINVAL;
14168 		fallthrough;
14169 	case BPF_MODIFY_RETURN:
14170 	case BPF_LSM_MAC:
14171 	case BPF_TRACE_FENTRY:
14172 	case BPF_TRACE_FEXIT:
14173 		if (!btf_type_is_func(t)) {
14174 			bpf_log(log, "attach_btf_id %u is not a function\n",
14175 				btf_id);
14176 			return -EINVAL;
14177 		}
14178 		if (prog_extension &&
14179 		    btf_check_type_match(log, prog, btf, t))
14180 			return -EINVAL;
14181 		t = btf_type_by_id(btf, t->type);
14182 		if (!btf_type_is_func_proto(t))
14183 			return -EINVAL;
14184 
14185 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14186 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14187 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14188 			return -EINVAL;
14189 
14190 		if (tgt_prog && conservative)
14191 			t = NULL;
14192 
14193 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14194 		if (ret < 0)
14195 			return ret;
14196 
14197 		if (tgt_prog) {
14198 			if (subprog == 0)
14199 				addr = (long) tgt_prog->bpf_func;
14200 			else
14201 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14202 		} else {
14203 			addr = kallsyms_lookup_name(tname);
14204 			if (!addr) {
14205 				bpf_log(log,
14206 					"The address of function %s cannot be found\n",
14207 					tname);
14208 				return -ENOENT;
14209 			}
14210 		}
14211 
14212 		if (prog->aux->sleepable) {
14213 			ret = -EINVAL;
14214 			switch (prog->type) {
14215 			case BPF_PROG_TYPE_TRACING:
14216 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
14217 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14218 				 */
14219 				if (!check_non_sleepable_error_inject(btf_id) &&
14220 				    within_error_injection_list(addr))
14221 					ret = 0;
14222 				break;
14223 			case BPF_PROG_TYPE_LSM:
14224 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
14225 				 * Only some of them are sleepable.
14226 				 */
14227 				if (bpf_lsm_is_sleepable_hook(btf_id))
14228 					ret = 0;
14229 				break;
14230 			default:
14231 				break;
14232 			}
14233 			if (ret) {
14234 				bpf_log(log, "%s is not sleepable\n", tname);
14235 				return ret;
14236 			}
14237 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
14238 			if (tgt_prog) {
14239 				bpf_log(log, "can't modify return codes of BPF programs\n");
14240 				return -EINVAL;
14241 			}
14242 			ret = check_attach_modify_return(addr, tname);
14243 			if (ret) {
14244 				bpf_log(log, "%s() is not modifiable\n", tname);
14245 				return ret;
14246 			}
14247 		}
14248 
14249 		break;
14250 	}
14251 	tgt_info->tgt_addr = addr;
14252 	tgt_info->tgt_name = tname;
14253 	tgt_info->tgt_type = t;
14254 	return 0;
14255 }
14256 
14257 BTF_SET_START(btf_id_deny)
14258 BTF_ID_UNUSED
14259 #ifdef CONFIG_SMP
14260 BTF_ID(func, migrate_disable)
14261 BTF_ID(func, migrate_enable)
14262 #endif
14263 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14264 BTF_ID(func, rcu_read_unlock_strict)
14265 #endif
14266 BTF_SET_END(btf_id_deny)
14267 
14268 static int check_attach_btf_id(struct bpf_verifier_env *env)
14269 {
14270 	struct bpf_prog *prog = env->prog;
14271 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
14272 	struct bpf_attach_target_info tgt_info = {};
14273 	u32 btf_id = prog->aux->attach_btf_id;
14274 	struct bpf_trampoline *tr;
14275 	int ret;
14276 	u64 key;
14277 
14278 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14279 		if (prog->aux->sleepable)
14280 			/* attach_btf_id checked to be zero already */
14281 			return 0;
14282 		verbose(env, "Syscall programs can only be sleepable\n");
14283 		return -EINVAL;
14284 	}
14285 
14286 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14287 	    prog->type != BPF_PROG_TYPE_LSM) {
14288 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
14289 		return -EINVAL;
14290 	}
14291 
14292 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14293 		return check_struct_ops_btf_id(env);
14294 
14295 	if (prog->type != BPF_PROG_TYPE_TRACING &&
14296 	    prog->type != BPF_PROG_TYPE_LSM &&
14297 	    prog->type != BPF_PROG_TYPE_EXT)
14298 		return 0;
14299 
14300 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14301 	if (ret)
14302 		return ret;
14303 
14304 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
14305 		/* to make freplace equivalent to their targets, they need to
14306 		 * inherit env->ops and expected_attach_type for the rest of the
14307 		 * verification
14308 		 */
14309 		env->ops = bpf_verifier_ops[tgt_prog->type];
14310 		prog->expected_attach_type = tgt_prog->expected_attach_type;
14311 	}
14312 
14313 	/* store info about the attachment target that will be used later */
14314 	prog->aux->attach_func_proto = tgt_info.tgt_type;
14315 	prog->aux->attach_func_name = tgt_info.tgt_name;
14316 
14317 	if (tgt_prog) {
14318 		prog->aux->saved_dst_prog_type = tgt_prog->type;
14319 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14320 	}
14321 
14322 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14323 		prog->aux->attach_btf_trace = true;
14324 		return 0;
14325 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14326 		if (!bpf_iter_prog_supported(prog))
14327 			return -EINVAL;
14328 		return 0;
14329 	}
14330 
14331 	if (prog->type == BPF_PROG_TYPE_LSM) {
14332 		ret = bpf_lsm_verify_prog(&env->log, prog);
14333 		if (ret < 0)
14334 			return ret;
14335 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
14336 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
14337 		return -EINVAL;
14338 	}
14339 
14340 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
14341 	tr = bpf_trampoline_get(key, &tgt_info);
14342 	if (!tr)
14343 		return -ENOMEM;
14344 
14345 	prog->aux->dst_trampoline = tr;
14346 	return 0;
14347 }
14348 
14349 struct btf *bpf_get_btf_vmlinux(void)
14350 {
14351 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14352 		mutex_lock(&bpf_verifier_lock);
14353 		if (!btf_vmlinux)
14354 			btf_vmlinux = btf_parse_vmlinux();
14355 		mutex_unlock(&bpf_verifier_lock);
14356 	}
14357 	return btf_vmlinux;
14358 }
14359 
14360 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
14361 {
14362 	u64 start_time = ktime_get_ns();
14363 	struct bpf_verifier_env *env;
14364 	struct bpf_verifier_log *log;
14365 	int i, len, ret = -EINVAL;
14366 	bool is_priv;
14367 
14368 	/* no program is valid */
14369 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14370 		return -EINVAL;
14371 
14372 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
14373 	 * allocate/free it every time bpf_check() is called
14374 	 */
14375 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
14376 	if (!env)
14377 		return -ENOMEM;
14378 	log = &env->log;
14379 
14380 	len = (*prog)->len;
14381 	env->insn_aux_data =
14382 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
14383 	ret = -ENOMEM;
14384 	if (!env->insn_aux_data)
14385 		goto err_free_env;
14386 	for (i = 0; i < len; i++)
14387 		env->insn_aux_data[i].orig_idx = i;
14388 	env->prog = *prog;
14389 	env->ops = bpf_verifier_ops[env->prog->type];
14390 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
14391 	is_priv = bpf_capable();
14392 
14393 	bpf_get_btf_vmlinux();
14394 
14395 	/* grab the mutex to protect few globals used by verifier */
14396 	if (!is_priv)
14397 		mutex_lock(&bpf_verifier_lock);
14398 
14399 	if (attr->log_level || attr->log_buf || attr->log_size) {
14400 		/* user requested verbose verifier output
14401 		 * and supplied buffer to store the verification trace
14402 		 */
14403 		log->level = attr->log_level;
14404 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14405 		log->len_total = attr->log_size;
14406 
14407 		/* log attributes have to be sane */
14408 		if (!bpf_verifier_log_attr_valid(log)) {
14409 			ret = -EINVAL;
14410 			goto err_unlock;
14411 		}
14412 	}
14413 
14414 	mark_verifier_state_clean(env);
14415 
14416 	if (IS_ERR(btf_vmlinux)) {
14417 		/* Either gcc or pahole or kernel are broken. */
14418 		verbose(env, "in-kernel BTF is malformed\n");
14419 		ret = PTR_ERR(btf_vmlinux);
14420 		goto skip_full_check;
14421 	}
14422 
14423 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14424 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
14425 		env->strict_alignment = true;
14426 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14427 		env->strict_alignment = false;
14428 
14429 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
14430 	env->allow_uninit_stack = bpf_allow_uninit_stack();
14431 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
14432 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
14433 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
14434 	env->bpf_capable = bpf_capable();
14435 
14436 	if (is_priv)
14437 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14438 
14439 	env->explored_states = kvcalloc(state_htab_size(env),
14440 				       sizeof(struct bpf_verifier_state_list *),
14441 				       GFP_USER);
14442 	ret = -ENOMEM;
14443 	if (!env->explored_states)
14444 		goto skip_full_check;
14445 
14446 	ret = add_subprog_and_kfunc(env);
14447 	if (ret < 0)
14448 		goto skip_full_check;
14449 
14450 	ret = check_subprogs(env);
14451 	if (ret < 0)
14452 		goto skip_full_check;
14453 
14454 	ret = check_btf_info(env, attr, uattr);
14455 	if (ret < 0)
14456 		goto skip_full_check;
14457 
14458 	ret = check_attach_btf_id(env);
14459 	if (ret)
14460 		goto skip_full_check;
14461 
14462 	ret = resolve_pseudo_ldimm64(env);
14463 	if (ret < 0)
14464 		goto skip_full_check;
14465 
14466 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
14467 		ret = bpf_prog_offload_verifier_prep(env->prog);
14468 		if (ret)
14469 			goto skip_full_check;
14470 	}
14471 
14472 	ret = check_cfg(env);
14473 	if (ret < 0)
14474 		goto skip_full_check;
14475 
14476 	ret = do_check_subprogs(env);
14477 	ret = ret ?: do_check_main(env);
14478 
14479 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14480 		ret = bpf_prog_offload_finalize(env);
14481 
14482 skip_full_check:
14483 	kvfree(env->explored_states);
14484 
14485 	if (ret == 0)
14486 		ret = check_max_stack_depth(env);
14487 
14488 	/* instruction rewrites happen after this point */
14489 	if (is_priv) {
14490 		if (ret == 0)
14491 			opt_hard_wire_dead_code_branches(env);
14492 		if (ret == 0)
14493 			ret = opt_remove_dead_code(env);
14494 		if (ret == 0)
14495 			ret = opt_remove_nops(env);
14496 	} else {
14497 		if (ret == 0)
14498 			sanitize_dead_code(env);
14499 	}
14500 
14501 	if (ret == 0)
14502 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14503 		ret = convert_ctx_accesses(env);
14504 
14505 	if (ret == 0)
14506 		ret = do_misc_fixups(env);
14507 
14508 	/* do 32-bit optimization after insn patching has done so those patched
14509 	 * insns could be handled correctly.
14510 	 */
14511 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14512 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14513 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14514 								     : false;
14515 	}
14516 
14517 	if (ret == 0)
14518 		ret = fixup_call_args(env);
14519 
14520 	env->verification_time = ktime_get_ns() - start_time;
14521 	print_verification_stats(env);
14522 	env->prog->aux->verified_insns = env->insn_processed;
14523 
14524 	if (log->level && bpf_verifier_log_full(log))
14525 		ret = -ENOSPC;
14526 	if (log->level && !log->ubuf) {
14527 		ret = -EFAULT;
14528 		goto err_release_maps;
14529 	}
14530 
14531 	if (ret)
14532 		goto err_release_maps;
14533 
14534 	if (env->used_map_cnt) {
14535 		/* if program passed verifier, update used_maps in bpf_prog_info */
14536 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14537 							  sizeof(env->used_maps[0]),
14538 							  GFP_KERNEL);
14539 
14540 		if (!env->prog->aux->used_maps) {
14541 			ret = -ENOMEM;
14542 			goto err_release_maps;
14543 		}
14544 
14545 		memcpy(env->prog->aux->used_maps, env->used_maps,
14546 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14547 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14548 	}
14549 	if (env->used_btf_cnt) {
14550 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14551 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14552 							  sizeof(env->used_btfs[0]),
14553 							  GFP_KERNEL);
14554 		if (!env->prog->aux->used_btfs) {
14555 			ret = -ENOMEM;
14556 			goto err_release_maps;
14557 		}
14558 
14559 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14560 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14561 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14562 	}
14563 	if (env->used_map_cnt || env->used_btf_cnt) {
14564 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14565 		 * bpf_ld_imm64 instructions
14566 		 */
14567 		convert_pseudo_ld_imm64(env);
14568 	}
14569 
14570 	adjust_btf_func(env);
14571 
14572 err_release_maps:
14573 	if (!env->prog->aux->used_maps)
14574 		/* if we didn't copy map pointers into bpf_prog_info, release
14575 		 * them now. Otherwise free_used_maps() will release them.
14576 		 */
14577 		release_maps(env);
14578 	if (!env->prog->aux->used_btfs)
14579 		release_btfs(env);
14580 
14581 	/* extension progs temporarily inherit the attach_type of their targets
14582 	   for verification purposes, so set it back to zero before returning
14583 	 */
14584 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14585 		env->prog->expected_attach_type = 0;
14586 
14587 	*prog = env->prog;
14588 err_unlock:
14589 	if (!is_priv)
14590 		mutex_unlock(&bpf_verifier_lock);
14591 	vfree(env->insn_aux_data);
14592 err_free_env:
14593 	kfree(env);
14594 	return ret;
14595 }
14596