xref: /openbmc/linux/kernel/bpf/verifier.c (revision 75016ca3)
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 }
457 
458 static bool type_is_rdonly_mem(u32 type)
459 {
460 	return type & MEM_RDONLY;
461 }
462 
463 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
464 {
465 	return type == ARG_PTR_TO_SOCK_COMMON;
466 }
467 
468 static bool type_may_be_null(u32 type)
469 {
470 	return type & PTR_MAYBE_NULL;
471 }
472 
473 /* Determine whether the function releases some resources allocated by another
474  * function call. The first reference type argument will be assumed to be
475  * released by release_reference().
476  */
477 static bool is_release_function(enum bpf_func_id func_id)
478 {
479 	return func_id == BPF_FUNC_sk_release ||
480 	       func_id == BPF_FUNC_ringbuf_submit ||
481 	       func_id == BPF_FUNC_ringbuf_discard;
482 }
483 
484 static bool may_be_acquire_function(enum bpf_func_id func_id)
485 {
486 	return func_id == BPF_FUNC_sk_lookup_tcp ||
487 		func_id == BPF_FUNC_sk_lookup_udp ||
488 		func_id == BPF_FUNC_skc_lookup_tcp ||
489 		func_id == BPF_FUNC_map_lookup_elem ||
490 	        func_id == BPF_FUNC_ringbuf_reserve;
491 }
492 
493 static bool is_acquire_function(enum bpf_func_id func_id,
494 				const struct bpf_map *map)
495 {
496 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
497 
498 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
499 	    func_id == BPF_FUNC_sk_lookup_udp ||
500 	    func_id == BPF_FUNC_skc_lookup_tcp ||
501 	    func_id == BPF_FUNC_ringbuf_reserve)
502 		return true;
503 
504 	if (func_id == BPF_FUNC_map_lookup_elem &&
505 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
506 	     map_type == BPF_MAP_TYPE_SOCKHASH))
507 		return true;
508 
509 	return false;
510 }
511 
512 static bool is_ptr_cast_function(enum bpf_func_id func_id)
513 {
514 	return func_id == BPF_FUNC_tcp_sock ||
515 		func_id == BPF_FUNC_sk_fullsock ||
516 		func_id == BPF_FUNC_skc_to_tcp_sock ||
517 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
518 		func_id == BPF_FUNC_skc_to_udp6_sock ||
519 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
520 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
521 }
522 
523 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
524 {
525 	return BPF_CLASS(insn->code) == BPF_STX &&
526 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
527 	       insn->imm == BPF_CMPXCHG;
528 }
529 
530 /* string representation of 'enum bpf_reg_type'
531  *
532  * Note that reg_type_str() can not appear more than once in a single verbose()
533  * statement.
534  */
535 static const char *reg_type_str(struct bpf_verifier_env *env,
536 				enum bpf_reg_type type)
537 {
538 	char postfix[16] = {0}, prefix[16] = {0};
539 	static const char * const str[] = {
540 		[NOT_INIT]		= "?",
541 		[SCALAR_VALUE]		= "inv",
542 		[PTR_TO_CTX]		= "ctx",
543 		[CONST_PTR_TO_MAP]	= "map_ptr",
544 		[PTR_TO_MAP_VALUE]	= "map_value",
545 		[PTR_TO_STACK]		= "fp",
546 		[PTR_TO_PACKET]		= "pkt",
547 		[PTR_TO_PACKET_META]	= "pkt_meta",
548 		[PTR_TO_PACKET_END]	= "pkt_end",
549 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
550 		[PTR_TO_SOCKET]		= "sock",
551 		[PTR_TO_SOCK_COMMON]	= "sock_common",
552 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
553 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
554 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
555 		[PTR_TO_BTF_ID]		= "ptr_",
556 		[PTR_TO_PERCPU_BTF_ID]	= "percpu_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 		    base_type(type) == PTR_TO_PERCPU_BTF_ID)
566 			strncpy(postfix, "or_null_", 16);
567 		else
568 			strncpy(postfix, "_or_null", 16);
569 	}
570 
571 	if (type & MEM_RDONLY)
572 		strncpy(prefix, "rdonly_", 16);
573 	if (type & MEM_ALLOC)
574 		strncpy(prefix, "alloc_", 16);
575 
576 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
577 		 prefix, str[base_type(type)], postfix);
578 	return env->type_str_buf;
579 }
580 
581 static char slot_type_char[] = {
582 	[STACK_INVALID]	= '?',
583 	[STACK_SPILL]	= 'r',
584 	[STACK_MISC]	= 'm',
585 	[STACK_ZERO]	= '0',
586 };
587 
588 static void print_liveness(struct bpf_verifier_env *env,
589 			   enum bpf_reg_liveness live)
590 {
591 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
592 	    verbose(env, "_");
593 	if (live & REG_LIVE_READ)
594 		verbose(env, "r");
595 	if (live & REG_LIVE_WRITTEN)
596 		verbose(env, "w");
597 	if (live & REG_LIVE_DONE)
598 		verbose(env, "D");
599 }
600 
601 static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 				   const struct bpf_reg_state *reg)
603 {
604 	struct bpf_verifier_state *cur = env->cur_state;
605 
606 	return cur->frame[reg->frameno];
607 }
608 
609 static const char *kernel_type_name(const struct btf* btf, u32 id)
610 {
611 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
612 }
613 
614 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
615 {
616 	env->scratched_regs |= 1U << regno;
617 }
618 
619 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
620 {
621 	env->scratched_stack_slots |= 1ULL << spi;
622 }
623 
624 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
625 {
626 	return (env->scratched_regs >> regno) & 1;
627 }
628 
629 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
630 {
631 	return (env->scratched_stack_slots >> regno) & 1;
632 }
633 
634 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
635 {
636 	return env->scratched_regs || env->scratched_stack_slots;
637 }
638 
639 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
640 {
641 	env->scratched_regs = 0U;
642 	env->scratched_stack_slots = 0ULL;
643 }
644 
645 /* Used for printing the entire verifier state. */
646 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
647 {
648 	env->scratched_regs = ~0U;
649 	env->scratched_stack_slots = ~0ULL;
650 }
651 
652 /* The reg state of a pointer or a bounded scalar was saved when
653  * it was spilled to the stack.
654  */
655 static bool is_spilled_reg(const struct bpf_stack_state *stack)
656 {
657 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
658 }
659 
660 static void scrub_spilled_slot(u8 *stype)
661 {
662 	if (*stype != STACK_INVALID)
663 		*stype = STACK_MISC;
664 }
665 
666 static void print_verifier_state(struct bpf_verifier_env *env,
667 				 const struct bpf_func_state *state,
668 				 bool print_all)
669 {
670 	const struct bpf_reg_state *reg;
671 	enum bpf_reg_type t;
672 	int i;
673 
674 	if (state->frameno)
675 		verbose(env, " frame%d:", state->frameno);
676 	for (i = 0; i < MAX_BPF_REG; i++) {
677 		reg = &state->regs[i];
678 		t = reg->type;
679 		if (t == NOT_INIT)
680 			continue;
681 		if (!print_all && !reg_scratched(env, i))
682 			continue;
683 		verbose(env, " R%d", i);
684 		print_liveness(env, reg->live);
685 		verbose(env, "=%s", reg_type_str(env, t));
686 		if (t == SCALAR_VALUE && reg->precise)
687 			verbose(env, "P");
688 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
689 		    tnum_is_const(reg->var_off)) {
690 			/* reg->off should be 0 for SCALAR_VALUE */
691 			verbose(env, "%lld", reg->var_off.value + reg->off);
692 		} else {
693 			if (base_type(t) == PTR_TO_BTF_ID ||
694 			    base_type(t) == PTR_TO_PERCPU_BTF_ID)
695 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
696 			verbose(env, "(id=%d", reg->id);
697 			if (reg_type_may_be_refcounted_or_null(t))
698 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
699 			if (t != SCALAR_VALUE)
700 				verbose(env, ",off=%d", reg->off);
701 			if (type_is_pkt_pointer(t))
702 				verbose(env, ",r=%d", reg->range);
703 			else if (base_type(t) == CONST_PTR_TO_MAP ||
704 				 base_type(t) == PTR_TO_MAP_KEY ||
705 				 base_type(t) == PTR_TO_MAP_VALUE)
706 				verbose(env, ",ks=%d,vs=%d",
707 					reg->map_ptr->key_size,
708 					reg->map_ptr->value_size);
709 			if (tnum_is_const(reg->var_off)) {
710 				/* Typically an immediate SCALAR_VALUE, but
711 				 * could be a pointer whose offset is too big
712 				 * for reg->off
713 				 */
714 				verbose(env, ",imm=%llx", reg->var_off.value);
715 			} else {
716 				if (reg->smin_value != reg->umin_value &&
717 				    reg->smin_value != S64_MIN)
718 					verbose(env, ",smin_value=%lld",
719 						(long long)reg->smin_value);
720 				if (reg->smax_value != reg->umax_value &&
721 				    reg->smax_value != S64_MAX)
722 					verbose(env, ",smax_value=%lld",
723 						(long long)reg->smax_value);
724 				if (reg->umin_value != 0)
725 					verbose(env, ",umin_value=%llu",
726 						(unsigned long long)reg->umin_value);
727 				if (reg->umax_value != U64_MAX)
728 					verbose(env, ",umax_value=%llu",
729 						(unsigned long long)reg->umax_value);
730 				if (!tnum_is_unknown(reg->var_off)) {
731 					char tn_buf[48];
732 
733 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
734 					verbose(env, ",var_off=%s", tn_buf);
735 				}
736 				if (reg->s32_min_value != reg->smin_value &&
737 				    reg->s32_min_value != S32_MIN)
738 					verbose(env, ",s32_min_value=%d",
739 						(int)(reg->s32_min_value));
740 				if (reg->s32_max_value != reg->smax_value &&
741 				    reg->s32_max_value != S32_MAX)
742 					verbose(env, ",s32_max_value=%d",
743 						(int)(reg->s32_max_value));
744 				if (reg->u32_min_value != reg->umin_value &&
745 				    reg->u32_min_value != U32_MIN)
746 					verbose(env, ",u32_min_value=%d",
747 						(int)(reg->u32_min_value));
748 				if (reg->u32_max_value != reg->umax_value &&
749 				    reg->u32_max_value != U32_MAX)
750 					verbose(env, ",u32_max_value=%d",
751 						(int)(reg->u32_max_value));
752 			}
753 			verbose(env, ")");
754 		}
755 	}
756 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
757 		char types_buf[BPF_REG_SIZE + 1];
758 		bool valid = false;
759 		int j;
760 
761 		for (j = 0; j < BPF_REG_SIZE; j++) {
762 			if (state->stack[i].slot_type[j] != STACK_INVALID)
763 				valid = true;
764 			types_buf[j] = slot_type_char[
765 					state->stack[i].slot_type[j]];
766 		}
767 		types_buf[BPF_REG_SIZE] = 0;
768 		if (!valid)
769 			continue;
770 		if (!print_all && !stack_slot_scratched(env, i))
771 			continue;
772 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
773 		print_liveness(env, state->stack[i].spilled_ptr.live);
774 		if (is_spilled_reg(&state->stack[i])) {
775 			reg = &state->stack[i].spilled_ptr;
776 			t = reg->type;
777 			verbose(env, "=%s", reg_type_str(env, t));
778 			if (t == SCALAR_VALUE && reg->precise)
779 				verbose(env, "P");
780 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
781 				verbose(env, "%lld", reg->var_off.value + reg->off);
782 		} else {
783 			verbose(env, "=%s", types_buf);
784 		}
785 	}
786 	if (state->acquired_refs && state->refs[0].id) {
787 		verbose(env, " refs=%d", state->refs[0].id);
788 		for (i = 1; i < state->acquired_refs; i++)
789 			if (state->refs[i].id)
790 				verbose(env, ",%d", state->refs[i].id);
791 	}
792 	if (state->in_callback_fn)
793 		verbose(env, " cb");
794 	if (state->in_async_callback_fn)
795 		verbose(env, " async_cb");
796 	verbose(env, "\n");
797 	mark_verifier_state_clean(env);
798 }
799 
800 static inline u32 vlog_alignment(u32 pos)
801 {
802 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
803 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
804 }
805 
806 static void print_insn_state(struct bpf_verifier_env *env,
807 			     const struct bpf_func_state *state)
808 {
809 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
810 		/* remove new line character */
811 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
812 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
813 	} else {
814 		verbose(env, "%d:", env->insn_idx);
815 	}
816 	print_verifier_state(env, state, false);
817 }
818 
819 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
820  * small to hold src. This is different from krealloc since we don't want to preserve
821  * the contents of dst.
822  *
823  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
824  * not be allocated.
825  */
826 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
827 {
828 	size_t bytes;
829 
830 	if (ZERO_OR_NULL_PTR(src))
831 		goto out;
832 
833 	if (unlikely(check_mul_overflow(n, size, &bytes)))
834 		return NULL;
835 
836 	if (ksize(dst) < bytes) {
837 		kfree(dst);
838 		dst = kmalloc_track_caller(bytes, flags);
839 		if (!dst)
840 			return NULL;
841 	}
842 
843 	memcpy(dst, src, bytes);
844 out:
845 	return dst ? dst : ZERO_SIZE_PTR;
846 }
847 
848 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
849  * small to hold new_n items. new items are zeroed out if the array grows.
850  *
851  * Contrary to krealloc_array, does not free arr if new_n is zero.
852  */
853 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
854 {
855 	if (!new_n || old_n == new_n)
856 		goto out;
857 
858 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
859 	if (!arr)
860 		return NULL;
861 
862 	if (new_n > old_n)
863 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
864 
865 out:
866 	return arr ? arr : ZERO_SIZE_PTR;
867 }
868 
869 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
870 {
871 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
872 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
873 	if (!dst->refs)
874 		return -ENOMEM;
875 
876 	dst->acquired_refs = src->acquired_refs;
877 	return 0;
878 }
879 
880 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
881 {
882 	size_t n = src->allocated_stack / BPF_REG_SIZE;
883 
884 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
885 				GFP_KERNEL);
886 	if (!dst->stack)
887 		return -ENOMEM;
888 
889 	dst->allocated_stack = src->allocated_stack;
890 	return 0;
891 }
892 
893 static int resize_reference_state(struct bpf_func_state *state, size_t n)
894 {
895 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
896 				    sizeof(struct bpf_reference_state));
897 	if (!state->refs)
898 		return -ENOMEM;
899 
900 	state->acquired_refs = n;
901 	return 0;
902 }
903 
904 static int grow_stack_state(struct bpf_func_state *state, int size)
905 {
906 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
907 
908 	if (old_n >= n)
909 		return 0;
910 
911 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
912 	if (!state->stack)
913 		return -ENOMEM;
914 
915 	state->allocated_stack = size;
916 	return 0;
917 }
918 
919 /* Acquire a pointer id from the env and update the state->refs to include
920  * this new pointer reference.
921  * On success, returns a valid pointer id to associate with the register
922  * On failure, returns a negative errno.
923  */
924 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
925 {
926 	struct bpf_func_state *state = cur_func(env);
927 	int new_ofs = state->acquired_refs;
928 	int id, err;
929 
930 	err = resize_reference_state(state, state->acquired_refs + 1);
931 	if (err)
932 		return err;
933 	id = ++env->id_gen;
934 	state->refs[new_ofs].id = id;
935 	state->refs[new_ofs].insn_idx = insn_idx;
936 
937 	return id;
938 }
939 
940 /* release function corresponding to acquire_reference_state(). Idempotent. */
941 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
942 {
943 	int i, last_idx;
944 
945 	last_idx = state->acquired_refs - 1;
946 	for (i = 0; i < state->acquired_refs; i++) {
947 		if (state->refs[i].id == ptr_id) {
948 			if (last_idx && i != last_idx)
949 				memcpy(&state->refs[i], &state->refs[last_idx],
950 				       sizeof(*state->refs));
951 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
952 			state->acquired_refs--;
953 			return 0;
954 		}
955 	}
956 	return -EINVAL;
957 }
958 
959 static void free_func_state(struct bpf_func_state *state)
960 {
961 	if (!state)
962 		return;
963 	kfree(state->refs);
964 	kfree(state->stack);
965 	kfree(state);
966 }
967 
968 static void clear_jmp_history(struct bpf_verifier_state *state)
969 {
970 	kfree(state->jmp_history);
971 	state->jmp_history = NULL;
972 	state->jmp_history_cnt = 0;
973 }
974 
975 static void free_verifier_state(struct bpf_verifier_state *state,
976 				bool free_self)
977 {
978 	int i;
979 
980 	for (i = 0; i <= state->curframe; i++) {
981 		free_func_state(state->frame[i]);
982 		state->frame[i] = NULL;
983 	}
984 	clear_jmp_history(state);
985 	if (free_self)
986 		kfree(state);
987 }
988 
989 /* copy verifier state from src to dst growing dst stack space
990  * when necessary to accommodate larger src stack
991  */
992 static int copy_func_state(struct bpf_func_state *dst,
993 			   const struct bpf_func_state *src)
994 {
995 	int err;
996 
997 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
998 	err = copy_reference_state(dst, src);
999 	if (err)
1000 		return err;
1001 	return copy_stack_state(dst, src);
1002 }
1003 
1004 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1005 			       const struct bpf_verifier_state *src)
1006 {
1007 	struct bpf_func_state *dst;
1008 	int i, err;
1009 
1010 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1011 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1012 					    GFP_USER);
1013 	if (!dst_state->jmp_history)
1014 		return -ENOMEM;
1015 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1016 
1017 	/* if dst has more stack frames then src frame, free them */
1018 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1019 		free_func_state(dst_state->frame[i]);
1020 		dst_state->frame[i] = NULL;
1021 	}
1022 	dst_state->speculative = src->speculative;
1023 	dst_state->curframe = src->curframe;
1024 	dst_state->active_spin_lock = src->active_spin_lock;
1025 	dst_state->branches = src->branches;
1026 	dst_state->parent = src->parent;
1027 	dst_state->first_insn_idx = src->first_insn_idx;
1028 	dst_state->last_insn_idx = src->last_insn_idx;
1029 	for (i = 0; i <= src->curframe; i++) {
1030 		dst = dst_state->frame[i];
1031 		if (!dst) {
1032 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1033 			if (!dst)
1034 				return -ENOMEM;
1035 			dst_state->frame[i] = dst;
1036 		}
1037 		err = copy_func_state(dst, src->frame[i]);
1038 		if (err)
1039 			return err;
1040 	}
1041 	return 0;
1042 }
1043 
1044 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1045 {
1046 	while (st) {
1047 		u32 br = --st->branches;
1048 
1049 		/* WARN_ON(br > 1) technically makes sense here,
1050 		 * but see comment in push_stack(), hence:
1051 		 */
1052 		WARN_ONCE((int)br < 0,
1053 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1054 			  br);
1055 		if (br)
1056 			break;
1057 		st = st->parent;
1058 	}
1059 }
1060 
1061 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1062 		     int *insn_idx, bool pop_log)
1063 {
1064 	struct bpf_verifier_state *cur = env->cur_state;
1065 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1066 	int err;
1067 
1068 	if (env->head == NULL)
1069 		return -ENOENT;
1070 
1071 	if (cur) {
1072 		err = copy_verifier_state(cur, &head->st);
1073 		if (err)
1074 			return err;
1075 	}
1076 	if (pop_log)
1077 		bpf_vlog_reset(&env->log, head->log_pos);
1078 	if (insn_idx)
1079 		*insn_idx = head->insn_idx;
1080 	if (prev_insn_idx)
1081 		*prev_insn_idx = head->prev_insn_idx;
1082 	elem = head->next;
1083 	free_verifier_state(&head->st, false);
1084 	kfree(head);
1085 	env->head = elem;
1086 	env->stack_size--;
1087 	return 0;
1088 }
1089 
1090 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1091 					     int insn_idx, int prev_insn_idx,
1092 					     bool speculative)
1093 {
1094 	struct bpf_verifier_state *cur = env->cur_state;
1095 	struct bpf_verifier_stack_elem *elem;
1096 	int err;
1097 
1098 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1099 	if (!elem)
1100 		goto err;
1101 
1102 	elem->insn_idx = insn_idx;
1103 	elem->prev_insn_idx = prev_insn_idx;
1104 	elem->next = env->head;
1105 	elem->log_pos = env->log.len_used;
1106 	env->head = elem;
1107 	env->stack_size++;
1108 	err = copy_verifier_state(&elem->st, cur);
1109 	if (err)
1110 		goto err;
1111 	elem->st.speculative |= speculative;
1112 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1113 		verbose(env, "The sequence of %d jumps is too complex.\n",
1114 			env->stack_size);
1115 		goto err;
1116 	}
1117 	if (elem->st.parent) {
1118 		++elem->st.parent->branches;
1119 		/* WARN_ON(branches > 2) technically makes sense here,
1120 		 * but
1121 		 * 1. speculative states will bump 'branches' for non-branch
1122 		 * instructions
1123 		 * 2. is_state_visited() heuristics may decide not to create
1124 		 * a new state for a sequence of branches and all such current
1125 		 * and cloned states will be pointing to a single parent state
1126 		 * which might have large 'branches' count.
1127 		 */
1128 	}
1129 	return &elem->st;
1130 err:
1131 	free_verifier_state(env->cur_state, true);
1132 	env->cur_state = NULL;
1133 	/* pop all elements and return */
1134 	while (!pop_stack(env, NULL, NULL, false));
1135 	return NULL;
1136 }
1137 
1138 #define CALLER_SAVED_REGS 6
1139 static const int caller_saved[CALLER_SAVED_REGS] = {
1140 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1141 };
1142 
1143 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1144 				struct bpf_reg_state *reg);
1145 
1146 /* This helper doesn't clear reg->id */
1147 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1148 {
1149 	reg->var_off = tnum_const(imm);
1150 	reg->smin_value = (s64)imm;
1151 	reg->smax_value = (s64)imm;
1152 	reg->umin_value = imm;
1153 	reg->umax_value = imm;
1154 
1155 	reg->s32_min_value = (s32)imm;
1156 	reg->s32_max_value = (s32)imm;
1157 	reg->u32_min_value = (u32)imm;
1158 	reg->u32_max_value = (u32)imm;
1159 }
1160 
1161 /* Mark the unknown part of a register (variable offset or scalar value) as
1162  * known to have the value @imm.
1163  */
1164 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1165 {
1166 	/* Clear id, off, and union(map_ptr, range) */
1167 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1168 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1169 	___mark_reg_known(reg, imm);
1170 }
1171 
1172 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1173 {
1174 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1175 	reg->s32_min_value = (s32)imm;
1176 	reg->s32_max_value = (s32)imm;
1177 	reg->u32_min_value = (u32)imm;
1178 	reg->u32_max_value = (u32)imm;
1179 }
1180 
1181 /* Mark the 'variable offset' part of a register as zero.  This should be
1182  * used only on registers holding a pointer type.
1183  */
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1185 {
1186 	__mark_reg_known(reg, 0);
1187 }
1188 
1189 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1190 {
1191 	__mark_reg_known(reg, 0);
1192 	reg->type = SCALAR_VALUE;
1193 }
1194 
1195 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1196 				struct bpf_reg_state *regs, u32 regno)
1197 {
1198 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1199 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1200 		/* Something bad happened, let's kill all regs */
1201 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1202 			__mark_reg_not_init(env, regs + regno);
1203 		return;
1204 	}
1205 	__mark_reg_known_zero(regs + regno);
1206 }
1207 
1208 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1209 {
1210 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1211 		const struct bpf_map *map = reg->map_ptr;
1212 
1213 		if (map->inner_map_meta) {
1214 			reg->type = CONST_PTR_TO_MAP;
1215 			reg->map_ptr = map->inner_map_meta;
1216 			/* transfer reg's id which is unique for every map_lookup_elem
1217 			 * as UID of the inner map.
1218 			 */
1219 			if (map_value_has_timer(map->inner_map_meta))
1220 				reg->map_uid = reg->id;
1221 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1222 			reg->type = PTR_TO_XDP_SOCK;
1223 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1224 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1225 			reg->type = PTR_TO_SOCKET;
1226 		} else {
1227 			reg->type = PTR_TO_MAP_VALUE;
1228 		}
1229 		return;
1230 	}
1231 
1232 	reg->type &= ~PTR_MAYBE_NULL;
1233 }
1234 
1235 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1236 {
1237 	return type_is_pkt_pointer(reg->type);
1238 }
1239 
1240 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1241 {
1242 	return reg_is_pkt_pointer(reg) ||
1243 	       reg->type == PTR_TO_PACKET_END;
1244 }
1245 
1246 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1247 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1248 				    enum bpf_reg_type which)
1249 {
1250 	/* The register can already have a range from prior markings.
1251 	 * This is fine as long as it hasn't been advanced from its
1252 	 * origin.
1253 	 */
1254 	return reg->type == which &&
1255 	       reg->id == 0 &&
1256 	       reg->off == 0 &&
1257 	       tnum_equals_const(reg->var_off, 0);
1258 }
1259 
1260 /* Reset the min/max bounds of a register */
1261 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1262 {
1263 	reg->smin_value = S64_MIN;
1264 	reg->smax_value = S64_MAX;
1265 	reg->umin_value = 0;
1266 	reg->umax_value = U64_MAX;
1267 
1268 	reg->s32_min_value = S32_MIN;
1269 	reg->s32_max_value = S32_MAX;
1270 	reg->u32_min_value = 0;
1271 	reg->u32_max_value = U32_MAX;
1272 }
1273 
1274 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1275 {
1276 	reg->smin_value = S64_MIN;
1277 	reg->smax_value = S64_MAX;
1278 	reg->umin_value = 0;
1279 	reg->umax_value = U64_MAX;
1280 }
1281 
1282 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1283 {
1284 	reg->s32_min_value = S32_MIN;
1285 	reg->s32_max_value = S32_MAX;
1286 	reg->u32_min_value = 0;
1287 	reg->u32_max_value = U32_MAX;
1288 }
1289 
1290 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1291 {
1292 	struct tnum var32_off = tnum_subreg(reg->var_off);
1293 
1294 	/* min signed is max(sign bit) | min(other bits) */
1295 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1296 			var32_off.value | (var32_off.mask & S32_MIN));
1297 	/* max signed is min(sign bit) | max(other bits) */
1298 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1299 			var32_off.value | (var32_off.mask & S32_MAX));
1300 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1301 	reg->u32_max_value = min(reg->u32_max_value,
1302 				 (u32)(var32_off.value | var32_off.mask));
1303 }
1304 
1305 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1306 {
1307 	/* min signed is max(sign bit) | min(other bits) */
1308 	reg->smin_value = max_t(s64, reg->smin_value,
1309 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1310 	/* max signed is min(sign bit) | max(other bits) */
1311 	reg->smax_value = min_t(s64, reg->smax_value,
1312 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1313 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1314 	reg->umax_value = min(reg->umax_value,
1315 			      reg->var_off.value | reg->var_off.mask);
1316 }
1317 
1318 static void __update_reg_bounds(struct bpf_reg_state *reg)
1319 {
1320 	__update_reg32_bounds(reg);
1321 	__update_reg64_bounds(reg);
1322 }
1323 
1324 /* Uses signed min/max values to inform unsigned, and vice-versa */
1325 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1326 {
1327 	/* Learn sign from signed bounds.
1328 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1329 	 * are the same, so combine.  This works even in the negative case, e.g.
1330 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1331 	 */
1332 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1333 		reg->s32_min_value = reg->u32_min_value =
1334 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1335 		reg->s32_max_value = reg->u32_max_value =
1336 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1337 		return;
1338 	}
1339 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1340 	 * boundary, so we must be careful.
1341 	 */
1342 	if ((s32)reg->u32_max_value >= 0) {
1343 		/* Positive.  We can't learn anything from the smin, but smax
1344 		 * is positive, hence safe.
1345 		 */
1346 		reg->s32_min_value = reg->u32_min_value;
1347 		reg->s32_max_value = reg->u32_max_value =
1348 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1349 	} else if ((s32)reg->u32_min_value < 0) {
1350 		/* Negative.  We can't learn anything from the smax, but smin
1351 		 * is negative, hence safe.
1352 		 */
1353 		reg->s32_min_value = reg->u32_min_value =
1354 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1355 		reg->s32_max_value = reg->u32_max_value;
1356 	}
1357 }
1358 
1359 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1360 {
1361 	/* Learn sign from signed bounds.
1362 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1363 	 * are the same, so combine.  This works even in the negative case, e.g.
1364 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1365 	 */
1366 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1367 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1368 							  reg->umin_value);
1369 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1370 							  reg->umax_value);
1371 		return;
1372 	}
1373 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1374 	 * boundary, so we must be careful.
1375 	 */
1376 	if ((s64)reg->umax_value >= 0) {
1377 		/* Positive.  We can't learn anything from the smin, but smax
1378 		 * is positive, hence safe.
1379 		 */
1380 		reg->smin_value = reg->umin_value;
1381 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1382 							  reg->umax_value);
1383 	} else if ((s64)reg->umin_value < 0) {
1384 		/* Negative.  We can't learn anything from the smax, but smin
1385 		 * is negative, hence safe.
1386 		 */
1387 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1388 							  reg->umin_value);
1389 		reg->smax_value = reg->umax_value;
1390 	}
1391 }
1392 
1393 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1394 {
1395 	__reg32_deduce_bounds(reg);
1396 	__reg64_deduce_bounds(reg);
1397 }
1398 
1399 /* Attempts to improve var_off based on unsigned min/max information */
1400 static void __reg_bound_offset(struct bpf_reg_state *reg)
1401 {
1402 	struct tnum var64_off = tnum_intersect(reg->var_off,
1403 					       tnum_range(reg->umin_value,
1404 							  reg->umax_value));
1405 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1406 						tnum_range(reg->u32_min_value,
1407 							   reg->u32_max_value));
1408 
1409 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1410 }
1411 
1412 static bool __reg32_bound_s64(s32 a)
1413 {
1414 	return a >= 0 && a <= S32_MAX;
1415 }
1416 
1417 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1418 {
1419 	reg->umin_value = reg->u32_min_value;
1420 	reg->umax_value = reg->u32_max_value;
1421 
1422 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1423 	 * be positive otherwise set to worse case bounds and refine later
1424 	 * from tnum.
1425 	 */
1426 	if (__reg32_bound_s64(reg->s32_min_value) &&
1427 	    __reg32_bound_s64(reg->s32_max_value)) {
1428 		reg->smin_value = reg->s32_min_value;
1429 		reg->smax_value = reg->s32_max_value;
1430 	} else {
1431 		reg->smin_value = 0;
1432 		reg->smax_value = U32_MAX;
1433 	}
1434 }
1435 
1436 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1437 {
1438 	/* special case when 64-bit register has upper 32-bit register
1439 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1440 	 * allowing us to use 32-bit bounds directly,
1441 	 */
1442 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1443 		__reg_assign_32_into_64(reg);
1444 	} else {
1445 		/* Otherwise the best we can do is push lower 32bit known and
1446 		 * unknown bits into register (var_off set from jmp logic)
1447 		 * then learn as much as possible from the 64-bit tnum
1448 		 * known and unknown bits. The previous smin/smax bounds are
1449 		 * invalid here because of jmp32 compare so mark them unknown
1450 		 * so they do not impact tnum bounds calculation.
1451 		 */
1452 		__mark_reg64_unbounded(reg);
1453 		__update_reg_bounds(reg);
1454 	}
1455 
1456 	/* Intersecting with the old var_off might have improved our bounds
1457 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1458 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1459 	 */
1460 	__reg_deduce_bounds(reg);
1461 	__reg_bound_offset(reg);
1462 	__update_reg_bounds(reg);
1463 }
1464 
1465 static bool __reg64_bound_s32(s64 a)
1466 {
1467 	return a >= S32_MIN && a <= S32_MAX;
1468 }
1469 
1470 static bool __reg64_bound_u32(u64 a)
1471 {
1472 	return a >= U32_MIN && a <= U32_MAX;
1473 }
1474 
1475 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1476 {
1477 	__mark_reg32_unbounded(reg);
1478 
1479 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1480 		reg->s32_min_value = (s32)reg->smin_value;
1481 		reg->s32_max_value = (s32)reg->smax_value;
1482 	}
1483 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1484 		reg->u32_min_value = (u32)reg->umin_value;
1485 		reg->u32_max_value = (u32)reg->umax_value;
1486 	}
1487 
1488 	/* Intersecting with the old var_off might have improved our bounds
1489 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1490 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1491 	 */
1492 	__reg_deduce_bounds(reg);
1493 	__reg_bound_offset(reg);
1494 	__update_reg_bounds(reg);
1495 }
1496 
1497 /* Mark a register as having a completely unknown (scalar) value. */
1498 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1499 			       struct bpf_reg_state *reg)
1500 {
1501 	/*
1502 	 * Clear type, id, off, and union(map_ptr, range) and
1503 	 * padding between 'type' and union
1504 	 */
1505 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1506 	reg->type = SCALAR_VALUE;
1507 	reg->var_off = tnum_unknown;
1508 	reg->frameno = 0;
1509 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1510 	__mark_reg_unbounded(reg);
1511 }
1512 
1513 static void mark_reg_unknown(struct bpf_verifier_env *env,
1514 			     struct bpf_reg_state *regs, u32 regno)
1515 {
1516 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1517 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1518 		/* Something bad happened, let's kill all regs except FP */
1519 		for (regno = 0; regno < BPF_REG_FP; regno++)
1520 			__mark_reg_not_init(env, regs + regno);
1521 		return;
1522 	}
1523 	__mark_reg_unknown(env, regs + regno);
1524 }
1525 
1526 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1527 				struct bpf_reg_state *reg)
1528 {
1529 	__mark_reg_unknown(env, reg);
1530 	reg->type = NOT_INIT;
1531 }
1532 
1533 static void mark_reg_not_init(struct bpf_verifier_env *env,
1534 			      struct bpf_reg_state *regs, u32 regno)
1535 {
1536 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1537 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1538 		/* Something bad happened, let's kill all regs except FP */
1539 		for (regno = 0; regno < BPF_REG_FP; regno++)
1540 			__mark_reg_not_init(env, regs + regno);
1541 		return;
1542 	}
1543 	__mark_reg_not_init(env, regs + regno);
1544 }
1545 
1546 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1547 			    struct bpf_reg_state *regs, u32 regno,
1548 			    enum bpf_reg_type reg_type,
1549 			    struct btf *btf, u32 btf_id)
1550 {
1551 	if (reg_type == SCALAR_VALUE) {
1552 		mark_reg_unknown(env, regs, regno);
1553 		return;
1554 	}
1555 	mark_reg_known_zero(env, regs, regno);
1556 	regs[regno].type = PTR_TO_BTF_ID;
1557 	regs[regno].btf = btf;
1558 	regs[regno].btf_id = btf_id;
1559 }
1560 
1561 #define DEF_NOT_SUBREG	(0)
1562 static void init_reg_state(struct bpf_verifier_env *env,
1563 			   struct bpf_func_state *state)
1564 {
1565 	struct bpf_reg_state *regs = state->regs;
1566 	int i;
1567 
1568 	for (i = 0; i < MAX_BPF_REG; i++) {
1569 		mark_reg_not_init(env, regs, i);
1570 		regs[i].live = REG_LIVE_NONE;
1571 		regs[i].parent = NULL;
1572 		regs[i].subreg_def = DEF_NOT_SUBREG;
1573 	}
1574 
1575 	/* frame pointer */
1576 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1577 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1578 	regs[BPF_REG_FP].frameno = state->frameno;
1579 }
1580 
1581 #define BPF_MAIN_FUNC (-1)
1582 static void init_func_state(struct bpf_verifier_env *env,
1583 			    struct bpf_func_state *state,
1584 			    int callsite, int frameno, int subprogno)
1585 {
1586 	state->callsite = callsite;
1587 	state->frameno = frameno;
1588 	state->subprogno = subprogno;
1589 	init_reg_state(env, state);
1590 	mark_verifier_state_scratched(env);
1591 }
1592 
1593 /* Similar to push_stack(), but for async callbacks */
1594 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1595 						int insn_idx, int prev_insn_idx,
1596 						int subprog)
1597 {
1598 	struct bpf_verifier_stack_elem *elem;
1599 	struct bpf_func_state *frame;
1600 
1601 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1602 	if (!elem)
1603 		goto err;
1604 
1605 	elem->insn_idx = insn_idx;
1606 	elem->prev_insn_idx = prev_insn_idx;
1607 	elem->next = env->head;
1608 	elem->log_pos = env->log.len_used;
1609 	env->head = elem;
1610 	env->stack_size++;
1611 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1612 		verbose(env,
1613 			"The sequence of %d jumps is too complex for async cb.\n",
1614 			env->stack_size);
1615 		goto err;
1616 	}
1617 	/* Unlike push_stack() do not copy_verifier_state().
1618 	 * The caller state doesn't matter.
1619 	 * This is async callback. It starts in a fresh stack.
1620 	 * Initialize it similar to do_check_common().
1621 	 */
1622 	elem->st.branches = 1;
1623 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1624 	if (!frame)
1625 		goto err;
1626 	init_func_state(env, frame,
1627 			BPF_MAIN_FUNC /* callsite */,
1628 			0 /* frameno within this callchain */,
1629 			subprog /* subprog number within this prog */);
1630 	elem->st.frame[0] = frame;
1631 	return &elem->st;
1632 err:
1633 	free_verifier_state(env->cur_state, true);
1634 	env->cur_state = NULL;
1635 	/* pop all elements and return */
1636 	while (!pop_stack(env, NULL, NULL, false));
1637 	return NULL;
1638 }
1639 
1640 
1641 enum reg_arg_type {
1642 	SRC_OP,		/* register is used as source operand */
1643 	DST_OP,		/* register is used as destination operand */
1644 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1645 };
1646 
1647 static int cmp_subprogs(const void *a, const void *b)
1648 {
1649 	return ((struct bpf_subprog_info *)a)->start -
1650 	       ((struct bpf_subprog_info *)b)->start;
1651 }
1652 
1653 static int find_subprog(struct bpf_verifier_env *env, int off)
1654 {
1655 	struct bpf_subprog_info *p;
1656 
1657 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1658 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1659 	if (!p)
1660 		return -ENOENT;
1661 	return p - env->subprog_info;
1662 
1663 }
1664 
1665 static int add_subprog(struct bpf_verifier_env *env, int off)
1666 {
1667 	int insn_cnt = env->prog->len;
1668 	int ret;
1669 
1670 	if (off >= insn_cnt || off < 0) {
1671 		verbose(env, "call to invalid destination\n");
1672 		return -EINVAL;
1673 	}
1674 	ret = find_subprog(env, off);
1675 	if (ret >= 0)
1676 		return ret;
1677 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1678 		verbose(env, "too many subprograms\n");
1679 		return -E2BIG;
1680 	}
1681 	/* determine subprog starts. The end is one before the next starts */
1682 	env->subprog_info[env->subprog_cnt++].start = off;
1683 	sort(env->subprog_info, env->subprog_cnt,
1684 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1685 	return env->subprog_cnt - 1;
1686 }
1687 
1688 #define MAX_KFUNC_DESCS 256
1689 #define MAX_KFUNC_BTFS	256
1690 
1691 struct bpf_kfunc_desc {
1692 	struct btf_func_model func_model;
1693 	u32 func_id;
1694 	s32 imm;
1695 	u16 offset;
1696 };
1697 
1698 struct bpf_kfunc_btf {
1699 	struct btf *btf;
1700 	struct module *module;
1701 	u16 offset;
1702 };
1703 
1704 struct bpf_kfunc_desc_tab {
1705 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1706 	u32 nr_descs;
1707 };
1708 
1709 struct bpf_kfunc_btf_tab {
1710 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1711 	u32 nr_descs;
1712 };
1713 
1714 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1715 {
1716 	const struct bpf_kfunc_desc *d0 = a;
1717 	const struct bpf_kfunc_desc *d1 = b;
1718 
1719 	/* func_id is not greater than BTF_MAX_TYPE */
1720 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1721 }
1722 
1723 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1724 {
1725 	const struct bpf_kfunc_btf *d0 = a;
1726 	const struct bpf_kfunc_btf *d1 = b;
1727 
1728 	return d0->offset - d1->offset;
1729 }
1730 
1731 static const struct bpf_kfunc_desc *
1732 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1733 {
1734 	struct bpf_kfunc_desc desc = {
1735 		.func_id = func_id,
1736 		.offset = offset,
1737 	};
1738 	struct bpf_kfunc_desc_tab *tab;
1739 
1740 	tab = prog->aux->kfunc_tab;
1741 	return bsearch(&desc, tab->descs, tab->nr_descs,
1742 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1743 }
1744 
1745 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1746 					 s16 offset, struct module **btf_modp)
1747 {
1748 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1749 	struct bpf_kfunc_btf_tab *tab;
1750 	struct bpf_kfunc_btf *b;
1751 	struct module *mod;
1752 	struct btf *btf;
1753 	int btf_fd;
1754 
1755 	tab = env->prog->aux->kfunc_btf_tab;
1756 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1757 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1758 	if (!b) {
1759 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1760 			verbose(env, "too many different module BTFs\n");
1761 			return ERR_PTR(-E2BIG);
1762 		}
1763 
1764 		if (bpfptr_is_null(env->fd_array)) {
1765 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1766 			return ERR_PTR(-EPROTO);
1767 		}
1768 
1769 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1770 					    offset * sizeof(btf_fd),
1771 					    sizeof(btf_fd)))
1772 			return ERR_PTR(-EFAULT);
1773 
1774 		btf = btf_get_by_fd(btf_fd);
1775 		if (IS_ERR(btf)) {
1776 			verbose(env, "invalid module BTF fd specified\n");
1777 			return btf;
1778 		}
1779 
1780 		if (!btf_is_module(btf)) {
1781 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1782 			btf_put(btf);
1783 			return ERR_PTR(-EINVAL);
1784 		}
1785 
1786 		mod = btf_try_get_module(btf);
1787 		if (!mod) {
1788 			btf_put(btf);
1789 			return ERR_PTR(-ENXIO);
1790 		}
1791 
1792 		b = &tab->descs[tab->nr_descs++];
1793 		b->btf = btf;
1794 		b->module = mod;
1795 		b->offset = offset;
1796 
1797 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1798 		     kfunc_btf_cmp_by_off, NULL);
1799 	}
1800 	if (btf_modp)
1801 		*btf_modp = b->module;
1802 	return b->btf;
1803 }
1804 
1805 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1806 {
1807 	if (!tab)
1808 		return;
1809 
1810 	while (tab->nr_descs--) {
1811 		module_put(tab->descs[tab->nr_descs].module);
1812 		btf_put(tab->descs[tab->nr_descs].btf);
1813 	}
1814 	kfree(tab);
1815 }
1816 
1817 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1818 				       u32 func_id, s16 offset,
1819 				       struct module **btf_modp)
1820 {
1821 	if (offset) {
1822 		if (offset < 0) {
1823 			/* In the future, this can be allowed to increase limit
1824 			 * of fd index into fd_array, interpreted as u16.
1825 			 */
1826 			verbose(env, "negative offset disallowed for kernel module function call\n");
1827 			return ERR_PTR(-EINVAL);
1828 		}
1829 
1830 		return __find_kfunc_desc_btf(env, offset, btf_modp);
1831 	}
1832 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1833 }
1834 
1835 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1836 {
1837 	const struct btf_type *func, *func_proto;
1838 	struct bpf_kfunc_btf_tab *btf_tab;
1839 	struct bpf_kfunc_desc_tab *tab;
1840 	struct bpf_prog_aux *prog_aux;
1841 	struct bpf_kfunc_desc *desc;
1842 	const char *func_name;
1843 	struct btf *desc_btf;
1844 	unsigned long addr;
1845 	int err;
1846 
1847 	prog_aux = env->prog->aux;
1848 	tab = prog_aux->kfunc_tab;
1849 	btf_tab = prog_aux->kfunc_btf_tab;
1850 	if (!tab) {
1851 		if (!btf_vmlinux) {
1852 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1853 			return -ENOTSUPP;
1854 		}
1855 
1856 		if (!env->prog->jit_requested) {
1857 			verbose(env, "JIT is required for calling kernel function\n");
1858 			return -ENOTSUPP;
1859 		}
1860 
1861 		if (!bpf_jit_supports_kfunc_call()) {
1862 			verbose(env, "JIT does not support calling kernel function\n");
1863 			return -ENOTSUPP;
1864 		}
1865 
1866 		if (!env->prog->gpl_compatible) {
1867 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1868 			return -EINVAL;
1869 		}
1870 
1871 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1872 		if (!tab)
1873 			return -ENOMEM;
1874 		prog_aux->kfunc_tab = tab;
1875 	}
1876 
1877 	/* func_id == 0 is always invalid, but instead of returning an error, be
1878 	 * conservative and wait until the code elimination pass before returning
1879 	 * error, so that invalid calls that get pruned out can be in BPF programs
1880 	 * loaded from userspace.  It is also required that offset be untouched
1881 	 * for such calls.
1882 	 */
1883 	if (!func_id && !offset)
1884 		return 0;
1885 
1886 	if (!btf_tab && offset) {
1887 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1888 		if (!btf_tab)
1889 			return -ENOMEM;
1890 		prog_aux->kfunc_btf_tab = btf_tab;
1891 	}
1892 
1893 	desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL);
1894 	if (IS_ERR(desc_btf)) {
1895 		verbose(env, "failed to find BTF for kernel function\n");
1896 		return PTR_ERR(desc_btf);
1897 	}
1898 
1899 	if (find_kfunc_desc(env->prog, func_id, offset))
1900 		return 0;
1901 
1902 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1903 		verbose(env, "too many different kernel function calls\n");
1904 		return -E2BIG;
1905 	}
1906 
1907 	func = btf_type_by_id(desc_btf, func_id);
1908 	if (!func || !btf_type_is_func(func)) {
1909 		verbose(env, "kernel btf_id %u is not a function\n",
1910 			func_id);
1911 		return -EINVAL;
1912 	}
1913 	func_proto = btf_type_by_id(desc_btf, func->type);
1914 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1915 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1916 			func_id);
1917 		return -EINVAL;
1918 	}
1919 
1920 	func_name = btf_name_by_offset(desc_btf, func->name_off);
1921 	addr = kallsyms_lookup_name(func_name);
1922 	if (!addr) {
1923 		verbose(env, "cannot find address for kernel function %s\n",
1924 			func_name);
1925 		return -EINVAL;
1926 	}
1927 
1928 	desc = &tab->descs[tab->nr_descs++];
1929 	desc->func_id = func_id;
1930 	desc->imm = BPF_CALL_IMM(addr);
1931 	desc->offset = offset;
1932 	err = btf_distill_func_proto(&env->log, desc_btf,
1933 				     func_proto, func_name,
1934 				     &desc->func_model);
1935 	if (!err)
1936 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1937 		     kfunc_desc_cmp_by_id_off, NULL);
1938 	return err;
1939 }
1940 
1941 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1942 {
1943 	const struct bpf_kfunc_desc *d0 = a;
1944 	const struct bpf_kfunc_desc *d1 = b;
1945 
1946 	if (d0->imm > d1->imm)
1947 		return 1;
1948 	else if (d0->imm < d1->imm)
1949 		return -1;
1950 	return 0;
1951 }
1952 
1953 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1954 {
1955 	struct bpf_kfunc_desc_tab *tab;
1956 
1957 	tab = prog->aux->kfunc_tab;
1958 	if (!tab)
1959 		return;
1960 
1961 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1962 	     kfunc_desc_cmp_by_imm, NULL);
1963 }
1964 
1965 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1966 {
1967 	return !!prog->aux->kfunc_tab;
1968 }
1969 
1970 const struct btf_func_model *
1971 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1972 			 const struct bpf_insn *insn)
1973 {
1974 	const struct bpf_kfunc_desc desc = {
1975 		.imm = insn->imm,
1976 	};
1977 	const struct bpf_kfunc_desc *res;
1978 	struct bpf_kfunc_desc_tab *tab;
1979 
1980 	tab = prog->aux->kfunc_tab;
1981 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1982 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1983 
1984 	return res ? &res->func_model : NULL;
1985 }
1986 
1987 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1988 {
1989 	struct bpf_subprog_info *subprog = env->subprog_info;
1990 	struct bpf_insn *insn = env->prog->insnsi;
1991 	int i, ret, insn_cnt = env->prog->len;
1992 
1993 	/* Add entry function. */
1994 	ret = add_subprog(env, 0);
1995 	if (ret)
1996 		return ret;
1997 
1998 	for (i = 0; i < insn_cnt; i++, insn++) {
1999 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2000 		    !bpf_pseudo_kfunc_call(insn))
2001 			continue;
2002 
2003 		if (!env->bpf_capable) {
2004 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2005 			return -EPERM;
2006 		}
2007 
2008 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2009 			ret = add_subprog(env, i + insn->imm + 1);
2010 		else
2011 			ret = add_kfunc_call(env, insn->imm, insn->off);
2012 
2013 		if (ret < 0)
2014 			return ret;
2015 	}
2016 
2017 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2018 	 * logic. 'subprog_cnt' should not be increased.
2019 	 */
2020 	subprog[env->subprog_cnt].start = insn_cnt;
2021 
2022 	if (env->log.level & BPF_LOG_LEVEL2)
2023 		for (i = 0; i < env->subprog_cnt; i++)
2024 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2025 
2026 	return 0;
2027 }
2028 
2029 static int check_subprogs(struct bpf_verifier_env *env)
2030 {
2031 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2032 	struct bpf_subprog_info *subprog = env->subprog_info;
2033 	struct bpf_insn *insn = env->prog->insnsi;
2034 	int insn_cnt = env->prog->len;
2035 
2036 	/* now check that all jumps are within the same subprog */
2037 	subprog_start = subprog[cur_subprog].start;
2038 	subprog_end = subprog[cur_subprog + 1].start;
2039 	for (i = 0; i < insn_cnt; i++) {
2040 		u8 code = insn[i].code;
2041 
2042 		if (code == (BPF_JMP | BPF_CALL) &&
2043 		    insn[i].imm == BPF_FUNC_tail_call &&
2044 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2045 			subprog[cur_subprog].has_tail_call = true;
2046 		if (BPF_CLASS(code) == BPF_LD &&
2047 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2048 			subprog[cur_subprog].has_ld_abs = true;
2049 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2050 			goto next;
2051 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2052 			goto next;
2053 		off = i + insn[i].off + 1;
2054 		if (off < subprog_start || off >= subprog_end) {
2055 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2056 			return -EINVAL;
2057 		}
2058 next:
2059 		if (i == subprog_end - 1) {
2060 			/* to avoid fall-through from one subprog into another
2061 			 * the last insn of the subprog should be either exit
2062 			 * or unconditional jump back
2063 			 */
2064 			if (code != (BPF_JMP | BPF_EXIT) &&
2065 			    code != (BPF_JMP | BPF_JA)) {
2066 				verbose(env, "last insn is not an exit or jmp\n");
2067 				return -EINVAL;
2068 			}
2069 			subprog_start = subprog_end;
2070 			cur_subprog++;
2071 			if (cur_subprog < env->subprog_cnt)
2072 				subprog_end = subprog[cur_subprog + 1].start;
2073 		}
2074 	}
2075 	return 0;
2076 }
2077 
2078 /* Parentage chain of this register (or stack slot) should take care of all
2079  * issues like callee-saved registers, stack slot allocation time, etc.
2080  */
2081 static int mark_reg_read(struct bpf_verifier_env *env,
2082 			 const struct bpf_reg_state *state,
2083 			 struct bpf_reg_state *parent, u8 flag)
2084 {
2085 	bool writes = parent == state->parent; /* Observe write marks */
2086 	int cnt = 0;
2087 
2088 	while (parent) {
2089 		/* if read wasn't screened by an earlier write ... */
2090 		if (writes && state->live & REG_LIVE_WRITTEN)
2091 			break;
2092 		if (parent->live & REG_LIVE_DONE) {
2093 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2094 				reg_type_str(env, parent->type),
2095 				parent->var_off.value, parent->off);
2096 			return -EFAULT;
2097 		}
2098 		/* The first condition is more likely to be true than the
2099 		 * second, checked it first.
2100 		 */
2101 		if ((parent->live & REG_LIVE_READ) == flag ||
2102 		    parent->live & REG_LIVE_READ64)
2103 			/* The parentage chain never changes and
2104 			 * this parent was already marked as LIVE_READ.
2105 			 * There is no need to keep walking the chain again and
2106 			 * keep re-marking all parents as LIVE_READ.
2107 			 * This case happens when the same register is read
2108 			 * multiple times without writes into it in-between.
2109 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2110 			 * then no need to set the weak REG_LIVE_READ32.
2111 			 */
2112 			break;
2113 		/* ... then we depend on parent's value */
2114 		parent->live |= flag;
2115 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2116 		if (flag == REG_LIVE_READ64)
2117 			parent->live &= ~REG_LIVE_READ32;
2118 		state = parent;
2119 		parent = state->parent;
2120 		writes = true;
2121 		cnt++;
2122 	}
2123 
2124 	if (env->longest_mark_read_walk < cnt)
2125 		env->longest_mark_read_walk = cnt;
2126 	return 0;
2127 }
2128 
2129 /* This function is supposed to be used by the following 32-bit optimization
2130  * code only. It returns TRUE if the source or destination register operates
2131  * on 64-bit, otherwise return FALSE.
2132  */
2133 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2134 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2135 {
2136 	u8 code, class, op;
2137 
2138 	code = insn->code;
2139 	class = BPF_CLASS(code);
2140 	op = BPF_OP(code);
2141 	if (class == BPF_JMP) {
2142 		/* BPF_EXIT for "main" will reach here. Return TRUE
2143 		 * conservatively.
2144 		 */
2145 		if (op == BPF_EXIT)
2146 			return true;
2147 		if (op == BPF_CALL) {
2148 			/* BPF to BPF call will reach here because of marking
2149 			 * caller saved clobber with DST_OP_NO_MARK for which we
2150 			 * don't care the register def because they are anyway
2151 			 * marked as NOT_INIT already.
2152 			 */
2153 			if (insn->src_reg == BPF_PSEUDO_CALL)
2154 				return false;
2155 			/* Helper call will reach here because of arg type
2156 			 * check, conservatively return TRUE.
2157 			 */
2158 			if (t == SRC_OP)
2159 				return true;
2160 
2161 			return false;
2162 		}
2163 	}
2164 
2165 	if (class == BPF_ALU64 || class == BPF_JMP ||
2166 	    /* BPF_END always use BPF_ALU class. */
2167 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2168 		return true;
2169 
2170 	if (class == BPF_ALU || class == BPF_JMP32)
2171 		return false;
2172 
2173 	if (class == BPF_LDX) {
2174 		if (t != SRC_OP)
2175 			return BPF_SIZE(code) == BPF_DW;
2176 		/* LDX source must be ptr. */
2177 		return true;
2178 	}
2179 
2180 	if (class == BPF_STX) {
2181 		/* BPF_STX (including atomic variants) has multiple source
2182 		 * operands, one of which is a ptr. Check whether the caller is
2183 		 * asking about it.
2184 		 */
2185 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2186 			return true;
2187 		return BPF_SIZE(code) == BPF_DW;
2188 	}
2189 
2190 	if (class == BPF_LD) {
2191 		u8 mode = BPF_MODE(code);
2192 
2193 		/* LD_IMM64 */
2194 		if (mode == BPF_IMM)
2195 			return true;
2196 
2197 		/* Both LD_IND and LD_ABS return 32-bit data. */
2198 		if (t != SRC_OP)
2199 			return  false;
2200 
2201 		/* Implicit ctx ptr. */
2202 		if (regno == BPF_REG_6)
2203 			return true;
2204 
2205 		/* Explicit source could be any width. */
2206 		return true;
2207 	}
2208 
2209 	if (class == BPF_ST)
2210 		/* The only source register for BPF_ST is a ptr. */
2211 		return true;
2212 
2213 	/* Conservatively return true at default. */
2214 	return true;
2215 }
2216 
2217 /* Return the regno defined by the insn, or -1. */
2218 static int insn_def_regno(const struct bpf_insn *insn)
2219 {
2220 	switch (BPF_CLASS(insn->code)) {
2221 	case BPF_JMP:
2222 	case BPF_JMP32:
2223 	case BPF_ST:
2224 		return -1;
2225 	case BPF_STX:
2226 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2227 		    (insn->imm & BPF_FETCH)) {
2228 			if (insn->imm == BPF_CMPXCHG)
2229 				return BPF_REG_0;
2230 			else
2231 				return insn->src_reg;
2232 		} else {
2233 			return -1;
2234 		}
2235 	default:
2236 		return insn->dst_reg;
2237 	}
2238 }
2239 
2240 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2241 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2242 {
2243 	int dst_reg = insn_def_regno(insn);
2244 
2245 	if (dst_reg == -1)
2246 		return false;
2247 
2248 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2249 }
2250 
2251 static void mark_insn_zext(struct bpf_verifier_env *env,
2252 			   struct bpf_reg_state *reg)
2253 {
2254 	s32 def_idx = reg->subreg_def;
2255 
2256 	if (def_idx == DEF_NOT_SUBREG)
2257 		return;
2258 
2259 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2260 	/* The dst will be zero extended, so won't be sub-register anymore. */
2261 	reg->subreg_def = DEF_NOT_SUBREG;
2262 }
2263 
2264 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2265 			 enum reg_arg_type t)
2266 {
2267 	struct bpf_verifier_state *vstate = env->cur_state;
2268 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2269 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2270 	struct bpf_reg_state *reg, *regs = state->regs;
2271 	bool rw64;
2272 
2273 	if (regno >= MAX_BPF_REG) {
2274 		verbose(env, "R%d is invalid\n", regno);
2275 		return -EINVAL;
2276 	}
2277 
2278 	mark_reg_scratched(env, regno);
2279 
2280 	reg = &regs[regno];
2281 	rw64 = is_reg64(env, insn, regno, reg, t);
2282 	if (t == SRC_OP) {
2283 		/* check whether register used as source operand can be read */
2284 		if (reg->type == NOT_INIT) {
2285 			verbose(env, "R%d !read_ok\n", regno);
2286 			return -EACCES;
2287 		}
2288 		/* We don't need to worry about FP liveness because it's read-only */
2289 		if (regno == BPF_REG_FP)
2290 			return 0;
2291 
2292 		if (rw64)
2293 			mark_insn_zext(env, reg);
2294 
2295 		return mark_reg_read(env, reg, reg->parent,
2296 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2297 	} else {
2298 		/* check whether register used as dest operand can be written to */
2299 		if (regno == BPF_REG_FP) {
2300 			verbose(env, "frame pointer is read only\n");
2301 			return -EACCES;
2302 		}
2303 		reg->live |= REG_LIVE_WRITTEN;
2304 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2305 		if (t == DST_OP)
2306 			mark_reg_unknown(env, regs, regno);
2307 	}
2308 	return 0;
2309 }
2310 
2311 /* for any branch, call, exit record the history of jmps in the given state */
2312 static int push_jmp_history(struct bpf_verifier_env *env,
2313 			    struct bpf_verifier_state *cur)
2314 {
2315 	u32 cnt = cur->jmp_history_cnt;
2316 	struct bpf_idx_pair *p;
2317 
2318 	cnt++;
2319 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2320 	if (!p)
2321 		return -ENOMEM;
2322 	p[cnt - 1].idx = env->insn_idx;
2323 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2324 	cur->jmp_history = p;
2325 	cur->jmp_history_cnt = cnt;
2326 	return 0;
2327 }
2328 
2329 /* Backtrack one insn at a time. If idx is not at the top of recorded
2330  * history then previous instruction came from straight line execution.
2331  */
2332 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2333 			     u32 *history)
2334 {
2335 	u32 cnt = *history;
2336 
2337 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2338 		i = st->jmp_history[cnt - 1].prev_idx;
2339 		(*history)--;
2340 	} else {
2341 		i--;
2342 	}
2343 	return i;
2344 }
2345 
2346 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2347 {
2348 	const struct btf_type *func;
2349 	struct btf *desc_btf;
2350 
2351 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2352 		return NULL;
2353 
2354 	desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL);
2355 	if (IS_ERR(desc_btf))
2356 		return "<error>";
2357 
2358 	func = btf_type_by_id(desc_btf, insn->imm);
2359 	return btf_name_by_offset(desc_btf, func->name_off);
2360 }
2361 
2362 /* For given verifier state backtrack_insn() is called from the last insn to
2363  * the first insn. Its purpose is to compute a bitmask of registers and
2364  * stack slots that needs precision in the parent verifier state.
2365  */
2366 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2367 			  u32 *reg_mask, u64 *stack_mask)
2368 {
2369 	const struct bpf_insn_cbs cbs = {
2370 		.cb_call	= disasm_kfunc_name,
2371 		.cb_print	= verbose,
2372 		.private_data	= env,
2373 	};
2374 	struct bpf_insn *insn = env->prog->insnsi + idx;
2375 	u8 class = BPF_CLASS(insn->code);
2376 	u8 opcode = BPF_OP(insn->code);
2377 	u8 mode = BPF_MODE(insn->code);
2378 	u32 dreg = 1u << insn->dst_reg;
2379 	u32 sreg = 1u << insn->src_reg;
2380 	u32 spi;
2381 
2382 	if (insn->code == 0)
2383 		return 0;
2384 	if (env->log.level & BPF_LOG_LEVEL2) {
2385 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2386 		verbose(env, "%d: ", idx);
2387 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2388 	}
2389 
2390 	if (class == BPF_ALU || class == BPF_ALU64) {
2391 		if (!(*reg_mask & dreg))
2392 			return 0;
2393 		if (opcode == BPF_MOV) {
2394 			if (BPF_SRC(insn->code) == BPF_X) {
2395 				/* dreg = sreg
2396 				 * dreg needs precision after this insn
2397 				 * sreg needs precision before this insn
2398 				 */
2399 				*reg_mask &= ~dreg;
2400 				*reg_mask |= sreg;
2401 			} else {
2402 				/* dreg = K
2403 				 * dreg needs precision after this insn.
2404 				 * Corresponding register is already marked
2405 				 * as precise=true in this verifier state.
2406 				 * No further markings in parent are necessary
2407 				 */
2408 				*reg_mask &= ~dreg;
2409 			}
2410 		} else {
2411 			if (BPF_SRC(insn->code) == BPF_X) {
2412 				/* dreg += sreg
2413 				 * both dreg and sreg need precision
2414 				 * before this insn
2415 				 */
2416 				*reg_mask |= sreg;
2417 			} /* else dreg += K
2418 			   * dreg still needs precision before this insn
2419 			   */
2420 		}
2421 	} else if (class == BPF_LDX) {
2422 		if (!(*reg_mask & dreg))
2423 			return 0;
2424 		*reg_mask &= ~dreg;
2425 
2426 		/* scalars can only be spilled into stack w/o losing precision.
2427 		 * Load from any other memory can be zero extended.
2428 		 * The desire to keep that precision is already indicated
2429 		 * by 'precise' mark in corresponding register of this state.
2430 		 * No further tracking necessary.
2431 		 */
2432 		if (insn->src_reg != BPF_REG_FP)
2433 			return 0;
2434 
2435 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2436 		 * that [fp - off] slot contains scalar that needs to be
2437 		 * tracked with precision
2438 		 */
2439 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2440 		if (spi >= 64) {
2441 			verbose(env, "BUG spi %d\n", spi);
2442 			WARN_ONCE(1, "verifier backtracking bug");
2443 			return -EFAULT;
2444 		}
2445 		*stack_mask |= 1ull << spi;
2446 	} else if (class == BPF_STX || class == BPF_ST) {
2447 		if (*reg_mask & dreg)
2448 			/* stx & st shouldn't be using _scalar_ dst_reg
2449 			 * to access memory. It means backtracking
2450 			 * encountered a case of pointer subtraction.
2451 			 */
2452 			return -ENOTSUPP;
2453 		/* scalars can only be spilled into stack */
2454 		if (insn->dst_reg != BPF_REG_FP)
2455 			return 0;
2456 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2457 		if (spi >= 64) {
2458 			verbose(env, "BUG spi %d\n", spi);
2459 			WARN_ONCE(1, "verifier backtracking bug");
2460 			return -EFAULT;
2461 		}
2462 		if (!(*stack_mask & (1ull << spi)))
2463 			return 0;
2464 		*stack_mask &= ~(1ull << spi);
2465 		if (class == BPF_STX)
2466 			*reg_mask |= sreg;
2467 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2468 		if (opcode == BPF_CALL) {
2469 			if (insn->src_reg == BPF_PSEUDO_CALL)
2470 				return -ENOTSUPP;
2471 			/* regular helper call sets R0 */
2472 			*reg_mask &= ~1;
2473 			if (*reg_mask & 0x3f) {
2474 				/* if backtracing was looking for registers R1-R5
2475 				 * they should have been found already.
2476 				 */
2477 				verbose(env, "BUG regs %x\n", *reg_mask);
2478 				WARN_ONCE(1, "verifier backtracking bug");
2479 				return -EFAULT;
2480 			}
2481 		} else if (opcode == BPF_EXIT) {
2482 			return -ENOTSUPP;
2483 		}
2484 	} else if (class == BPF_LD) {
2485 		if (!(*reg_mask & dreg))
2486 			return 0;
2487 		*reg_mask &= ~dreg;
2488 		/* It's ld_imm64 or ld_abs or ld_ind.
2489 		 * For ld_imm64 no further tracking of precision
2490 		 * into parent is necessary
2491 		 */
2492 		if (mode == BPF_IND || mode == BPF_ABS)
2493 			/* to be analyzed */
2494 			return -ENOTSUPP;
2495 	}
2496 	return 0;
2497 }
2498 
2499 /* the scalar precision tracking algorithm:
2500  * . at the start all registers have precise=false.
2501  * . scalar ranges are tracked as normal through alu and jmp insns.
2502  * . once precise value of the scalar register is used in:
2503  *   .  ptr + scalar alu
2504  *   . if (scalar cond K|scalar)
2505  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2506  *   backtrack through the verifier states and mark all registers and
2507  *   stack slots with spilled constants that these scalar regisers
2508  *   should be precise.
2509  * . during state pruning two registers (or spilled stack slots)
2510  *   are equivalent if both are not precise.
2511  *
2512  * Note the verifier cannot simply walk register parentage chain,
2513  * since many different registers and stack slots could have been
2514  * used to compute single precise scalar.
2515  *
2516  * The approach of starting with precise=true for all registers and then
2517  * backtrack to mark a register as not precise when the verifier detects
2518  * that program doesn't care about specific value (e.g., when helper
2519  * takes register as ARG_ANYTHING parameter) is not safe.
2520  *
2521  * It's ok to walk single parentage chain of the verifier states.
2522  * It's possible that this backtracking will go all the way till 1st insn.
2523  * All other branches will be explored for needing precision later.
2524  *
2525  * The backtracking needs to deal with cases like:
2526  *   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)
2527  * r9 -= r8
2528  * r5 = r9
2529  * if r5 > 0x79f goto pc+7
2530  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2531  * r5 += 1
2532  * ...
2533  * call bpf_perf_event_output#25
2534  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2535  *
2536  * and this case:
2537  * r6 = 1
2538  * call foo // uses callee's r6 inside to compute r0
2539  * r0 += r6
2540  * if r0 == 0 goto
2541  *
2542  * to track above reg_mask/stack_mask needs to be independent for each frame.
2543  *
2544  * Also if parent's curframe > frame where backtracking started,
2545  * the verifier need to mark registers in both frames, otherwise callees
2546  * may incorrectly prune callers. This is similar to
2547  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2548  *
2549  * For now backtracking falls back into conservative marking.
2550  */
2551 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2552 				     struct bpf_verifier_state *st)
2553 {
2554 	struct bpf_func_state *func;
2555 	struct bpf_reg_state *reg;
2556 	int i, j;
2557 
2558 	/* big hammer: mark all scalars precise in this path.
2559 	 * pop_stack may still get !precise scalars.
2560 	 */
2561 	for (; st; st = st->parent)
2562 		for (i = 0; i <= st->curframe; i++) {
2563 			func = st->frame[i];
2564 			for (j = 0; j < BPF_REG_FP; j++) {
2565 				reg = &func->regs[j];
2566 				if (reg->type != SCALAR_VALUE)
2567 					continue;
2568 				reg->precise = true;
2569 			}
2570 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2571 				if (!is_spilled_reg(&func->stack[j]))
2572 					continue;
2573 				reg = &func->stack[j].spilled_ptr;
2574 				if (reg->type != SCALAR_VALUE)
2575 					continue;
2576 				reg->precise = true;
2577 			}
2578 		}
2579 }
2580 
2581 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2582 				  int spi)
2583 {
2584 	struct bpf_verifier_state *st = env->cur_state;
2585 	int first_idx = st->first_insn_idx;
2586 	int last_idx = env->insn_idx;
2587 	struct bpf_func_state *func;
2588 	struct bpf_reg_state *reg;
2589 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2590 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2591 	bool skip_first = true;
2592 	bool new_marks = false;
2593 	int i, err;
2594 
2595 	if (!env->bpf_capable)
2596 		return 0;
2597 
2598 	func = st->frame[st->curframe];
2599 	if (regno >= 0) {
2600 		reg = &func->regs[regno];
2601 		if (reg->type != SCALAR_VALUE) {
2602 			WARN_ONCE(1, "backtracing misuse");
2603 			return -EFAULT;
2604 		}
2605 		if (!reg->precise)
2606 			new_marks = true;
2607 		else
2608 			reg_mask = 0;
2609 		reg->precise = true;
2610 	}
2611 
2612 	while (spi >= 0) {
2613 		if (!is_spilled_reg(&func->stack[spi])) {
2614 			stack_mask = 0;
2615 			break;
2616 		}
2617 		reg = &func->stack[spi].spilled_ptr;
2618 		if (reg->type != SCALAR_VALUE) {
2619 			stack_mask = 0;
2620 			break;
2621 		}
2622 		if (!reg->precise)
2623 			new_marks = true;
2624 		else
2625 			stack_mask = 0;
2626 		reg->precise = true;
2627 		break;
2628 	}
2629 
2630 	if (!new_marks)
2631 		return 0;
2632 	if (!reg_mask && !stack_mask)
2633 		return 0;
2634 	for (;;) {
2635 		DECLARE_BITMAP(mask, 64);
2636 		u32 history = st->jmp_history_cnt;
2637 
2638 		if (env->log.level & BPF_LOG_LEVEL2)
2639 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2640 		for (i = last_idx;;) {
2641 			if (skip_first) {
2642 				err = 0;
2643 				skip_first = false;
2644 			} else {
2645 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2646 			}
2647 			if (err == -ENOTSUPP) {
2648 				mark_all_scalars_precise(env, st);
2649 				return 0;
2650 			} else if (err) {
2651 				return err;
2652 			}
2653 			if (!reg_mask && !stack_mask)
2654 				/* Found assignment(s) into tracked register in this state.
2655 				 * Since this state is already marked, just return.
2656 				 * Nothing to be tracked further in the parent state.
2657 				 */
2658 				return 0;
2659 			if (i == first_idx)
2660 				break;
2661 			i = get_prev_insn_idx(st, i, &history);
2662 			if (i >= env->prog->len) {
2663 				/* This can happen if backtracking reached insn 0
2664 				 * and there are still reg_mask or stack_mask
2665 				 * to backtrack.
2666 				 * It means the backtracking missed the spot where
2667 				 * particular register was initialized with a constant.
2668 				 */
2669 				verbose(env, "BUG backtracking idx %d\n", i);
2670 				WARN_ONCE(1, "verifier backtracking bug");
2671 				return -EFAULT;
2672 			}
2673 		}
2674 		st = st->parent;
2675 		if (!st)
2676 			break;
2677 
2678 		new_marks = false;
2679 		func = st->frame[st->curframe];
2680 		bitmap_from_u64(mask, reg_mask);
2681 		for_each_set_bit(i, mask, 32) {
2682 			reg = &func->regs[i];
2683 			if (reg->type != SCALAR_VALUE) {
2684 				reg_mask &= ~(1u << i);
2685 				continue;
2686 			}
2687 			if (!reg->precise)
2688 				new_marks = true;
2689 			reg->precise = true;
2690 		}
2691 
2692 		bitmap_from_u64(mask, stack_mask);
2693 		for_each_set_bit(i, mask, 64) {
2694 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2695 				/* the sequence of instructions:
2696 				 * 2: (bf) r3 = r10
2697 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2698 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2699 				 * doesn't contain jmps. It's backtracked
2700 				 * as a single block.
2701 				 * During backtracking insn 3 is not recognized as
2702 				 * stack access, so at the end of backtracking
2703 				 * stack slot fp-8 is still marked in stack_mask.
2704 				 * However the parent state may not have accessed
2705 				 * fp-8 and it's "unallocated" stack space.
2706 				 * In such case fallback to conservative.
2707 				 */
2708 				mark_all_scalars_precise(env, st);
2709 				return 0;
2710 			}
2711 
2712 			if (!is_spilled_reg(&func->stack[i])) {
2713 				stack_mask &= ~(1ull << i);
2714 				continue;
2715 			}
2716 			reg = &func->stack[i].spilled_ptr;
2717 			if (reg->type != SCALAR_VALUE) {
2718 				stack_mask &= ~(1ull << i);
2719 				continue;
2720 			}
2721 			if (!reg->precise)
2722 				new_marks = true;
2723 			reg->precise = true;
2724 		}
2725 		if (env->log.level & BPF_LOG_LEVEL2) {
2726 			verbose(env, "parent %s regs=%x stack=%llx marks:",
2727 				new_marks ? "didn't have" : "already had",
2728 				reg_mask, stack_mask);
2729 			print_verifier_state(env, func, true);
2730 		}
2731 
2732 		if (!reg_mask && !stack_mask)
2733 			break;
2734 		if (!new_marks)
2735 			break;
2736 
2737 		last_idx = st->last_insn_idx;
2738 		first_idx = st->first_insn_idx;
2739 	}
2740 	return 0;
2741 }
2742 
2743 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2744 {
2745 	return __mark_chain_precision(env, regno, -1);
2746 }
2747 
2748 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2749 {
2750 	return __mark_chain_precision(env, -1, spi);
2751 }
2752 
2753 static bool is_spillable_regtype(enum bpf_reg_type type)
2754 {
2755 	switch (base_type(type)) {
2756 	case PTR_TO_MAP_VALUE:
2757 	case PTR_TO_STACK:
2758 	case PTR_TO_CTX:
2759 	case PTR_TO_PACKET:
2760 	case PTR_TO_PACKET_META:
2761 	case PTR_TO_PACKET_END:
2762 	case PTR_TO_FLOW_KEYS:
2763 	case CONST_PTR_TO_MAP:
2764 	case PTR_TO_SOCKET:
2765 	case PTR_TO_SOCK_COMMON:
2766 	case PTR_TO_TCP_SOCK:
2767 	case PTR_TO_XDP_SOCK:
2768 	case PTR_TO_BTF_ID:
2769 	case PTR_TO_BUF:
2770 	case PTR_TO_PERCPU_BTF_ID:
2771 	case PTR_TO_MEM:
2772 	case PTR_TO_FUNC:
2773 	case PTR_TO_MAP_KEY:
2774 		return true;
2775 	default:
2776 		return false;
2777 	}
2778 }
2779 
2780 /* Does this register contain a constant zero? */
2781 static bool register_is_null(struct bpf_reg_state *reg)
2782 {
2783 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2784 }
2785 
2786 static bool register_is_const(struct bpf_reg_state *reg)
2787 {
2788 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2789 }
2790 
2791 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2792 {
2793 	return tnum_is_unknown(reg->var_off) &&
2794 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2795 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2796 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2797 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2798 }
2799 
2800 static bool register_is_bounded(struct bpf_reg_state *reg)
2801 {
2802 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2803 }
2804 
2805 static bool __is_pointer_value(bool allow_ptr_leaks,
2806 			       const struct bpf_reg_state *reg)
2807 {
2808 	if (allow_ptr_leaks)
2809 		return false;
2810 
2811 	return reg->type != SCALAR_VALUE;
2812 }
2813 
2814 static void save_register_state(struct bpf_func_state *state,
2815 				int spi, struct bpf_reg_state *reg,
2816 				int size)
2817 {
2818 	int i;
2819 
2820 	state->stack[spi].spilled_ptr = *reg;
2821 	if (size == BPF_REG_SIZE)
2822 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2823 
2824 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2825 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2826 
2827 	/* size < 8 bytes spill */
2828 	for (; i; i--)
2829 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2830 }
2831 
2832 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2833  * stack boundary and alignment are checked in check_mem_access()
2834  */
2835 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2836 				       /* stack frame we're writing to */
2837 				       struct bpf_func_state *state,
2838 				       int off, int size, int value_regno,
2839 				       int insn_idx)
2840 {
2841 	struct bpf_func_state *cur; /* state of the current function */
2842 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2843 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2844 	struct bpf_reg_state *reg = NULL;
2845 
2846 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2847 	if (err)
2848 		return err;
2849 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2850 	 * so it's aligned access and [off, off + size) are within stack limits
2851 	 */
2852 	if (!env->allow_ptr_leaks &&
2853 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2854 	    size != BPF_REG_SIZE) {
2855 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2856 		return -EACCES;
2857 	}
2858 
2859 	cur = env->cur_state->frame[env->cur_state->curframe];
2860 	if (value_regno >= 0)
2861 		reg = &cur->regs[value_regno];
2862 	if (!env->bypass_spec_v4) {
2863 		bool sanitize = reg && is_spillable_regtype(reg->type);
2864 
2865 		for (i = 0; i < size; i++) {
2866 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2867 				sanitize = true;
2868 				break;
2869 			}
2870 		}
2871 
2872 		if (sanitize)
2873 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2874 	}
2875 
2876 	mark_stack_slot_scratched(env, spi);
2877 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2878 	    !register_is_null(reg) && env->bpf_capable) {
2879 		if (dst_reg != BPF_REG_FP) {
2880 			/* The backtracking logic can only recognize explicit
2881 			 * stack slot address like [fp - 8]. Other spill of
2882 			 * scalar via different register has to be conservative.
2883 			 * Backtrack from here and mark all registers as precise
2884 			 * that contributed into 'reg' being a constant.
2885 			 */
2886 			err = mark_chain_precision(env, value_regno);
2887 			if (err)
2888 				return err;
2889 		}
2890 		save_register_state(state, spi, reg, size);
2891 	} else if (reg && is_spillable_regtype(reg->type)) {
2892 		/* register containing pointer is being spilled into stack */
2893 		if (size != BPF_REG_SIZE) {
2894 			verbose_linfo(env, insn_idx, "; ");
2895 			verbose(env, "invalid size of register spill\n");
2896 			return -EACCES;
2897 		}
2898 		if (state != cur && reg->type == PTR_TO_STACK) {
2899 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2900 			return -EINVAL;
2901 		}
2902 		save_register_state(state, spi, reg, size);
2903 	} else {
2904 		u8 type = STACK_MISC;
2905 
2906 		/* regular write of data into stack destroys any spilled ptr */
2907 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2908 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2909 		if (is_spilled_reg(&state->stack[spi]))
2910 			for (i = 0; i < BPF_REG_SIZE; i++)
2911 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2912 
2913 		/* only mark the slot as written if all 8 bytes were written
2914 		 * otherwise read propagation may incorrectly stop too soon
2915 		 * when stack slots are partially written.
2916 		 * This heuristic means that read propagation will be
2917 		 * conservative, since it will add reg_live_read marks
2918 		 * to stack slots all the way to first state when programs
2919 		 * writes+reads less than 8 bytes
2920 		 */
2921 		if (size == BPF_REG_SIZE)
2922 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2923 
2924 		/* when we zero initialize stack slots mark them as such */
2925 		if (reg && register_is_null(reg)) {
2926 			/* backtracking doesn't work for STACK_ZERO yet. */
2927 			err = mark_chain_precision(env, value_regno);
2928 			if (err)
2929 				return err;
2930 			type = STACK_ZERO;
2931 		}
2932 
2933 		/* Mark slots affected by this stack write. */
2934 		for (i = 0; i < size; i++)
2935 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2936 				type;
2937 	}
2938 	return 0;
2939 }
2940 
2941 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2942  * known to contain a variable offset.
2943  * This function checks whether the write is permitted and conservatively
2944  * tracks the effects of the write, considering that each stack slot in the
2945  * dynamic range is potentially written to.
2946  *
2947  * 'off' includes 'regno->off'.
2948  * 'value_regno' can be -1, meaning that an unknown value is being written to
2949  * the stack.
2950  *
2951  * Spilled pointers in range are not marked as written because we don't know
2952  * what's going to be actually written. This means that read propagation for
2953  * future reads cannot be terminated by this write.
2954  *
2955  * For privileged programs, uninitialized stack slots are considered
2956  * initialized by this write (even though we don't know exactly what offsets
2957  * are going to be written to). The idea is that we don't want the verifier to
2958  * reject future reads that access slots written to through variable offsets.
2959  */
2960 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2961 				     /* func where register points to */
2962 				     struct bpf_func_state *state,
2963 				     int ptr_regno, int off, int size,
2964 				     int value_regno, int insn_idx)
2965 {
2966 	struct bpf_func_state *cur; /* state of the current function */
2967 	int min_off, max_off;
2968 	int i, err;
2969 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2970 	bool writing_zero = false;
2971 	/* set if the fact that we're writing a zero is used to let any
2972 	 * stack slots remain STACK_ZERO
2973 	 */
2974 	bool zero_used = false;
2975 
2976 	cur = env->cur_state->frame[env->cur_state->curframe];
2977 	ptr_reg = &cur->regs[ptr_regno];
2978 	min_off = ptr_reg->smin_value + off;
2979 	max_off = ptr_reg->smax_value + off + size;
2980 	if (value_regno >= 0)
2981 		value_reg = &cur->regs[value_regno];
2982 	if (value_reg && register_is_null(value_reg))
2983 		writing_zero = true;
2984 
2985 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2986 	if (err)
2987 		return err;
2988 
2989 
2990 	/* Variable offset writes destroy any spilled pointers in range. */
2991 	for (i = min_off; i < max_off; i++) {
2992 		u8 new_type, *stype;
2993 		int slot, spi;
2994 
2995 		slot = -i - 1;
2996 		spi = slot / BPF_REG_SIZE;
2997 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2998 		mark_stack_slot_scratched(env, spi);
2999 
3000 		if (!env->allow_ptr_leaks
3001 				&& *stype != NOT_INIT
3002 				&& *stype != SCALAR_VALUE) {
3003 			/* Reject the write if there's are spilled pointers in
3004 			 * range. If we didn't reject here, the ptr status
3005 			 * would be erased below (even though not all slots are
3006 			 * actually overwritten), possibly opening the door to
3007 			 * leaks.
3008 			 */
3009 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3010 				insn_idx, i);
3011 			return -EINVAL;
3012 		}
3013 
3014 		/* Erase all spilled pointers. */
3015 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3016 
3017 		/* Update the slot type. */
3018 		new_type = STACK_MISC;
3019 		if (writing_zero && *stype == STACK_ZERO) {
3020 			new_type = STACK_ZERO;
3021 			zero_used = true;
3022 		}
3023 		/* If the slot is STACK_INVALID, we check whether it's OK to
3024 		 * pretend that it will be initialized by this write. The slot
3025 		 * might not actually be written to, and so if we mark it as
3026 		 * initialized future reads might leak uninitialized memory.
3027 		 * For privileged programs, we will accept such reads to slots
3028 		 * that may or may not be written because, if we're reject
3029 		 * them, the error would be too confusing.
3030 		 */
3031 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3032 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3033 					insn_idx, i);
3034 			return -EINVAL;
3035 		}
3036 		*stype = new_type;
3037 	}
3038 	if (zero_used) {
3039 		/* backtracking doesn't work for STACK_ZERO yet. */
3040 		err = mark_chain_precision(env, value_regno);
3041 		if (err)
3042 			return err;
3043 	}
3044 	return 0;
3045 }
3046 
3047 /* When register 'dst_regno' is assigned some values from stack[min_off,
3048  * max_off), we set the register's type according to the types of the
3049  * respective stack slots. If all the stack values are known to be zeros, then
3050  * so is the destination reg. Otherwise, the register is considered to be
3051  * SCALAR. This function does not deal with register filling; the caller must
3052  * ensure that all spilled registers in the stack range have been marked as
3053  * read.
3054  */
3055 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3056 				/* func where src register points to */
3057 				struct bpf_func_state *ptr_state,
3058 				int min_off, int max_off, int dst_regno)
3059 {
3060 	struct bpf_verifier_state *vstate = env->cur_state;
3061 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3062 	int i, slot, spi;
3063 	u8 *stype;
3064 	int zeros = 0;
3065 
3066 	for (i = min_off; i < max_off; i++) {
3067 		slot = -i - 1;
3068 		spi = slot / BPF_REG_SIZE;
3069 		stype = ptr_state->stack[spi].slot_type;
3070 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3071 			break;
3072 		zeros++;
3073 	}
3074 	if (zeros == max_off - min_off) {
3075 		/* any access_size read into register is zero extended,
3076 		 * so the whole register == const_zero
3077 		 */
3078 		__mark_reg_const_zero(&state->regs[dst_regno]);
3079 		/* backtracking doesn't support STACK_ZERO yet,
3080 		 * so mark it precise here, so that later
3081 		 * backtracking can stop here.
3082 		 * Backtracking may not need this if this register
3083 		 * doesn't participate in pointer adjustment.
3084 		 * Forward propagation of precise flag is not
3085 		 * necessary either. This mark is only to stop
3086 		 * backtracking. Any register that contributed
3087 		 * to const 0 was marked precise before spill.
3088 		 */
3089 		state->regs[dst_regno].precise = true;
3090 	} else {
3091 		/* have read misc data from the stack */
3092 		mark_reg_unknown(env, state->regs, dst_regno);
3093 	}
3094 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3095 }
3096 
3097 /* Read the stack at 'off' and put the results into the register indicated by
3098  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3099  * spilled reg.
3100  *
3101  * 'dst_regno' can be -1, meaning that the read value is not going to a
3102  * register.
3103  *
3104  * The access is assumed to be within the current stack bounds.
3105  */
3106 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3107 				      /* func where src register points to */
3108 				      struct bpf_func_state *reg_state,
3109 				      int off, int size, int dst_regno)
3110 {
3111 	struct bpf_verifier_state *vstate = env->cur_state;
3112 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3113 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3114 	struct bpf_reg_state *reg;
3115 	u8 *stype, type;
3116 
3117 	stype = reg_state->stack[spi].slot_type;
3118 	reg = &reg_state->stack[spi].spilled_ptr;
3119 
3120 	if (is_spilled_reg(&reg_state->stack[spi])) {
3121 		u8 spill_size = 1;
3122 
3123 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3124 			spill_size++;
3125 
3126 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3127 			if (reg->type != SCALAR_VALUE) {
3128 				verbose_linfo(env, env->insn_idx, "; ");
3129 				verbose(env, "invalid size of register fill\n");
3130 				return -EACCES;
3131 			}
3132 
3133 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3134 			if (dst_regno < 0)
3135 				return 0;
3136 
3137 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3138 				/* The earlier check_reg_arg() has decided the
3139 				 * subreg_def for this insn.  Save it first.
3140 				 */
3141 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3142 
3143 				state->regs[dst_regno] = *reg;
3144 				state->regs[dst_regno].subreg_def = subreg_def;
3145 			} else {
3146 				for (i = 0; i < size; i++) {
3147 					type = stype[(slot - i) % BPF_REG_SIZE];
3148 					if (type == STACK_SPILL)
3149 						continue;
3150 					if (type == STACK_MISC)
3151 						continue;
3152 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3153 						off, i, size);
3154 					return -EACCES;
3155 				}
3156 				mark_reg_unknown(env, state->regs, dst_regno);
3157 			}
3158 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3159 			return 0;
3160 		}
3161 
3162 		if (dst_regno >= 0) {
3163 			/* restore register state from stack */
3164 			state->regs[dst_regno] = *reg;
3165 			/* mark reg as written since spilled pointer state likely
3166 			 * has its liveness marks cleared by is_state_visited()
3167 			 * which resets stack/reg liveness for state transitions
3168 			 */
3169 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3170 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3171 			/* If dst_regno==-1, the caller is asking us whether
3172 			 * it is acceptable to use this value as a SCALAR_VALUE
3173 			 * (e.g. for XADD).
3174 			 * We must not allow unprivileged callers to do that
3175 			 * with spilled pointers.
3176 			 */
3177 			verbose(env, "leaking pointer from stack off %d\n",
3178 				off);
3179 			return -EACCES;
3180 		}
3181 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3182 	} else {
3183 		for (i = 0; i < size; i++) {
3184 			type = stype[(slot - i) % BPF_REG_SIZE];
3185 			if (type == STACK_MISC)
3186 				continue;
3187 			if (type == STACK_ZERO)
3188 				continue;
3189 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3190 				off, i, size);
3191 			return -EACCES;
3192 		}
3193 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3194 		if (dst_regno >= 0)
3195 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3196 	}
3197 	return 0;
3198 }
3199 
3200 enum stack_access_src {
3201 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3202 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3203 };
3204 
3205 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3206 					 int regno, int off, int access_size,
3207 					 bool zero_size_allowed,
3208 					 enum stack_access_src type,
3209 					 struct bpf_call_arg_meta *meta);
3210 
3211 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3212 {
3213 	return cur_regs(env) + regno;
3214 }
3215 
3216 /* Read the stack at 'ptr_regno + off' and put the result into the register
3217  * 'dst_regno'.
3218  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3219  * but not its variable offset.
3220  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3221  *
3222  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3223  * filling registers (i.e. reads of spilled register cannot be detected when
3224  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3225  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3226  * offset; for a fixed offset check_stack_read_fixed_off should be used
3227  * instead.
3228  */
3229 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3230 				    int ptr_regno, int off, int size, int dst_regno)
3231 {
3232 	/* The state of the source register. */
3233 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3234 	struct bpf_func_state *ptr_state = func(env, reg);
3235 	int err;
3236 	int min_off, max_off;
3237 
3238 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3239 	 */
3240 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3241 					    false, ACCESS_DIRECT, NULL);
3242 	if (err)
3243 		return err;
3244 
3245 	min_off = reg->smin_value + off;
3246 	max_off = reg->smax_value + off;
3247 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3248 	return 0;
3249 }
3250 
3251 /* check_stack_read dispatches to check_stack_read_fixed_off or
3252  * check_stack_read_var_off.
3253  *
3254  * The caller must ensure that the offset falls within the allocated stack
3255  * bounds.
3256  *
3257  * 'dst_regno' is a register which will receive the value from the stack. It
3258  * can be -1, meaning that the read value is not going to a register.
3259  */
3260 static int check_stack_read(struct bpf_verifier_env *env,
3261 			    int ptr_regno, int off, int size,
3262 			    int dst_regno)
3263 {
3264 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3265 	struct bpf_func_state *state = func(env, reg);
3266 	int err;
3267 	/* Some accesses are only permitted with a static offset. */
3268 	bool var_off = !tnum_is_const(reg->var_off);
3269 
3270 	/* The offset is required to be static when reads don't go to a
3271 	 * register, in order to not leak pointers (see
3272 	 * check_stack_read_fixed_off).
3273 	 */
3274 	if (dst_regno < 0 && var_off) {
3275 		char tn_buf[48];
3276 
3277 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3278 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3279 			tn_buf, off, size);
3280 		return -EACCES;
3281 	}
3282 	/* Variable offset is prohibited for unprivileged mode for simplicity
3283 	 * since it requires corresponding support in Spectre masking for stack
3284 	 * ALU. See also retrieve_ptr_limit().
3285 	 */
3286 	if (!env->bypass_spec_v1 && var_off) {
3287 		char tn_buf[48];
3288 
3289 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3290 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3291 				ptr_regno, tn_buf);
3292 		return -EACCES;
3293 	}
3294 
3295 	if (!var_off) {
3296 		off += reg->var_off.value;
3297 		err = check_stack_read_fixed_off(env, state, off, size,
3298 						 dst_regno);
3299 	} else {
3300 		/* Variable offset stack reads need more conservative handling
3301 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3302 		 * branch.
3303 		 */
3304 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3305 					       dst_regno);
3306 	}
3307 	return err;
3308 }
3309 
3310 
3311 /* check_stack_write dispatches to check_stack_write_fixed_off or
3312  * check_stack_write_var_off.
3313  *
3314  * 'ptr_regno' is the register used as a pointer into the stack.
3315  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3316  * 'value_regno' is the register whose value we're writing to the stack. It can
3317  * be -1, meaning that we're not writing from a register.
3318  *
3319  * The caller must ensure that the offset falls within the maximum stack size.
3320  */
3321 static int check_stack_write(struct bpf_verifier_env *env,
3322 			     int ptr_regno, int off, int size,
3323 			     int value_regno, int insn_idx)
3324 {
3325 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3326 	struct bpf_func_state *state = func(env, reg);
3327 	int err;
3328 
3329 	if (tnum_is_const(reg->var_off)) {
3330 		off += reg->var_off.value;
3331 		err = check_stack_write_fixed_off(env, state, off, size,
3332 						  value_regno, insn_idx);
3333 	} else {
3334 		/* Variable offset stack reads need more conservative handling
3335 		 * than fixed offset ones.
3336 		 */
3337 		err = check_stack_write_var_off(env, state,
3338 						ptr_regno, off, size,
3339 						value_regno, insn_idx);
3340 	}
3341 	return err;
3342 }
3343 
3344 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3345 				 int off, int size, enum bpf_access_type type)
3346 {
3347 	struct bpf_reg_state *regs = cur_regs(env);
3348 	struct bpf_map *map = regs[regno].map_ptr;
3349 	u32 cap = bpf_map_flags_to_cap(map);
3350 
3351 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3352 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3353 			map->value_size, off, size);
3354 		return -EACCES;
3355 	}
3356 
3357 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3358 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3359 			map->value_size, off, size);
3360 		return -EACCES;
3361 	}
3362 
3363 	return 0;
3364 }
3365 
3366 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3367 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3368 			      int off, int size, u32 mem_size,
3369 			      bool zero_size_allowed)
3370 {
3371 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3372 	struct bpf_reg_state *reg;
3373 
3374 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3375 		return 0;
3376 
3377 	reg = &cur_regs(env)[regno];
3378 	switch (reg->type) {
3379 	case PTR_TO_MAP_KEY:
3380 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3381 			mem_size, off, size);
3382 		break;
3383 	case PTR_TO_MAP_VALUE:
3384 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3385 			mem_size, off, size);
3386 		break;
3387 	case PTR_TO_PACKET:
3388 	case PTR_TO_PACKET_META:
3389 	case PTR_TO_PACKET_END:
3390 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3391 			off, size, regno, reg->id, off, mem_size);
3392 		break;
3393 	case PTR_TO_MEM:
3394 	default:
3395 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3396 			mem_size, off, size);
3397 	}
3398 
3399 	return -EACCES;
3400 }
3401 
3402 /* check read/write into a memory region with possible variable offset */
3403 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3404 				   int off, int size, u32 mem_size,
3405 				   bool zero_size_allowed)
3406 {
3407 	struct bpf_verifier_state *vstate = env->cur_state;
3408 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3409 	struct bpf_reg_state *reg = &state->regs[regno];
3410 	int err;
3411 
3412 	/* We may have adjusted the register pointing to memory region, so we
3413 	 * need to try adding each of min_value and max_value to off
3414 	 * to make sure our theoretical access will be safe.
3415 	 *
3416 	 * The minimum value is only important with signed
3417 	 * comparisons where we can't assume the floor of a
3418 	 * value is 0.  If we are using signed variables for our
3419 	 * index'es we need to make sure that whatever we use
3420 	 * will have a set floor within our range.
3421 	 */
3422 	if (reg->smin_value < 0 &&
3423 	    (reg->smin_value == S64_MIN ||
3424 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3425 	      reg->smin_value + off < 0)) {
3426 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3427 			regno);
3428 		return -EACCES;
3429 	}
3430 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3431 				 mem_size, zero_size_allowed);
3432 	if (err) {
3433 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3434 			regno);
3435 		return err;
3436 	}
3437 
3438 	/* If we haven't set a max value then we need to bail since we can't be
3439 	 * sure we won't do bad things.
3440 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3441 	 */
3442 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3443 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3444 			regno);
3445 		return -EACCES;
3446 	}
3447 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3448 				 mem_size, zero_size_allowed);
3449 	if (err) {
3450 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3451 			regno);
3452 		return err;
3453 	}
3454 
3455 	return 0;
3456 }
3457 
3458 /* check read/write into a map element with possible variable offset */
3459 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3460 			    int off, int size, bool zero_size_allowed)
3461 {
3462 	struct bpf_verifier_state *vstate = env->cur_state;
3463 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3464 	struct bpf_reg_state *reg = &state->regs[regno];
3465 	struct bpf_map *map = reg->map_ptr;
3466 	int err;
3467 
3468 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3469 				      zero_size_allowed);
3470 	if (err)
3471 		return err;
3472 
3473 	if (map_value_has_spin_lock(map)) {
3474 		u32 lock = map->spin_lock_off;
3475 
3476 		/* if any part of struct bpf_spin_lock can be touched by
3477 		 * load/store reject this program.
3478 		 * To check that [x1, x2) overlaps with [y1, y2)
3479 		 * it is sufficient to check x1 < y2 && y1 < x2.
3480 		 */
3481 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3482 		     lock < reg->umax_value + off + size) {
3483 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3484 			return -EACCES;
3485 		}
3486 	}
3487 	if (map_value_has_timer(map)) {
3488 		u32 t = map->timer_off;
3489 
3490 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3491 		     t < reg->umax_value + off + size) {
3492 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3493 			return -EACCES;
3494 		}
3495 	}
3496 	return err;
3497 }
3498 
3499 #define MAX_PACKET_OFF 0xffff
3500 
3501 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3502 {
3503 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3504 }
3505 
3506 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3507 				       const struct bpf_call_arg_meta *meta,
3508 				       enum bpf_access_type t)
3509 {
3510 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3511 
3512 	switch (prog_type) {
3513 	/* Program types only with direct read access go here! */
3514 	case BPF_PROG_TYPE_LWT_IN:
3515 	case BPF_PROG_TYPE_LWT_OUT:
3516 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3517 	case BPF_PROG_TYPE_SK_REUSEPORT:
3518 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3519 	case BPF_PROG_TYPE_CGROUP_SKB:
3520 		if (t == BPF_WRITE)
3521 			return false;
3522 		fallthrough;
3523 
3524 	/* Program types with direct read + write access go here! */
3525 	case BPF_PROG_TYPE_SCHED_CLS:
3526 	case BPF_PROG_TYPE_SCHED_ACT:
3527 	case BPF_PROG_TYPE_XDP:
3528 	case BPF_PROG_TYPE_LWT_XMIT:
3529 	case BPF_PROG_TYPE_SK_SKB:
3530 	case BPF_PROG_TYPE_SK_MSG:
3531 		if (meta)
3532 			return meta->pkt_access;
3533 
3534 		env->seen_direct_write = true;
3535 		return true;
3536 
3537 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3538 		if (t == BPF_WRITE)
3539 			env->seen_direct_write = true;
3540 
3541 		return true;
3542 
3543 	default:
3544 		return false;
3545 	}
3546 }
3547 
3548 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3549 			       int size, bool zero_size_allowed)
3550 {
3551 	struct bpf_reg_state *regs = cur_regs(env);
3552 	struct bpf_reg_state *reg = &regs[regno];
3553 	int err;
3554 
3555 	/* We may have added a variable offset to the packet pointer; but any
3556 	 * reg->range we have comes after that.  We are only checking the fixed
3557 	 * offset.
3558 	 */
3559 
3560 	/* We don't allow negative numbers, because we aren't tracking enough
3561 	 * detail to prove they're safe.
3562 	 */
3563 	if (reg->smin_value < 0) {
3564 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3565 			regno);
3566 		return -EACCES;
3567 	}
3568 
3569 	err = reg->range < 0 ? -EINVAL :
3570 	      __check_mem_access(env, regno, off, size, reg->range,
3571 				 zero_size_allowed);
3572 	if (err) {
3573 		verbose(env, "R%d offset is outside of the packet\n", regno);
3574 		return err;
3575 	}
3576 
3577 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3578 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3579 	 * otherwise find_good_pkt_pointers would have refused to set range info
3580 	 * that __check_mem_access would have rejected this pkt access.
3581 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3582 	 */
3583 	env->prog->aux->max_pkt_offset =
3584 		max_t(u32, env->prog->aux->max_pkt_offset,
3585 		      off + reg->umax_value + size - 1);
3586 
3587 	return err;
3588 }
3589 
3590 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3591 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3592 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3593 			    struct btf **btf, u32 *btf_id)
3594 {
3595 	struct bpf_insn_access_aux info = {
3596 		.reg_type = *reg_type,
3597 		.log = &env->log,
3598 	};
3599 
3600 	if (env->ops->is_valid_access &&
3601 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3602 		/* A non zero info.ctx_field_size indicates that this field is a
3603 		 * candidate for later verifier transformation to load the whole
3604 		 * field and then apply a mask when accessed with a narrower
3605 		 * access than actual ctx access size. A zero info.ctx_field_size
3606 		 * will only allow for whole field access and rejects any other
3607 		 * type of narrower access.
3608 		 */
3609 		*reg_type = info.reg_type;
3610 
3611 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3612 			*btf = info.btf;
3613 			*btf_id = info.btf_id;
3614 		} else {
3615 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3616 		}
3617 		/* remember the offset of last byte accessed in ctx */
3618 		if (env->prog->aux->max_ctx_offset < off + size)
3619 			env->prog->aux->max_ctx_offset = off + size;
3620 		return 0;
3621 	}
3622 
3623 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3624 	return -EACCES;
3625 }
3626 
3627 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3628 				  int size)
3629 {
3630 	if (size < 0 || off < 0 ||
3631 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3632 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3633 			off, size);
3634 		return -EACCES;
3635 	}
3636 	return 0;
3637 }
3638 
3639 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3640 			     u32 regno, int off, int size,
3641 			     enum bpf_access_type t)
3642 {
3643 	struct bpf_reg_state *regs = cur_regs(env);
3644 	struct bpf_reg_state *reg = &regs[regno];
3645 	struct bpf_insn_access_aux info = {};
3646 	bool valid;
3647 
3648 	if (reg->smin_value < 0) {
3649 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3650 			regno);
3651 		return -EACCES;
3652 	}
3653 
3654 	switch (reg->type) {
3655 	case PTR_TO_SOCK_COMMON:
3656 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3657 		break;
3658 	case PTR_TO_SOCKET:
3659 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3660 		break;
3661 	case PTR_TO_TCP_SOCK:
3662 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3663 		break;
3664 	case PTR_TO_XDP_SOCK:
3665 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3666 		break;
3667 	default:
3668 		valid = false;
3669 	}
3670 
3671 
3672 	if (valid) {
3673 		env->insn_aux_data[insn_idx].ctx_field_size =
3674 			info.ctx_field_size;
3675 		return 0;
3676 	}
3677 
3678 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3679 		regno, reg_type_str(env, reg->type), off, size);
3680 
3681 	return -EACCES;
3682 }
3683 
3684 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3685 {
3686 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3687 }
3688 
3689 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3690 {
3691 	const struct bpf_reg_state *reg = reg_state(env, regno);
3692 
3693 	return reg->type == PTR_TO_CTX;
3694 }
3695 
3696 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3697 {
3698 	const struct bpf_reg_state *reg = reg_state(env, regno);
3699 
3700 	return type_is_sk_pointer(reg->type);
3701 }
3702 
3703 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3704 {
3705 	const struct bpf_reg_state *reg = reg_state(env, regno);
3706 
3707 	return type_is_pkt_pointer(reg->type);
3708 }
3709 
3710 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3711 {
3712 	const struct bpf_reg_state *reg = reg_state(env, regno);
3713 
3714 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3715 	return reg->type == PTR_TO_FLOW_KEYS;
3716 }
3717 
3718 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3719 				   const struct bpf_reg_state *reg,
3720 				   int off, int size, bool strict)
3721 {
3722 	struct tnum reg_off;
3723 	int ip_align;
3724 
3725 	/* Byte size accesses are always allowed. */
3726 	if (!strict || size == 1)
3727 		return 0;
3728 
3729 	/* For platforms that do not have a Kconfig enabling
3730 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3731 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3732 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3733 	 * to this code only in strict mode where we want to emulate
3734 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3735 	 * unconditional IP align value of '2'.
3736 	 */
3737 	ip_align = 2;
3738 
3739 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3740 	if (!tnum_is_aligned(reg_off, size)) {
3741 		char tn_buf[48];
3742 
3743 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3744 		verbose(env,
3745 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3746 			ip_align, tn_buf, reg->off, off, size);
3747 		return -EACCES;
3748 	}
3749 
3750 	return 0;
3751 }
3752 
3753 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3754 				       const struct bpf_reg_state *reg,
3755 				       const char *pointer_desc,
3756 				       int off, int size, bool strict)
3757 {
3758 	struct tnum reg_off;
3759 
3760 	/* Byte size accesses are always allowed. */
3761 	if (!strict || size == 1)
3762 		return 0;
3763 
3764 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3765 	if (!tnum_is_aligned(reg_off, size)) {
3766 		char tn_buf[48];
3767 
3768 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3769 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3770 			pointer_desc, tn_buf, reg->off, off, size);
3771 		return -EACCES;
3772 	}
3773 
3774 	return 0;
3775 }
3776 
3777 static int check_ptr_alignment(struct bpf_verifier_env *env,
3778 			       const struct bpf_reg_state *reg, int off,
3779 			       int size, bool strict_alignment_once)
3780 {
3781 	bool strict = env->strict_alignment || strict_alignment_once;
3782 	const char *pointer_desc = "";
3783 
3784 	switch (reg->type) {
3785 	case PTR_TO_PACKET:
3786 	case PTR_TO_PACKET_META:
3787 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3788 		 * right in front, treat it the very same way.
3789 		 */
3790 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3791 	case PTR_TO_FLOW_KEYS:
3792 		pointer_desc = "flow keys ";
3793 		break;
3794 	case PTR_TO_MAP_KEY:
3795 		pointer_desc = "key ";
3796 		break;
3797 	case PTR_TO_MAP_VALUE:
3798 		pointer_desc = "value ";
3799 		break;
3800 	case PTR_TO_CTX:
3801 		pointer_desc = "context ";
3802 		break;
3803 	case PTR_TO_STACK:
3804 		pointer_desc = "stack ";
3805 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3806 		 * and check_stack_read_fixed_off() relies on stack accesses being
3807 		 * aligned.
3808 		 */
3809 		strict = true;
3810 		break;
3811 	case PTR_TO_SOCKET:
3812 		pointer_desc = "sock ";
3813 		break;
3814 	case PTR_TO_SOCK_COMMON:
3815 		pointer_desc = "sock_common ";
3816 		break;
3817 	case PTR_TO_TCP_SOCK:
3818 		pointer_desc = "tcp_sock ";
3819 		break;
3820 	case PTR_TO_XDP_SOCK:
3821 		pointer_desc = "xdp_sock ";
3822 		break;
3823 	default:
3824 		break;
3825 	}
3826 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3827 					   strict);
3828 }
3829 
3830 static int update_stack_depth(struct bpf_verifier_env *env,
3831 			      const struct bpf_func_state *func,
3832 			      int off)
3833 {
3834 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3835 
3836 	if (stack >= -off)
3837 		return 0;
3838 
3839 	/* update known max for given subprogram */
3840 	env->subprog_info[func->subprogno].stack_depth = -off;
3841 	return 0;
3842 }
3843 
3844 /* starting from main bpf function walk all instructions of the function
3845  * and recursively walk all callees that given function can call.
3846  * Ignore jump and exit insns.
3847  * Since recursion is prevented by check_cfg() this algorithm
3848  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3849  */
3850 static int check_max_stack_depth(struct bpf_verifier_env *env)
3851 {
3852 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3853 	struct bpf_subprog_info *subprog = env->subprog_info;
3854 	struct bpf_insn *insn = env->prog->insnsi;
3855 	bool tail_call_reachable = false;
3856 	int ret_insn[MAX_CALL_FRAMES];
3857 	int ret_prog[MAX_CALL_FRAMES];
3858 	int j;
3859 
3860 process_func:
3861 	/* protect against potential stack overflow that might happen when
3862 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3863 	 * depth for such case down to 256 so that the worst case scenario
3864 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3865 	 * 8k).
3866 	 *
3867 	 * To get the idea what might happen, see an example:
3868 	 * func1 -> sub rsp, 128
3869 	 *  subfunc1 -> sub rsp, 256
3870 	 *  tailcall1 -> add rsp, 256
3871 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3872 	 *   subfunc2 -> sub rsp, 64
3873 	 *   subfunc22 -> sub rsp, 128
3874 	 *   tailcall2 -> add rsp, 128
3875 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3876 	 *
3877 	 * tailcall will unwind the current stack frame but it will not get rid
3878 	 * of caller's stack as shown on the example above.
3879 	 */
3880 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3881 		verbose(env,
3882 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3883 			depth);
3884 		return -EACCES;
3885 	}
3886 	/* round up to 32-bytes, since this is granularity
3887 	 * of interpreter stack size
3888 	 */
3889 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3890 	if (depth > MAX_BPF_STACK) {
3891 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3892 			frame + 1, depth);
3893 		return -EACCES;
3894 	}
3895 continue_func:
3896 	subprog_end = subprog[idx + 1].start;
3897 	for (; i < subprog_end; i++) {
3898 		int next_insn;
3899 
3900 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3901 			continue;
3902 		/* remember insn and function to return to */
3903 		ret_insn[frame] = i + 1;
3904 		ret_prog[frame] = idx;
3905 
3906 		/* find the callee */
3907 		next_insn = i + insn[i].imm + 1;
3908 		idx = find_subprog(env, next_insn);
3909 		if (idx < 0) {
3910 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3911 				  next_insn);
3912 			return -EFAULT;
3913 		}
3914 		if (subprog[idx].is_async_cb) {
3915 			if (subprog[idx].has_tail_call) {
3916 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3917 				return -EFAULT;
3918 			}
3919 			 /* async callbacks don't increase bpf prog stack size */
3920 			continue;
3921 		}
3922 		i = next_insn;
3923 
3924 		if (subprog[idx].has_tail_call)
3925 			tail_call_reachable = true;
3926 
3927 		frame++;
3928 		if (frame >= MAX_CALL_FRAMES) {
3929 			verbose(env, "the call stack of %d frames is too deep !\n",
3930 				frame);
3931 			return -E2BIG;
3932 		}
3933 		goto process_func;
3934 	}
3935 	/* if tail call got detected across bpf2bpf calls then mark each of the
3936 	 * currently present subprog frames as tail call reachable subprogs;
3937 	 * this info will be utilized by JIT so that we will be preserving the
3938 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3939 	 */
3940 	if (tail_call_reachable)
3941 		for (j = 0; j < frame; j++)
3942 			subprog[ret_prog[j]].tail_call_reachable = true;
3943 	if (subprog[0].tail_call_reachable)
3944 		env->prog->aux->tail_call_reachable = true;
3945 
3946 	/* end of for() loop means the last insn of the 'subprog'
3947 	 * was reached. Doesn't matter whether it was JA or EXIT
3948 	 */
3949 	if (frame == 0)
3950 		return 0;
3951 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3952 	frame--;
3953 	i = ret_insn[frame];
3954 	idx = ret_prog[frame];
3955 	goto continue_func;
3956 }
3957 
3958 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3959 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3960 				  const struct bpf_insn *insn, int idx)
3961 {
3962 	int start = idx + insn->imm + 1, subprog;
3963 
3964 	subprog = find_subprog(env, start);
3965 	if (subprog < 0) {
3966 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3967 			  start);
3968 		return -EFAULT;
3969 	}
3970 	return env->subprog_info[subprog].stack_depth;
3971 }
3972 #endif
3973 
3974 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3975 			       const struct bpf_reg_state *reg, int regno,
3976 			       bool fixed_off_ok)
3977 {
3978 	/* Access to this pointer-typed register or passing it to a helper
3979 	 * is only allowed in its original, unmodified form.
3980 	 */
3981 
3982 	if (!fixed_off_ok && reg->off) {
3983 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3984 			reg_type_str(env, reg->type), regno, reg->off);
3985 		return -EACCES;
3986 	}
3987 
3988 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3989 		char tn_buf[48];
3990 
3991 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3992 		verbose(env, "variable %s access var_off=%s disallowed\n",
3993 			reg_type_str(env, reg->type), tn_buf);
3994 		return -EACCES;
3995 	}
3996 
3997 	return 0;
3998 }
3999 
4000 int check_ptr_off_reg(struct bpf_verifier_env *env,
4001 		      const struct bpf_reg_state *reg, int regno)
4002 {
4003 	return __check_ptr_off_reg(env, reg, regno, false);
4004 }
4005 
4006 static int __check_buffer_access(struct bpf_verifier_env *env,
4007 				 const char *buf_info,
4008 				 const struct bpf_reg_state *reg,
4009 				 int regno, int off, int size)
4010 {
4011 	if (off < 0) {
4012 		verbose(env,
4013 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4014 			regno, buf_info, off, size);
4015 		return -EACCES;
4016 	}
4017 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4018 		char tn_buf[48];
4019 
4020 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4021 		verbose(env,
4022 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4023 			regno, off, tn_buf);
4024 		return -EACCES;
4025 	}
4026 
4027 	return 0;
4028 }
4029 
4030 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4031 				  const struct bpf_reg_state *reg,
4032 				  int regno, int off, int size)
4033 {
4034 	int err;
4035 
4036 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4037 	if (err)
4038 		return err;
4039 
4040 	if (off + size > env->prog->aux->max_tp_access)
4041 		env->prog->aux->max_tp_access = off + size;
4042 
4043 	return 0;
4044 }
4045 
4046 static int check_buffer_access(struct bpf_verifier_env *env,
4047 			       const struct bpf_reg_state *reg,
4048 			       int regno, int off, int size,
4049 			       bool zero_size_allowed,
4050 			       const char *buf_info,
4051 			       u32 *max_access)
4052 {
4053 	int err;
4054 
4055 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4056 	if (err)
4057 		return err;
4058 
4059 	if (off + size > *max_access)
4060 		*max_access = off + size;
4061 
4062 	return 0;
4063 }
4064 
4065 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4066 static void zext_32_to_64(struct bpf_reg_state *reg)
4067 {
4068 	reg->var_off = tnum_subreg(reg->var_off);
4069 	__reg_assign_32_into_64(reg);
4070 }
4071 
4072 /* truncate register to smaller size (in bytes)
4073  * must be called with size < BPF_REG_SIZE
4074  */
4075 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4076 {
4077 	u64 mask;
4078 
4079 	/* clear high bits in bit representation */
4080 	reg->var_off = tnum_cast(reg->var_off, size);
4081 
4082 	/* fix arithmetic bounds */
4083 	mask = ((u64)1 << (size * 8)) - 1;
4084 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4085 		reg->umin_value &= mask;
4086 		reg->umax_value &= mask;
4087 	} else {
4088 		reg->umin_value = 0;
4089 		reg->umax_value = mask;
4090 	}
4091 	reg->smin_value = reg->umin_value;
4092 	reg->smax_value = reg->umax_value;
4093 
4094 	/* If size is smaller than 32bit register the 32bit register
4095 	 * values are also truncated so we push 64-bit bounds into
4096 	 * 32-bit bounds. Above were truncated < 32-bits already.
4097 	 */
4098 	if (size >= 4)
4099 		return;
4100 	__reg_combine_64_into_32(reg);
4101 }
4102 
4103 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4104 {
4105 	/* A map is considered read-only if the following condition are true:
4106 	 *
4107 	 * 1) BPF program side cannot change any of the map content. The
4108 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4109 	 *    and was set at map creation time.
4110 	 * 2) The map value(s) have been initialized from user space by a
4111 	 *    loader and then "frozen", such that no new map update/delete
4112 	 *    operations from syscall side are possible for the rest of
4113 	 *    the map's lifetime from that point onwards.
4114 	 * 3) Any parallel/pending map update/delete operations from syscall
4115 	 *    side have been completed. Only after that point, it's safe to
4116 	 *    assume that map value(s) are immutable.
4117 	 */
4118 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4119 	       READ_ONCE(map->frozen) &&
4120 	       !bpf_map_write_active(map);
4121 }
4122 
4123 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4124 {
4125 	void *ptr;
4126 	u64 addr;
4127 	int err;
4128 
4129 	err = map->ops->map_direct_value_addr(map, &addr, off);
4130 	if (err)
4131 		return err;
4132 	ptr = (void *)(long)addr + off;
4133 
4134 	switch (size) {
4135 	case sizeof(u8):
4136 		*val = (u64)*(u8 *)ptr;
4137 		break;
4138 	case sizeof(u16):
4139 		*val = (u64)*(u16 *)ptr;
4140 		break;
4141 	case sizeof(u32):
4142 		*val = (u64)*(u32 *)ptr;
4143 		break;
4144 	case sizeof(u64):
4145 		*val = *(u64 *)ptr;
4146 		break;
4147 	default:
4148 		return -EINVAL;
4149 	}
4150 	return 0;
4151 }
4152 
4153 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4154 				   struct bpf_reg_state *regs,
4155 				   int regno, int off, int size,
4156 				   enum bpf_access_type atype,
4157 				   int value_regno)
4158 {
4159 	struct bpf_reg_state *reg = regs + regno;
4160 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4161 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4162 	u32 btf_id;
4163 	int ret;
4164 
4165 	if (off < 0) {
4166 		verbose(env,
4167 			"R%d is ptr_%s invalid negative access: off=%d\n",
4168 			regno, tname, off);
4169 		return -EACCES;
4170 	}
4171 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4172 		char tn_buf[48];
4173 
4174 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4175 		verbose(env,
4176 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4177 			regno, tname, off, tn_buf);
4178 		return -EACCES;
4179 	}
4180 
4181 	if (env->ops->btf_struct_access) {
4182 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4183 						  off, size, atype, &btf_id);
4184 	} else {
4185 		if (atype != BPF_READ) {
4186 			verbose(env, "only read is supported\n");
4187 			return -EACCES;
4188 		}
4189 
4190 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4191 					atype, &btf_id);
4192 	}
4193 
4194 	if (ret < 0)
4195 		return ret;
4196 
4197 	if (atype == BPF_READ && value_regno >= 0)
4198 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4199 
4200 	return 0;
4201 }
4202 
4203 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4204 				   struct bpf_reg_state *regs,
4205 				   int regno, int off, int size,
4206 				   enum bpf_access_type atype,
4207 				   int value_regno)
4208 {
4209 	struct bpf_reg_state *reg = regs + regno;
4210 	struct bpf_map *map = reg->map_ptr;
4211 	const struct btf_type *t;
4212 	const char *tname;
4213 	u32 btf_id;
4214 	int ret;
4215 
4216 	if (!btf_vmlinux) {
4217 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4218 		return -ENOTSUPP;
4219 	}
4220 
4221 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4222 		verbose(env, "map_ptr access not supported for map type %d\n",
4223 			map->map_type);
4224 		return -ENOTSUPP;
4225 	}
4226 
4227 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4228 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4229 
4230 	if (!env->allow_ptr_to_map_access) {
4231 		verbose(env,
4232 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4233 			tname);
4234 		return -EPERM;
4235 	}
4236 
4237 	if (off < 0) {
4238 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4239 			regno, tname, off);
4240 		return -EACCES;
4241 	}
4242 
4243 	if (atype != BPF_READ) {
4244 		verbose(env, "only read from %s is supported\n", tname);
4245 		return -EACCES;
4246 	}
4247 
4248 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4249 	if (ret < 0)
4250 		return ret;
4251 
4252 	if (value_regno >= 0)
4253 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4254 
4255 	return 0;
4256 }
4257 
4258 /* Check that the stack access at the given offset is within bounds. The
4259  * maximum valid offset is -1.
4260  *
4261  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4262  * -state->allocated_stack for reads.
4263  */
4264 static int check_stack_slot_within_bounds(int off,
4265 					  struct bpf_func_state *state,
4266 					  enum bpf_access_type t)
4267 {
4268 	int min_valid_off;
4269 
4270 	if (t == BPF_WRITE)
4271 		min_valid_off = -MAX_BPF_STACK;
4272 	else
4273 		min_valid_off = -state->allocated_stack;
4274 
4275 	if (off < min_valid_off || off > -1)
4276 		return -EACCES;
4277 	return 0;
4278 }
4279 
4280 /* Check that the stack access at 'regno + off' falls within the maximum stack
4281  * bounds.
4282  *
4283  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4284  */
4285 static int check_stack_access_within_bounds(
4286 		struct bpf_verifier_env *env,
4287 		int regno, int off, int access_size,
4288 		enum stack_access_src src, enum bpf_access_type type)
4289 {
4290 	struct bpf_reg_state *regs = cur_regs(env);
4291 	struct bpf_reg_state *reg = regs + regno;
4292 	struct bpf_func_state *state = func(env, reg);
4293 	int min_off, max_off;
4294 	int err;
4295 	char *err_extra;
4296 
4297 	if (src == ACCESS_HELPER)
4298 		/* We don't know if helpers are reading or writing (or both). */
4299 		err_extra = " indirect access to";
4300 	else if (type == BPF_READ)
4301 		err_extra = " read from";
4302 	else
4303 		err_extra = " write to";
4304 
4305 	if (tnum_is_const(reg->var_off)) {
4306 		min_off = reg->var_off.value + off;
4307 		if (access_size > 0)
4308 			max_off = min_off + access_size - 1;
4309 		else
4310 			max_off = min_off;
4311 	} else {
4312 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4313 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4314 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4315 				err_extra, regno);
4316 			return -EACCES;
4317 		}
4318 		min_off = reg->smin_value + off;
4319 		if (access_size > 0)
4320 			max_off = reg->smax_value + off + access_size - 1;
4321 		else
4322 			max_off = min_off;
4323 	}
4324 
4325 	err = check_stack_slot_within_bounds(min_off, state, type);
4326 	if (!err)
4327 		err = check_stack_slot_within_bounds(max_off, state, type);
4328 
4329 	if (err) {
4330 		if (tnum_is_const(reg->var_off)) {
4331 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4332 				err_extra, regno, off, access_size);
4333 		} else {
4334 			char tn_buf[48];
4335 
4336 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4337 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4338 				err_extra, regno, tn_buf, access_size);
4339 		}
4340 	}
4341 	return err;
4342 }
4343 
4344 /* check whether memory at (regno + off) is accessible for t = (read | write)
4345  * if t==write, value_regno is a register which value is stored into memory
4346  * if t==read, value_regno is a register which will receive the value from memory
4347  * if t==write && value_regno==-1, some unknown value is stored into memory
4348  * if t==read && value_regno==-1, don't care what we read from memory
4349  */
4350 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4351 			    int off, int bpf_size, enum bpf_access_type t,
4352 			    int value_regno, bool strict_alignment_once)
4353 {
4354 	struct bpf_reg_state *regs = cur_regs(env);
4355 	struct bpf_reg_state *reg = regs + regno;
4356 	struct bpf_func_state *state;
4357 	int size, err = 0;
4358 
4359 	size = bpf_size_to_bytes(bpf_size);
4360 	if (size < 0)
4361 		return size;
4362 
4363 	/* alignment checks will add in reg->off themselves */
4364 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4365 	if (err)
4366 		return err;
4367 
4368 	/* for access checks, reg->off is just part of off */
4369 	off += reg->off;
4370 
4371 	if (reg->type == PTR_TO_MAP_KEY) {
4372 		if (t == BPF_WRITE) {
4373 			verbose(env, "write to change key R%d not allowed\n", regno);
4374 			return -EACCES;
4375 		}
4376 
4377 		err = check_mem_region_access(env, regno, off, size,
4378 					      reg->map_ptr->key_size, false);
4379 		if (err)
4380 			return err;
4381 		if (value_regno >= 0)
4382 			mark_reg_unknown(env, regs, value_regno);
4383 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4384 		if (t == BPF_WRITE && value_regno >= 0 &&
4385 		    is_pointer_value(env, value_regno)) {
4386 			verbose(env, "R%d leaks addr into map\n", value_regno);
4387 			return -EACCES;
4388 		}
4389 		err = check_map_access_type(env, regno, off, size, t);
4390 		if (err)
4391 			return err;
4392 		err = check_map_access(env, regno, off, size, false);
4393 		if (!err && t == BPF_READ && value_regno >= 0) {
4394 			struct bpf_map *map = reg->map_ptr;
4395 
4396 			/* if map is read-only, track its contents as scalars */
4397 			if (tnum_is_const(reg->var_off) &&
4398 			    bpf_map_is_rdonly(map) &&
4399 			    map->ops->map_direct_value_addr) {
4400 				int map_off = off + reg->var_off.value;
4401 				u64 val = 0;
4402 
4403 				err = bpf_map_direct_read(map, map_off, size,
4404 							  &val);
4405 				if (err)
4406 					return err;
4407 
4408 				regs[value_regno].type = SCALAR_VALUE;
4409 				__mark_reg_known(&regs[value_regno], val);
4410 			} else {
4411 				mark_reg_unknown(env, regs, value_regno);
4412 			}
4413 		}
4414 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4415 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4416 
4417 		if (type_may_be_null(reg->type)) {
4418 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4419 				reg_type_str(env, reg->type));
4420 			return -EACCES;
4421 		}
4422 
4423 		if (t == BPF_WRITE && rdonly_mem) {
4424 			verbose(env, "R%d cannot write into %s\n",
4425 				regno, reg_type_str(env, reg->type));
4426 			return -EACCES;
4427 		}
4428 
4429 		if (t == BPF_WRITE && value_regno >= 0 &&
4430 		    is_pointer_value(env, value_regno)) {
4431 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4432 			return -EACCES;
4433 		}
4434 
4435 		err = check_mem_region_access(env, regno, off, size,
4436 					      reg->mem_size, false);
4437 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4438 			mark_reg_unknown(env, regs, value_regno);
4439 	} else if (reg->type == PTR_TO_CTX) {
4440 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4441 		struct btf *btf = NULL;
4442 		u32 btf_id = 0;
4443 
4444 		if (t == BPF_WRITE && value_regno >= 0 &&
4445 		    is_pointer_value(env, value_regno)) {
4446 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4447 			return -EACCES;
4448 		}
4449 
4450 		err = check_ptr_off_reg(env, reg, regno);
4451 		if (err < 0)
4452 			return err;
4453 
4454 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4455 		if (err)
4456 			verbose_linfo(env, insn_idx, "; ");
4457 		if (!err && t == BPF_READ && value_regno >= 0) {
4458 			/* ctx access returns either a scalar, or a
4459 			 * PTR_TO_PACKET[_META,_END]. In the latter
4460 			 * case, we know the offset is zero.
4461 			 */
4462 			if (reg_type == SCALAR_VALUE) {
4463 				mark_reg_unknown(env, regs, value_regno);
4464 			} else {
4465 				mark_reg_known_zero(env, regs,
4466 						    value_regno);
4467 				if (type_may_be_null(reg_type))
4468 					regs[value_regno].id = ++env->id_gen;
4469 				/* A load of ctx field could have different
4470 				 * actual load size with the one encoded in the
4471 				 * insn. When the dst is PTR, it is for sure not
4472 				 * a sub-register.
4473 				 */
4474 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4475 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4476 					regs[value_regno].btf = btf;
4477 					regs[value_regno].btf_id = btf_id;
4478 				}
4479 			}
4480 			regs[value_regno].type = reg_type;
4481 		}
4482 
4483 	} else if (reg->type == PTR_TO_STACK) {
4484 		/* Basic bounds checks. */
4485 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4486 		if (err)
4487 			return err;
4488 
4489 		state = func(env, reg);
4490 		err = update_stack_depth(env, state, off);
4491 		if (err)
4492 			return err;
4493 
4494 		if (t == BPF_READ)
4495 			err = check_stack_read(env, regno, off, size,
4496 					       value_regno);
4497 		else
4498 			err = check_stack_write(env, regno, off, size,
4499 						value_regno, insn_idx);
4500 	} else if (reg_is_pkt_pointer(reg)) {
4501 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4502 			verbose(env, "cannot write into packet\n");
4503 			return -EACCES;
4504 		}
4505 		if (t == BPF_WRITE && value_regno >= 0 &&
4506 		    is_pointer_value(env, value_regno)) {
4507 			verbose(env, "R%d leaks addr into packet\n",
4508 				value_regno);
4509 			return -EACCES;
4510 		}
4511 		err = check_packet_access(env, regno, off, size, false);
4512 		if (!err && t == BPF_READ && value_regno >= 0)
4513 			mark_reg_unknown(env, regs, value_regno);
4514 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4515 		if (t == BPF_WRITE && value_regno >= 0 &&
4516 		    is_pointer_value(env, value_regno)) {
4517 			verbose(env, "R%d leaks addr into flow keys\n",
4518 				value_regno);
4519 			return -EACCES;
4520 		}
4521 
4522 		err = check_flow_keys_access(env, off, size);
4523 		if (!err && t == BPF_READ && value_regno >= 0)
4524 			mark_reg_unknown(env, regs, value_regno);
4525 	} else if (type_is_sk_pointer(reg->type)) {
4526 		if (t == BPF_WRITE) {
4527 			verbose(env, "R%d cannot write into %s\n",
4528 				regno, reg_type_str(env, reg->type));
4529 			return -EACCES;
4530 		}
4531 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4532 		if (!err && value_regno >= 0)
4533 			mark_reg_unknown(env, regs, value_regno);
4534 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4535 		err = check_tp_buffer_access(env, reg, regno, off, size);
4536 		if (!err && t == BPF_READ && value_regno >= 0)
4537 			mark_reg_unknown(env, regs, value_regno);
4538 	} else if (reg->type == PTR_TO_BTF_ID) {
4539 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4540 					      value_regno);
4541 	} else if (reg->type == CONST_PTR_TO_MAP) {
4542 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4543 					      value_regno);
4544 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4545 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4546 		const char *buf_info;
4547 		u32 *max_access;
4548 
4549 		if (rdonly_mem) {
4550 			if (t == BPF_WRITE) {
4551 				verbose(env, "R%d cannot write into %s\n",
4552 					regno, reg_type_str(env, reg->type));
4553 				return -EACCES;
4554 			}
4555 			buf_info = "rdonly";
4556 			max_access = &env->prog->aux->max_rdonly_access;
4557 		} else {
4558 			buf_info = "rdwr";
4559 			max_access = &env->prog->aux->max_rdwr_access;
4560 		}
4561 
4562 		err = check_buffer_access(env, reg, regno, off, size, false,
4563 					  buf_info, max_access);
4564 
4565 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4566 			mark_reg_unknown(env, regs, value_regno);
4567 	} else {
4568 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4569 			reg_type_str(env, reg->type));
4570 		return -EACCES;
4571 	}
4572 
4573 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4574 	    regs[value_regno].type == SCALAR_VALUE) {
4575 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4576 		coerce_reg_to_size(&regs[value_regno], size);
4577 	}
4578 	return err;
4579 }
4580 
4581 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4582 {
4583 	int load_reg;
4584 	int err;
4585 
4586 	switch (insn->imm) {
4587 	case BPF_ADD:
4588 	case BPF_ADD | BPF_FETCH:
4589 	case BPF_AND:
4590 	case BPF_AND | BPF_FETCH:
4591 	case BPF_OR:
4592 	case BPF_OR | BPF_FETCH:
4593 	case BPF_XOR:
4594 	case BPF_XOR | BPF_FETCH:
4595 	case BPF_XCHG:
4596 	case BPF_CMPXCHG:
4597 		break;
4598 	default:
4599 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4600 		return -EINVAL;
4601 	}
4602 
4603 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4604 		verbose(env, "invalid atomic operand size\n");
4605 		return -EINVAL;
4606 	}
4607 
4608 	/* check src1 operand */
4609 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4610 	if (err)
4611 		return err;
4612 
4613 	/* check src2 operand */
4614 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4615 	if (err)
4616 		return err;
4617 
4618 	if (insn->imm == BPF_CMPXCHG) {
4619 		/* Check comparison of R0 with memory location */
4620 		const u32 aux_reg = BPF_REG_0;
4621 
4622 		err = check_reg_arg(env, aux_reg, SRC_OP);
4623 		if (err)
4624 			return err;
4625 
4626 		if (is_pointer_value(env, aux_reg)) {
4627 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4628 			return -EACCES;
4629 		}
4630 	}
4631 
4632 	if (is_pointer_value(env, insn->src_reg)) {
4633 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4634 		return -EACCES;
4635 	}
4636 
4637 	if (is_ctx_reg(env, insn->dst_reg) ||
4638 	    is_pkt_reg(env, insn->dst_reg) ||
4639 	    is_flow_key_reg(env, insn->dst_reg) ||
4640 	    is_sk_reg(env, insn->dst_reg)) {
4641 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4642 			insn->dst_reg,
4643 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4644 		return -EACCES;
4645 	}
4646 
4647 	if (insn->imm & BPF_FETCH) {
4648 		if (insn->imm == BPF_CMPXCHG)
4649 			load_reg = BPF_REG_0;
4650 		else
4651 			load_reg = insn->src_reg;
4652 
4653 		/* check and record load of old value */
4654 		err = check_reg_arg(env, load_reg, DST_OP);
4655 		if (err)
4656 			return err;
4657 	} else {
4658 		/* This instruction accesses a memory location but doesn't
4659 		 * actually load it into a register.
4660 		 */
4661 		load_reg = -1;
4662 	}
4663 
4664 	/* Check whether we can read the memory, with second call for fetch
4665 	 * case to simulate the register fill.
4666 	 */
4667 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4668 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4669 	if (!err && load_reg >= 0)
4670 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4671 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
4672 				       true);
4673 	if (err)
4674 		return err;
4675 
4676 	/* Check whether we can write into the same memory. */
4677 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4678 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4679 	if (err)
4680 		return err;
4681 
4682 	return 0;
4683 }
4684 
4685 /* When register 'regno' is used to read the stack (either directly or through
4686  * a helper function) make sure that it's within stack boundary and, depending
4687  * on the access type, that all elements of the stack are initialized.
4688  *
4689  * 'off' includes 'regno->off', but not its dynamic part (if any).
4690  *
4691  * All registers that have been spilled on the stack in the slots within the
4692  * read offsets are marked as read.
4693  */
4694 static int check_stack_range_initialized(
4695 		struct bpf_verifier_env *env, int regno, int off,
4696 		int access_size, bool zero_size_allowed,
4697 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4698 {
4699 	struct bpf_reg_state *reg = reg_state(env, regno);
4700 	struct bpf_func_state *state = func(env, reg);
4701 	int err, min_off, max_off, i, j, slot, spi;
4702 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4703 	enum bpf_access_type bounds_check_type;
4704 	/* Some accesses can write anything into the stack, others are
4705 	 * read-only.
4706 	 */
4707 	bool clobber = false;
4708 
4709 	if (access_size == 0 && !zero_size_allowed) {
4710 		verbose(env, "invalid zero-sized read\n");
4711 		return -EACCES;
4712 	}
4713 
4714 	if (type == ACCESS_HELPER) {
4715 		/* The bounds checks for writes are more permissive than for
4716 		 * reads. However, if raw_mode is not set, we'll do extra
4717 		 * checks below.
4718 		 */
4719 		bounds_check_type = BPF_WRITE;
4720 		clobber = true;
4721 	} else {
4722 		bounds_check_type = BPF_READ;
4723 	}
4724 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4725 					       type, bounds_check_type);
4726 	if (err)
4727 		return err;
4728 
4729 
4730 	if (tnum_is_const(reg->var_off)) {
4731 		min_off = max_off = reg->var_off.value + off;
4732 	} else {
4733 		/* Variable offset is prohibited for unprivileged mode for
4734 		 * simplicity since it requires corresponding support in
4735 		 * Spectre masking for stack ALU.
4736 		 * See also retrieve_ptr_limit().
4737 		 */
4738 		if (!env->bypass_spec_v1) {
4739 			char tn_buf[48];
4740 
4741 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4742 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4743 				regno, err_extra, tn_buf);
4744 			return -EACCES;
4745 		}
4746 		/* Only initialized buffer on stack is allowed to be accessed
4747 		 * with variable offset. With uninitialized buffer it's hard to
4748 		 * guarantee that whole memory is marked as initialized on
4749 		 * helper return since specific bounds are unknown what may
4750 		 * cause uninitialized stack leaking.
4751 		 */
4752 		if (meta && meta->raw_mode)
4753 			meta = NULL;
4754 
4755 		min_off = reg->smin_value + off;
4756 		max_off = reg->smax_value + off;
4757 	}
4758 
4759 	if (meta && meta->raw_mode) {
4760 		meta->access_size = access_size;
4761 		meta->regno = regno;
4762 		return 0;
4763 	}
4764 
4765 	for (i = min_off; i < max_off + access_size; i++) {
4766 		u8 *stype;
4767 
4768 		slot = -i - 1;
4769 		spi = slot / BPF_REG_SIZE;
4770 		if (state->allocated_stack <= slot)
4771 			goto err;
4772 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4773 		if (*stype == STACK_MISC)
4774 			goto mark;
4775 		if (*stype == STACK_ZERO) {
4776 			if (clobber) {
4777 				/* helper can write anything into the stack */
4778 				*stype = STACK_MISC;
4779 			}
4780 			goto mark;
4781 		}
4782 
4783 		if (is_spilled_reg(&state->stack[spi]) &&
4784 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4785 			goto mark;
4786 
4787 		if (is_spilled_reg(&state->stack[spi]) &&
4788 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4789 		     env->allow_ptr_leaks)) {
4790 			if (clobber) {
4791 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4792 				for (j = 0; j < BPF_REG_SIZE; j++)
4793 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4794 			}
4795 			goto mark;
4796 		}
4797 
4798 err:
4799 		if (tnum_is_const(reg->var_off)) {
4800 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4801 				err_extra, regno, min_off, i - min_off, access_size);
4802 		} else {
4803 			char tn_buf[48];
4804 
4805 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4806 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4807 				err_extra, regno, tn_buf, i - min_off, access_size);
4808 		}
4809 		return -EACCES;
4810 mark:
4811 		/* reading any byte out of 8-byte 'spill_slot' will cause
4812 		 * the whole slot to be marked as 'read'
4813 		 */
4814 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4815 			      state->stack[spi].spilled_ptr.parent,
4816 			      REG_LIVE_READ64);
4817 	}
4818 	return update_stack_depth(env, state, min_off);
4819 }
4820 
4821 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4822 				   int access_size, bool zero_size_allowed,
4823 				   struct bpf_call_arg_meta *meta)
4824 {
4825 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4826 	const char *buf_info;
4827 	u32 *max_access;
4828 
4829 	switch (base_type(reg->type)) {
4830 	case PTR_TO_PACKET:
4831 	case PTR_TO_PACKET_META:
4832 		return check_packet_access(env, regno, reg->off, access_size,
4833 					   zero_size_allowed);
4834 	case PTR_TO_MAP_KEY:
4835 		return check_mem_region_access(env, regno, reg->off, access_size,
4836 					       reg->map_ptr->key_size, false);
4837 	case PTR_TO_MAP_VALUE:
4838 		if (check_map_access_type(env, regno, reg->off, access_size,
4839 					  meta && meta->raw_mode ? BPF_WRITE :
4840 					  BPF_READ))
4841 			return -EACCES;
4842 		return check_map_access(env, regno, reg->off, access_size,
4843 					zero_size_allowed);
4844 	case PTR_TO_MEM:
4845 		return check_mem_region_access(env, regno, reg->off,
4846 					       access_size, reg->mem_size,
4847 					       zero_size_allowed);
4848 	case PTR_TO_BUF:
4849 		if (type_is_rdonly_mem(reg->type)) {
4850 			if (meta && meta->raw_mode)
4851 				return -EACCES;
4852 
4853 			buf_info = "rdonly";
4854 			max_access = &env->prog->aux->max_rdonly_access;
4855 		} else {
4856 			buf_info = "rdwr";
4857 			max_access = &env->prog->aux->max_rdwr_access;
4858 		}
4859 		return check_buffer_access(env, reg, regno, reg->off,
4860 					   access_size, zero_size_allowed,
4861 					   buf_info, max_access);
4862 	case PTR_TO_STACK:
4863 		return check_stack_range_initialized(
4864 				env,
4865 				regno, reg->off, access_size,
4866 				zero_size_allowed, ACCESS_HELPER, meta);
4867 	default: /* scalar_value or invalid ptr */
4868 		/* Allow zero-byte read from NULL, regardless of pointer type */
4869 		if (zero_size_allowed && access_size == 0 &&
4870 		    register_is_null(reg))
4871 			return 0;
4872 
4873 		verbose(env, "R%d type=%s ", regno,
4874 			reg_type_str(env, reg->type));
4875 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4876 		return -EACCES;
4877 	}
4878 }
4879 
4880 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4881 		   u32 regno, u32 mem_size)
4882 {
4883 	if (register_is_null(reg))
4884 		return 0;
4885 
4886 	if (type_may_be_null(reg->type)) {
4887 		/* Assuming that the register contains a value check if the memory
4888 		 * access is safe. Temporarily save and restore the register's state as
4889 		 * the conversion shouldn't be visible to a caller.
4890 		 */
4891 		const struct bpf_reg_state saved_reg = *reg;
4892 		int rv;
4893 
4894 		mark_ptr_not_null_reg(reg);
4895 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4896 		*reg = saved_reg;
4897 		return rv;
4898 	}
4899 
4900 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4901 }
4902 
4903 /* Implementation details:
4904  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4905  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4906  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4907  * value_or_null->value transition, since the verifier only cares about
4908  * the range of access to valid map value pointer and doesn't care about actual
4909  * address of the map element.
4910  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4911  * reg->id > 0 after value_or_null->value transition. By doing so
4912  * two bpf_map_lookups will be considered two different pointers that
4913  * point to different bpf_spin_locks.
4914  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4915  * dead-locks.
4916  * Since only one bpf_spin_lock is allowed the checks are simpler than
4917  * reg_is_refcounted() logic. The verifier needs to remember only
4918  * one spin_lock instead of array of acquired_refs.
4919  * cur_state->active_spin_lock remembers which map value element got locked
4920  * and clears it after bpf_spin_unlock.
4921  */
4922 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4923 			     bool is_lock)
4924 {
4925 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4926 	struct bpf_verifier_state *cur = env->cur_state;
4927 	bool is_const = tnum_is_const(reg->var_off);
4928 	struct bpf_map *map = reg->map_ptr;
4929 	u64 val = reg->var_off.value;
4930 
4931 	if (!is_const) {
4932 		verbose(env,
4933 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4934 			regno);
4935 		return -EINVAL;
4936 	}
4937 	if (!map->btf) {
4938 		verbose(env,
4939 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4940 			map->name);
4941 		return -EINVAL;
4942 	}
4943 	if (!map_value_has_spin_lock(map)) {
4944 		if (map->spin_lock_off == -E2BIG)
4945 			verbose(env,
4946 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4947 				map->name);
4948 		else if (map->spin_lock_off == -ENOENT)
4949 			verbose(env,
4950 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4951 				map->name);
4952 		else
4953 			verbose(env,
4954 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4955 				map->name);
4956 		return -EINVAL;
4957 	}
4958 	if (map->spin_lock_off != val + reg->off) {
4959 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4960 			val + reg->off);
4961 		return -EINVAL;
4962 	}
4963 	if (is_lock) {
4964 		if (cur->active_spin_lock) {
4965 			verbose(env,
4966 				"Locking two bpf_spin_locks are not allowed\n");
4967 			return -EINVAL;
4968 		}
4969 		cur->active_spin_lock = reg->id;
4970 	} else {
4971 		if (!cur->active_spin_lock) {
4972 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4973 			return -EINVAL;
4974 		}
4975 		if (cur->active_spin_lock != reg->id) {
4976 			verbose(env, "bpf_spin_unlock of different lock\n");
4977 			return -EINVAL;
4978 		}
4979 		cur->active_spin_lock = 0;
4980 	}
4981 	return 0;
4982 }
4983 
4984 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4985 			      struct bpf_call_arg_meta *meta)
4986 {
4987 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4988 	bool is_const = tnum_is_const(reg->var_off);
4989 	struct bpf_map *map = reg->map_ptr;
4990 	u64 val = reg->var_off.value;
4991 
4992 	if (!is_const) {
4993 		verbose(env,
4994 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4995 			regno);
4996 		return -EINVAL;
4997 	}
4998 	if (!map->btf) {
4999 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5000 			map->name);
5001 		return -EINVAL;
5002 	}
5003 	if (!map_value_has_timer(map)) {
5004 		if (map->timer_off == -E2BIG)
5005 			verbose(env,
5006 				"map '%s' has more than one 'struct bpf_timer'\n",
5007 				map->name);
5008 		else if (map->timer_off == -ENOENT)
5009 			verbose(env,
5010 				"map '%s' doesn't have 'struct bpf_timer'\n",
5011 				map->name);
5012 		else
5013 			verbose(env,
5014 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5015 				map->name);
5016 		return -EINVAL;
5017 	}
5018 	if (map->timer_off != val + reg->off) {
5019 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5020 			val + reg->off, map->timer_off);
5021 		return -EINVAL;
5022 	}
5023 	if (meta->map_ptr) {
5024 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5025 		return -EFAULT;
5026 	}
5027 	meta->map_uid = reg->map_uid;
5028 	meta->map_ptr = map;
5029 	return 0;
5030 }
5031 
5032 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5033 {
5034 	return base_type(type) == ARG_PTR_TO_MEM ||
5035 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
5036 }
5037 
5038 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5039 {
5040 	return type == ARG_CONST_SIZE ||
5041 	       type == ARG_CONST_SIZE_OR_ZERO;
5042 }
5043 
5044 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5045 {
5046 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5047 }
5048 
5049 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5050 {
5051 	return type == ARG_PTR_TO_INT ||
5052 	       type == ARG_PTR_TO_LONG;
5053 }
5054 
5055 static int int_ptr_type_to_size(enum bpf_arg_type type)
5056 {
5057 	if (type == ARG_PTR_TO_INT)
5058 		return sizeof(u32);
5059 	else if (type == ARG_PTR_TO_LONG)
5060 		return sizeof(u64);
5061 
5062 	return -EINVAL;
5063 }
5064 
5065 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5066 				 const struct bpf_call_arg_meta *meta,
5067 				 enum bpf_arg_type *arg_type)
5068 {
5069 	if (!meta->map_ptr) {
5070 		/* kernel subsystem misconfigured verifier */
5071 		verbose(env, "invalid map_ptr to access map->type\n");
5072 		return -EACCES;
5073 	}
5074 
5075 	switch (meta->map_ptr->map_type) {
5076 	case BPF_MAP_TYPE_SOCKMAP:
5077 	case BPF_MAP_TYPE_SOCKHASH:
5078 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5079 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5080 		} else {
5081 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5082 			return -EINVAL;
5083 		}
5084 		break;
5085 	case BPF_MAP_TYPE_BLOOM_FILTER:
5086 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5087 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5088 		break;
5089 	default:
5090 		break;
5091 	}
5092 	return 0;
5093 }
5094 
5095 struct bpf_reg_types {
5096 	const enum bpf_reg_type types[10];
5097 	u32 *btf_id;
5098 };
5099 
5100 static const struct bpf_reg_types map_key_value_types = {
5101 	.types = {
5102 		PTR_TO_STACK,
5103 		PTR_TO_PACKET,
5104 		PTR_TO_PACKET_META,
5105 		PTR_TO_MAP_KEY,
5106 		PTR_TO_MAP_VALUE,
5107 	},
5108 };
5109 
5110 static const struct bpf_reg_types sock_types = {
5111 	.types = {
5112 		PTR_TO_SOCK_COMMON,
5113 		PTR_TO_SOCKET,
5114 		PTR_TO_TCP_SOCK,
5115 		PTR_TO_XDP_SOCK,
5116 	},
5117 };
5118 
5119 #ifdef CONFIG_NET
5120 static const struct bpf_reg_types btf_id_sock_common_types = {
5121 	.types = {
5122 		PTR_TO_SOCK_COMMON,
5123 		PTR_TO_SOCKET,
5124 		PTR_TO_TCP_SOCK,
5125 		PTR_TO_XDP_SOCK,
5126 		PTR_TO_BTF_ID,
5127 	},
5128 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5129 };
5130 #endif
5131 
5132 static const struct bpf_reg_types mem_types = {
5133 	.types = {
5134 		PTR_TO_STACK,
5135 		PTR_TO_PACKET,
5136 		PTR_TO_PACKET_META,
5137 		PTR_TO_MAP_KEY,
5138 		PTR_TO_MAP_VALUE,
5139 		PTR_TO_MEM,
5140 		PTR_TO_MEM | MEM_ALLOC,
5141 		PTR_TO_BUF,
5142 	},
5143 };
5144 
5145 static const struct bpf_reg_types int_ptr_types = {
5146 	.types = {
5147 		PTR_TO_STACK,
5148 		PTR_TO_PACKET,
5149 		PTR_TO_PACKET_META,
5150 		PTR_TO_MAP_KEY,
5151 		PTR_TO_MAP_VALUE,
5152 	},
5153 };
5154 
5155 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5156 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5157 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5158 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5159 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5160 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5161 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5162 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5163 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5164 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5165 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5166 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5167 
5168 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5169 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5170 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5171 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5172 	[ARG_CONST_SIZE]		= &scalar_types,
5173 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5174 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5175 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5176 	[ARG_PTR_TO_CTX]		= &context_types,
5177 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5178 #ifdef CONFIG_NET
5179 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5180 #endif
5181 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5182 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5183 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5184 	[ARG_PTR_TO_MEM]		= &mem_types,
5185 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5186 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5187 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5188 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5189 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5190 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5191 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5192 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5193 	[ARG_PTR_TO_TIMER]		= &timer_types,
5194 };
5195 
5196 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5197 			  enum bpf_arg_type arg_type,
5198 			  const u32 *arg_btf_id)
5199 {
5200 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5201 	enum bpf_reg_type expected, type = reg->type;
5202 	const struct bpf_reg_types *compatible;
5203 	int i, j;
5204 
5205 	compatible = compatible_reg_types[base_type(arg_type)];
5206 	if (!compatible) {
5207 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5208 		return -EFAULT;
5209 	}
5210 
5211 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5212 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5213 	 *
5214 	 * Same for MAYBE_NULL:
5215 	 *
5216 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5217 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5218 	 *
5219 	 * Therefore we fold these flags depending on the arg_type before comparison.
5220 	 */
5221 	if (arg_type & MEM_RDONLY)
5222 		type &= ~MEM_RDONLY;
5223 	if (arg_type & PTR_MAYBE_NULL)
5224 		type &= ~PTR_MAYBE_NULL;
5225 
5226 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5227 		expected = compatible->types[i];
5228 		if (expected == NOT_INIT)
5229 			break;
5230 
5231 		if (type == expected)
5232 			goto found;
5233 	}
5234 
5235 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5236 	for (j = 0; j + 1 < i; j++)
5237 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5238 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5239 	return -EACCES;
5240 
5241 found:
5242 	if (reg->type == PTR_TO_BTF_ID) {
5243 		if (!arg_btf_id) {
5244 			if (!compatible->btf_id) {
5245 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5246 				return -EFAULT;
5247 			}
5248 			arg_btf_id = compatible->btf_id;
5249 		}
5250 
5251 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5252 					  btf_vmlinux, *arg_btf_id)) {
5253 			verbose(env, "R%d is of type %s but %s is expected\n",
5254 				regno, kernel_type_name(reg->btf, reg->btf_id),
5255 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5256 			return -EACCES;
5257 		}
5258 	}
5259 
5260 	return 0;
5261 }
5262 
5263 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5264 			  struct bpf_call_arg_meta *meta,
5265 			  const struct bpf_func_proto *fn)
5266 {
5267 	u32 regno = BPF_REG_1 + arg;
5268 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5269 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5270 	enum bpf_reg_type type = reg->type;
5271 	int err = 0;
5272 
5273 	if (arg_type == ARG_DONTCARE)
5274 		return 0;
5275 
5276 	err = check_reg_arg(env, regno, SRC_OP);
5277 	if (err)
5278 		return err;
5279 
5280 	if (arg_type == ARG_ANYTHING) {
5281 		if (is_pointer_value(env, regno)) {
5282 			verbose(env, "R%d leaks addr into helper function\n",
5283 				regno);
5284 			return -EACCES;
5285 		}
5286 		return 0;
5287 	}
5288 
5289 	if (type_is_pkt_pointer(type) &&
5290 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5291 		verbose(env, "helper access to the packet is not allowed\n");
5292 		return -EACCES;
5293 	}
5294 
5295 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5296 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5297 		err = resolve_map_arg_type(env, meta, &arg_type);
5298 		if (err)
5299 			return err;
5300 	}
5301 
5302 	if (register_is_null(reg) && type_may_be_null(arg_type))
5303 		/* A NULL register has a SCALAR_VALUE type, so skip
5304 		 * type checking.
5305 		 */
5306 		goto skip_type_check;
5307 
5308 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5309 	if (err)
5310 		return err;
5311 
5312 	switch ((u32)type) {
5313 	case SCALAR_VALUE:
5314 	/* Pointer types where reg offset is explicitly allowed: */
5315 	case PTR_TO_PACKET:
5316 	case PTR_TO_PACKET_META:
5317 	case PTR_TO_MAP_KEY:
5318 	case PTR_TO_MAP_VALUE:
5319 	case PTR_TO_MEM:
5320 	case PTR_TO_MEM | MEM_RDONLY:
5321 	case PTR_TO_MEM | MEM_ALLOC:
5322 	case PTR_TO_BUF:
5323 	case PTR_TO_BUF | MEM_RDONLY:
5324 	case PTR_TO_STACK:
5325 		/* Some of the argument types nevertheless require a
5326 		 * zero register offset.
5327 		 */
5328 		if (arg_type == ARG_PTR_TO_ALLOC_MEM)
5329 			goto force_off_check;
5330 		break;
5331 	/* All the rest must be rejected: */
5332 	default:
5333 force_off_check:
5334 		err = __check_ptr_off_reg(env, reg, regno,
5335 					  type == PTR_TO_BTF_ID);
5336 		if (err < 0)
5337 			return err;
5338 		break;
5339 	}
5340 
5341 skip_type_check:
5342 	if (reg->ref_obj_id) {
5343 		if (meta->ref_obj_id) {
5344 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5345 				regno, reg->ref_obj_id,
5346 				meta->ref_obj_id);
5347 			return -EFAULT;
5348 		}
5349 		meta->ref_obj_id = reg->ref_obj_id;
5350 	}
5351 
5352 	if (arg_type == ARG_CONST_MAP_PTR) {
5353 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5354 		if (meta->map_ptr) {
5355 			/* Use map_uid (which is unique id of inner map) to reject:
5356 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5357 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5358 			 * if (inner_map1 && inner_map2) {
5359 			 *     timer = bpf_map_lookup_elem(inner_map1);
5360 			 *     if (timer)
5361 			 *         // mismatch would have been allowed
5362 			 *         bpf_timer_init(timer, inner_map2);
5363 			 * }
5364 			 *
5365 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5366 			 */
5367 			if (meta->map_ptr != reg->map_ptr ||
5368 			    meta->map_uid != reg->map_uid) {
5369 				verbose(env,
5370 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5371 					meta->map_uid, reg->map_uid);
5372 				return -EINVAL;
5373 			}
5374 		}
5375 		meta->map_ptr = reg->map_ptr;
5376 		meta->map_uid = reg->map_uid;
5377 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5378 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5379 		 * check that [key, key + map->key_size) are within
5380 		 * stack limits and initialized
5381 		 */
5382 		if (!meta->map_ptr) {
5383 			/* in function declaration map_ptr must come before
5384 			 * map_key, so that it's verified and known before
5385 			 * we have to check map_key here. Otherwise it means
5386 			 * that kernel subsystem misconfigured verifier
5387 			 */
5388 			verbose(env, "invalid map_ptr to access map->key\n");
5389 			return -EACCES;
5390 		}
5391 		err = check_helper_mem_access(env, regno,
5392 					      meta->map_ptr->key_size, false,
5393 					      NULL);
5394 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5395 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5396 		if (type_may_be_null(arg_type) && register_is_null(reg))
5397 			return 0;
5398 
5399 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5400 		 * check [value, value + map->value_size) validity
5401 		 */
5402 		if (!meta->map_ptr) {
5403 			/* kernel subsystem misconfigured verifier */
5404 			verbose(env, "invalid map_ptr to access map->value\n");
5405 			return -EACCES;
5406 		}
5407 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5408 		err = check_helper_mem_access(env, regno,
5409 					      meta->map_ptr->value_size, false,
5410 					      meta);
5411 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5412 		if (!reg->btf_id) {
5413 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5414 			return -EACCES;
5415 		}
5416 		meta->ret_btf = reg->btf;
5417 		meta->ret_btf_id = reg->btf_id;
5418 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5419 		if (meta->func_id == BPF_FUNC_spin_lock) {
5420 			if (process_spin_lock(env, regno, true))
5421 				return -EACCES;
5422 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5423 			if (process_spin_lock(env, regno, false))
5424 				return -EACCES;
5425 		} else {
5426 			verbose(env, "verifier internal error\n");
5427 			return -EFAULT;
5428 		}
5429 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5430 		if (process_timer_func(env, regno, meta))
5431 			return -EACCES;
5432 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5433 		meta->subprogno = reg->subprogno;
5434 	} else if (arg_type_is_mem_ptr(arg_type)) {
5435 		/* The access to this pointer is only checked when we hit the
5436 		 * next is_mem_size argument below.
5437 		 */
5438 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5439 	} else if (arg_type_is_mem_size(arg_type)) {
5440 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5441 
5442 		/* This is used to refine r0 return value bounds for helpers
5443 		 * that enforce this value as an upper bound on return values.
5444 		 * See do_refine_retval_range() for helpers that can refine
5445 		 * the return value. C type of helper is u32 so we pull register
5446 		 * bound from umax_value however, if negative verifier errors
5447 		 * out. Only upper bounds can be learned because retval is an
5448 		 * int type and negative retvals are allowed.
5449 		 */
5450 		meta->msize_max_value = reg->umax_value;
5451 
5452 		/* The register is SCALAR_VALUE; the access check
5453 		 * happens using its boundaries.
5454 		 */
5455 		if (!tnum_is_const(reg->var_off))
5456 			/* For unprivileged variable accesses, disable raw
5457 			 * mode so that the program is required to
5458 			 * initialize all the memory that the helper could
5459 			 * just partially fill up.
5460 			 */
5461 			meta = NULL;
5462 
5463 		if (reg->smin_value < 0) {
5464 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5465 				regno);
5466 			return -EACCES;
5467 		}
5468 
5469 		if (reg->umin_value == 0) {
5470 			err = check_helper_mem_access(env, regno - 1, 0,
5471 						      zero_size_allowed,
5472 						      meta);
5473 			if (err)
5474 				return err;
5475 		}
5476 
5477 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5478 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5479 				regno);
5480 			return -EACCES;
5481 		}
5482 		err = check_helper_mem_access(env, regno - 1,
5483 					      reg->umax_value,
5484 					      zero_size_allowed, meta);
5485 		if (!err)
5486 			err = mark_chain_precision(env, regno);
5487 	} else if (arg_type_is_alloc_size(arg_type)) {
5488 		if (!tnum_is_const(reg->var_off)) {
5489 			verbose(env, "R%d is not a known constant'\n",
5490 				regno);
5491 			return -EACCES;
5492 		}
5493 		meta->mem_size = reg->var_off.value;
5494 	} else if (arg_type_is_int_ptr(arg_type)) {
5495 		int size = int_ptr_type_to_size(arg_type);
5496 
5497 		err = check_helper_mem_access(env, regno, size, false, meta);
5498 		if (err)
5499 			return err;
5500 		err = check_ptr_alignment(env, reg, 0, size, true);
5501 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5502 		struct bpf_map *map = reg->map_ptr;
5503 		int map_off;
5504 		u64 map_addr;
5505 		char *str_ptr;
5506 
5507 		if (!bpf_map_is_rdonly(map)) {
5508 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5509 			return -EACCES;
5510 		}
5511 
5512 		if (!tnum_is_const(reg->var_off)) {
5513 			verbose(env, "R%d is not a constant address'\n", regno);
5514 			return -EACCES;
5515 		}
5516 
5517 		if (!map->ops->map_direct_value_addr) {
5518 			verbose(env, "no direct value access support for this map type\n");
5519 			return -EACCES;
5520 		}
5521 
5522 		err = check_map_access(env, regno, reg->off,
5523 				       map->value_size - reg->off, false);
5524 		if (err)
5525 			return err;
5526 
5527 		map_off = reg->off + reg->var_off.value;
5528 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5529 		if (err) {
5530 			verbose(env, "direct value access on string failed\n");
5531 			return err;
5532 		}
5533 
5534 		str_ptr = (char *)(long)(map_addr);
5535 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5536 			verbose(env, "string is not zero-terminated\n");
5537 			return -EINVAL;
5538 		}
5539 	}
5540 
5541 	return err;
5542 }
5543 
5544 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5545 {
5546 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5547 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5548 
5549 	if (func_id != BPF_FUNC_map_update_elem)
5550 		return false;
5551 
5552 	/* It's not possible to get access to a locked struct sock in these
5553 	 * contexts, so updating is safe.
5554 	 */
5555 	switch (type) {
5556 	case BPF_PROG_TYPE_TRACING:
5557 		if (eatype == BPF_TRACE_ITER)
5558 			return true;
5559 		break;
5560 	case BPF_PROG_TYPE_SOCKET_FILTER:
5561 	case BPF_PROG_TYPE_SCHED_CLS:
5562 	case BPF_PROG_TYPE_SCHED_ACT:
5563 	case BPF_PROG_TYPE_XDP:
5564 	case BPF_PROG_TYPE_SK_REUSEPORT:
5565 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5566 	case BPF_PROG_TYPE_SK_LOOKUP:
5567 		return true;
5568 	default:
5569 		break;
5570 	}
5571 
5572 	verbose(env, "cannot update sockmap in this context\n");
5573 	return false;
5574 }
5575 
5576 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5577 {
5578 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5579 }
5580 
5581 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5582 					struct bpf_map *map, int func_id)
5583 {
5584 	if (!map)
5585 		return 0;
5586 
5587 	/* We need a two way check, first is from map perspective ... */
5588 	switch (map->map_type) {
5589 	case BPF_MAP_TYPE_PROG_ARRAY:
5590 		if (func_id != BPF_FUNC_tail_call)
5591 			goto error;
5592 		break;
5593 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5594 		if (func_id != BPF_FUNC_perf_event_read &&
5595 		    func_id != BPF_FUNC_perf_event_output &&
5596 		    func_id != BPF_FUNC_skb_output &&
5597 		    func_id != BPF_FUNC_perf_event_read_value &&
5598 		    func_id != BPF_FUNC_xdp_output)
5599 			goto error;
5600 		break;
5601 	case BPF_MAP_TYPE_RINGBUF:
5602 		if (func_id != BPF_FUNC_ringbuf_output &&
5603 		    func_id != BPF_FUNC_ringbuf_reserve &&
5604 		    func_id != BPF_FUNC_ringbuf_query)
5605 			goto error;
5606 		break;
5607 	case BPF_MAP_TYPE_STACK_TRACE:
5608 		if (func_id != BPF_FUNC_get_stackid)
5609 			goto error;
5610 		break;
5611 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5612 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5613 		    func_id != BPF_FUNC_current_task_under_cgroup)
5614 			goto error;
5615 		break;
5616 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5617 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5618 		if (func_id != BPF_FUNC_get_local_storage)
5619 			goto error;
5620 		break;
5621 	case BPF_MAP_TYPE_DEVMAP:
5622 	case BPF_MAP_TYPE_DEVMAP_HASH:
5623 		if (func_id != BPF_FUNC_redirect_map &&
5624 		    func_id != BPF_FUNC_map_lookup_elem)
5625 			goto error;
5626 		break;
5627 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5628 	 * appear.
5629 	 */
5630 	case BPF_MAP_TYPE_CPUMAP:
5631 		if (func_id != BPF_FUNC_redirect_map)
5632 			goto error;
5633 		break;
5634 	case BPF_MAP_TYPE_XSKMAP:
5635 		if (func_id != BPF_FUNC_redirect_map &&
5636 		    func_id != BPF_FUNC_map_lookup_elem)
5637 			goto error;
5638 		break;
5639 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5640 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5641 		if (func_id != BPF_FUNC_map_lookup_elem)
5642 			goto error;
5643 		break;
5644 	case BPF_MAP_TYPE_SOCKMAP:
5645 		if (func_id != BPF_FUNC_sk_redirect_map &&
5646 		    func_id != BPF_FUNC_sock_map_update &&
5647 		    func_id != BPF_FUNC_map_delete_elem &&
5648 		    func_id != BPF_FUNC_msg_redirect_map &&
5649 		    func_id != BPF_FUNC_sk_select_reuseport &&
5650 		    func_id != BPF_FUNC_map_lookup_elem &&
5651 		    !may_update_sockmap(env, func_id))
5652 			goto error;
5653 		break;
5654 	case BPF_MAP_TYPE_SOCKHASH:
5655 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5656 		    func_id != BPF_FUNC_sock_hash_update &&
5657 		    func_id != BPF_FUNC_map_delete_elem &&
5658 		    func_id != BPF_FUNC_msg_redirect_hash &&
5659 		    func_id != BPF_FUNC_sk_select_reuseport &&
5660 		    func_id != BPF_FUNC_map_lookup_elem &&
5661 		    !may_update_sockmap(env, func_id))
5662 			goto error;
5663 		break;
5664 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5665 		if (func_id != BPF_FUNC_sk_select_reuseport)
5666 			goto error;
5667 		break;
5668 	case BPF_MAP_TYPE_QUEUE:
5669 	case BPF_MAP_TYPE_STACK:
5670 		if (func_id != BPF_FUNC_map_peek_elem &&
5671 		    func_id != BPF_FUNC_map_pop_elem &&
5672 		    func_id != BPF_FUNC_map_push_elem)
5673 			goto error;
5674 		break;
5675 	case BPF_MAP_TYPE_SK_STORAGE:
5676 		if (func_id != BPF_FUNC_sk_storage_get &&
5677 		    func_id != BPF_FUNC_sk_storage_delete)
5678 			goto error;
5679 		break;
5680 	case BPF_MAP_TYPE_INODE_STORAGE:
5681 		if (func_id != BPF_FUNC_inode_storage_get &&
5682 		    func_id != BPF_FUNC_inode_storage_delete)
5683 			goto error;
5684 		break;
5685 	case BPF_MAP_TYPE_TASK_STORAGE:
5686 		if (func_id != BPF_FUNC_task_storage_get &&
5687 		    func_id != BPF_FUNC_task_storage_delete)
5688 			goto error;
5689 		break;
5690 	case BPF_MAP_TYPE_BLOOM_FILTER:
5691 		if (func_id != BPF_FUNC_map_peek_elem &&
5692 		    func_id != BPF_FUNC_map_push_elem)
5693 			goto error;
5694 		break;
5695 	default:
5696 		break;
5697 	}
5698 
5699 	/* ... and second from the function itself. */
5700 	switch (func_id) {
5701 	case BPF_FUNC_tail_call:
5702 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5703 			goto error;
5704 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5705 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5706 			return -EINVAL;
5707 		}
5708 		break;
5709 	case BPF_FUNC_perf_event_read:
5710 	case BPF_FUNC_perf_event_output:
5711 	case BPF_FUNC_perf_event_read_value:
5712 	case BPF_FUNC_skb_output:
5713 	case BPF_FUNC_xdp_output:
5714 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5715 			goto error;
5716 		break;
5717 	case BPF_FUNC_ringbuf_output:
5718 	case BPF_FUNC_ringbuf_reserve:
5719 	case BPF_FUNC_ringbuf_query:
5720 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5721 			goto error;
5722 		break;
5723 	case BPF_FUNC_get_stackid:
5724 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5725 			goto error;
5726 		break;
5727 	case BPF_FUNC_current_task_under_cgroup:
5728 	case BPF_FUNC_skb_under_cgroup:
5729 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5730 			goto error;
5731 		break;
5732 	case BPF_FUNC_redirect_map:
5733 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5734 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5735 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5736 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5737 			goto error;
5738 		break;
5739 	case BPF_FUNC_sk_redirect_map:
5740 	case BPF_FUNC_msg_redirect_map:
5741 	case BPF_FUNC_sock_map_update:
5742 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5743 			goto error;
5744 		break;
5745 	case BPF_FUNC_sk_redirect_hash:
5746 	case BPF_FUNC_msg_redirect_hash:
5747 	case BPF_FUNC_sock_hash_update:
5748 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5749 			goto error;
5750 		break;
5751 	case BPF_FUNC_get_local_storage:
5752 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5753 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5754 			goto error;
5755 		break;
5756 	case BPF_FUNC_sk_select_reuseport:
5757 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5758 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5759 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5760 			goto error;
5761 		break;
5762 	case BPF_FUNC_map_pop_elem:
5763 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5764 		    map->map_type != BPF_MAP_TYPE_STACK)
5765 			goto error;
5766 		break;
5767 	case BPF_FUNC_map_peek_elem:
5768 	case BPF_FUNC_map_push_elem:
5769 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5770 		    map->map_type != BPF_MAP_TYPE_STACK &&
5771 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5772 			goto error;
5773 		break;
5774 	case BPF_FUNC_sk_storage_get:
5775 	case BPF_FUNC_sk_storage_delete:
5776 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5777 			goto error;
5778 		break;
5779 	case BPF_FUNC_inode_storage_get:
5780 	case BPF_FUNC_inode_storage_delete:
5781 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5782 			goto error;
5783 		break;
5784 	case BPF_FUNC_task_storage_get:
5785 	case BPF_FUNC_task_storage_delete:
5786 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5787 			goto error;
5788 		break;
5789 	default:
5790 		break;
5791 	}
5792 
5793 	return 0;
5794 error:
5795 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5796 		map->map_type, func_id_name(func_id), func_id);
5797 	return -EINVAL;
5798 }
5799 
5800 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5801 {
5802 	int count = 0;
5803 
5804 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5805 		count++;
5806 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5807 		count++;
5808 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5809 		count++;
5810 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5811 		count++;
5812 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5813 		count++;
5814 
5815 	/* We only support one arg being in raw mode at the moment,
5816 	 * which is sufficient for the helper functions we have
5817 	 * right now.
5818 	 */
5819 	return count <= 1;
5820 }
5821 
5822 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5823 				    enum bpf_arg_type arg_next)
5824 {
5825 	return (arg_type_is_mem_ptr(arg_curr) &&
5826 	        !arg_type_is_mem_size(arg_next)) ||
5827 	       (!arg_type_is_mem_ptr(arg_curr) &&
5828 		arg_type_is_mem_size(arg_next));
5829 }
5830 
5831 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5832 {
5833 	/* bpf_xxx(..., buf, len) call will access 'len'
5834 	 * bytes from memory 'buf'. Both arg types need
5835 	 * to be paired, so make sure there's no buggy
5836 	 * helper function specification.
5837 	 */
5838 	if (arg_type_is_mem_size(fn->arg1_type) ||
5839 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5840 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5841 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5842 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5843 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5844 		return false;
5845 
5846 	return true;
5847 }
5848 
5849 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5850 {
5851 	int count = 0;
5852 
5853 	if (arg_type_may_be_refcounted(fn->arg1_type))
5854 		count++;
5855 	if (arg_type_may_be_refcounted(fn->arg2_type))
5856 		count++;
5857 	if (arg_type_may_be_refcounted(fn->arg3_type))
5858 		count++;
5859 	if (arg_type_may_be_refcounted(fn->arg4_type))
5860 		count++;
5861 	if (arg_type_may_be_refcounted(fn->arg5_type))
5862 		count++;
5863 
5864 	/* A reference acquiring function cannot acquire
5865 	 * another refcounted ptr.
5866 	 */
5867 	if (may_be_acquire_function(func_id) && count)
5868 		return false;
5869 
5870 	/* We only support one arg being unreferenced at the moment,
5871 	 * which is sufficient for the helper functions we have right now.
5872 	 */
5873 	return count <= 1;
5874 }
5875 
5876 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5877 {
5878 	int i;
5879 
5880 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5881 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5882 			return false;
5883 
5884 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5885 			return false;
5886 	}
5887 
5888 	return true;
5889 }
5890 
5891 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5892 {
5893 	return check_raw_mode_ok(fn) &&
5894 	       check_arg_pair_ok(fn) &&
5895 	       check_btf_id_ok(fn) &&
5896 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5897 }
5898 
5899 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5900  * are now invalid, so turn them into unknown SCALAR_VALUE.
5901  */
5902 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5903 				     struct bpf_func_state *state)
5904 {
5905 	struct bpf_reg_state *regs = state->regs, *reg;
5906 	int i;
5907 
5908 	for (i = 0; i < MAX_BPF_REG; i++)
5909 		if (reg_is_pkt_pointer_any(&regs[i]))
5910 			mark_reg_unknown(env, regs, i);
5911 
5912 	bpf_for_each_spilled_reg(i, state, reg) {
5913 		if (!reg)
5914 			continue;
5915 		if (reg_is_pkt_pointer_any(reg))
5916 			__mark_reg_unknown(env, reg);
5917 	}
5918 }
5919 
5920 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5921 {
5922 	struct bpf_verifier_state *vstate = env->cur_state;
5923 	int i;
5924 
5925 	for (i = 0; i <= vstate->curframe; i++)
5926 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5927 }
5928 
5929 enum {
5930 	AT_PKT_END = -1,
5931 	BEYOND_PKT_END = -2,
5932 };
5933 
5934 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5935 {
5936 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5937 	struct bpf_reg_state *reg = &state->regs[regn];
5938 
5939 	if (reg->type != PTR_TO_PACKET)
5940 		/* PTR_TO_PACKET_META is not supported yet */
5941 		return;
5942 
5943 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5944 	 * How far beyond pkt_end it goes is unknown.
5945 	 * if (!range_open) it's the case of pkt >= pkt_end
5946 	 * if (range_open) it's the case of pkt > pkt_end
5947 	 * hence this pointer is at least 1 byte bigger than pkt_end
5948 	 */
5949 	if (range_open)
5950 		reg->range = BEYOND_PKT_END;
5951 	else
5952 		reg->range = AT_PKT_END;
5953 }
5954 
5955 static void release_reg_references(struct bpf_verifier_env *env,
5956 				   struct bpf_func_state *state,
5957 				   int ref_obj_id)
5958 {
5959 	struct bpf_reg_state *regs = state->regs, *reg;
5960 	int i;
5961 
5962 	for (i = 0; i < MAX_BPF_REG; i++)
5963 		if (regs[i].ref_obj_id == ref_obj_id)
5964 			mark_reg_unknown(env, regs, i);
5965 
5966 	bpf_for_each_spilled_reg(i, state, reg) {
5967 		if (!reg)
5968 			continue;
5969 		if (reg->ref_obj_id == ref_obj_id)
5970 			__mark_reg_unknown(env, reg);
5971 	}
5972 }
5973 
5974 /* The pointer with the specified id has released its reference to kernel
5975  * resources. Identify all copies of the same pointer and clear the reference.
5976  */
5977 static int release_reference(struct bpf_verifier_env *env,
5978 			     int ref_obj_id)
5979 {
5980 	struct bpf_verifier_state *vstate = env->cur_state;
5981 	int err;
5982 	int i;
5983 
5984 	err = release_reference_state(cur_func(env), ref_obj_id);
5985 	if (err)
5986 		return err;
5987 
5988 	for (i = 0; i <= vstate->curframe; i++)
5989 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5990 
5991 	return 0;
5992 }
5993 
5994 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5995 				    struct bpf_reg_state *regs)
5996 {
5997 	int i;
5998 
5999 	/* after the call registers r0 - r5 were scratched */
6000 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6001 		mark_reg_not_init(env, regs, caller_saved[i]);
6002 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6003 	}
6004 }
6005 
6006 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6007 				   struct bpf_func_state *caller,
6008 				   struct bpf_func_state *callee,
6009 				   int insn_idx);
6010 
6011 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6012 			     int *insn_idx, int subprog,
6013 			     set_callee_state_fn set_callee_state_cb)
6014 {
6015 	struct bpf_verifier_state *state = env->cur_state;
6016 	struct bpf_func_info_aux *func_info_aux;
6017 	struct bpf_func_state *caller, *callee;
6018 	int err;
6019 	bool is_global = false;
6020 
6021 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6022 		verbose(env, "the call stack of %d frames is too deep\n",
6023 			state->curframe + 2);
6024 		return -E2BIG;
6025 	}
6026 
6027 	caller = state->frame[state->curframe];
6028 	if (state->frame[state->curframe + 1]) {
6029 		verbose(env, "verifier bug. Frame %d already allocated\n",
6030 			state->curframe + 1);
6031 		return -EFAULT;
6032 	}
6033 
6034 	func_info_aux = env->prog->aux->func_info_aux;
6035 	if (func_info_aux)
6036 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6037 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6038 	if (err == -EFAULT)
6039 		return err;
6040 	if (is_global) {
6041 		if (err) {
6042 			verbose(env, "Caller passes invalid args into func#%d\n",
6043 				subprog);
6044 			return err;
6045 		} else {
6046 			if (env->log.level & BPF_LOG_LEVEL)
6047 				verbose(env,
6048 					"Func#%d is global and valid. Skipping.\n",
6049 					subprog);
6050 			clear_caller_saved_regs(env, caller->regs);
6051 
6052 			/* All global functions return a 64-bit SCALAR_VALUE */
6053 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6054 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6055 
6056 			/* continue with next insn after call */
6057 			return 0;
6058 		}
6059 	}
6060 
6061 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6062 	    insn->src_reg == 0 &&
6063 	    insn->imm == BPF_FUNC_timer_set_callback) {
6064 		struct bpf_verifier_state *async_cb;
6065 
6066 		/* there is no real recursion here. timer callbacks are async */
6067 		env->subprog_info[subprog].is_async_cb = true;
6068 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6069 					 *insn_idx, subprog);
6070 		if (!async_cb)
6071 			return -EFAULT;
6072 		callee = async_cb->frame[0];
6073 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6074 
6075 		/* Convert bpf_timer_set_callback() args into timer callback args */
6076 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6077 		if (err)
6078 			return err;
6079 
6080 		clear_caller_saved_regs(env, caller->regs);
6081 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6082 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6083 		/* continue with next insn after call */
6084 		return 0;
6085 	}
6086 
6087 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6088 	if (!callee)
6089 		return -ENOMEM;
6090 	state->frame[state->curframe + 1] = callee;
6091 
6092 	/* callee cannot access r0, r6 - r9 for reading and has to write
6093 	 * into its own stack before reading from it.
6094 	 * callee can read/write into caller's stack
6095 	 */
6096 	init_func_state(env, callee,
6097 			/* remember the callsite, it will be used by bpf_exit */
6098 			*insn_idx /* callsite */,
6099 			state->curframe + 1 /* frameno within this callchain */,
6100 			subprog /* subprog number within this prog */);
6101 
6102 	/* Transfer references to the callee */
6103 	err = copy_reference_state(callee, caller);
6104 	if (err)
6105 		return err;
6106 
6107 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6108 	if (err)
6109 		return err;
6110 
6111 	clear_caller_saved_regs(env, caller->regs);
6112 
6113 	/* only increment it after check_reg_arg() finished */
6114 	state->curframe++;
6115 
6116 	/* and go analyze first insn of the callee */
6117 	*insn_idx = env->subprog_info[subprog].start - 1;
6118 
6119 	if (env->log.level & BPF_LOG_LEVEL) {
6120 		verbose(env, "caller:\n");
6121 		print_verifier_state(env, caller, true);
6122 		verbose(env, "callee:\n");
6123 		print_verifier_state(env, callee, true);
6124 	}
6125 	return 0;
6126 }
6127 
6128 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6129 				   struct bpf_func_state *caller,
6130 				   struct bpf_func_state *callee)
6131 {
6132 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6133 	 *      void *callback_ctx, u64 flags);
6134 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6135 	 *      void *callback_ctx);
6136 	 */
6137 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6138 
6139 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6140 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6141 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6142 
6143 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6144 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6145 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6146 
6147 	/* pointer to stack or null */
6148 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6149 
6150 	/* unused */
6151 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6152 	return 0;
6153 }
6154 
6155 static int set_callee_state(struct bpf_verifier_env *env,
6156 			    struct bpf_func_state *caller,
6157 			    struct bpf_func_state *callee, int insn_idx)
6158 {
6159 	int i;
6160 
6161 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6162 	 * pointers, which connects us up to the liveness chain
6163 	 */
6164 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6165 		callee->regs[i] = caller->regs[i];
6166 	return 0;
6167 }
6168 
6169 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6170 			   int *insn_idx)
6171 {
6172 	int subprog, target_insn;
6173 
6174 	target_insn = *insn_idx + insn->imm + 1;
6175 	subprog = find_subprog(env, target_insn);
6176 	if (subprog < 0) {
6177 		verbose(env, "verifier bug. No program starts at insn %d\n",
6178 			target_insn);
6179 		return -EFAULT;
6180 	}
6181 
6182 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6183 }
6184 
6185 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6186 				       struct bpf_func_state *caller,
6187 				       struct bpf_func_state *callee,
6188 				       int insn_idx)
6189 {
6190 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6191 	struct bpf_map *map;
6192 	int err;
6193 
6194 	if (bpf_map_ptr_poisoned(insn_aux)) {
6195 		verbose(env, "tail_call abusing map_ptr\n");
6196 		return -EINVAL;
6197 	}
6198 
6199 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6200 	if (!map->ops->map_set_for_each_callback_args ||
6201 	    !map->ops->map_for_each_callback) {
6202 		verbose(env, "callback function not allowed for map\n");
6203 		return -ENOTSUPP;
6204 	}
6205 
6206 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6207 	if (err)
6208 		return err;
6209 
6210 	callee->in_callback_fn = true;
6211 	return 0;
6212 }
6213 
6214 static int set_loop_callback_state(struct bpf_verifier_env *env,
6215 				   struct bpf_func_state *caller,
6216 				   struct bpf_func_state *callee,
6217 				   int insn_idx)
6218 {
6219 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6220 	 *	    u64 flags);
6221 	 * callback_fn(u32 index, void *callback_ctx);
6222 	 */
6223 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6224 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6225 
6226 	/* unused */
6227 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6228 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6229 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6230 
6231 	callee->in_callback_fn = true;
6232 	return 0;
6233 }
6234 
6235 static int set_timer_callback_state(struct bpf_verifier_env *env,
6236 				    struct bpf_func_state *caller,
6237 				    struct bpf_func_state *callee,
6238 				    int insn_idx)
6239 {
6240 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6241 
6242 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6243 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6244 	 */
6245 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6246 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6247 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6248 
6249 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6250 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6251 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6252 
6253 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6254 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6255 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6256 
6257 	/* unused */
6258 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6259 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6260 	callee->in_async_callback_fn = true;
6261 	return 0;
6262 }
6263 
6264 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6265 				       struct bpf_func_state *caller,
6266 				       struct bpf_func_state *callee,
6267 				       int insn_idx)
6268 {
6269 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6270 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6271 	 * (callback_fn)(struct task_struct *task,
6272 	 *               struct vm_area_struct *vma, void *callback_ctx);
6273 	 */
6274 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6275 
6276 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6277 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6278 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6279 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6280 
6281 	/* pointer to stack or null */
6282 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6283 
6284 	/* unused */
6285 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6286 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6287 	callee->in_callback_fn = true;
6288 	return 0;
6289 }
6290 
6291 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6292 {
6293 	struct bpf_verifier_state *state = env->cur_state;
6294 	struct bpf_func_state *caller, *callee;
6295 	struct bpf_reg_state *r0;
6296 	int err;
6297 
6298 	callee = state->frame[state->curframe];
6299 	r0 = &callee->regs[BPF_REG_0];
6300 	if (r0->type == PTR_TO_STACK) {
6301 		/* technically it's ok to return caller's stack pointer
6302 		 * (or caller's caller's pointer) back to the caller,
6303 		 * since these pointers are valid. Only current stack
6304 		 * pointer will be invalid as soon as function exits,
6305 		 * but let's be conservative
6306 		 */
6307 		verbose(env, "cannot return stack pointer to the caller\n");
6308 		return -EINVAL;
6309 	}
6310 
6311 	state->curframe--;
6312 	caller = state->frame[state->curframe];
6313 	if (callee->in_callback_fn) {
6314 		/* enforce R0 return value range [0, 1]. */
6315 		struct tnum range = tnum_range(0, 1);
6316 
6317 		if (r0->type != SCALAR_VALUE) {
6318 			verbose(env, "R0 not a scalar value\n");
6319 			return -EACCES;
6320 		}
6321 		if (!tnum_in(range, r0->var_off)) {
6322 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6323 			return -EINVAL;
6324 		}
6325 	} else {
6326 		/* return to the caller whatever r0 had in the callee */
6327 		caller->regs[BPF_REG_0] = *r0;
6328 	}
6329 
6330 	/* Transfer references to the caller */
6331 	err = copy_reference_state(caller, callee);
6332 	if (err)
6333 		return err;
6334 
6335 	*insn_idx = callee->callsite + 1;
6336 	if (env->log.level & BPF_LOG_LEVEL) {
6337 		verbose(env, "returning from callee:\n");
6338 		print_verifier_state(env, callee, true);
6339 		verbose(env, "to caller at %d:\n", *insn_idx);
6340 		print_verifier_state(env, caller, true);
6341 	}
6342 	/* clear everything in the callee */
6343 	free_func_state(callee);
6344 	state->frame[state->curframe + 1] = NULL;
6345 	return 0;
6346 }
6347 
6348 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6349 				   int func_id,
6350 				   struct bpf_call_arg_meta *meta)
6351 {
6352 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6353 
6354 	if (ret_type != RET_INTEGER ||
6355 	    (func_id != BPF_FUNC_get_stack &&
6356 	     func_id != BPF_FUNC_get_task_stack &&
6357 	     func_id != BPF_FUNC_probe_read_str &&
6358 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6359 	     func_id != BPF_FUNC_probe_read_user_str))
6360 		return;
6361 
6362 	ret_reg->smax_value = meta->msize_max_value;
6363 	ret_reg->s32_max_value = meta->msize_max_value;
6364 	ret_reg->smin_value = -MAX_ERRNO;
6365 	ret_reg->s32_min_value = -MAX_ERRNO;
6366 	__reg_deduce_bounds(ret_reg);
6367 	__reg_bound_offset(ret_reg);
6368 	__update_reg_bounds(ret_reg);
6369 }
6370 
6371 static int
6372 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6373 		int func_id, int insn_idx)
6374 {
6375 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6376 	struct bpf_map *map = meta->map_ptr;
6377 
6378 	if (func_id != BPF_FUNC_tail_call &&
6379 	    func_id != BPF_FUNC_map_lookup_elem &&
6380 	    func_id != BPF_FUNC_map_update_elem &&
6381 	    func_id != BPF_FUNC_map_delete_elem &&
6382 	    func_id != BPF_FUNC_map_push_elem &&
6383 	    func_id != BPF_FUNC_map_pop_elem &&
6384 	    func_id != BPF_FUNC_map_peek_elem &&
6385 	    func_id != BPF_FUNC_for_each_map_elem &&
6386 	    func_id != BPF_FUNC_redirect_map)
6387 		return 0;
6388 
6389 	if (map == NULL) {
6390 		verbose(env, "kernel subsystem misconfigured verifier\n");
6391 		return -EINVAL;
6392 	}
6393 
6394 	/* In case of read-only, some additional restrictions
6395 	 * need to be applied in order to prevent altering the
6396 	 * state of the map from program side.
6397 	 */
6398 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6399 	    (func_id == BPF_FUNC_map_delete_elem ||
6400 	     func_id == BPF_FUNC_map_update_elem ||
6401 	     func_id == BPF_FUNC_map_push_elem ||
6402 	     func_id == BPF_FUNC_map_pop_elem)) {
6403 		verbose(env, "write into map forbidden\n");
6404 		return -EACCES;
6405 	}
6406 
6407 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6408 		bpf_map_ptr_store(aux, meta->map_ptr,
6409 				  !meta->map_ptr->bypass_spec_v1);
6410 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6411 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6412 				  !meta->map_ptr->bypass_spec_v1);
6413 	return 0;
6414 }
6415 
6416 static int
6417 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6418 		int func_id, int insn_idx)
6419 {
6420 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6421 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6422 	struct bpf_map *map = meta->map_ptr;
6423 	struct tnum range;
6424 	u64 val;
6425 	int err;
6426 
6427 	if (func_id != BPF_FUNC_tail_call)
6428 		return 0;
6429 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6430 		verbose(env, "kernel subsystem misconfigured verifier\n");
6431 		return -EINVAL;
6432 	}
6433 
6434 	range = tnum_range(0, map->max_entries - 1);
6435 	reg = &regs[BPF_REG_3];
6436 
6437 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6438 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6439 		return 0;
6440 	}
6441 
6442 	err = mark_chain_precision(env, BPF_REG_3);
6443 	if (err)
6444 		return err;
6445 
6446 	val = reg->var_off.value;
6447 	if (bpf_map_key_unseen(aux))
6448 		bpf_map_key_store(aux, val);
6449 	else if (!bpf_map_key_poisoned(aux) &&
6450 		  bpf_map_key_immediate(aux) != val)
6451 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6452 	return 0;
6453 }
6454 
6455 static int check_reference_leak(struct bpf_verifier_env *env)
6456 {
6457 	struct bpf_func_state *state = cur_func(env);
6458 	int i;
6459 
6460 	for (i = 0; i < state->acquired_refs; i++) {
6461 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6462 			state->refs[i].id, state->refs[i].insn_idx);
6463 	}
6464 	return state->acquired_refs ? -EINVAL : 0;
6465 }
6466 
6467 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6468 				   struct bpf_reg_state *regs)
6469 {
6470 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6471 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6472 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6473 	int err, fmt_map_off, num_args;
6474 	u64 fmt_addr;
6475 	char *fmt;
6476 
6477 	/* data must be an array of u64 */
6478 	if (data_len_reg->var_off.value % 8)
6479 		return -EINVAL;
6480 	num_args = data_len_reg->var_off.value / 8;
6481 
6482 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6483 	 * and map_direct_value_addr is set.
6484 	 */
6485 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6486 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6487 						  fmt_map_off);
6488 	if (err) {
6489 		verbose(env, "verifier bug\n");
6490 		return -EFAULT;
6491 	}
6492 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6493 
6494 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6495 	 * can focus on validating the format specifiers.
6496 	 */
6497 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6498 	if (err < 0)
6499 		verbose(env, "Invalid format string\n");
6500 
6501 	return err;
6502 }
6503 
6504 static int check_get_func_ip(struct bpf_verifier_env *env)
6505 {
6506 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6507 	int func_id = BPF_FUNC_get_func_ip;
6508 
6509 	if (type == BPF_PROG_TYPE_TRACING) {
6510 		if (!bpf_prog_has_trampoline(env->prog)) {
6511 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6512 				func_id_name(func_id), func_id);
6513 			return -ENOTSUPP;
6514 		}
6515 		return 0;
6516 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6517 		return 0;
6518 	}
6519 
6520 	verbose(env, "func %s#%d not supported for program type %d\n",
6521 		func_id_name(func_id), func_id, type);
6522 	return -ENOTSUPP;
6523 }
6524 
6525 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6526 			     int *insn_idx_p)
6527 {
6528 	const struct bpf_func_proto *fn = NULL;
6529 	enum bpf_return_type ret_type;
6530 	enum bpf_type_flag ret_flag;
6531 	struct bpf_reg_state *regs;
6532 	struct bpf_call_arg_meta meta;
6533 	int insn_idx = *insn_idx_p;
6534 	bool changes_data;
6535 	int i, err, func_id;
6536 
6537 	/* find function prototype */
6538 	func_id = insn->imm;
6539 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6540 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6541 			func_id);
6542 		return -EINVAL;
6543 	}
6544 
6545 	if (env->ops->get_func_proto)
6546 		fn = env->ops->get_func_proto(func_id, env->prog);
6547 	if (!fn) {
6548 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6549 			func_id);
6550 		return -EINVAL;
6551 	}
6552 
6553 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6554 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6555 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6556 		return -EINVAL;
6557 	}
6558 
6559 	if (fn->allowed && !fn->allowed(env->prog)) {
6560 		verbose(env, "helper call is not allowed in probe\n");
6561 		return -EINVAL;
6562 	}
6563 
6564 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6565 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6566 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6567 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6568 			func_id_name(func_id), func_id);
6569 		return -EINVAL;
6570 	}
6571 
6572 	memset(&meta, 0, sizeof(meta));
6573 	meta.pkt_access = fn->pkt_access;
6574 
6575 	err = check_func_proto(fn, func_id);
6576 	if (err) {
6577 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6578 			func_id_name(func_id), func_id);
6579 		return err;
6580 	}
6581 
6582 	meta.func_id = func_id;
6583 	/* check args */
6584 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6585 		err = check_func_arg(env, i, &meta, fn);
6586 		if (err)
6587 			return err;
6588 	}
6589 
6590 	err = record_func_map(env, &meta, func_id, insn_idx);
6591 	if (err)
6592 		return err;
6593 
6594 	err = record_func_key(env, &meta, func_id, insn_idx);
6595 	if (err)
6596 		return err;
6597 
6598 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6599 	 * is inferred from register state.
6600 	 */
6601 	for (i = 0; i < meta.access_size; i++) {
6602 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6603 				       BPF_WRITE, -1, false);
6604 		if (err)
6605 			return err;
6606 	}
6607 
6608 	if (is_release_function(func_id)) {
6609 		err = release_reference(env, meta.ref_obj_id);
6610 		if (err) {
6611 			verbose(env, "func %s#%d reference has not been acquired before\n",
6612 				func_id_name(func_id), func_id);
6613 			return err;
6614 		}
6615 	}
6616 
6617 	regs = cur_regs(env);
6618 
6619 	switch (func_id) {
6620 	case BPF_FUNC_tail_call:
6621 		err = check_reference_leak(env);
6622 		if (err) {
6623 			verbose(env, "tail_call would lead to reference leak\n");
6624 			return err;
6625 		}
6626 		break;
6627 	case BPF_FUNC_get_local_storage:
6628 		/* check that flags argument in get_local_storage(map, flags) is 0,
6629 		 * this is required because get_local_storage() can't return an error.
6630 		 */
6631 		if (!register_is_null(&regs[BPF_REG_2])) {
6632 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6633 			return -EINVAL;
6634 		}
6635 		break;
6636 	case BPF_FUNC_for_each_map_elem:
6637 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6638 					set_map_elem_callback_state);
6639 		break;
6640 	case BPF_FUNC_timer_set_callback:
6641 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6642 					set_timer_callback_state);
6643 		break;
6644 	case BPF_FUNC_find_vma:
6645 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6646 					set_find_vma_callback_state);
6647 		break;
6648 	case BPF_FUNC_snprintf:
6649 		err = check_bpf_snprintf_call(env, regs);
6650 		break;
6651 	case BPF_FUNC_loop:
6652 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6653 					set_loop_callback_state);
6654 		break;
6655 	}
6656 
6657 	if (err)
6658 		return err;
6659 
6660 	/* reset caller saved regs */
6661 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6662 		mark_reg_not_init(env, regs, caller_saved[i]);
6663 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6664 	}
6665 
6666 	/* helper call returns 64-bit value. */
6667 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6668 
6669 	/* update return register (already marked as written above) */
6670 	ret_type = fn->ret_type;
6671 	ret_flag = type_flag(fn->ret_type);
6672 	if (ret_type == RET_INTEGER) {
6673 		/* sets type to SCALAR_VALUE */
6674 		mark_reg_unknown(env, regs, BPF_REG_0);
6675 	} else if (ret_type == RET_VOID) {
6676 		regs[BPF_REG_0].type = NOT_INIT;
6677 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6678 		/* There is no offset yet applied, variable or fixed */
6679 		mark_reg_known_zero(env, regs, BPF_REG_0);
6680 		/* remember map_ptr, so that check_map_access()
6681 		 * can check 'value_size' boundary of memory access
6682 		 * to map element returned from bpf_map_lookup_elem()
6683 		 */
6684 		if (meta.map_ptr == NULL) {
6685 			verbose(env,
6686 				"kernel subsystem misconfigured verifier\n");
6687 			return -EINVAL;
6688 		}
6689 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6690 		regs[BPF_REG_0].map_uid = meta.map_uid;
6691 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6692 		if (!type_may_be_null(ret_type) &&
6693 		    map_value_has_spin_lock(meta.map_ptr)) {
6694 			regs[BPF_REG_0].id = ++env->id_gen;
6695 		}
6696 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6697 		mark_reg_known_zero(env, regs, BPF_REG_0);
6698 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6699 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6700 		mark_reg_known_zero(env, regs, BPF_REG_0);
6701 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6702 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6703 		mark_reg_known_zero(env, regs, BPF_REG_0);
6704 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6705 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6706 		mark_reg_known_zero(env, regs, BPF_REG_0);
6707 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6708 		regs[BPF_REG_0].mem_size = meta.mem_size;
6709 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6710 		const struct btf_type *t;
6711 
6712 		mark_reg_known_zero(env, regs, BPF_REG_0);
6713 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6714 		if (!btf_type_is_struct(t)) {
6715 			u32 tsize;
6716 			const struct btf_type *ret;
6717 			const char *tname;
6718 
6719 			/* resolve the type size of ksym. */
6720 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6721 			if (IS_ERR(ret)) {
6722 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6723 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6724 					tname, PTR_ERR(ret));
6725 				return -EINVAL;
6726 			}
6727 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6728 			regs[BPF_REG_0].mem_size = tsize;
6729 		} else {
6730 			/* MEM_RDONLY may be carried from ret_flag, but it
6731 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6732 			 * it will confuse the check of PTR_TO_BTF_ID in
6733 			 * check_mem_access().
6734 			 */
6735 			ret_flag &= ~MEM_RDONLY;
6736 
6737 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6738 			regs[BPF_REG_0].btf = meta.ret_btf;
6739 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6740 		}
6741 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6742 		int ret_btf_id;
6743 
6744 		mark_reg_known_zero(env, regs, BPF_REG_0);
6745 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6746 		ret_btf_id = *fn->ret_btf_id;
6747 		if (ret_btf_id == 0) {
6748 			verbose(env, "invalid return type %u of func %s#%d\n",
6749 				base_type(ret_type), func_id_name(func_id),
6750 				func_id);
6751 			return -EINVAL;
6752 		}
6753 		/* current BPF helper definitions are only coming from
6754 		 * built-in code with type IDs from  vmlinux BTF
6755 		 */
6756 		regs[BPF_REG_0].btf = btf_vmlinux;
6757 		regs[BPF_REG_0].btf_id = ret_btf_id;
6758 	} else {
6759 		verbose(env, "unknown return type %u of func %s#%d\n",
6760 			base_type(ret_type), func_id_name(func_id), func_id);
6761 		return -EINVAL;
6762 	}
6763 
6764 	if (type_may_be_null(regs[BPF_REG_0].type))
6765 		regs[BPF_REG_0].id = ++env->id_gen;
6766 
6767 	if (is_ptr_cast_function(func_id)) {
6768 		/* For release_reference() */
6769 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6770 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6771 		int id = acquire_reference_state(env, insn_idx);
6772 
6773 		if (id < 0)
6774 			return id;
6775 		/* For mark_ptr_or_null_reg() */
6776 		regs[BPF_REG_0].id = id;
6777 		/* For release_reference() */
6778 		regs[BPF_REG_0].ref_obj_id = id;
6779 	}
6780 
6781 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6782 
6783 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6784 	if (err)
6785 		return err;
6786 
6787 	if ((func_id == BPF_FUNC_get_stack ||
6788 	     func_id == BPF_FUNC_get_task_stack) &&
6789 	    !env->prog->has_callchain_buf) {
6790 		const char *err_str;
6791 
6792 #ifdef CONFIG_PERF_EVENTS
6793 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6794 		err_str = "cannot get callchain buffer for func %s#%d\n";
6795 #else
6796 		err = -ENOTSUPP;
6797 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6798 #endif
6799 		if (err) {
6800 			verbose(env, err_str, func_id_name(func_id), func_id);
6801 			return err;
6802 		}
6803 
6804 		env->prog->has_callchain_buf = true;
6805 	}
6806 
6807 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6808 		env->prog->call_get_stack = true;
6809 
6810 	if (func_id == BPF_FUNC_get_func_ip) {
6811 		if (check_get_func_ip(env))
6812 			return -ENOTSUPP;
6813 		env->prog->call_get_func_ip = true;
6814 	}
6815 
6816 	if (changes_data)
6817 		clear_all_pkt_pointers(env);
6818 	return 0;
6819 }
6820 
6821 /* mark_btf_func_reg_size() is used when the reg size is determined by
6822  * the BTF func_proto's return value size and argument.
6823  */
6824 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6825 				   size_t reg_size)
6826 {
6827 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6828 
6829 	if (regno == BPF_REG_0) {
6830 		/* Function return value */
6831 		reg->live |= REG_LIVE_WRITTEN;
6832 		reg->subreg_def = reg_size == sizeof(u64) ?
6833 			DEF_NOT_SUBREG : env->insn_idx + 1;
6834 	} else {
6835 		/* Function argument */
6836 		if (reg_size == sizeof(u64)) {
6837 			mark_insn_zext(env, reg);
6838 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6839 		} else {
6840 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6841 		}
6842 	}
6843 }
6844 
6845 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6846 {
6847 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6848 	struct bpf_reg_state *regs = cur_regs(env);
6849 	const char *func_name, *ptr_type_name;
6850 	u32 i, nargs, func_id, ptr_type_id;
6851 	struct module *btf_mod = NULL;
6852 	const struct btf_param *args;
6853 	struct btf *desc_btf;
6854 	int err;
6855 
6856 	/* skip for now, but return error when we find this in fixup_kfunc_call */
6857 	if (!insn->imm)
6858 		return 0;
6859 
6860 	desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6861 	if (IS_ERR(desc_btf))
6862 		return PTR_ERR(desc_btf);
6863 
6864 	func_id = insn->imm;
6865 	func = btf_type_by_id(desc_btf, func_id);
6866 	func_name = btf_name_by_offset(desc_btf, func->name_off);
6867 	func_proto = btf_type_by_id(desc_btf, func->type);
6868 
6869 	if (!env->ops->check_kfunc_call ||
6870 	    !env->ops->check_kfunc_call(func_id, btf_mod)) {
6871 		verbose(env, "calling kernel function %s is not allowed\n",
6872 			func_name);
6873 		return -EACCES;
6874 	}
6875 
6876 	/* Check the arguments */
6877 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6878 	if (err)
6879 		return err;
6880 
6881 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6882 		mark_reg_not_init(env, regs, caller_saved[i]);
6883 
6884 	/* Check return type */
6885 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6886 	if (btf_type_is_scalar(t)) {
6887 		mark_reg_unknown(env, regs, BPF_REG_0);
6888 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6889 	} else if (btf_type_is_ptr(t)) {
6890 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
6891 						   &ptr_type_id);
6892 		if (!btf_type_is_struct(ptr_type)) {
6893 			ptr_type_name = btf_name_by_offset(desc_btf,
6894 							   ptr_type->name_off);
6895 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6896 				func_name, btf_type_str(ptr_type),
6897 				ptr_type_name);
6898 			return -EINVAL;
6899 		}
6900 		mark_reg_known_zero(env, regs, BPF_REG_0);
6901 		regs[BPF_REG_0].btf = desc_btf;
6902 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6903 		regs[BPF_REG_0].btf_id = ptr_type_id;
6904 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6905 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6906 
6907 	nargs = btf_type_vlen(func_proto);
6908 	args = (const struct btf_param *)(func_proto + 1);
6909 	for (i = 0; i < nargs; i++) {
6910 		u32 regno = i + 1;
6911 
6912 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
6913 		if (btf_type_is_ptr(t))
6914 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6915 		else
6916 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6917 			mark_btf_func_reg_size(env, regno, t->size);
6918 	}
6919 
6920 	return 0;
6921 }
6922 
6923 static bool signed_add_overflows(s64 a, s64 b)
6924 {
6925 	/* Do the add in u64, where overflow is well-defined */
6926 	s64 res = (s64)((u64)a + (u64)b);
6927 
6928 	if (b < 0)
6929 		return res > a;
6930 	return res < a;
6931 }
6932 
6933 static bool signed_add32_overflows(s32 a, s32 b)
6934 {
6935 	/* Do the add in u32, where overflow is well-defined */
6936 	s32 res = (s32)((u32)a + (u32)b);
6937 
6938 	if (b < 0)
6939 		return res > a;
6940 	return res < a;
6941 }
6942 
6943 static bool signed_sub_overflows(s64 a, s64 b)
6944 {
6945 	/* Do the sub in u64, where overflow is well-defined */
6946 	s64 res = (s64)((u64)a - (u64)b);
6947 
6948 	if (b < 0)
6949 		return res < a;
6950 	return res > a;
6951 }
6952 
6953 static bool signed_sub32_overflows(s32 a, s32 b)
6954 {
6955 	/* Do the sub in u32, where overflow is well-defined */
6956 	s32 res = (s32)((u32)a - (u32)b);
6957 
6958 	if (b < 0)
6959 		return res < a;
6960 	return res > a;
6961 }
6962 
6963 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6964 				  const struct bpf_reg_state *reg,
6965 				  enum bpf_reg_type type)
6966 {
6967 	bool known = tnum_is_const(reg->var_off);
6968 	s64 val = reg->var_off.value;
6969 	s64 smin = reg->smin_value;
6970 
6971 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6972 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6973 			reg_type_str(env, type), val);
6974 		return false;
6975 	}
6976 
6977 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6978 		verbose(env, "%s pointer offset %d is not allowed\n",
6979 			reg_type_str(env, type), reg->off);
6980 		return false;
6981 	}
6982 
6983 	if (smin == S64_MIN) {
6984 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6985 			reg_type_str(env, type));
6986 		return false;
6987 	}
6988 
6989 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6990 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6991 			smin, reg_type_str(env, type));
6992 		return false;
6993 	}
6994 
6995 	return true;
6996 }
6997 
6998 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6999 {
7000 	return &env->insn_aux_data[env->insn_idx];
7001 }
7002 
7003 enum {
7004 	REASON_BOUNDS	= -1,
7005 	REASON_TYPE	= -2,
7006 	REASON_PATHS	= -3,
7007 	REASON_LIMIT	= -4,
7008 	REASON_STACK	= -5,
7009 };
7010 
7011 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7012 			      u32 *alu_limit, bool mask_to_left)
7013 {
7014 	u32 max = 0, ptr_limit = 0;
7015 
7016 	switch (ptr_reg->type) {
7017 	case PTR_TO_STACK:
7018 		/* Offset 0 is out-of-bounds, but acceptable start for the
7019 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7020 		 * offset where we would need to deal with min/max bounds is
7021 		 * currently prohibited for unprivileged.
7022 		 */
7023 		max = MAX_BPF_STACK + mask_to_left;
7024 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7025 		break;
7026 	case PTR_TO_MAP_VALUE:
7027 		max = ptr_reg->map_ptr->value_size;
7028 		ptr_limit = (mask_to_left ?
7029 			     ptr_reg->smin_value :
7030 			     ptr_reg->umax_value) + ptr_reg->off;
7031 		break;
7032 	default:
7033 		return REASON_TYPE;
7034 	}
7035 
7036 	if (ptr_limit >= max)
7037 		return REASON_LIMIT;
7038 	*alu_limit = ptr_limit;
7039 	return 0;
7040 }
7041 
7042 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7043 				    const struct bpf_insn *insn)
7044 {
7045 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7046 }
7047 
7048 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7049 				       u32 alu_state, u32 alu_limit)
7050 {
7051 	/* If we arrived here from different branches with different
7052 	 * state or limits to sanitize, then this won't work.
7053 	 */
7054 	if (aux->alu_state &&
7055 	    (aux->alu_state != alu_state ||
7056 	     aux->alu_limit != alu_limit))
7057 		return REASON_PATHS;
7058 
7059 	/* Corresponding fixup done in do_misc_fixups(). */
7060 	aux->alu_state = alu_state;
7061 	aux->alu_limit = alu_limit;
7062 	return 0;
7063 }
7064 
7065 static int sanitize_val_alu(struct bpf_verifier_env *env,
7066 			    struct bpf_insn *insn)
7067 {
7068 	struct bpf_insn_aux_data *aux = cur_aux(env);
7069 
7070 	if (can_skip_alu_sanitation(env, insn))
7071 		return 0;
7072 
7073 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7074 }
7075 
7076 static bool sanitize_needed(u8 opcode)
7077 {
7078 	return opcode == BPF_ADD || opcode == BPF_SUB;
7079 }
7080 
7081 struct bpf_sanitize_info {
7082 	struct bpf_insn_aux_data aux;
7083 	bool mask_to_left;
7084 };
7085 
7086 static struct bpf_verifier_state *
7087 sanitize_speculative_path(struct bpf_verifier_env *env,
7088 			  const struct bpf_insn *insn,
7089 			  u32 next_idx, u32 curr_idx)
7090 {
7091 	struct bpf_verifier_state *branch;
7092 	struct bpf_reg_state *regs;
7093 
7094 	branch = push_stack(env, next_idx, curr_idx, true);
7095 	if (branch && insn) {
7096 		regs = branch->frame[branch->curframe]->regs;
7097 		if (BPF_SRC(insn->code) == BPF_K) {
7098 			mark_reg_unknown(env, regs, insn->dst_reg);
7099 		} else if (BPF_SRC(insn->code) == BPF_X) {
7100 			mark_reg_unknown(env, regs, insn->dst_reg);
7101 			mark_reg_unknown(env, regs, insn->src_reg);
7102 		}
7103 	}
7104 	return branch;
7105 }
7106 
7107 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7108 			    struct bpf_insn *insn,
7109 			    const struct bpf_reg_state *ptr_reg,
7110 			    const struct bpf_reg_state *off_reg,
7111 			    struct bpf_reg_state *dst_reg,
7112 			    struct bpf_sanitize_info *info,
7113 			    const bool commit_window)
7114 {
7115 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7116 	struct bpf_verifier_state *vstate = env->cur_state;
7117 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7118 	bool off_is_neg = off_reg->smin_value < 0;
7119 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7120 	u8 opcode = BPF_OP(insn->code);
7121 	u32 alu_state, alu_limit;
7122 	struct bpf_reg_state tmp;
7123 	bool ret;
7124 	int err;
7125 
7126 	if (can_skip_alu_sanitation(env, insn))
7127 		return 0;
7128 
7129 	/* We already marked aux for masking from non-speculative
7130 	 * paths, thus we got here in the first place. We only care
7131 	 * to explore bad access from here.
7132 	 */
7133 	if (vstate->speculative)
7134 		goto do_sim;
7135 
7136 	if (!commit_window) {
7137 		if (!tnum_is_const(off_reg->var_off) &&
7138 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7139 			return REASON_BOUNDS;
7140 
7141 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7142 				     (opcode == BPF_SUB && !off_is_neg);
7143 	}
7144 
7145 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7146 	if (err < 0)
7147 		return err;
7148 
7149 	if (commit_window) {
7150 		/* In commit phase we narrow the masking window based on
7151 		 * the observed pointer move after the simulated operation.
7152 		 */
7153 		alu_state = info->aux.alu_state;
7154 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7155 	} else {
7156 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7157 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7158 		alu_state |= ptr_is_dst_reg ?
7159 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7160 
7161 		/* Limit pruning on unknown scalars to enable deep search for
7162 		 * potential masking differences from other program paths.
7163 		 */
7164 		if (!off_is_imm)
7165 			env->explore_alu_limits = true;
7166 	}
7167 
7168 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7169 	if (err < 0)
7170 		return err;
7171 do_sim:
7172 	/* If we're in commit phase, we're done here given we already
7173 	 * pushed the truncated dst_reg into the speculative verification
7174 	 * stack.
7175 	 *
7176 	 * Also, when register is a known constant, we rewrite register-based
7177 	 * operation to immediate-based, and thus do not need masking (and as
7178 	 * a consequence, do not need to simulate the zero-truncation either).
7179 	 */
7180 	if (commit_window || off_is_imm)
7181 		return 0;
7182 
7183 	/* Simulate and find potential out-of-bounds access under
7184 	 * speculative execution from truncation as a result of
7185 	 * masking when off was not within expected range. If off
7186 	 * sits in dst, then we temporarily need to move ptr there
7187 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7188 	 * for cases where we use K-based arithmetic in one direction
7189 	 * and truncated reg-based in the other in order to explore
7190 	 * bad access.
7191 	 */
7192 	if (!ptr_is_dst_reg) {
7193 		tmp = *dst_reg;
7194 		*dst_reg = *ptr_reg;
7195 	}
7196 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7197 					env->insn_idx);
7198 	if (!ptr_is_dst_reg && ret)
7199 		*dst_reg = tmp;
7200 	return !ret ? REASON_STACK : 0;
7201 }
7202 
7203 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7204 {
7205 	struct bpf_verifier_state *vstate = env->cur_state;
7206 
7207 	/* If we simulate paths under speculation, we don't update the
7208 	 * insn as 'seen' such that when we verify unreachable paths in
7209 	 * the non-speculative domain, sanitize_dead_code() can still
7210 	 * rewrite/sanitize them.
7211 	 */
7212 	if (!vstate->speculative)
7213 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7214 }
7215 
7216 static int sanitize_err(struct bpf_verifier_env *env,
7217 			const struct bpf_insn *insn, int reason,
7218 			const struct bpf_reg_state *off_reg,
7219 			const struct bpf_reg_state *dst_reg)
7220 {
7221 	static const char *err = "pointer arithmetic with it prohibited for !root";
7222 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7223 	u32 dst = insn->dst_reg, src = insn->src_reg;
7224 
7225 	switch (reason) {
7226 	case REASON_BOUNDS:
7227 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7228 			off_reg == dst_reg ? dst : src, err);
7229 		break;
7230 	case REASON_TYPE:
7231 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7232 			off_reg == dst_reg ? src : dst, err);
7233 		break;
7234 	case REASON_PATHS:
7235 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7236 			dst, op, err);
7237 		break;
7238 	case REASON_LIMIT:
7239 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7240 			dst, op, err);
7241 		break;
7242 	case REASON_STACK:
7243 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7244 			dst, err);
7245 		break;
7246 	default:
7247 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7248 			reason);
7249 		break;
7250 	}
7251 
7252 	return -EACCES;
7253 }
7254 
7255 /* check that stack access falls within stack limits and that 'reg' doesn't
7256  * have a variable offset.
7257  *
7258  * Variable offset is prohibited for unprivileged mode for simplicity since it
7259  * requires corresponding support in Spectre masking for stack ALU.  See also
7260  * retrieve_ptr_limit().
7261  *
7262  *
7263  * 'off' includes 'reg->off'.
7264  */
7265 static int check_stack_access_for_ptr_arithmetic(
7266 				struct bpf_verifier_env *env,
7267 				int regno,
7268 				const struct bpf_reg_state *reg,
7269 				int off)
7270 {
7271 	if (!tnum_is_const(reg->var_off)) {
7272 		char tn_buf[48];
7273 
7274 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7275 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7276 			regno, tn_buf, off);
7277 		return -EACCES;
7278 	}
7279 
7280 	if (off >= 0 || off < -MAX_BPF_STACK) {
7281 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7282 			"prohibited for !root; off=%d\n", regno, off);
7283 		return -EACCES;
7284 	}
7285 
7286 	return 0;
7287 }
7288 
7289 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7290 				 const struct bpf_insn *insn,
7291 				 const struct bpf_reg_state *dst_reg)
7292 {
7293 	u32 dst = insn->dst_reg;
7294 
7295 	/* For unprivileged we require that resulting offset must be in bounds
7296 	 * in order to be able to sanitize access later on.
7297 	 */
7298 	if (env->bypass_spec_v1)
7299 		return 0;
7300 
7301 	switch (dst_reg->type) {
7302 	case PTR_TO_STACK:
7303 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7304 					dst_reg->off + dst_reg->var_off.value))
7305 			return -EACCES;
7306 		break;
7307 	case PTR_TO_MAP_VALUE:
7308 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7309 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7310 				"prohibited for !root\n", dst);
7311 			return -EACCES;
7312 		}
7313 		break;
7314 	default:
7315 		break;
7316 	}
7317 
7318 	return 0;
7319 }
7320 
7321 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7322  * Caller should also handle BPF_MOV case separately.
7323  * If we return -EACCES, caller may want to try again treating pointer as a
7324  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7325  */
7326 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7327 				   struct bpf_insn *insn,
7328 				   const struct bpf_reg_state *ptr_reg,
7329 				   const struct bpf_reg_state *off_reg)
7330 {
7331 	struct bpf_verifier_state *vstate = env->cur_state;
7332 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7333 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7334 	bool known = tnum_is_const(off_reg->var_off);
7335 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7336 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7337 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7338 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7339 	struct bpf_sanitize_info info = {};
7340 	u8 opcode = BPF_OP(insn->code);
7341 	u32 dst = insn->dst_reg;
7342 	int ret;
7343 
7344 	dst_reg = &regs[dst];
7345 
7346 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7347 	    smin_val > smax_val || umin_val > umax_val) {
7348 		/* Taint dst register if offset had invalid bounds derived from
7349 		 * e.g. dead branches.
7350 		 */
7351 		__mark_reg_unknown(env, dst_reg);
7352 		return 0;
7353 	}
7354 
7355 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7356 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7357 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7358 			__mark_reg_unknown(env, dst_reg);
7359 			return 0;
7360 		}
7361 
7362 		verbose(env,
7363 			"R%d 32-bit pointer arithmetic prohibited\n",
7364 			dst);
7365 		return -EACCES;
7366 	}
7367 
7368 	if (ptr_reg->type & PTR_MAYBE_NULL) {
7369 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7370 			dst, reg_type_str(env, ptr_reg->type));
7371 		return -EACCES;
7372 	}
7373 
7374 	switch (base_type(ptr_reg->type)) {
7375 	case CONST_PTR_TO_MAP:
7376 		/* smin_val represents the known value */
7377 		if (known && smin_val == 0 && opcode == BPF_ADD)
7378 			break;
7379 		fallthrough;
7380 	case PTR_TO_PACKET_END:
7381 	case PTR_TO_SOCKET:
7382 	case PTR_TO_SOCK_COMMON:
7383 	case PTR_TO_TCP_SOCK:
7384 	case PTR_TO_XDP_SOCK:
7385 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7386 			dst, reg_type_str(env, ptr_reg->type));
7387 		return -EACCES;
7388 	default:
7389 		break;
7390 	}
7391 
7392 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7393 	 * The id may be overwritten later if we create a new variable offset.
7394 	 */
7395 	dst_reg->type = ptr_reg->type;
7396 	dst_reg->id = ptr_reg->id;
7397 
7398 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7399 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7400 		return -EINVAL;
7401 
7402 	/* pointer types do not carry 32-bit bounds at the moment. */
7403 	__mark_reg32_unbounded(dst_reg);
7404 
7405 	if (sanitize_needed(opcode)) {
7406 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7407 				       &info, false);
7408 		if (ret < 0)
7409 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7410 	}
7411 
7412 	switch (opcode) {
7413 	case BPF_ADD:
7414 		/* We can take a fixed offset as long as it doesn't overflow
7415 		 * the s32 'off' field
7416 		 */
7417 		if (known && (ptr_reg->off + smin_val ==
7418 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7419 			/* pointer += K.  Accumulate it into fixed offset */
7420 			dst_reg->smin_value = smin_ptr;
7421 			dst_reg->smax_value = smax_ptr;
7422 			dst_reg->umin_value = umin_ptr;
7423 			dst_reg->umax_value = umax_ptr;
7424 			dst_reg->var_off = ptr_reg->var_off;
7425 			dst_reg->off = ptr_reg->off + smin_val;
7426 			dst_reg->raw = ptr_reg->raw;
7427 			break;
7428 		}
7429 		/* A new variable offset is created.  Note that off_reg->off
7430 		 * == 0, since it's a scalar.
7431 		 * dst_reg gets the pointer type and since some positive
7432 		 * integer value was added to the pointer, give it a new 'id'
7433 		 * if it's a PTR_TO_PACKET.
7434 		 * this creates a new 'base' pointer, off_reg (variable) gets
7435 		 * added into the variable offset, and we copy the fixed offset
7436 		 * from ptr_reg.
7437 		 */
7438 		if (signed_add_overflows(smin_ptr, smin_val) ||
7439 		    signed_add_overflows(smax_ptr, smax_val)) {
7440 			dst_reg->smin_value = S64_MIN;
7441 			dst_reg->smax_value = S64_MAX;
7442 		} else {
7443 			dst_reg->smin_value = smin_ptr + smin_val;
7444 			dst_reg->smax_value = smax_ptr + smax_val;
7445 		}
7446 		if (umin_ptr + umin_val < umin_ptr ||
7447 		    umax_ptr + umax_val < umax_ptr) {
7448 			dst_reg->umin_value = 0;
7449 			dst_reg->umax_value = U64_MAX;
7450 		} else {
7451 			dst_reg->umin_value = umin_ptr + umin_val;
7452 			dst_reg->umax_value = umax_ptr + umax_val;
7453 		}
7454 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7455 		dst_reg->off = ptr_reg->off;
7456 		dst_reg->raw = ptr_reg->raw;
7457 		if (reg_is_pkt_pointer(ptr_reg)) {
7458 			dst_reg->id = ++env->id_gen;
7459 			/* something was added to pkt_ptr, set range to zero */
7460 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7461 		}
7462 		break;
7463 	case BPF_SUB:
7464 		if (dst_reg == off_reg) {
7465 			/* scalar -= pointer.  Creates an unknown scalar */
7466 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7467 				dst);
7468 			return -EACCES;
7469 		}
7470 		/* We don't allow subtraction from FP, because (according to
7471 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7472 		 * be able to deal with it.
7473 		 */
7474 		if (ptr_reg->type == PTR_TO_STACK) {
7475 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7476 				dst);
7477 			return -EACCES;
7478 		}
7479 		if (known && (ptr_reg->off - smin_val ==
7480 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7481 			/* pointer -= K.  Subtract it from fixed offset */
7482 			dst_reg->smin_value = smin_ptr;
7483 			dst_reg->smax_value = smax_ptr;
7484 			dst_reg->umin_value = umin_ptr;
7485 			dst_reg->umax_value = umax_ptr;
7486 			dst_reg->var_off = ptr_reg->var_off;
7487 			dst_reg->id = ptr_reg->id;
7488 			dst_reg->off = ptr_reg->off - smin_val;
7489 			dst_reg->raw = ptr_reg->raw;
7490 			break;
7491 		}
7492 		/* A new variable offset is created.  If the subtrahend is known
7493 		 * nonnegative, then any reg->range we had before is still good.
7494 		 */
7495 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7496 		    signed_sub_overflows(smax_ptr, smin_val)) {
7497 			/* Overflow possible, we know nothing */
7498 			dst_reg->smin_value = S64_MIN;
7499 			dst_reg->smax_value = S64_MAX;
7500 		} else {
7501 			dst_reg->smin_value = smin_ptr - smax_val;
7502 			dst_reg->smax_value = smax_ptr - smin_val;
7503 		}
7504 		if (umin_ptr < umax_val) {
7505 			/* Overflow possible, we know nothing */
7506 			dst_reg->umin_value = 0;
7507 			dst_reg->umax_value = U64_MAX;
7508 		} else {
7509 			/* Cannot overflow (as long as bounds are consistent) */
7510 			dst_reg->umin_value = umin_ptr - umax_val;
7511 			dst_reg->umax_value = umax_ptr - umin_val;
7512 		}
7513 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7514 		dst_reg->off = ptr_reg->off;
7515 		dst_reg->raw = ptr_reg->raw;
7516 		if (reg_is_pkt_pointer(ptr_reg)) {
7517 			dst_reg->id = ++env->id_gen;
7518 			/* something was added to pkt_ptr, set range to zero */
7519 			if (smin_val < 0)
7520 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7521 		}
7522 		break;
7523 	case BPF_AND:
7524 	case BPF_OR:
7525 	case BPF_XOR:
7526 		/* bitwise ops on pointers are troublesome, prohibit. */
7527 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7528 			dst, bpf_alu_string[opcode >> 4]);
7529 		return -EACCES;
7530 	default:
7531 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7532 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7533 			dst, bpf_alu_string[opcode >> 4]);
7534 		return -EACCES;
7535 	}
7536 
7537 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7538 		return -EINVAL;
7539 
7540 	__update_reg_bounds(dst_reg);
7541 	__reg_deduce_bounds(dst_reg);
7542 	__reg_bound_offset(dst_reg);
7543 
7544 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7545 		return -EACCES;
7546 	if (sanitize_needed(opcode)) {
7547 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7548 				       &info, true);
7549 		if (ret < 0)
7550 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7551 	}
7552 
7553 	return 0;
7554 }
7555 
7556 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7557 				 struct bpf_reg_state *src_reg)
7558 {
7559 	s32 smin_val = src_reg->s32_min_value;
7560 	s32 smax_val = src_reg->s32_max_value;
7561 	u32 umin_val = src_reg->u32_min_value;
7562 	u32 umax_val = src_reg->u32_max_value;
7563 
7564 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7565 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7566 		dst_reg->s32_min_value = S32_MIN;
7567 		dst_reg->s32_max_value = S32_MAX;
7568 	} else {
7569 		dst_reg->s32_min_value += smin_val;
7570 		dst_reg->s32_max_value += smax_val;
7571 	}
7572 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7573 	    dst_reg->u32_max_value + umax_val < umax_val) {
7574 		dst_reg->u32_min_value = 0;
7575 		dst_reg->u32_max_value = U32_MAX;
7576 	} else {
7577 		dst_reg->u32_min_value += umin_val;
7578 		dst_reg->u32_max_value += umax_val;
7579 	}
7580 }
7581 
7582 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7583 			       struct bpf_reg_state *src_reg)
7584 {
7585 	s64 smin_val = src_reg->smin_value;
7586 	s64 smax_val = src_reg->smax_value;
7587 	u64 umin_val = src_reg->umin_value;
7588 	u64 umax_val = src_reg->umax_value;
7589 
7590 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7591 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7592 		dst_reg->smin_value = S64_MIN;
7593 		dst_reg->smax_value = S64_MAX;
7594 	} else {
7595 		dst_reg->smin_value += smin_val;
7596 		dst_reg->smax_value += smax_val;
7597 	}
7598 	if (dst_reg->umin_value + umin_val < umin_val ||
7599 	    dst_reg->umax_value + umax_val < umax_val) {
7600 		dst_reg->umin_value = 0;
7601 		dst_reg->umax_value = U64_MAX;
7602 	} else {
7603 		dst_reg->umin_value += umin_val;
7604 		dst_reg->umax_value += umax_val;
7605 	}
7606 }
7607 
7608 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7609 				 struct bpf_reg_state *src_reg)
7610 {
7611 	s32 smin_val = src_reg->s32_min_value;
7612 	s32 smax_val = src_reg->s32_max_value;
7613 	u32 umin_val = src_reg->u32_min_value;
7614 	u32 umax_val = src_reg->u32_max_value;
7615 
7616 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7617 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7618 		/* Overflow possible, we know nothing */
7619 		dst_reg->s32_min_value = S32_MIN;
7620 		dst_reg->s32_max_value = S32_MAX;
7621 	} else {
7622 		dst_reg->s32_min_value -= smax_val;
7623 		dst_reg->s32_max_value -= smin_val;
7624 	}
7625 	if (dst_reg->u32_min_value < umax_val) {
7626 		/* Overflow possible, we know nothing */
7627 		dst_reg->u32_min_value = 0;
7628 		dst_reg->u32_max_value = U32_MAX;
7629 	} else {
7630 		/* Cannot overflow (as long as bounds are consistent) */
7631 		dst_reg->u32_min_value -= umax_val;
7632 		dst_reg->u32_max_value -= umin_val;
7633 	}
7634 }
7635 
7636 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7637 			       struct bpf_reg_state *src_reg)
7638 {
7639 	s64 smin_val = src_reg->smin_value;
7640 	s64 smax_val = src_reg->smax_value;
7641 	u64 umin_val = src_reg->umin_value;
7642 	u64 umax_val = src_reg->umax_value;
7643 
7644 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7645 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7646 		/* Overflow possible, we know nothing */
7647 		dst_reg->smin_value = S64_MIN;
7648 		dst_reg->smax_value = S64_MAX;
7649 	} else {
7650 		dst_reg->smin_value -= smax_val;
7651 		dst_reg->smax_value -= smin_val;
7652 	}
7653 	if (dst_reg->umin_value < umax_val) {
7654 		/* Overflow possible, we know nothing */
7655 		dst_reg->umin_value = 0;
7656 		dst_reg->umax_value = U64_MAX;
7657 	} else {
7658 		/* Cannot overflow (as long as bounds are consistent) */
7659 		dst_reg->umin_value -= umax_val;
7660 		dst_reg->umax_value -= umin_val;
7661 	}
7662 }
7663 
7664 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7665 				 struct bpf_reg_state *src_reg)
7666 {
7667 	s32 smin_val = src_reg->s32_min_value;
7668 	u32 umin_val = src_reg->u32_min_value;
7669 	u32 umax_val = src_reg->u32_max_value;
7670 
7671 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7672 		/* Ain't nobody got time to multiply that sign */
7673 		__mark_reg32_unbounded(dst_reg);
7674 		return;
7675 	}
7676 	/* Both values are positive, so we can work with unsigned and
7677 	 * copy the result to signed (unless it exceeds S32_MAX).
7678 	 */
7679 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7680 		/* Potential overflow, we know nothing */
7681 		__mark_reg32_unbounded(dst_reg);
7682 		return;
7683 	}
7684 	dst_reg->u32_min_value *= umin_val;
7685 	dst_reg->u32_max_value *= umax_val;
7686 	if (dst_reg->u32_max_value > S32_MAX) {
7687 		/* Overflow possible, we know nothing */
7688 		dst_reg->s32_min_value = S32_MIN;
7689 		dst_reg->s32_max_value = S32_MAX;
7690 	} else {
7691 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7692 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7693 	}
7694 }
7695 
7696 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7697 			       struct bpf_reg_state *src_reg)
7698 {
7699 	s64 smin_val = src_reg->smin_value;
7700 	u64 umin_val = src_reg->umin_value;
7701 	u64 umax_val = src_reg->umax_value;
7702 
7703 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7704 		/* Ain't nobody got time to multiply that sign */
7705 		__mark_reg64_unbounded(dst_reg);
7706 		return;
7707 	}
7708 	/* Both values are positive, so we can work with unsigned and
7709 	 * copy the result to signed (unless it exceeds S64_MAX).
7710 	 */
7711 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7712 		/* Potential overflow, we know nothing */
7713 		__mark_reg64_unbounded(dst_reg);
7714 		return;
7715 	}
7716 	dst_reg->umin_value *= umin_val;
7717 	dst_reg->umax_value *= umax_val;
7718 	if (dst_reg->umax_value > S64_MAX) {
7719 		/* Overflow possible, we know nothing */
7720 		dst_reg->smin_value = S64_MIN;
7721 		dst_reg->smax_value = S64_MAX;
7722 	} else {
7723 		dst_reg->smin_value = dst_reg->umin_value;
7724 		dst_reg->smax_value = dst_reg->umax_value;
7725 	}
7726 }
7727 
7728 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7729 				 struct bpf_reg_state *src_reg)
7730 {
7731 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7732 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7733 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7734 	s32 smin_val = src_reg->s32_min_value;
7735 	u32 umax_val = src_reg->u32_max_value;
7736 
7737 	if (src_known && dst_known) {
7738 		__mark_reg32_known(dst_reg, var32_off.value);
7739 		return;
7740 	}
7741 
7742 	/* We get our minimum from the var_off, since that's inherently
7743 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7744 	 */
7745 	dst_reg->u32_min_value = var32_off.value;
7746 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7747 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7748 		/* Lose signed bounds when ANDing negative numbers,
7749 		 * ain't nobody got time for that.
7750 		 */
7751 		dst_reg->s32_min_value = S32_MIN;
7752 		dst_reg->s32_max_value = S32_MAX;
7753 	} else {
7754 		/* ANDing two positives gives a positive, so safe to
7755 		 * cast result into s64.
7756 		 */
7757 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7758 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7759 	}
7760 }
7761 
7762 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7763 			       struct bpf_reg_state *src_reg)
7764 {
7765 	bool src_known = tnum_is_const(src_reg->var_off);
7766 	bool dst_known = tnum_is_const(dst_reg->var_off);
7767 	s64 smin_val = src_reg->smin_value;
7768 	u64 umax_val = src_reg->umax_value;
7769 
7770 	if (src_known && dst_known) {
7771 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7772 		return;
7773 	}
7774 
7775 	/* We get our minimum from the var_off, since that's inherently
7776 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7777 	 */
7778 	dst_reg->umin_value = dst_reg->var_off.value;
7779 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7780 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7781 		/* Lose signed bounds when ANDing negative numbers,
7782 		 * ain't nobody got time for that.
7783 		 */
7784 		dst_reg->smin_value = S64_MIN;
7785 		dst_reg->smax_value = S64_MAX;
7786 	} else {
7787 		/* ANDing two positives gives a positive, so safe to
7788 		 * cast result into s64.
7789 		 */
7790 		dst_reg->smin_value = dst_reg->umin_value;
7791 		dst_reg->smax_value = dst_reg->umax_value;
7792 	}
7793 	/* We may learn something more from the var_off */
7794 	__update_reg_bounds(dst_reg);
7795 }
7796 
7797 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7798 				struct bpf_reg_state *src_reg)
7799 {
7800 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7801 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7802 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7803 	s32 smin_val = src_reg->s32_min_value;
7804 	u32 umin_val = src_reg->u32_min_value;
7805 
7806 	if (src_known && dst_known) {
7807 		__mark_reg32_known(dst_reg, var32_off.value);
7808 		return;
7809 	}
7810 
7811 	/* We get our maximum from the var_off, and our minimum is the
7812 	 * maximum of the operands' minima
7813 	 */
7814 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7815 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7816 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7817 		/* Lose signed bounds when ORing negative numbers,
7818 		 * ain't nobody got time for that.
7819 		 */
7820 		dst_reg->s32_min_value = S32_MIN;
7821 		dst_reg->s32_max_value = S32_MAX;
7822 	} else {
7823 		/* ORing two positives gives a positive, so safe to
7824 		 * cast result into s64.
7825 		 */
7826 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7827 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7828 	}
7829 }
7830 
7831 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7832 			      struct bpf_reg_state *src_reg)
7833 {
7834 	bool src_known = tnum_is_const(src_reg->var_off);
7835 	bool dst_known = tnum_is_const(dst_reg->var_off);
7836 	s64 smin_val = src_reg->smin_value;
7837 	u64 umin_val = src_reg->umin_value;
7838 
7839 	if (src_known && dst_known) {
7840 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7841 		return;
7842 	}
7843 
7844 	/* We get our maximum from the var_off, and our minimum is the
7845 	 * maximum of the operands' minima
7846 	 */
7847 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7848 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7849 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7850 		/* Lose signed bounds when ORing negative numbers,
7851 		 * ain't nobody got time for that.
7852 		 */
7853 		dst_reg->smin_value = S64_MIN;
7854 		dst_reg->smax_value = S64_MAX;
7855 	} else {
7856 		/* ORing two positives gives a positive, so safe to
7857 		 * cast result into s64.
7858 		 */
7859 		dst_reg->smin_value = dst_reg->umin_value;
7860 		dst_reg->smax_value = dst_reg->umax_value;
7861 	}
7862 	/* We may learn something more from the var_off */
7863 	__update_reg_bounds(dst_reg);
7864 }
7865 
7866 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7867 				 struct bpf_reg_state *src_reg)
7868 {
7869 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7870 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7871 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7872 	s32 smin_val = src_reg->s32_min_value;
7873 
7874 	if (src_known && dst_known) {
7875 		__mark_reg32_known(dst_reg, var32_off.value);
7876 		return;
7877 	}
7878 
7879 	/* We get both minimum and maximum from the var32_off. */
7880 	dst_reg->u32_min_value = var32_off.value;
7881 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7882 
7883 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7884 		/* XORing two positive sign numbers gives a positive,
7885 		 * so safe to cast u32 result into s32.
7886 		 */
7887 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7888 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7889 	} else {
7890 		dst_reg->s32_min_value = S32_MIN;
7891 		dst_reg->s32_max_value = S32_MAX;
7892 	}
7893 }
7894 
7895 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7896 			       struct bpf_reg_state *src_reg)
7897 {
7898 	bool src_known = tnum_is_const(src_reg->var_off);
7899 	bool dst_known = tnum_is_const(dst_reg->var_off);
7900 	s64 smin_val = src_reg->smin_value;
7901 
7902 	if (src_known && dst_known) {
7903 		/* dst_reg->var_off.value has been updated earlier */
7904 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7905 		return;
7906 	}
7907 
7908 	/* We get both minimum and maximum from the var_off. */
7909 	dst_reg->umin_value = dst_reg->var_off.value;
7910 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7911 
7912 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7913 		/* XORing two positive sign numbers gives a positive,
7914 		 * so safe to cast u64 result into s64.
7915 		 */
7916 		dst_reg->smin_value = dst_reg->umin_value;
7917 		dst_reg->smax_value = dst_reg->umax_value;
7918 	} else {
7919 		dst_reg->smin_value = S64_MIN;
7920 		dst_reg->smax_value = S64_MAX;
7921 	}
7922 
7923 	__update_reg_bounds(dst_reg);
7924 }
7925 
7926 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7927 				   u64 umin_val, u64 umax_val)
7928 {
7929 	/* We lose all sign bit information (except what we can pick
7930 	 * up from var_off)
7931 	 */
7932 	dst_reg->s32_min_value = S32_MIN;
7933 	dst_reg->s32_max_value = S32_MAX;
7934 	/* If we might shift our top bit out, then we know nothing */
7935 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7936 		dst_reg->u32_min_value = 0;
7937 		dst_reg->u32_max_value = U32_MAX;
7938 	} else {
7939 		dst_reg->u32_min_value <<= umin_val;
7940 		dst_reg->u32_max_value <<= umax_val;
7941 	}
7942 }
7943 
7944 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7945 				 struct bpf_reg_state *src_reg)
7946 {
7947 	u32 umax_val = src_reg->u32_max_value;
7948 	u32 umin_val = src_reg->u32_min_value;
7949 	/* u32 alu operation will zext upper bits */
7950 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7951 
7952 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7953 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7954 	/* Not required but being careful mark reg64 bounds as unknown so
7955 	 * that we are forced to pick them up from tnum and zext later and
7956 	 * if some path skips this step we are still safe.
7957 	 */
7958 	__mark_reg64_unbounded(dst_reg);
7959 	__update_reg32_bounds(dst_reg);
7960 }
7961 
7962 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7963 				   u64 umin_val, u64 umax_val)
7964 {
7965 	/* Special case <<32 because it is a common compiler pattern to sign
7966 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7967 	 * positive we know this shift will also be positive so we can track
7968 	 * bounds correctly. Otherwise we lose all sign bit information except
7969 	 * what we can pick up from var_off. Perhaps we can generalize this
7970 	 * later to shifts of any length.
7971 	 */
7972 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7973 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7974 	else
7975 		dst_reg->smax_value = S64_MAX;
7976 
7977 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7978 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7979 	else
7980 		dst_reg->smin_value = S64_MIN;
7981 
7982 	/* If we might shift our top bit out, then we know nothing */
7983 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7984 		dst_reg->umin_value = 0;
7985 		dst_reg->umax_value = U64_MAX;
7986 	} else {
7987 		dst_reg->umin_value <<= umin_val;
7988 		dst_reg->umax_value <<= umax_val;
7989 	}
7990 }
7991 
7992 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7993 			       struct bpf_reg_state *src_reg)
7994 {
7995 	u64 umax_val = src_reg->umax_value;
7996 	u64 umin_val = src_reg->umin_value;
7997 
7998 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7999 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8000 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8001 
8002 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8003 	/* We may learn something more from the var_off */
8004 	__update_reg_bounds(dst_reg);
8005 }
8006 
8007 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8008 				 struct bpf_reg_state *src_reg)
8009 {
8010 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8011 	u32 umax_val = src_reg->u32_max_value;
8012 	u32 umin_val = src_reg->u32_min_value;
8013 
8014 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8015 	 * be negative, then either:
8016 	 * 1) src_reg might be zero, so the sign bit of the result is
8017 	 *    unknown, so we lose our signed bounds
8018 	 * 2) it's known negative, thus the unsigned bounds capture the
8019 	 *    signed bounds
8020 	 * 3) the signed bounds cross zero, so they tell us nothing
8021 	 *    about the result
8022 	 * If the value in dst_reg is known nonnegative, then again the
8023 	 * unsigned bounds capture the signed bounds.
8024 	 * Thus, in all cases it suffices to blow away our signed bounds
8025 	 * and rely on inferring new ones from the unsigned bounds and
8026 	 * var_off of the result.
8027 	 */
8028 	dst_reg->s32_min_value = S32_MIN;
8029 	dst_reg->s32_max_value = S32_MAX;
8030 
8031 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8032 	dst_reg->u32_min_value >>= umax_val;
8033 	dst_reg->u32_max_value >>= umin_val;
8034 
8035 	__mark_reg64_unbounded(dst_reg);
8036 	__update_reg32_bounds(dst_reg);
8037 }
8038 
8039 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8040 			       struct bpf_reg_state *src_reg)
8041 {
8042 	u64 umax_val = src_reg->umax_value;
8043 	u64 umin_val = src_reg->umin_value;
8044 
8045 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8046 	 * be negative, then either:
8047 	 * 1) src_reg might be zero, so the sign bit of the result is
8048 	 *    unknown, so we lose our signed bounds
8049 	 * 2) it's known negative, thus the unsigned bounds capture the
8050 	 *    signed bounds
8051 	 * 3) the signed bounds cross zero, so they tell us nothing
8052 	 *    about the result
8053 	 * If the value in dst_reg is known nonnegative, then again the
8054 	 * unsigned bounds capture the signed bounds.
8055 	 * Thus, in all cases it suffices to blow away our signed bounds
8056 	 * and rely on inferring new ones from the unsigned bounds and
8057 	 * var_off of the result.
8058 	 */
8059 	dst_reg->smin_value = S64_MIN;
8060 	dst_reg->smax_value = S64_MAX;
8061 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8062 	dst_reg->umin_value >>= umax_val;
8063 	dst_reg->umax_value >>= umin_val;
8064 
8065 	/* Its not easy to operate on alu32 bounds here because it depends
8066 	 * on bits being shifted in. Take easy way out and mark unbounded
8067 	 * so we can recalculate later from tnum.
8068 	 */
8069 	__mark_reg32_unbounded(dst_reg);
8070 	__update_reg_bounds(dst_reg);
8071 }
8072 
8073 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8074 				  struct bpf_reg_state *src_reg)
8075 {
8076 	u64 umin_val = src_reg->u32_min_value;
8077 
8078 	/* Upon reaching here, src_known is true and
8079 	 * umax_val is equal to umin_val.
8080 	 */
8081 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8082 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8083 
8084 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8085 
8086 	/* blow away the dst_reg umin_value/umax_value and rely on
8087 	 * dst_reg var_off to refine the result.
8088 	 */
8089 	dst_reg->u32_min_value = 0;
8090 	dst_reg->u32_max_value = U32_MAX;
8091 
8092 	__mark_reg64_unbounded(dst_reg);
8093 	__update_reg32_bounds(dst_reg);
8094 }
8095 
8096 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8097 				struct bpf_reg_state *src_reg)
8098 {
8099 	u64 umin_val = src_reg->umin_value;
8100 
8101 	/* Upon reaching here, src_known is true and umax_val is equal
8102 	 * to umin_val.
8103 	 */
8104 	dst_reg->smin_value >>= umin_val;
8105 	dst_reg->smax_value >>= umin_val;
8106 
8107 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8108 
8109 	/* blow away the dst_reg umin_value/umax_value and rely on
8110 	 * dst_reg var_off to refine the result.
8111 	 */
8112 	dst_reg->umin_value = 0;
8113 	dst_reg->umax_value = U64_MAX;
8114 
8115 	/* Its not easy to operate on alu32 bounds here because it depends
8116 	 * on bits being shifted in from upper 32-bits. Take easy way out
8117 	 * and mark unbounded so we can recalculate later from tnum.
8118 	 */
8119 	__mark_reg32_unbounded(dst_reg);
8120 	__update_reg_bounds(dst_reg);
8121 }
8122 
8123 /* WARNING: This function does calculations on 64-bit values, but the actual
8124  * execution may occur on 32-bit values. Therefore, things like bitshifts
8125  * need extra checks in the 32-bit case.
8126  */
8127 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8128 				      struct bpf_insn *insn,
8129 				      struct bpf_reg_state *dst_reg,
8130 				      struct bpf_reg_state src_reg)
8131 {
8132 	struct bpf_reg_state *regs = cur_regs(env);
8133 	u8 opcode = BPF_OP(insn->code);
8134 	bool src_known;
8135 	s64 smin_val, smax_val;
8136 	u64 umin_val, umax_val;
8137 	s32 s32_min_val, s32_max_val;
8138 	u32 u32_min_val, u32_max_val;
8139 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8140 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8141 	int ret;
8142 
8143 	smin_val = src_reg.smin_value;
8144 	smax_val = src_reg.smax_value;
8145 	umin_val = src_reg.umin_value;
8146 	umax_val = src_reg.umax_value;
8147 
8148 	s32_min_val = src_reg.s32_min_value;
8149 	s32_max_val = src_reg.s32_max_value;
8150 	u32_min_val = src_reg.u32_min_value;
8151 	u32_max_val = src_reg.u32_max_value;
8152 
8153 	if (alu32) {
8154 		src_known = tnum_subreg_is_const(src_reg.var_off);
8155 		if ((src_known &&
8156 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8157 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8158 			/* Taint dst register if offset had invalid bounds
8159 			 * derived from e.g. dead branches.
8160 			 */
8161 			__mark_reg_unknown(env, dst_reg);
8162 			return 0;
8163 		}
8164 	} else {
8165 		src_known = tnum_is_const(src_reg.var_off);
8166 		if ((src_known &&
8167 		     (smin_val != smax_val || umin_val != umax_val)) ||
8168 		    smin_val > smax_val || umin_val > umax_val) {
8169 			/* Taint dst register if offset had invalid bounds
8170 			 * derived from e.g. dead branches.
8171 			 */
8172 			__mark_reg_unknown(env, dst_reg);
8173 			return 0;
8174 		}
8175 	}
8176 
8177 	if (!src_known &&
8178 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8179 		__mark_reg_unknown(env, dst_reg);
8180 		return 0;
8181 	}
8182 
8183 	if (sanitize_needed(opcode)) {
8184 		ret = sanitize_val_alu(env, insn);
8185 		if (ret < 0)
8186 			return sanitize_err(env, insn, ret, NULL, NULL);
8187 	}
8188 
8189 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8190 	 * There are two classes of instructions: The first class we track both
8191 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8192 	 * greatest amount of precision when alu operations are mixed with jmp32
8193 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8194 	 * and BPF_OR. This is possible because these ops have fairly easy to
8195 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8196 	 * See alu32 verifier tests for examples. The second class of
8197 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8198 	 * with regards to tracking sign/unsigned bounds because the bits may
8199 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8200 	 * the reg unbounded in the subreg bound space and use the resulting
8201 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8202 	 */
8203 	switch (opcode) {
8204 	case BPF_ADD:
8205 		scalar32_min_max_add(dst_reg, &src_reg);
8206 		scalar_min_max_add(dst_reg, &src_reg);
8207 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8208 		break;
8209 	case BPF_SUB:
8210 		scalar32_min_max_sub(dst_reg, &src_reg);
8211 		scalar_min_max_sub(dst_reg, &src_reg);
8212 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8213 		break;
8214 	case BPF_MUL:
8215 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8216 		scalar32_min_max_mul(dst_reg, &src_reg);
8217 		scalar_min_max_mul(dst_reg, &src_reg);
8218 		break;
8219 	case BPF_AND:
8220 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8221 		scalar32_min_max_and(dst_reg, &src_reg);
8222 		scalar_min_max_and(dst_reg, &src_reg);
8223 		break;
8224 	case BPF_OR:
8225 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8226 		scalar32_min_max_or(dst_reg, &src_reg);
8227 		scalar_min_max_or(dst_reg, &src_reg);
8228 		break;
8229 	case BPF_XOR:
8230 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8231 		scalar32_min_max_xor(dst_reg, &src_reg);
8232 		scalar_min_max_xor(dst_reg, &src_reg);
8233 		break;
8234 	case BPF_LSH:
8235 		if (umax_val >= insn_bitness) {
8236 			/* Shifts greater than 31 or 63 are undefined.
8237 			 * This includes shifts by a negative number.
8238 			 */
8239 			mark_reg_unknown(env, regs, insn->dst_reg);
8240 			break;
8241 		}
8242 		if (alu32)
8243 			scalar32_min_max_lsh(dst_reg, &src_reg);
8244 		else
8245 			scalar_min_max_lsh(dst_reg, &src_reg);
8246 		break;
8247 	case BPF_RSH:
8248 		if (umax_val >= insn_bitness) {
8249 			/* Shifts greater than 31 or 63 are undefined.
8250 			 * This includes shifts by a negative number.
8251 			 */
8252 			mark_reg_unknown(env, regs, insn->dst_reg);
8253 			break;
8254 		}
8255 		if (alu32)
8256 			scalar32_min_max_rsh(dst_reg, &src_reg);
8257 		else
8258 			scalar_min_max_rsh(dst_reg, &src_reg);
8259 		break;
8260 	case BPF_ARSH:
8261 		if (umax_val >= insn_bitness) {
8262 			/* Shifts greater than 31 or 63 are undefined.
8263 			 * This includes shifts by a negative number.
8264 			 */
8265 			mark_reg_unknown(env, regs, insn->dst_reg);
8266 			break;
8267 		}
8268 		if (alu32)
8269 			scalar32_min_max_arsh(dst_reg, &src_reg);
8270 		else
8271 			scalar_min_max_arsh(dst_reg, &src_reg);
8272 		break;
8273 	default:
8274 		mark_reg_unknown(env, regs, insn->dst_reg);
8275 		break;
8276 	}
8277 
8278 	/* ALU32 ops are zero extended into 64bit register */
8279 	if (alu32)
8280 		zext_32_to_64(dst_reg);
8281 
8282 	__update_reg_bounds(dst_reg);
8283 	__reg_deduce_bounds(dst_reg);
8284 	__reg_bound_offset(dst_reg);
8285 	return 0;
8286 }
8287 
8288 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8289  * and var_off.
8290  */
8291 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8292 				   struct bpf_insn *insn)
8293 {
8294 	struct bpf_verifier_state *vstate = env->cur_state;
8295 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8296 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8297 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8298 	u8 opcode = BPF_OP(insn->code);
8299 	int err;
8300 
8301 	dst_reg = &regs[insn->dst_reg];
8302 	src_reg = NULL;
8303 	if (dst_reg->type != SCALAR_VALUE)
8304 		ptr_reg = dst_reg;
8305 	else
8306 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8307 		 * incorrectly propagated into other registers by find_equal_scalars()
8308 		 */
8309 		dst_reg->id = 0;
8310 	if (BPF_SRC(insn->code) == BPF_X) {
8311 		src_reg = &regs[insn->src_reg];
8312 		if (src_reg->type != SCALAR_VALUE) {
8313 			if (dst_reg->type != SCALAR_VALUE) {
8314 				/* Combining two pointers by any ALU op yields
8315 				 * an arbitrary scalar. Disallow all math except
8316 				 * pointer subtraction
8317 				 */
8318 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8319 					mark_reg_unknown(env, regs, insn->dst_reg);
8320 					return 0;
8321 				}
8322 				verbose(env, "R%d pointer %s pointer prohibited\n",
8323 					insn->dst_reg,
8324 					bpf_alu_string[opcode >> 4]);
8325 				return -EACCES;
8326 			} else {
8327 				/* scalar += pointer
8328 				 * This is legal, but we have to reverse our
8329 				 * src/dest handling in computing the range
8330 				 */
8331 				err = mark_chain_precision(env, insn->dst_reg);
8332 				if (err)
8333 					return err;
8334 				return adjust_ptr_min_max_vals(env, insn,
8335 							       src_reg, dst_reg);
8336 			}
8337 		} else if (ptr_reg) {
8338 			/* pointer += scalar */
8339 			err = mark_chain_precision(env, insn->src_reg);
8340 			if (err)
8341 				return err;
8342 			return adjust_ptr_min_max_vals(env, insn,
8343 						       dst_reg, src_reg);
8344 		}
8345 	} else {
8346 		/* Pretend the src is a reg with a known value, since we only
8347 		 * need to be able to read from this state.
8348 		 */
8349 		off_reg.type = SCALAR_VALUE;
8350 		__mark_reg_known(&off_reg, insn->imm);
8351 		src_reg = &off_reg;
8352 		if (ptr_reg) /* pointer += K */
8353 			return adjust_ptr_min_max_vals(env, insn,
8354 						       ptr_reg, src_reg);
8355 	}
8356 
8357 	/* Got here implies adding two SCALAR_VALUEs */
8358 	if (WARN_ON_ONCE(ptr_reg)) {
8359 		print_verifier_state(env, state, true);
8360 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8361 		return -EINVAL;
8362 	}
8363 	if (WARN_ON(!src_reg)) {
8364 		print_verifier_state(env, state, true);
8365 		verbose(env, "verifier internal error: no src_reg\n");
8366 		return -EINVAL;
8367 	}
8368 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8369 }
8370 
8371 /* check validity of 32-bit and 64-bit arithmetic operations */
8372 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8373 {
8374 	struct bpf_reg_state *regs = cur_regs(env);
8375 	u8 opcode = BPF_OP(insn->code);
8376 	int err;
8377 
8378 	if (opcode == BPF_END || opcode == BPF_NEG) {
8379 		if (opcode == BPF_NEG) {
8380 			if (BPF_SRC(insn->code) != 0 ||
8381 			    insn->src_reg != BPF_REG_0 ||
8382 			    insn->off != 0 || insn->imm != 0) {
8383 				verbose(env, "BPF_NEG uses reserved fields\n");
8384 				return -EINVAL;
8385 			}
8386 		} else {
8387 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8388 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8389 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8390 				verbose(env, "BPF_END uses reserved fields\n");
8391 				return -EINVAL;
8392 			}
8393 		}
8394 
8395 		/* check src operand */
8396 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8397 		if (err)
8398 			return err;
8399 
8400 		if (is_pointer_value(env, insn->dst_reg)) {
8401 			verbose(env, "R%d pointer arithmetic prohibited\n",
8402 				insn->dst_reg);
8403 			return -EACCES;
8404 		}
8405 
8406 		/* check dest operand */
8407 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8408 		if (err)
8409 			return err;
8410 
8411 	} else if (opcode == BPF_MOV) {
8412 
8413 		if (BPF_SRC(insn->code) == BPF_X) {
8414 			if (insn->imm != 0 || insn->off != 0) {
8415 				verbose(env, "BPF_MOV uses reserved fields\n");
8416 				return -EINVAL;
8417 			}
8418 
8419 			/* check src operand */
8420 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8421 			if (err)
8422 				return err;
8423 		} else {
8424 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8425 				verbose(env, "BPF_MOV uses reserved fields\n");
8426 				return -EINVAL;
8427 			}
8428 		}
8429 
8430 		/* check dest operand, mark as required later */
8431 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8432 		if (err)
8433 			return err;
8434 
8435 		if (BPF_SRC(insn->code) == BPF_X) {
8436 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8437 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8438 
8439 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8440 				/* case: R1 = R2
8441 				 * copy register state to dest reg
8442 				 */
8443 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8444 					/* Assign src and dst registers the same ID
8445 					 * that will be used by find_equal_scalars()
8446 					 * to propagate min/max range.
8447 					 */
8448 					src_reg->id = ++env->id_gen;
8449 				*dst_reg = *src_reg;
8450 				dst_reg->live |= REG_LIVE_WRITTEN;
8451 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8452 			} else {
8453 				/* R1 = (u32) R2 */
8454 				if (is_pointer_value(env, insn->src_reg)) {
8455 					verbose(env,
8456 						"R%d partial copy of pointer\n",
8457 						insn->src_reg);
8458 					return -EACCES;
8459 				} else if (src_reg->type == SCALAR_VALUE) {
8460 					*dst_reg = *src_reg;
8461 					/* Make sure ID is cleared otherwise
8462 					 * dst_reg min/max could be incorrectly
8463 					 * propagated into src_reg by find_equal_scalars()
8464 					 */
8465 					dst_reg->id = 0;
8466 					dst_reg->live |= REG_LIVE_WRITTEN;
8467 					dst_reg->subreg_def = env->insn_idx + 1;
8468 				} else {
8469 					mark_reg_unknown(env, regs,
8470 							 insn->dst_reg);
8471 				}
8472 				zext_32_to_64(dst_reg);
8473 
8474 				__update_reg_bounds(dst_reg);
8475 				__reg_deduce_bounds(dst_reg);
8476 				__reg_bound_offset(dst_reg);
8477 			}
8478 		} else {
8479 			/* case: R = imm
8480 			 * remember the value we stored into this reg
8481 			 */
8482 			/* clear any state __mark_reg_known doesn't set */
8483 			mark_reg_unknown(env, regs, insn->dst_reg);
8484 			regs[insn->dst_reg].type = SCALAR_VALUE;
8485 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8486 				__mark_reg_known(regs + insn->dst_reg,
8487 						 insn->imm);
8488 			} else {
8489 				__mark_reg_known(regs + insn->dst_reg,
8490 						 (u32)insn->imm);
8491 			}
8492 		}
8493 
8494 	} else if (opcode > BPF_END) {
8495 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8496 		return -EINVAL;
8497 
8498 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8499 
8500 		if (BPF_SRC(insn->code) == BPF_X) {
8501 			if (insn->imm != 0 || insn->off != 0) {
8502 				verbose(env, "BPF_ALU uses reserved fields\n");
8503 				return -EINVAL;
8504 			}
8505 			/* check src1 operand */
8506 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8507 			if (err)
8508 				return err;
8509 		} else {
8510 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8511 				verbose(env, "BPF_ALU uses reserved fields\n");
8512 				return -EINVAL;
8513 			}
8514 		}
8515 
8516 		/* check src2 operand */
8517 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8518 		if (err)
8519 			return err;
8520 
8521 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8522 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8523 			verbose(env, "div by zero\n");
8524 			return -EINVAL;
8525 		}
8526 
8527 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8528 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8529 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8530 
8531 			if (insn->imm < 0 || insn->imm >= size) {
8532 				verbose(env, "invalid shift %d\n", insn->imm);
8533 				return -EINVAL;
8534 			}
8535 		}
8536 
8537 		/* check dest operand */
8538 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8539 		if (err)
8540 			return err;
8541 
8542 		return adjust_reg_min_max_vals(env, insn);
8543 	}
8544 
8545 	return 0;
8546 }
8547 
8548 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8549 				     struct bpf_reg_state *dst_reg,
8550 				     enum bpf_reg_type type, int new_range)
8551 {
8552 	struct bpf_reg_state *reg;
8553 	int i;
8554 
8555 	for (i = 0; i < MAX_BPF_REG; i++) {
8556 		reg = &state->regs[i];
8557 		if (reg->type == type && reg->id == dst_reg->id)
8558 			/* keep the maximum range already checked */
8559 			reg->range = max(reg->range, new_range);
8560 	}
8561 
8562 	bpf_for_each_spilled_reg(i, state, reg) {
8563 		if (!reg)
8564 			continue;
8565 		if (reg->type == type && reg->id == dst_reg->id)
8566 			reg->range = max(reg->range, new_range);
8567 	}
8568 }
8569 
8570 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8571 				   struct bpf_reg_state *dst_reg,
8572 				   enum bpf_reg_type type,
8573 				   bool range_right_open)
8574 {
8575 	int new_range, i;
8576 
8577 	if (dst_reg->off < 0 ||
8578 	    (dst_reg->off == 0 && range_right_open))
8579 		/* This doesn't give us any range */
8580 		return;
8581 
8582 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8583 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8584 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8585 		 * than pkt_end, but that's because it's also less than pkt.
8586 		 */
8587 		return;
8588 
8589 	new_range = dst_reg->off;
8590 	if (range_right_open)
8591 		new_range++;
8592 
8593 	/* Examples for register markings:
8594 	 *
8595 	 * pkt_data in dst register:
8596 	 *
8597 	 *   r2 = r3;
8598 	 *   r2 += 8;
8599 	 *   if (r2 > pkt_end) goto <handle exception>
8600 	 *   <access okay>
8601 	 *
8602 	 *   r2 = r3;
8603 	 *   r2 += 8;
8604 	 *   if (r2 < pkt_end) goto <access okay>
8605 	 *   <handle exception>
8606 	 *
8607 	 *   Where:
8608 	 *     r2 == dst_reg, pkt_end == src_reg
8609 	 *     r2=pkt(id=n,off=8,r=0)
8610 	 *     r3=pkt(id=n,off=0,r=0)
8611 	 *
8612 	 * pkt_data in src register:
8613 	 *
8614 	 *   r2 = r3;
8615 	 *   r2 += 8;
8616 	 *   if (pkt_end >= r2) goto <access okay>
8617 	 *   <handle exception>
8618 	 *
8619 	 *   r2 = r3;
8620 	 *   r2 += 8;
8621 	 *   if (pkt_end <= r2) goto <handle exception>
8622 	 *   <access okay>
8623 	 *
8624 	 *   Where:
8625 	 *     pkt_end == dst_reg, r2 == src_reg
8626 	 *     r2=pkt(id=n,off=8,r=0)
8627 	 *     r3=pkt(id=n,off=0,r=0)
8628 	 *
8629 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8630 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8631 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8632 	 * the check.
8633 	 */
8634 
8635 	/* If our ids match, then we must have the same max_value.  And we
8636 	 * don't care about the other reg's fixed offset, since if it's too big
8637 	 * the range won't allow anything.
8638 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8639 	 */
8640 	for (i = 0; i <= vstate->curframe; i++)
8641 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8642 					 new_range);
8643 }
8644 
8645 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8646 {
8647 	struct tnum subreg = tnum_subreg(reg->var_off);
8648 	s32 sval = (s32)val;
8649 
8650 	switch (opcode) {
8651 	case BPF_JEQ:
8652 		if (tnum_is_const(subreg))
8653 			return !!tnum_equals_const(subreg, val);
8654 		break;
8655 	case BPF_JNE:
8656 		if (tnum_is_const(subreg))
8657 			return !tnum_equals_const(subreg, val);
8658 		break;
8659 	case BPF_JSET:
8660 		if ((~subreg.mask & subreg.value) & val)
8661 			return 1;
8662 		if (!((subreg.mask | subreg.value) & val))
8663 			return 0;
8664 		break;
8665 	case BPF_JGT:
8666 		if (reg->u32_min_value > val)
8667 			return 1;
8668 		else if (reg->u32_max_value <= val)
8669 			return 0;
8670 		break;
8671 	case BPF_JSGT:
8672 		if (reg->s32_min_value > sval)
8673 			return 1;
8674 		else if (reg->s32_max_value <= sval)
8675 			return 0;
8676 		break;
8677 	case BPF_JLT:
8678 		if (reg->u32_max_value < val)
8679 			return 1;
8680 		else if (reg->u32_min_value >= val)
8681 			return 0;
8682 		break;
8683 	case BPF_JSLT:
8684 		if (reg->s32_max_value < sval)
8685 			return 1;
8686 		else if (reg->s32_min_value >= sval)
8687 			return 0;
8688 		break;
8689 	case BPF_JGE:
8690 		if (reg->u32_min_value >= val)
8691 			return 1;
8692 		else if (reg->u32_max_value < val)
8693 			return 0;
8694 		break;
8695 	case BPF_JSGE:
8696 		if (reg->s32_min_value >= sval)
8697 			return 1;
8698 		else if (reg->s32_max_value < sval)
8699 			return 0;
8700 		break;
8701 	case BPF_JLE:
8702 		if (reg->u32_max_value <= val)
8703 			return 1;
8704 		else if (reg->u32_min_value > val)
8705 			return 0;
8706 		break;
8707 	case BPF_JSLE:
8708 		if (reg->s32_max_value <= sval)
8709 			return 1;
8710 		else if (reg->s32_min_value > sval)
8711 			return 0;
8712 		break;
8713 	}
8714 
8715 	return -1;
8716 }
8717 
8718 
8719 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8720 {
8721 	s64 sval = (s64)val;
8722 
8723 	switch (opcode) {
8724 	case BPF_JEQ:
8725 		if (tnum_is_const(reg->var_off))
8726 			return !!tnum_equals_const(reg->var_off, val);
8727 		break;
8728 	case BPF_JNE:
8729 		if (tnum_is_const(reg->var_off))
8730 			return !tnum_equals_const(reg->var_off, val);
8731 		break;
8732 	case BPF_JSET:
8733 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8734 			return 1;
8735 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8736 			return 0;
8737 		break;
8738 	case BPF_JGT:
8739 		if (reg->umin_value > val)
8740 			return 1;
8741 		else if (reg->umax_value <= val)
8742 			return 0;
8743 		break;
8744 	case BPF_JSGT:
8745 		if (reg->smin_value > sval)
8746 			return 1;
8747 		else if (reg->smax_value <= sval)
8748 			return 0;
8749 		break;
8750 	case BPF_JLT:
8751 		if (reg->umax_value < val)
8752 			return 1;
8753 		else if (reg->umin_value >= val)
8754 			return 0;
8755 		break;
8756 	case BPF_JSLT:
8757 		if (reg->smax_value < sval)
8758 			return 1;
8759 		else if (reg->smin_value >= sval)
8760 			return 0;
8761 		break;
8762 	case BPF_JGE:
8763 		if (reg->umin_value >= val)
8764 			return 1;
8765 		else if (reg->umax_value < val)
8766 			return 0;
8767 		break;
8768 	case BPF_JSGE:
8769 		if (reg->smin_value >= sval)
8770 			return 1;
8771 		else if (reg->smax_value < sval)
8772 			return 0;
8773 		break;
8774 	case BPF_JLE:
8775 		if (reg->umax_value <= val)
8776 			return 1;
8777 		else if (reg->umin_value > val)
8778 			return 0;
8779 		break;
8780 	case BPF_JSLE:
8781 		if (reg->smax_value <= sval)
8782 			return 1;
8783 		else if (reg->smin_value > sval)
8784 			return 0;
8785 		break;
8786 	}
8787 
8788 	return -1;
8789 }
8790 
8791 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8792  * and return:
8793  *  1 - branch will be taken and "goto target" will be executed
8794  *  0 - branch will not be taken and fall-through to next insn
8795  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8796  *      range [0,10]
8797  */
8798 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8799 			   bool is_jmp32)
8800 {
8801 	if (__is_pointer_value(false, reg)) {
8802 		if (!reg_type_not_null(reg->type))
8803 			return -1;
8804 
8805 		/* If pointer is valid tests against zero will fail so we can
8806 		 * use this to direct branch taken.
8807 		 */
8808 		if (val != 0)
8809 			return -1;
8810 
8811 		switch (opcode) {
8812 		case BPF_JEQ:
8813 			return 0;
8814 		case BPF_JNE:
8815 			return 1;
8816 		default:
8817 			return -1;
8818 		}
8819 	}
8820 
8821 	if (is_jmp32)
8822 		return is_branch32_taken(reg, val, opcode);
8823 	return is_branch64_taken(reg, val, opcode);
8824 }
8825 
8826 static int flip_opcode(u32 opcode)
8827 {
8828 	/* How can we transform "a <op> b" into "b <op> a"? */
8829 	static const u8 opcode_flip[16] = {
8830 		/* these stay the same */
8831 		[BPF_JEQ  >> 4] = BPF_JEQ,
8832 		[BPF_JNE  >> 4] = BPF_JNE,
8833 		[BPF_JSET >> 4] = BPF_JSET,
8834 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8835 		[BPF_JGE  >> 4] = BPF_JLE,
8836 		[BPF_JGT  >> 4] = BPF_JLT,
8837 		[BPF_JLE  >> 4] = BPF_JGE,
8838 		[BPF_JLT  >> 4] = BPF_JGT,
8839 		[BPF_JSGE >> 4] = BPF_JSLE,
8840 		[BPF_JSGT >> 4] = BPF_JSLT,
8841 		[BPF_JSLE >> 4] = BPF_JSGE,
8842 		[BPF_JSLT >> 4] = BPF_JSGT
8843 	};
8844 	return opcode_flip[opcode >> 4];
8845 }
8846 
8847 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8848 				   struct bpf_reg_state *src_reg,
8849 				   u8 opcode)
8850 {
8851 	struct bpf_reg_state *pkt;
8852 
8853 	if (src_reg->type == PTR_TO_PACKET_END) {
8854 		pkt = dst_reg;
8855 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8856 		pkt = src_reg;
8857 		opcode = flip_opcode(opcode);
8858 	} else {
8859 		return -1;
8860 	}
8861 
8862 	if (pkt->range >= 0)
8863 		return -1;
8864 
8865 	switch (opcode) {
8866 	case BPF_JLE:
8867 		/* pkt <= pkt_end */
8868 		fallthrough;
8869 	case BPF_JGT:
8870 		/* pkt > pkt_end */
8871 		if (pkt->range == BEYOND_PKT_END)
8872 			/* pkt has at last one extra byte beyond pkt_end */
8873 			return opcode == BPF_JGT;
8874 		break;
8875 	case BPF_JLT:
8876 		/* pkt < pkt_end */
8877 		fallthrough;
8878 	case BPF_JGE:
8879 		/* pkt >= pkt_end */
8880 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8881 			return opcode == BPF_JGE;
8882 		break;
8883 	}
8884 	return -1;
8885 }
8886 
8887 /* Adjusts the register min/max values in the case that the dst_reg is the
8888  * variable register that we are working on, and src_reg is a constant or we're
8889  * simply doing a BPF_K check.
8890  * In JEQ/JNE cases we also adjust the var_off values.
8891  */
8892 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8893 			    struct bpf_reg_state *false_reg,
8894 			    u64 val, u32 val32,
8895 			    u8 opcode, bool is_jmp32)
8896 {
8897 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8898 	struct tnum false_64off = false_reg->var_off;
8899 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8900 	struct tnum true_64off = true_reg->var_off;
8901 	s64 sval = (s64)val;
8902 	s32 sval32 = (s32)val32;
8903 
8904 	/* If the dst_reg is a pointer, we can't learn anything about its
8905 	 * variable offset from the compare (unless src_reg were a pointer into
8906 	 * the same object, but we don't bother with that.
8907 	 * Since false_reg and true_reg have the same type by construction, we
8908 	 * only need to check one of them for pointerness.
8909 	 */
8910 	if (__is_pointer_value(false, false_reg))
8911 		return;
8912 
8913 	switch (opcode) {
8914 	case BPF_JEQ:
8915 	case BPF_JNE:
8916 	{
8917 		struct bpf_reg_state *reg =
8918 			opcode == BPF_JEQ ? true_reg : false_reg;
8919 
8920 		/* JEQ/JNE comparison doesn't change the register equivalence.
8921 		 * r1 = r2;
8922 		 * if (r1 == 42) goto label;
8923 		 * ...
8924 		 * label: // here both r1 and r2 are known to be 42.
8925 		 *
8926 		 * Hence when marking register as known preserve it's ID.
8927 		 */
8928 		if (is_jmp32)
8929 			__mark_reg32_known(reg, val32);
8930 		else
8931 			___mark_reg_known(reg, val);
8932 		break;
8933 	}
8934 	case BPF_JSET:
8935 		if (is_jmp32) {
8936 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8937 			if (is_power_of_2(val32))
8938 				true_32off = tnum_or(true_32off,
8939 						     tnum_const(val32));
8940 		} else {
8941 			false_64off = tnum_and(false_64off, tnum_const(~val));
8942 			if (is_power_of_2(val))
8943 				true_64off = tnum_or(true_64off,
8944 						     tnum_const(val));
8945 		}
8946 		break;
8947 	case BPF_JGE:
8948 	case BPF_JGT:
8949 	{
8950 		if (is_jmp32) {
8951 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8952 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8953 
8954 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8955 						       false_umax);
8956 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8957 						      true_umin);
8958 		} else {
8959 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8960 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8961 
8962 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8963 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8964 		}
8965 		break;
8966 	}
8967 	case BPF_JSGE:
8968 	case BPF_JSGT:
8969 	{
8970 		if (is_jmp32) {
8971 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8972 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8973 
8974 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8975 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8976 		} else {
8977 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8978 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8979 
8980 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8981 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8982 		}
8983 		break;
8984 	}
8985 	case BPF_JLE:
8986 	case BPF_JLT:
8987 	{
8988 		if (is_jmp32) {
8989 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8990 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8991 
8992 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8993 						       false_umin);
8994 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8995 						      true_umax);
8996 		} else {
8997 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8998 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8999 
9000 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9001 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9002 		}
9003 		break;
9004 	}
9005 	case BPF_JSLE:
9006 	case BPF_JSLT:
9007 	{
9008 		if (is_jmp32) {
9009 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9010 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9011 
9012 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9013 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9014 		} else {
9015 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9016 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9017 
9018 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9019 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9020 		}
9021 		break;
9022 	}
9023 	default:
9024 		return;
9025 	}
9026 
9027 	if (is_jmp32) {
9028 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9029 					     tnum_subreg(false_32off));
9030 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9031 					    tnum_subreg(true_32off));
9032 		__reg_combine_32_into_64(false_reg);
9033 		__reg_combine_32_into_64(true_reg);
9034 	} else {
9035 		false_reg->var_off = false_64off;
9036 		true_reg->var_off = true_64off;
9037 		__reg_combine_64_into_32(false_reg);
9038 		__reg_combine_64_into_32(true_reg);
9039 	}
9040 }
9041 
9042 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9043  * the variable reg.
9044  */
9045 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9046 				struct bpf_reg_state *false_reg,
9047 				u64 val, u32 val32,
9048 				u8 opcode, bool is_jmp32)
9049 {
9050 	opcode = flip_opcode(opcode);
9051 	/* This uses zero as "not present in table"; luckily the zero opcode,
9052 	 * BPF_JA, can't get here.
9053 	 */
9054 	if (opcode)
9055 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9056 }
9057 
9058 /* Regs are known to be equal, so intersect their min/max/var_off */
9059 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9060 				  struct bpf_reg_state *dst_reg)
9061 {
9062 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9063 							dst_reg->umin_value);
9064 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9065 							dst_reg->umax_value);
9066 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9067 							dst_reg->smin_value);
9068 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9069 							dst_reg->smax_value);
9070 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9071 							     dst_reg->var_off);
9072 	/* We might have learned new bounds from the var_off. */
9073 	__update_reg_bounds(src_reg);
9074 	__update_reg_bounds(dst_reg);
9075 	/* We might have learned something about the sign bit. */
9076 	__reg_deduce_bounds(src_reg);
9077 	__reg_deduce_bounds(dst_reg);
9078 	/* We might have learned some bits from the bounds. */
9079 	__reg_bound_offset(src_reg);
9080 	__reg_bound_offset(dst_reg);
9081 	/* Intersecting with the old var_off might have improved our bounds
9082 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
9083 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
9084 	 */
9085 	__update_reg_bounds(src_reg);
9086 	__update_reg_bounds(dst_reg);
9087 }
9088 
9089 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9090 				struct bpf_reg_state *true_dst,
9091 				struct bpf_reg_state *false_src,
9092 				struct bpf_reg_state *false_dst,
9093 				u8 opcode)
9094 {
9095 	switch (opcode) {
9096 	case BPF_JEQ:
9097 		__reg_combine_min_max(true_src, true_dst);
9098 		break;
9099 	case BPF_JNE:
9100 		__reg_combine_min_max(false_src, false_dst);
9101 		break;
9102 	}
9103 }
9104 
9105 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9106 				 struct bpf_reg_state *reg, u32 id,
9107 				 bool is_null)
9108 {
9109 	if (type_may_be_null(reg->type) && reg->id == id &&
9110 	    !WARN_ON_ONCE(!reg->id)) {
9111 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9112 				 !tnum_equals_const(reg->var_off, 0) ||
9113 				 reg->off)) {
9114 			/* Old offset (both fixed and variable parts) should
9115 			 * have been known-zero, because we don't allow pointer
9116 			 * arithmetic on pointers that might be NULL. If we
9117 			 * see this happening, don't convert the register.
9118 			 */
9119 			return;
9120 		}
9121 		if (is_null) {
9122 			reg->type = SCALAR_VALUE;
9123 			/* We don't need id and ref_obj_id from this point
9124 			 * onwards anymore, thus we should better reset it,
9125 			 * so that state pruning has chances to take effect.
9126 			 */
9127 			reg->id = 0;
9128 			reg->ref_obj_id = 0;
9129 
9130 			return;
9131 		}
9132 
9133 		mark_ptr_not_null_reg(reg);
9134 
9135 		if (!reg_may_point_to_spin_lock(reg)) {
9136 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9137 			 * in release_reg_references().
9138 			 *
9139 			 * reg->id is still used by spin_lock ptr. Other
9140 			 * than spin_lock ptr type, reg->id can be reset.
9141 			 */
9142 			reg->id = 0;
9143 		}
9144 	}
9145 }
9146 
9147 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9148 				    bool is_null)
9149 {
9150 	struct bpf_reg_state *reg;
9151 	int i;
9152 
9153 	for (i = 0; i < MAX_BPF_REG; i++)
9154 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9155 
9156 	bpf_for_each_spilled_reg(i, state, reg) {
9157 		if (!reg)
9158 			continue;
9159 		mark_ptr_or_null_reg(state, reg, id, is_null);
9160 	}
9161 }
9162 
9163 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9164  * be folded together at some point.
9165  */
9166 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9167 				  bool is_null)
9168 {
9169 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9170 	struct bpf_reg_state *regs = state->regs;
9171 	u32 ref_obj_id = regs[regno].ref_obj_id;
9172 	u32 id = regs[regno].id;
9173 	int i;
9174 
9175 	if (ref_obj_id && ref_obj_id == id && is_null)
9176 		/* regs[regno] is in the " == NULL" branch.
9177 		 * No one could have freed the reference state before
9178 		 * doing the NULL check.
9179 		 */
9180 		WARN_ON_ONCE(release_reference_state(state, id));
9181 
9182 	for (i = 0; i <= vstate->curframe; i++)
9183 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9184 }
9185 
9186 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9187 				   struct bpf_reg_state *dst_reg,
9188 				   struct bpf_reg_state *src_reg,
9189 				   struct bpf_verifier_state *this_branch,
9190 				   struct bpf_verifier_state *other_branch)
9191 {
9192 	if (BPF_SRC(insn->code) != BPF_X)
9193 		return false;
9194 
9195 	/* Pointers are always 64-bit. */
9196 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9197 		return false;
9198 
9199 	switch (BPF_OP(insn->code)) {
9200 	case BPF_JGT:
9201 		if ((dst_reg->type == PTR_TO_PACKET &&
9202 		     src_reg->type == PTR_TO_PACKET_END) ||
9203 		    (dst_reg->type == PTR_TO_PACKET_META &&
9204 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9205 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9206 			find_good_pkt_pointers(this_branch, dst_reg,
9207 					       dst_reg->type, false);
9208 			mark_pkt_end(other_branch, insn->dst_reg, true);
9209 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9210 			    src_reg->type == PTR_TO_PACKET) ||
9211 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9212 			    src_reg->type == PTR_TO_PACKET_META)) {
9213 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9214 			find_good_pkt_pointers(other_branch, src_reg,
9215 					       src_reg->type, true);
9216 			mark_pkt_end(this_branch, insn->src_reg, false);
9217 		} else {
9218 			return false;
9219 		}
9220 		break;
9221 	case BPF_JLT:
9222 		if ((dst_reg->type == PTR_TO_PACKET &&
9223 		     src_reg->type == PTR_TO_PACKET_END) ||
9224 		    (dst_reg->type == PTR_TO_PACKET_META &&
9225 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9226 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9227 			find_good_pkt_pointers(other_branch, dst_reg,
9228 					       dst_reg->type, true);
9229 			mark_pkt_end(this_branch, insn->dst_reg, false);
9230 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9231 			    src_reg->type == PTR_TO_PACKET) ||
9232 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9233 			    src_reg->type == PTR_TO_PACKET_META)) {
9234 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9235 			find_good_pkt_pointers(this_branch, src_reg,
9236 					       src_reg->type, false);
9237 			mark_pkt_end(other_branch, insn->src_reg, true);
9238 		} else {
9239 			return false;
9240 		}
9241 		break;
9242 	case BPF_JGE:
9243 		if ((dst_reg->type == PTR_TO_PACKET &&
9244 		     src_reg->type == PTR_TO_PACKET_END) ||
9245 		    (dst_reg->type == PTR_TO_PACKET_META &&
9246 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9247 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9248 			find_good_pkt_pointers(this_branch, dst_reg,
9249 					       dst_reg->type, true);
9250 			mark_pkt_end(other_branch, insn->dst_reg, false);
9251 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9252 			    src_reg->type == PTR_TO_PACKET) ||
9253 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9254 			    src_reg->type == PTR_TO_PACKET_META)) {
9255 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9256 			find_good_pkt_pointers(other_branch, src_reg,
9257 					       src_reg->type, false);
9258 			mark_pkt_end(this_branch, insn->src_reg, true);
9259 		} else {
9260 			return false;
9261 		}
9262 		break;
9263 	case BPF_JLE:
9264 		if ((dst_reg->type == PTR_TO_PACKET &&
9265 		     src_reg->type == PTR_TO_PACKET_END) ||
9266 		    (dst_reg->type == PTR_TO_PACKET_META &&
9267 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9268 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9269 			find_good_pkt_pointers(other_branch, dst_reg,
9270 					       dst_reg->type, false);
9271 			mark_pkt_end(this_branch, insn->dst_reg, true);
9272 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9273 			    src_reg->type == PTR_TO_PACKET) ||
9274 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9275 			    src_reg->type == PTR_TO_PACKET_META)) {
9276 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9277 			find_good_pkt_pointers(this_branch, src_reg,
9278 					       src_reg->type, true);
9279 			mark_pkt_end(other_branch, insn->src_reg, false);
9280 		} else {
9281 			return false;
9282 		}
9283 		break;
9284 	default:
9285 		return false;
9286 	}
9287 
9288 	return true;
9289 }
9290 
9291 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9292 			       struct bpf_reg_state *known_reg)
9293 {
9294 	struct bpf_func_state *state;
9295 	struct bpf_reg_state *reg;
9296 	int i, j;
9297 
9298 	for (i = 0; i <= vstate->curframe; i++) {
9299 		state = vstate->frame[i];
9300 		for (j = 0; j < MAX_BPF_REG; j++) {
9301 			reg = &state->regs[j];
9302 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9303 				*reg = *known_reg;
9304 		}
9305 
9306 		bpf_for_each_spilled_reg(j, state, reg) {
9307 			if (!reg)
9308 				continue;
9309 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9310 				*reg = *known_reg;
9311 		}
9312 	}
9313 }
9314 
9315 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9316 			     struct bpf_insn *insn, int *insn_idx)
9317 {
9318 	struct bpf_verifier_state *this_branch = env->cur_state;
9319 	struct bpf_verifier_state *other_branch;
9320 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9321 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9322 	u8 opcode = BPF_OP(insn->code);
9323 	bool is_jmp32;
9324 	int pred = -1;
9325 	int err;
9326 
9327 	/* Only conditional jumps are expected to reach here. */
9328 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9329 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9330 		return -EINVAL;
9331 	}
9332 
9333 	if (BPF_SRC(insn->code) == BPF_X) {
9334 		if (insn->imm != 0) {
9335 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9336 			return -EINVAL;
9337 		}
9338 
9339 		/* check src1 operand */
9340 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9341 		if (err)
9342 			return err;
9343 
9344 		if (is_pointer_value(env, insn->src_reg)) {
9345 			verbose(env, "R%d pointer comparison prohibited\n",
9346 				insn->src_reg);
9347 			return -EACCES;
9348 		}
9349 		src_reg = &regs[insn->src_reg];
9350 	} else {
9351 		if (insn->src_reg != BPF_REG_0) {
9352 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9353 			return -EINVAL;
9354 		}
9355 	}
9356 
9357 	/* check src2 operand */
9358 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9359 	if (err)
9360 		return err;
9361 
9362 	dst_reg = &regs[insn->dst_reg];
9363 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9364 
9365 	if (BPF_SRC(insn->code) == BPF_K) {
9366 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9367 	} else if (src_reg->type == SCALAR_VALUE &&
9368 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9369 		pred = is_branch_taken(dst_reg,
9370 				       tnum_subreg(src_reg->var_off).value,
9371 				       opcode,
9372 				       is_jmp32);
9373 	} else if (src_reg->type == SCALAR_VALUE &&
9374 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9375 		pred = is_branch_taken(dst_reg,
9376 				       src_reg->var_off.value,
9377 				       opcode,
9378 				       is_jmp32);
9379 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9380 		   reg_is_pkt_pointer_any(src_reg) &&
9381 		   !is_jmp32) {
9382 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9383 	}
9384 
9385 	if (pred >= 0) {
9386 		/* If we get here with a dst_reg pointer type it is because
9387 		 * above is_branch_taken() special cased the 0 comparison.
9388 		 */
9389 		if (!__is_pointer_value(false, dst_reg))
9390 			err = mark_chain_precision(env, insn->dst_reg);
9391 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9392 		    !__is_pointer_value(false, src_reg))
9393 			err = mark_chain_precision(env, insn->src_reg);
9394 		if (err)
9395 			return err;
9396 	}
9397 
9398 	if (pred == 1) {
9399 		/* Only follow the goto, ignore fall-through. If needed, push
9400 		 * the fall-through branch for simulation under speculative
9401 		 * execution.
9402 		 */
9403 		if (!env->bypass_spec_v1 &&
9404 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9405 					       *insn_idx))
9406 			return -EFAULT;
9407 		*insn_idx += insn->off;
9408 		return 0;
9409 	} else if (pred == 0) {
9410 		/* Only follow the fall-through branch, since that's where the
9411 		 * program will go. If needed, push the goto branch for
9412 		 * simulation under speculative execution.
9413 		 */
9414 		if (!env->bypass_spec_v1 &&
9415 		    !sanitize_speculative_path(env, insn,
9416 					       *insn_idx + insn->off + 1,
9417 					       *insn_idx))
9418 			return -EFAULT;
9419 		return 0;
9420 	}
9421 
9422 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9423 				  false);
9424 	if (!other_branch)
9425 		return -EFAULT;
9426 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9427 
9428 	/* detect if we are comparing against a constant value so we can adjust
9429 	 * our min/max values for our dst register.
9430 	 * this is only legit if both are scalars (or pointers to the same
9431 	 * object, I suppose, but we don't support that right now), because
9432 	 * otherwise the different base pointers mean the offsets aren't
9433 	 * comparable.
9434 	 */
9435 	if (BPF_SRC(insn->code) == BPF_X) {
9436 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9437 
9438 		if (dst_reg->type == SCALAR_VALUE &&
9439 		    src_reg->type == SCALAR_VALUE) {
9440 			if (tnum_is_const(src_reg->var_off) ||
9441 			    (is_jmp32 &&
9442 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9443 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9444 						dst_reg,
9445 						src_reg->var_off.value,
9446 						tnum_subreg(src_reg->var_off).value,
9447 						opcode, is_jmp32);
9448 			else if (tnum_is_const(dst_reg->var_off) ||
9449 				 (is_jmp32 &&
9450 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9451 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9452 						    src_reg,
9453 						    dst_reg->var_off.value,
9454 						    tnum_subreg(dst_reg->var_off).value,
9455 						    opcode, is_jmp32);
9456 			else if (!is_jmp32 &&
9457 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9458 				/* Comparing for equality, we can combine knowledge */
9459 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9460 						    &other_branch_regs[insn->dst_reg],
9461 						    src_reg, dst_reg, opcode);
9462 			if (src_reg->id &&
9463 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9464 				find_equal_scalars(this_branch, src_reg);
9465 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9466 			}
9467 
9468 		}
9469 	} else if (dst_reg->type == SCALAR_VALUE) {
9470 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9471 					dst_reg, insn->imm, (u32)insn->imm,
9472 					opcode, is_jmp32);
9473 	}
9474 
9475 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9476 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9477 		find_equal_scalars(this_branch, dst_reg);
9478 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9479 	}
9480 
9481 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9482 	 * NOTE: these optimizations below are related with pointer comparison
9483 	 *       which will never be JMP32.
9484 	 */
9485 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9486 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9487 	    type_may_be_null(dst_reg->type)) {
9488 		/* Mark all identical registers in each branch as either
9489 		 * safe or unknown depending R == 0 or R != 0 conditional.
9490 		 */
9491 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9492 				      opcode == BPF_JNE);
9493 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9494 				      opcode == BPF_JEQ);
9495 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9496 					   this_branch, other_branch) &&
9497 		   is_pointer_value(env, insn->dst_reg)) {
9498 		verbose(env, "R%d pointer comparison prohibited\n",
9499 			insn->dst_reg);
9500 		return -EACCES;
9501 	}
9502 	if (env->log.level & BPF_LOG_LEVEL)
9503 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
9504 	return 0;
9505 }
9506 
9507 /* verify BPF_LD_IMM64 instruction */
9508 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9509 {
9510 	struct bpf_insn_aux_data *aux = cur_aux(env);
9511 	struct bpf_reg_state *regs = cur_regs(env);
9512 	struct bpf_reg_state *dst_reg;
9513 	struct bpf_map *map;
9514 	int err;
9515 
9516 	if (BPF_SIZE(insn->code) != BPF_DW) {
9517 		verbose(env, "invalid BPF_LD_IMM insn\n");
9518 		return -EINVAL;
9519 	}
9520 	if (insn->off != 0) {
9521 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9522 		return -EINVAL;
9523 	}
9524 
9525 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9526 	if (err)
9527 		return err;
9528 
9529 	dst_reg = &regs[insn->dst_reg];
9530 	if (insn->src_reg == 0) {
9531 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9532 
9533 		dst_reg->type = SCALAR_VALUE;
9534 		__mark_reg_known(&regs[insn->dst_reg], imm);
9535 		return 0;
9536 	}
9537 
9538 	/* All special src_reg cases are listed below. From this point onwards
9539 	 * we either succeed and assign a corresponding dst_reg->type after
9540 	 * zeroing the offset, or fail and reject the program.
9541 	 */
9542 	mark_reg_known_zero(env, regs, insn->dst_reg);
9543 
9544 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9545 		dst_reg->type = aux->btf_var.reg_type;
9546 		switch (base_type(dst_reg->type)) {
9547 		case PTR_TO_MEM:
9548 			dst_reg->mem_size = aux->btf_var.mem_size;
9549 			break;
9550 		case PTR_TO_BTF_ID:
9551 		case PTR_TO_PERCPU_BTF_ID:
9552 			dst_reg->btf = aux->btf_var.btf;
9553 			dst_reg->btf_id = aux->btf_var.btf_id;
9554 			break;
9555 		default:
9556 			verbose(env, "bpf verifier is misconfigured\n");
9557 			return -EFAULT;
9558 		}
9559 		return 0;
9560 	}
9561 
9562 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9563 		struct bpf_prog_aux *aux = env->prog->aux;
9564 		u32 subprogno = find_subprog(env,
9565 					     env->insn_idx + insn->imm + 1);
9566 
9567 		if (!aux->func_info) {
9568 			verbose(env, "missing btf func_info\n");
9569 			return -EINVAL;
9570 		}
9571 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9572 			verbose(env, "callback function not static\n");
9573 			return -EINVAL;
9574 		}
9575 
9576 		dst_reg->type = PTR_TO_FUNC;
9577 		dst_reg->subprogno = subprogno;
9578 		return 0;
9579 	}
9580 
9581 	map = env->used_maps[aux->map_index];
9582 	dst_reg->map_ptr = map;
9583 
9584 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9585 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9586 		dst_reg->type = PTR_TO_MAP_VALUE;
9587 		dst_reg->off = aux->map_off;
9588 		if (map_value_has_spin_lock(map))
9589 			dst_reg->id = ++env->id_gen;
9590 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9591 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9592 		dst_reg->type = CONST_PTR_TO_MAP;
9593 	} else {
9594 		verbose(env, "bpf verifier is misconfigured\n");
9595 		return -EINVAL;
9596 	}
9597 
9598 	return 0;
9599 }
9600 
9601 static bool may_access_skb(enum bpf_prog_type type)
9602 {
9603 	switch (type) {
9604 	case BPF_PROG_TYPE_SOCKET_FILTER:
9605 	case BPF_PROG_TYPE_SCHED_CLS:
9606 	case BPF_PROG_TYPE_SCHED_ACT:
9607 		return true;
9608 	default:
9609 		return false;
9610 	}
9611 }
9612 
9613 /* verify safety of LD_ABS|LD_IND instructions:
9614  * - they can only appear in the programs where ctx == skb
9615  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9616  *   preserve R6-R9, and store return value into R0
9617  *
9618  * Implicit input:
9619  *   ctx == skb == R6 == CTX
9620  *
9621  * Explicit input:
9622  *   SRC == any register
9623  *   IMM == 32-bit immediate
9624  *
9625  * Output:
9626  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9627  */
9628 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9629 {
9630 	struct bpf_reg_state *regs = cur_regs(env);
9631 	static const int ctx_reg = BPF_REG_6;
9632 	u8 mode = BPF_MODE(insn->code);
9633 	int i, err;
9634 
9635 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9636 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9637 		return -EINVAL;
9638 	}
9639 
9640 	if (!env->ops->gen_ld_abs) {
9641 		verbose(env, "bpf verifier is misconfigured\n");
9642 		return -EINVAL;
9643 	}
9644 
9645 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9646 	    BPF_SIZE(insn->code) == BPF_DW ||
9647 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9648 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9649 		return -EINVAL;
9650 	}
9651 
9652 	/* check whether implicit source operand (register R6) is readable */
9653 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9654 	if (err)
9655 		return err;
9656 
9657 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9658 	 * gen_ld_abs() may terminate the program at runtime, leading to
9659 	 * reference leak.
9660 	 */
9661 	err = check_reference_leak(env);
9662 	if (err) {
9663 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9664 		return err;
9665 	}
9666 
9667 	if (env->cur_state->active_spin_lock) {
9668 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9669 		return -EINVAL;
9670 	}
9671 
9672 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9673 		verbose(env,
9674 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9675 		return -EINVAL;
9676 	}
9677 
9678 	if (mode == BPF_IND) {
9679 		/* check explicit source operand */
9680 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9681 		if (err)
9682 			return err;
9683 	}
9684 
9685 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
9686 	if (err < 0)
9687 		return err;
9688 
9689 	/* reset caller saved regs to unreadable */
9690 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9691 		mark_reg_not_init(env, regs, caller_saved[i]);
9692 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9693 	}
9694 
9695 	/* mark destination R0 register as readable, since it contains
9696 	 * the value fetched from the packet.
9697 	 * Already marked as written above.
9698 	 */
9699 	mark_reg_unknown(env, regs, BPF_REG_0);
9700 	/* ld_abs load up to 32-bit skb data. */
9701 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9702 	return 0;
9703 }
9704 
9705 static int check_return_code(struct bpf_verifier_env *env)
9706 {
9707 	struct tnum enforce_attach_type_range = tnum_unknown;
9708 	const struct bpf_prog *prog = env->prog;
9709 	struct bpf_reg_state *reg;
9710 	struct tnum range = tnum_range(0, 1);
9711 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9712 	int err;
9713 	struct bpf_func_state *frame = env->cur_state->frame[0];
9714 	const bool is_subprog = frame->subprogno;
9715 
9716 	/* LSM and struct_ops func-ptr's return type could be "void" */
9717 	if (!is_subprog &&
9718 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9719 	     prog_type == BPF_PROG_TYPE_LSM) &&
9720 	    !prog->aux->attach_func_proto->type)
9721 		return 0;
9722 
9723 	/* eBPF calling convention is such that R0 is used
9724 	 * to return the value from eBPF program.
9725 	 * Make sure that it's readable at this time
9726 	 * of bpf_exit, which means that program wrote
9727 	 * something into it earlier
9728 	 */
9729 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9730 	if (err)
9731 		return err;
9732 
9733 	if (is_pointer_value(env, BPF_REG_0)) {
9734 		verbose(env, "R0 leaks addr as return value\n");
9735 		return -EACCES;
9736 	}
9737 
9738 	reg = cur_regs(env) + BPF_REG_0;
9739 
9740 	if (frame->in_async_callback_fn) {
9741 		/* enforce return zero from async callbacks like timer */
9742 		if (reg->type != SCALAR_VALUE) {
9743 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9744 				reg_type_str(env, reg->type));
9745 			return -EINVAL;
9746 		}
9747 
9748 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9749 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9750 			return -EINVAL;
9751 		}
9752 		return 0;
9753 	}
9754 
9755 	if (is_subprog) {
9756 		if (reg->type != SCALAR_VALUE) {
9757 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9758 				reg_type_str(env, reg->type));
9759 			return -EINVAL;
9760 		}
9761 		return 0;
9762 	}
9763 
9764 	switch (prog_type) {
9765 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9766 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9767 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9768 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9769 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9770 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9771 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9772 			range = tnum_range(1, 1);
9773 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9774 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9775 			range = tnum_range(0, 3);
9776 		break;
9777 	case BPF_PROG_TYPE_CGROUP_SKB:
9778 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9779 			range = tnum_range(0, 3);
9780 			enforce_attach_type_range = tnum_range(2, 3);
9781 		}
9782 		break;
9783 	case BPF_PROG_TYPE_CGROUP_SOCK:
9784 	case BPF_PROG_TYPE_SOCK_OPS:
9785 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9786 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9787 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9788 		break;
9789 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9790 		if (!env->prog->aux->attach_btf_id)
9791 			return 0;
9792 		range = tnum_const(0);
9793 		break;
9794 	case BPF_PROG_TYPE_TRACING:
9795 		switch (env->prog->expected_attach_type) {
9796 		case BPF_TRACE_FENTRY:
9797 		case BPF_TRACE_FEXIT:
9798 			range = tnum_const(0);
9799 			break;
9800 		case BPF_TRACE_RAW_TP:
9801 		case BPF_MODIFY_RETURN:
9802 			return 0;
9803 		case BPF_TRACE_ITER:
9804 			break;
9805 		default:
9806 			return -ENOTSUPP;
9807 		}
9808 		break;
9809 	case BPF_PROG_TYPE_SK_LOOKUP:
9810 		range = tnum_range(SK_DROP, SK_PASS);
9811 		break;
9812 	case BPF_PROG_TYPE_EXT:
9813 		/* freplace program can return anything as its return value
9814 		 * depends on the to-be-replaced kernel func or bpf program.
9815 		 */
9816 	default:
9817 		return 0;
9818 	}
9819 
9820 	if (reg->type != SCALAR_VALUE) {
9821 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9822 			reg_type_str(env, reg->type));
9823 		return -EINVAL;
9824 	}
9825 
9826 	if (!tnum_in(range, reg->var_off)) {
9827 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9828 		return -EINVAL;
9829 	}
9830 
9831 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9832 	    tnum_in(enforce_attach_type_range, reg->var_off))
9833 		env->prog->enforce_expected_attach_type = 1;
9834 	return 0;
9835 }
9836 
9837 /* non-recursive DFS pseudo code
9838  * 1  procedure DFS-iterative(G,v):
9839  * 2      label v as discovered
9840  * 3      let S be a stack
9841  * 4      S.push(v)
9842  * 5      while S is not empty
9843  * 6            t <- S.pop()
9844  * 7            if t is what we're looking for:
9845  * 8                return t
9846  * 9            for all edges e in G.adjacentEdges(t) do
9847  * 10               if edge e is already labelled
9848  * 11                   continue with the next edge
9849  * 12               w <- G.adjacentVertex(t,e)
9850  * 13               if vertex w is not discovered and not explored
9851  * 14                   label e as tree-edge
9852  * 15                   label w as discovered
9853  * 16                   S.push(w)
9854  * 17                   continue at 5
9855  * 18               else if vertex w is discovered
9856  * 19                   label e as back-edge
9857  * 20               else
9858  * 21                   // vertex w is explored
9859  * 22                   label e as forward- or cross-edge
9860  * 23           label t as explored
9861  * 24           S.pop()
9862  *
9863  * convention:
9864  * 0x10 - discovered
9865  * 0x11 - discovered and fall-through edge labelled
9866  * 0x12 - discovered and fall-through and branch edges labelled
9867  * 0x20 - explored
9868  */
9869 
9870 enum {
9871 	DISCOVERED = 0x10,
9872 	EXPLORED = 0x20,
9873 	FALLTHROUGH = 1,
9874 	BRANCH = 2,
9875 };
9876 
9877 static u32 state_htab_size(struct bpf_verifier_env *env)
9878 {
9879 	return env->prog->len;
9880 }
9881 
9882 static struct bpf_verifier_state_list **explored_state(
9883 					struct bpf_verifier_env *env,
9884 					int idx)
9885 {
9886 	struct bpf_verifier_state *cur = env->cur_state;
9887 	struct bpf_func_state *state = cur->frame[cur->curframe];
9888 
9889 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9890 }
9891 
9892 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9893 {
9894 	env->insn_aux_data[idx].prune_point = true;
9895 }
9896 
9897 enum {
9898 	DONE_EXPLORING = 0,
9899 	KEEP_EXPLORING = 1,
9900 };
9901 
9902 /* t, w, e - match pseudo-code above:
9903  * t - index of current instruction
9904  * w - next instruction
9905  * e - edge
9906  */
9907 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9908 		     bool loop_ok)
9909 {
9910 	int *insn_stack = env->cfg.insn_stack;
9911 	int *insn_state = env->cfg.insn_state;
9912 
9913 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9914 		return DONE_EXPLORING;
9915 
9916 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9917 		return DONE_EXPLORING;
9918 
9919 	if (w < 0 || w >= env->prog->len) {
9920 		verbose_linfo(env, t, "%d: ", t);
9921 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9922 		return -EINVAL;
9923 	}
9924 
9925 	if (e == BRANCH)
9926 		/* mark branch target for state pruning */
9927 		init_explored_state(env, w);
9928 
9929 	if (insn_state[w] == 0) {
9930 		/* tree-edge */
9931 		insn_state[t] = DISCOVERED | e;
9932 		insn_state[w] = DISCOVERED;
9933 		if (env->cfg.cur_stack >= env->prog->len)
9934 			return -E2BIG;
9935 		insn_stack[env->cfg.cur_stack++] = w;
9936 		return KEEP_EXPLORING;
9937 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9938 		if (loop_ok && env->bpf_capable)
9939 			return DONE_EXPLORING;
9940 		verbose_linfo(env, t, "%d: ", t);
9941 		verbose_linfo(env, w, "%d: ", w);
9942 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9943 		return -EINVAL;
9944 	} else if (insn_state[w] == EXPLORED) {
9945 		/* forward- or cross-edge */
9946 		insn_state[t] = DISCOVERED | e;
9947 	} else {
9948 		verbose(env, "insn state internal bug\n");
9949 		return -EFAULT;
9950 	}
9951 	return DONE_EXPLORING;
9952 }
9953 
9954 static int visit_func_call_insn(int t, int insn_cnt,
9955 				struct bpf_insn *insns,
9956 				struct bpf_verifier_env *env,
9957 				bool visit_callee)
9958 {
9959 	int ret;
9960 
9961 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9962 	if (ret)
9963 		return ret;
9964 
9965 	if (t + 1 < insn_cnt)
9966 		init_explored_state(env, t + 1);
9967 	if (visit_callee) {
9968 		init_explored_state(env, t);
9969 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9970 				/* It's ok to allow recursion from CFG point of
9971 				 * view. __check_func_call() will do the actual
9972 				 * check.
9973 				 */
9974 				bpf_pseudo_func(insns + t));
9975 	}
9976 	return ret;
9977 }
9978 
9979 /* Visits the instruction at index t and returns one of the following:
9980  *  < 0 - an error occurred
9981  *  DONE_EXPLORING - the instruction was fully explored
9982  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9983  */
9984 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9985 {
9986 	struct bpf_insn *insns = env->prog->insnsi;
9987 	int ret;
9988 
9989 	if (bpf_pseudo_func(insns + t))
9990 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9991 
9992 	/* All non-branch instructions have a single fall-through edge. */
9993 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9994 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9995 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9996 
9997 	switch (BPF_OP(insns[t].code)) {
9998 	case BPF_EXIT:
9999 		return DONE_EXPLORING;
10000 
10001 	case BPF_CALL:
10002 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10003 			/* Mark this call insn to trigger is_state_visited() check
10004 			 * before call itself is processed by __check_func_call().
10005 			 * Otherwise new async state will be pushed for further
10006 			 * exploration.
10007 			 */
10008 			init_explored_state(env, t);
10009 		return visit_func_call_insn(t, insn_cnt, insns, env,
10010 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10011 
10012 	case BPF_JA:
10013 		if (BPF_SRC(insns[t].code) != BPF_K)
10014 			return -EINVAL;
10015 
10016 		/* unconditional jump with single edge */
10017 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10018 				true);
10019 		if (ret)
10020 			return ret;
10021 
10022 		/* unconditional jmp is not a good pruning point,
10023 		 * but it's marked, since backtracking needs
10024 		 * to record jmp history in is_state_visited().
10025 		 */
10026 		init_explored_state(env, t + insns[t].off + 1);
10027 		/* tell verifier to check for equivalent states
10028 		 * after every call and jump
10029 		 */
10030 		if (t + 1 < insn_cnt)
10031 			init_explored_state(env, t + 1);
10032 
10033 		return ret;
10034 
10035 	default:
10036 		/* conditional jump with two edges */
10037 		init_explored_state(env, t);
10038 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10039 		if (ret)
10040 			return ret;
10041 
10042 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10043 	}
10044 }
10045 
10046 /* non-recursive depth-first-search to detect loops in BPF program
10047  * loop == back-edge in directed graph
10048  */
10049 static int check_cfg(struct bpf_verifier_env *env)
10050 {
10051 	int insn_cnt = env->prog->len;
10052 	int *insn_stack, *insn_state;
10053 	int ret = 0;
10054 	int i;
10055 
10056 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10057 	if (!insn_state)
10058 		return -ENOMEM;
10059 
10060 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10061 	if (!insn_stack) {
10062 		kvfree(insn_state);
10063 		return -ENOMEM;
10064 	}
10065 
10066 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10067 	insn_stack[0] = 0; /* 0 is the first instruction */
10068 	env->cfg.cur_stack = 1;
10069 
10070 	while (env->cfg.cur_stack > 0) {
10071 		int t = insn_stack[env->cfg.cur_stack - 1];
10072 
10073 		ret = visit_insn(t, insn_cnt, env);
10074 		switch (ret) {
10075 		case DONE_EXPLORING:
10076 			insn_state[t] = EXPLORED;
10077 			env->cfg.cur_stack--;
10078 			break;
10079 		case KEEP_EXPLORING:
10080 			break;
10081 		default:
10082 			if (ret > 0) {
10083 				verbose(env, "visit_insn internal bug\n");
10084 				ret = -EFAULT;
10085 			}
10086 			goto err_free;
10087 		}
10088 	}
10089 
10090 	if (env->cfg.cur_stack < 0) {
10091 		verbose(env, "pop stack internal bug\n");
10092 		ret = -EFAULT;
10093 		goto err_free;
10094 	}
10095 
10096 	for (i = 0; i < insn_cnt; i++) {
10097 		if (insn_state[i] != EXPLORED) {
10098 			verbose(env, "unreachable insn %d\n", i);
10099 			ret = -EINVAL;
10100 			goto err_free;
10101 		}
10102 	}
10103 	ret = 0; /* cfg looks good */
10104 
10105 err_free:
10106 	kvfree(insn_state);
10107 	kvfree(insn_stack);
10108 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10109 	return ret;
10110 }
10111 
10112 static int check_abnormal_return(struct bpf_verifier_env *env)
10113 {
10114 	int i;
10115 
10116 	for (i = 1; i < env->subprog_cnt; i++) {
10117 		if (env->subprog_info[i].has_ld_abs) {
10118 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10119 			return -EINVAL;
10120 		}
10121 		if (env->subprog_info[i].has_tail_call) {
10122 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10123 			return -EINVAL;
10124 		}
10125 	}
10126 	return 0;
10127 }
10128 
10129 /* The minimum supported BTF func info size */
10130 #define MIN_BPF_FUNCINFO_SIZE	8
10131 #define MAX_FUNCINFO_REC_SIZE	252
10132 
10133 static int check_btf_func(struct bpf_verifier_env *env,
10134 			  const union bpf_attr *attr,
10135 			  bpfptr_t uattr)
10136 {
10137 	const struct btf_type *type, *func_proto, *ret_type;
10138 	u32 i, nfuncs, urec_size, min_size;
10139 	u32 krec_size = sizeof(struct bpf_func_info);
10140 	struct bpf_func_info *krecord;
10141 	struct bpf_func_info_aux *info_aux = NULL;
10142 	struct bpf_prog *prog;
10143 	const struct btf *btf;
10144 	bpfptr_t urecord;
10145 	u32 prev_offset = 0;
10146 	bool scalar_return;
10147 	int ret = -ENOMEM;
10148 
10149 	nfuncs = attr->func_info_cnt;
10150 	if (!nfuncs) {
10151 		if (check_abnormal_return(env))
10152 			return -EINVAL;
10153 		return 0;
10154 	}
10155 
10156 	if (nfuncs != env->subprog_cnt) {
10157 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10158 		return -EINVAL;
10159 	}
10160 
10161 	urec_size = attr->func_info_rec_size;
10162 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10163 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10164 	    urec_size % sizeof(u32)) {
10165 		verbose(env, "invalid func info rec size %u\n", urec_size);
10166 		return -EINVAL;
10167 	}
10168 
10169 	prog = env->prog;
10170 	btf = prog->aux->btf;
10171 
10172 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10173 	min_size = min_t(u32, krec_size, urec_size);
10174 
10175 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10176 	if (!krecord)
10177 		return -ENOMEM;
10178 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10179 	if (!info_aux)
10180 		goto err_free;
10181 
10182 	for (i = 0; i < nfuncs; i++) {
10183 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10184 		if (ret) {
10185 			if (ret == -E2BIG) {
10186 				verbose(env, "nonzero tailing record in func info");
10187 				/* set the size kernel expects so loader can zero
10188 				 * out the rest of the record.
10189 				 */
10190 				if (copy_to_bpfptr_offset(uattr,
10191 							  offsetof(union bpf_attr, func_info_rec_size),
10192 							  &min_size, sizeof(min_size)))
10193 					ret = -EFAULT;
10194 			}
10195 			goto err_free;
10196 		}
10197 
10198 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10199 			ret = -EFAULT;
10200 			goto err_free;
10201 		}
10202 
10203 		/* check insn_off */
10204 		ret = -EINVAL;
10205 		if (i == 0) {
10206 			if (krecord[i].insn_off) {
10207 				verbose(env,
10208 					"nonzero insn_off %u for the first func info record",
10209 					krecord[i].insn_off);
10210 				goto err_free;
10211 			}
10212 		} else if (krecord[i].insn_off <= prev_offset) {
10213 			verbose(env,
10214 				"same or smaller insn offset (%u) than previous func info record (%u)",
10215 				krecord[i].insn_off, prev_offset);
10216 			goto err_free;
10217 		}
10218 
10219 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10220 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10221 			goto err_free;
10222 		}
10223 
10224 		/* check type_id */
10225 		type = btf_type_by_id(btf, krecord[i].type_id);
10226 		if (!type || !btf_type_is_func(type)) {
10227 			verbose(env, "invalid type id %d in func info",
10228 				krecord[i].type_id);
10229 			goto err_free;
10230 		}
10231 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10232 
10233 		func_proto = btf_type_by_id(btf, type->type);
10234 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10235 			/* btf_func_check() already verified it during BTF load */
10236 			goto err_free;
10237 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10238 		scalar_return =
10239 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10240 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10241 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10242 			goto err_free;
10243 		}
10244 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10245 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10246 			goto err_free;
10247 		}
10248 
10249 		prev_offset = krecord[i].insn_off;
10250 		bpfptr_add(&urecord, urec_size);
10251 	}
10252 
10253 	prog->aux->func_info = krecord;
10254 	prog->aux->func_info_cnt = nfuncs;
10255 	prog->aux->func_info_aux = info_aux;
10256 	return 0;
10257 
10258 err_free:
10259 	kvfree(krecord);
10260 	kfree(info_aux);
10261 	return ret;
10262 }
10263 
10264 static void adjust_btf_func(struct bpf_verifier_env *env)
10265 {
10266 	struct bpf_prog_aux *aux = env->prog->aux;
10267 	int i;
10268 
10269 	if (!aux->func_info)
10270 		return;
10271 
10272 	for (i = 0; i < env->subprog_cnt; i++)
10273 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10274 }
10275 
10276 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10277 		sizeof(((struct bpf_line_info *)(0))->line_col))
10278 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10279 
10280 static int check_btf_line(struct bpf_verifier_env *env,
10281 			  const union bpf_attr *attr,
10282 			  bpfptr_t uattr)
10283 {
10284 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10285 	struct bpf_subprog_info *sub;
10286 	struct bpf_line_info *linfo;
10287 	struct bpf_prog *prog;
10288 	const struct btf *btf;
10289 	bpfptr_t ulinfo;
10290 	int err;
10291 
10292 	nr_linfo = attr->line_info_cnt;
10293 	if (!nr_linfo)
10294 		return 0;
10295 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10296 		return -EINVAL;
10297 
10298 	rec_size = attr->line_info_rec_size;
10299 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10300 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10301 	    rec_size & (sizeof(u32) - 1))
10302 		return -EINVAL;
10303 
10304 	/* Need to zero it in case the userspace may
10305 	 * pass in a smaller bpf_line_info object.
10306 	 */
10307 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10308 			 GFP_KERNEL | __GFP_NOWARN);
10309 	if (!linfo)
10310 		return -ENOMEM;
10311 
10312 	prog = env->prog;
10313 	btf = prog->aux->btf;
10314 
10315 	s = 0;
10316 	sub = env->subprog_info;
10317 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10318 	expected_size = sizeof(struct bpf_line_info);
10319 	ncopy = min_t(u32, expected_size, rec_size);
10320 	for (i = 0; i < nr_linfo; i++) {
10321 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10322 		if (err) {
10323 			if (err == -E2BIG) {
10324 				verbose(env, "nonzero tailing record in line_info");
10325 				if (copy_to_bpfptr_offset(uattr,
10326 							  offsetof(union bpf_attr, line_info_rec_size),
10327 							  &expected_size, sizeof(expected_size)))
10328 					err = -EFAULT;
10329 			}
10330 			goto err_free;
10331 		}
10332 
10333 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10334 			err = -EFAULT;
10335 			goto err_free;
10336 		}
10337 
10338 		/*
10339 		 * Check insn_off to ensure
10340 		 * 1) strictly increasing AND
10341 		 * 2) bounded by prog->len
10342 		 *
10343 		 * The linfo[0].insn_off == 0 check logically falls into
10344 		 * the later "missing bpf_line_info for func..." case
10345 		 * because the first linfo[0].insn_off must be the
10346 		 * first sub also and the first sub must have
10347 		 * subprog_info[0].start == 0.
10348 		 */
10349 		if ((i && linfo[i].insn_off <= prev_offset) ||
10350 		    linfo[i].insn_off >= prog->len) {
10351 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10352 				i, linfo[i].insn_off, prev_offset,
10353 				prog->len);
10354 			err = -EINVAL;
10355 			goto err_free;
10356 		}
10357 
10358 		if (!prog->insnsi[linfo[i].insn_off].code) {
10359 			verbose(env,
10360 				"Invalid insn code at line_info[%u].insn_off\n",
10361 				i);
10362 			err = -EINVAL;
10363 			goto err_free;
10364 		}
10365 
10366 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10367 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10368 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10369 			err = -EINVAL;
10370 			goto err_free;
10371 		}
10372 
10373 		if (s != env->subprog_cnt) {
10374 			if (linfo[i].insn_off == sub[s].start) {
10375 				sub[s].linfo_idx = i;
10376 				s++;
10377 			} else if (sub[s].start < linfo[i].insn_off) {
10378 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10379 				err = -EINVAL;
10380 				goto err_free;
10381 			}
10382 		}
10383 
10384 		prev_offset = linfo[i].insn_off;
10385 		bpfptr_add(&ulinfo, rec_size);
10386 	}
10387 
10388 	if (s != env->subprog_cnt) {
10389 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10390 			env->subprog_cnt - s, s);
10391 		err = -EINVAL;
10392 		goto err_free;
10393 	}
10394 
10395 	prog->aux->linfo = linfo;
10396 	prog->aux->nr_linfo = nr_linfo;
10397 
10398 	return 0;
10399 
10400 err_free:
10401 	kvfree(linfo);
10402 	return err;
10403 }
10404 
10405 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
10406 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
10407 
10408 static int check_core_relo(struct bpf_verifier_env *env,
10409 			   const union bpf_attr *attr,
10410 			   bpfptr_t uattr)
10411 {
10412 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
10413 	struct bpf_core_relo core_relo = {};
10414 	struct bpf_prog *prog = env->prog;
10415 	const struct btf *btf = prog->aux->btf;
10416 	struct bpf_core_ctx ctx = {
10417 		.log = &env->log,
10418 		.btf = btf,
10419 	};
10420 	bpfptr_t u_core_relo;
10421 	int err;
10422 
10423 	nr_core_relo = attr->core_relo_cnt;
10424 	if (!nr_core_relo)
10425 		return 0;
10426 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
10427 		return -EINVAL;
10428 
10429 	rec_size = attr->core_relo_rec_size;
10430 	if (rec_size < MIN_CORE_RELO_SIZE ||
10431 	    rec_size > MAX_CORE_RELO_SIZE ||
10432 	    rec_size % sizeof(u32))
10433 		return -EINVAL;
10434 
10435 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
10436 	expected_size = sizeof(struct bpf_core_relo);
10437 	ncopy = min_t(u32, expected_size, rec_size);
10438 
10439 	/* Unlike func_info and line_info, copy and apply each CO-RE
10440 	 * relocation record one at a time.
10441 	 */
10442 	for (i = 0; i < nr_core_relo; i++) {
10443 		/* future proofing when sizeof(bpf_core_relo) changes */
10444 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
10445 		if (err) {
10446 			if (err == -E2BIG) {
10447 				verbose(env, "nonzero tailing record in core_relo");
10448 				if (copy_to_bpfptr_offset(uattr,
10449 							  offsetof(union bpf_attr, core_relo_rec_size),
10450 							  &expected_size, sizeof(expected_size)))
10451 					err = -EFAULT;
10452 			}
10453 			break;
10454 		}
10455 
10456 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
10457 			err = -EFAULT;
10458 			break;
10459 		}
10460 
10461 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
10462 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
10463 				i, core_relo.insn_off, prog->len);
10464 			err = -EINVAL;
10465 			break;
10466 		}
10467 
10468 		err = bpf_core_apply(&ctx, &core_relo, i,
10469 				     &prog->insnsi[core_relo.insn_off / 8]);
10470 		if (err)
10471 			break;
10472 		bpfptr_add(&u_core_relo, rec_size);
10473 	}
10474 	return err;
10475 }
10476 
10477 static int check_btf_info(struct bpf_verifier_env *env,
10478 			  const union bpf_attr *attr,
10479 			  bpfptr_t uattr)
10480 {
10481 	struct btf *btf;
10482 	int err;
10483 
10484 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10485 		if (check_abnormal_return(env))
10486 			return -EINVAL;
10487 		return 0;
10488 	}
10489 
10490 	btf = btf_get_by_fd(attr->prog_btf_fd);
10491 	if (IS_ERR(btf))
10492 		return PTR_ERR(btf);
10493 	if (btf_is_kernel(btf)) {
10494 		btf_put(btf);
10495 		return -EACCES;
10496 	}
10497 	env->prog->aux->btf = btf;
10498 
10499 	err = check_btf_func(env, attr, uattr);
10500 	if (err)
10501 		return err;
10502 
10503 	err = check_btf_line(env, attr, uattr);
10504 	if (err)
10505 		return err;
10506 
10507 	err = check_core_relo(env, attr, uattr);
10508 	if (err)
10509 		return err;
10510 
10511 	return 0;
10512 }
10513 
10514 /* check %cur's range satisfies %old's */
10515 static bool range_within(struct bpf_reg_state *old,
10516 			 struct bpf_reg_state *cur)
10517 {
10518 	return old->umin_value <= cur->umin_value &&
10519 	       old->umax_value >= cur->umax_value &&
10520 	       old->smin_value <= cur->smin_value &&
10521 	       old->smax_value >= cur->smax_value &&
10522 	       old->u32_min_value <= cur->u32_min_value &&
10523 	       old->u32_max_value >= cur->u32_max_value &&
10524 	       old->s32_min_value <= cur->s32_min_value &&
10525 	       old->s32_max_value >= cur->s32_max_value;
10526 }
10527 
10528 /* If in the old state two registers had the same id, then they need to have
10529  * the same id in the new state as well.  But that id could be different from
10530  * the old state, so we need to track the mapping from old to new ids.
10531  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10532  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10533  * regs with a different old id could still have new id 9, we don't care about
10534  * that.
10535  * So we look through our idmap to see if this old id has been seen before.  If
10536  * so, we require the new id to match; otherwise, we add the id pair to the map.
10537  */
10538 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10539 {
10540 	unsigned int i;
10541 
10542 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10543 		if (!idmap[i].old) {
10544 			/* Reached an empty slot; haven't seen this id before */
10545 			idmap[i].old = old_id;
10546 			idmap[i].cur = cur_id;
10547 			return true;
10548 		}
10549 		if (idmap[i].old == old_id)
10550 			return idmap[i].cur == cur_id;
10551 	}
10552 	/* We ran out of idmap slots, which should be impossible */
10553 	WARN_ON_ONCE(1);
10554 	return false;
10555 }
10556 
10557 static void clean_func_state(struct bpf_verifier_env *env,
10558 			     struct bpf_func_state *st)
10559 {
10560 	enum bpf_reg_liveness live;
10561 	int i, j;
10562 
10563 	for (i = 0; i < BPF_REG_FP; i++) {
10564 		live = st->regs[i].live;
10565 		/* liveness must not touch this register anymore */
10566 		st->regs[i].live |= REG_LIVE_DONE;
10567 		if (!(live & REG_LIVE_READ))
10568 			/* since the register is unused, clear its state
10569 			 * to make further comparison simpler
10570 			 */
10571 			__mark_reg_not_init(env, &st->regs[i]);
10572 	}
10573 
10574 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10575 		live = st->stack[i].spilled_ptr.live;
10576 		/* liveness must not touch this stack slot anymore */
10577 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10578 		if (!(live & REG_LIVE_READ)) {
10579 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10580 			for (j = 0; j < BPF_REG_SIZE; j++)
10581 				st->stack[i].slot_type[j] = STACK_INVALID;
10582 		}
10583 	}
10584 }
10585 
10586 static void clean_verifier_state(struct bpf_verifier_env *env,
10587 				 struct bpf_verifier_state *st)
10588 {
10589 	int i;
10590 
10591 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10592 		/* all regs in this state in all frames were already marked */
10593 		return;
10594 
10595 	for (i = 0; i <= st->curframe; i++)
10596 		clean_func_state(env, st->frame[i]);
10597 }
10598 
10599 /* the parentage chains form a tree.
10600  * the verifier states are added to state lists at given insn and
10601  * pushed into state stack for future exploration.
10602  * when the verifier reaches bpf_exit insn some of the verifer states
10603  * stored in the state lists have their final liveness state already,
10604  * but a lot of states will get revised from liveness point of view when
10605  * the verifier explores other branches.
10606  * Example:
10607  * 1: r0 = 1
10608  * 2: if r1 == 100 goto pc+1
10609  * 3: r0 = 2
10610  * 4: exit
10611  * when the verifier reaches exit insn the register r0 in the state list of
10612  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10613  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10614  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10615  *
10616  * Since the verifier pushes the branch states as it sees them while exploring
10617  * the program the condition of walking the branch instruction for the second
10618  * time means that all states below this branch were already explored and
10619  * their final liveness marks are already propagated.
10620  * Hence when the verifier completes the search of state list in is_state_visited()
10621  * we can call this clean_live_states() function to mark all liveness states
10622  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10623  * will not be used.
10624  * This function also clears the registers and stack for states that !READ
10625  * to simplify state merging.
10626  *
10627  * Important note here that walking the same branch instruction in the callee
10628  * doesn't meant that the states are DONE. The verifier has to compare
10629  * the callsites
10630  */
10631 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10632 			      struct bpf_verifier_state *cur)
10633 {
10634 	struct bpf_verifier_state_list *sl;
10635 	int i;
10636 
10637 	sl = *explored_state(env, insn);
10638 	while (sl) {
10639 		if (sl->state.branches)
10640 			goto next;
10641 		if (sl->state.insn_idx != insn ||
10642 		    sl->state.curframe != cur->curframe)
10643 			goto next;
10644 		for (i = 0; i <= cur->curframe; i++)
10645 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10646 				goto next;
10647 		clean_verifier_state(env, &sl->state);
10648 next:
10649 		sl = sl->next;
10650 	}
10651 }
10652 
10653 /* Returns true if (rold safe implies rcur safe) */
10654 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10655 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10656 {
10657 	bool equal;
10658 
10659 	if (!(rold->live & REG_LIVE_READ))
10660 		/* explored state didn't use this */
10661 		return true;
10662 
10663 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10664 
10665 	if (rold->type == PTR_TO_STACK)
10666 		/* two stack pointers are equal only if they're pointing to
10667 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10668 		 */
10669 		return equal && rold->frameno == rcur->frameno;
10670 
10671 	if (equal)
10672 		return true;
10673 
10674 	if (rold->type == NOT_INIT)
10675 		/* explored state can't have used this */
10676 		return true;
10677 	if (rcur->type == NOT_INIT)
10678 		return false;
10679 	switch (base_type(rold->type)) {
10680 	case SCALAR_VALUE:
10681 		if (env->explore_alu_limits)
10682 			return false;
10683 		if (rcur->type == SCALAR_VALUE) {
10684 			if (!rold->precise && !rcur->precise)
10685 				return true;
10686 			/* new val must satisfy old val knowledge */
10687 			return range_within(rold, rcur) &&
10688 			       tnum_in(rold->var_off, rcur->var_off);
10689 		} else {
10690 			/* We're trying to use a pointer in place of a scalar.
10691 			 * Even if the scalar was unbounded, this could lead to
10692 			 * pointer leaks because scalars are allowed to leak
10693 			 * while pointers are not. We could make this safe in
10694 			 * special cases if root is calling us, but it's
10695 			 * probably not worth the hassle.
10696 			 */
10697 			return false;
10698 		}
10699 	case PTR_TO_MAP_KEY:
10700 	case PTR_TO_MAP_VALUE:
10701 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10702 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10703 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10704 		 * checked, doing so could have affected others with the same
10705 		 * id, and we can't check for that because we lost the id when
10706 		 * we converted to a PTR_TO_MAP_VALUE.
10707 		 */
10708 		if (type_may_be_null(rold->type)) {
10709 			if (!type_may_be_null(rcur->type))
10710 				return false;
10711 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10712 				return false;
10713 			/* Check our ids match any regs they're supposed to */
10714 			return check_ids(rold->id, rcur->id, idmap);
10715 		}
10716 
10717 		/* If the new min/max/var_off satisfy the old ones and
10718 		 * everything else matches, we are OK.
10719 		 * 'id' is not compared, since it's only used for maps with
10720 		 * bpf_spin_lock inside map element and in such cases if
10721 		 * the rest of the prog is valid for one map element then
10722 		 * it's valid for all map elements regardless of the key
10723 		 * used in bpf_map_lookup()
10724 		 */
10725 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10726 		       range_within(rold, rcur) &&
10727 		       tnum_in(rold->var_off, rcur->var_off);
10728 	case PTR_TO_PACKET_META:
10729 	case PTR_TO_PACKET:
10730 		if (rcur->type != rold->type)
10731 			return false;
10732 		/* We must have at least as much range as the old ptr
10733 		 * did, so that any accesses which were safe before are
10734 		 * still safe.  This is true even if old range < old off,
10735 		 * since someone could have accessed through (ptr - k), or
10736 		 * even done ptr -= k in a register, to get a safe access.
10737 		 */
10738 		if (rold->range > rcur->range)
10739 			return false;
10740 		/* If the offsets don't match, we can't trust our alignment;
10741 		 * nor can we be sure that we won't fall out of range.
10742 		 */
10743 		if (rold->off != rcur->off)
10744 			return false;
10745 		/* id relations must be preserved */
10746 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10747 			return false;
10748 		/* new val must satisfy old val knowledge */
10749 		return range_within(rold, rcur) &&
10750 		       tnum_in(rold->var_off, rcur->var_off);
10751 	case PTR_TO_CTX:
10752 	case CONST_PTR_TO_MAP:
10753 	case PTR_TO_PACKET_END:
10754 	case PTR_TO_FLOW_KEYS:
10755 	case PTR_TO_SOCKET:
10756 	case PTR_TO_SOCK_COMMON:
10757 	case PTR_TO_TCP_SOCK:
10758 	case PTR_TO_XDP_SOCK:
10759 		/* Only valid matches are exact, which memcmp() above
10760 		 * would have accepted
10761 		 */
10762 	default:
10763 		/* Don't know what's going on, just say it's not safe */
10764 		return false;
10765 	}
10766 
10767 	/* Shouldn't get here; if we do, say it's not safe */
10768 	WARN_ON_ONCE(1);
10769 	return false;
10770 }
10771 
10772 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10773 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10774 {
10775 	int i, spi;
10776 
10777 	/* walk slots of the explored stack and ignore any additional
10778 	 * slots in the current stack, since explored(safe) state
10779 	 * didn't use them
10780 	 */
10781 	for (i = 0; i < old->allocated_stack; i++) {
10782 		spi = i / BPF_REG_SIZE;
10783 
10784 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10785 			i += BPF_REG_SIZE - 1;
10786 			/* explored state didn't use this */
10787 			continue;
10788 		}
10789 
10790 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10791 			continue;
10792 
10793 		/* explored stack has more populated slots than current stack
10794 		 * and these slots were used
10795 		 */
10796 		if (i >= cur->allocated_stack)
10797 			return false;
10798 
10799 		/* if old state was safe with misc data in the stack
10800 		 * it will be safe with zero-initialized stack.
10801 		 * The opposite is not true
10802 		 */
10803 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10804 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10805 			continue;
10806 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10807 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10808 			/* Ex: old explored (safe) state has STACK_SPILL in
10809 			 * this stack slot, but current has STACK_MISC ->
10810 			 * this verifier states are not equivalent,
10811 			 * return false to continue verification of this path
10812 			 */
10813 			return false;
10814 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10815 			continue;
10816 		if (!is_spilled_reg(&old->stack[spi]))
10817 			continue;
10818 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10819 			     &cur->stack[spi].spilled_ptr, idmap))
10820 			/* when explored and current stack slot are both storing
10821 			 * spilled registers, check that stored pointers types
10822 			 * are the same as well.
10823 			 * Ex: explored safe path could have stored
10824 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10825 			 * but current path has stored:
10826 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10827 			 * such verifier states are not equivalent.
10828 			 * return false to continue verification of this path
10829 			 */
10830 			return false;
10831 	}
10832 	return true;
10833 }
10834 
10835 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10836 {
10837 	if (old->acquired_refs != cur->acquired_refs)
10838 		return false;
10839 	return !memcmp(old->refs, cur->refs,
10840 		       sizeof(*old->refs) * old->acquired_refs);
10841 }
10842 
10843 /* compare two verifier states
10844  *
10845  * all states stored in state_list are known to be valid, since
10846  * verifier reached 'bpf_exit' instruction through them
10847  *
10848  * this function is called when verifier exploring different branches of
10849  * execution popped from the state stack. If it sees an old state that has
10850  * more strict register state and more strict stack state then this execution
10851  * branch doesn't need to be explored further, since verifier already
10852  * concluded that more strict state leads to valid finish.
10853  *
10854  * Therefore two states are equivalent if register state is more conservative
10855  * and explored stack state is more conservative than the current one.
10856  * Example:
10857  *       explored                   current
10858  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10859  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10860  *
10861  * In other words if current stack state (one being explored) has more
10862  * valid slots than old one that already passed validation, it means
10863  * the verifier can stop exploring and conclude that current state is valid too
10864  *
10865  * Similarly with registers. If explored state has register type as invalid
10866  * whereas register type in current state is meaningful, it means that
10867  * the current state will reach 'bpf_exit' instruction safely
10868  */
10869 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10870 			      struct bpf_func_state *cur)
10871 {
10872 	int i;
10873 
10874 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10875 	for (i = 0; i < MAX_BPF_REG; i++)
10876 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10877 			     env->idmap_scratch))
10878 			return false;
10879 
10880 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10881 		return false;
10882 
10883 	if (!refsafe(old, cur))
10884 		return false;
10885 
10886 	return true;
10887 }
10888 
10889 static bool states_equal(struct bpf_verifier_env *env,
10890 			 struct bpf_verifier_state *old,
10891 			 struct bpf_verifier_state *cur)
10892 {
10893 	int i;
10894 
10895 	if (old->curframe != cur->curframe)
10896 		return false;
10897 
10898 	/* Verification state from speculative execution simulation
10899 	 * must never prune a non-speculative execution one.
10900 	 */
10901 	if (old->speculative && !cur->speculative)
10902 		return false;
10903 
10904 	if (old->active_spin_lock != cur->active_spin_lock)
10905 		return false;
10906 
10907 	/* for states to be equal callsites have to be the same
10908 	 * and all frame states need to be equivalent
10909 	 */
10910 	for (i = 0; i <= old->curframe; i++) {
10911 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10912 			return false;
10913 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10914 			return false;
10915 	}
10916 	return true;
10917 }
10918 
10919 /* Return 0 if no propagation happened. Return negative error code if error
10920  * happened. Otherwise, return the propagated bit.
10921  */
10922 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10923 				  struct bpf_reg_state *reg,
10924 				  struct bpf_reg_state *parent_reg)
10925 {
10926 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10927 	u8 flag = reg->live & REG_LIVE_READ;
10928 	int err;
10929 
10930 	/* When comes here, read flags of PARENT_REG or REG could be any of
10931 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10932 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10933 	 */
10934 	if (parent_flag == REG_LIVE_READ64 ||
10935 	    /* Or if there is no read flag from REG. */
10936 	    !flag ||
10937 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10938 	    parent_flag == flag)
10939 		return 0;
10940 
10941 	err = mark_reg_read(env, reg, parent_reg, flag);
10942 	if (err)
10943 		return err;
10944 
10945 	return flag;
10946 }
10947 
10948 /* A write screens off any subsequent reads; but write marks come from the
10949  * straight-line code between a state and its parent.  When we arrive at an
10950  * equivalent state (jump target or such) we didn't arrive by the straight-line
10951  * code, so read marks in the state must propagate to the parent regardless
10952  * of the state's write marks. That's what 'parent == state->parent' comparison
10953  * in mark_reg_read() is for.
10954  */
10955 static int propagate_liveness(struct bpf_verifier_env *env,
10956 			      const struct bpf_verifier_state *vstate,
10957 			      struct bpf_verifier_state *vparent)
10958 {
10959 	struct bpf_reg_state *state_reg, *parent_reg;
10960 	struct bpf_func_state *state, *parent;
10961 	int i, frame, err = 0;
10962 
10963 	if (vparent->curframe != vstate->curframe) {
10964 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10965 		     vparent->curframe, vstate->curframe);
10966 		return -EFAULT;
10967 	}
10968 	/* Propagate read liveness of registers... */
10969 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10970 	for (frame = 0; frame <= vstate->curframe; frame++) {
10971 		parent = vparent->frame[frame];
10972 		state = vstate->frame[frame];
10973 		parent_reg = parent->regs;
10974 		state_reg = state->regs;
10975 		/* We don't need to worry about FP liveness, it's read-only */
10976 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10977 			err = propagate_liveness_reg(env, &state_reg[i],
10978 						     &parent_reg[i]);
10979 			if (err < 0)
10980 				return err;
10981 			if (err == REG_LIVE_READ64)
10982 				mark_insn_zext(env, &parent_reg[i]);
10983 		}
10984 
10985 		/* Propagate stack slots. */
10986 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10987 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10988 			parent_reg = &parent->stack[i].spilled_ptr;
10989 			state_reg = &state->stack[i].spilled_ptr;
10990 			err = propagate_liveness_reg(env, state_reg,
10991 						     parent_reg);
10992 			if (err < 0)
10993 				return err;
10994 		}
10995 	}
10996 	return 0;
10997 }
10998 
10999 /* find precise scalars in the previous equivalent state and
11000  * propagate them into the current state
11001  */
11002 static int propagate_precision(struct bpf_verifier_env *env,
11003 			       const struct bpf_verifier_state *old)
11004 {
11005 	struct bpf_reg_state *state_reg;
11006 	struct bpf_func_state *state;
11007 	int i, err = 0;
11008 
11009 	state = old->frame[old->curframe];
11010 	state_reg = state->regs;
11011 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11012 		if (state_reg->type != SCALAR_VALUE ||
11013 		    !state_reg->precise)
11014 			continue;
11015 		if (env->log.level & BPF_LOG_LEVEL2)
11016 			verbose(env, "propagating r%d\n", i);
11017 		err = mark_chain_precision(env, i);
11018 		if (err < 0)
11019 			return err;
11020 	}
11021 
11022 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11023 		if (!is_spilled_reg(&state->stack[i]))
11024 			continue;
11025 		state_reg = &state->stack[i].spilled_ptr;
11026 		if (state_reg->type != SCALAR_VALUE ||
11027 		    !state_reg->precise)
11028 			continue;
11029 		if (env->log.level & BPF_LOG_LEVEL2)
11030 			verbose(env, "propagating fp%d\n",
11031 				(-i - 1) * BPF_REG_SIZE);
11032 		err = mark_chain_precision_stack(env, i);
11033 		if (err < 0)
11034 			return err;
11035 	}
11036 	return 0;
11037 }
11038 
11039 static bool states_maybe_looping(struct bpf_verifier_state *old,
11040 				 struct bpf_verifier_state *cur)
11041 {
11042 	struct bpf_func_state *fold, *fcur;
11043 	int i, fr = cur->curframe;
11044 
11045 	if (old->curframe != fr)
11046 		return false;
11047 
11048 	fold = old->frame[fr];
11049 	fcur = cur->frame[fr];
11050 	for (i = 0; i < MAX_BPF_REG; i++)
11051 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11052 			   offsetof(struct bpf_reg_state, parent)))
11053 			return false;
11054 	return true;
11055 }
11056 
11057 
11058 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11059 {
11060 	struct bpf_verifier_state_list *new_sl;
11061 	struct bpf_verifier_state_list *sl, **pprev;
11062 	struct bpf_verifier_state *cur = env->cur_state, *new;
11063 	int i, j, err, states_cnt = 0;
11064 	bool add_new_state = env->test_state_freq ? true : false;
11065 
11066 	cur->last_insn_idx = env->prev_insn_idx;
11067 	if (!env->insn_aux_data[insn_idx].prune_point)
11068 		/* this 'insn_idx' instruction wasn't marked, so we will not
11069 		 * be doing state search here
11070 		 */
11071 		return 0;
11072 
11073 	/* bpf progs typically have pruning point every 4 instructions
11074 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11075 	 * Do not add new state for future pruning if the verifier hasn't seen
11076 	 * at least 2 jumps and at least 8 instructions.
11077 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11078 	 * In tests that amounts to up to 50% reduction into total verifier
11079 	 * memory consumption and 20% verifier time speedup.
11080 	 */
11081 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11082 	    env->insn_processed - env->prev_insn_processed >= 8)
11083 		add_new_state = true;
11084 
11085 	pprev = explored_state(env, insn_idx);
11086 	sl = *pprev;
11087 
11088 	clean_live_states(env, insn_idx, cur);
11089 
11090 	while (sl) {
11091 		states_cnt++;
11092 		if (sl->state.insn_idx != insn_idx)
11093 			goto next;
11094 
11095 		if (sl->state.branches) {
11096 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11097 
11098 			if (frame->in_async_callback_fn &&
11099 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11100 				/* Different async_entry_cnt means that the verifier is
11101 				 * processing another entry into async callback.
11102 				 * Seeing the same state is not an indication of infinite
11103 				 * loop or infinite recursion.
11104 				 * But finding the same state doesn't mean that it's safe
11105 				 * to stop processing the current state. The previous state
11106 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11107 				 * Checking in_async_callback_fn alone is not enough either.
11108 				 * Since the verifier still needs to catch infinite loops
11109 				 * inside async callbacks.
11110 				 */
11111 			} else if (states_maybe_looping(&sl->state, cur) &&
11112 				   states_equal(env, &sl->state, cur)) {
11113 				verbose_linfo(env, insn_idx, "; ");
11114 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11115 				return -EINVAL;
11116 			}
11117 			/* if the verifier is processing a loop, avoid adding new state
11118 			 * too often, since different loop iterations have distinct
11119 			 * states and may not help future pruning.
11120 			 * This threshold shouldn't be too low to make sure that
11121 			 * a loop with large bound will be rejected quickly.
11122 			 * The most abusive loop will be:
11123 			 * r1 += 1
11124 			 * if r1 < 1000000 goto pc-2
11125 			 * 1M insn_procssed limit / 100 == 10k peak states.
11126 			 * This threshold shouldn't be too high either, since states
11127 			 * at the end of the loop are likely to be useful in pruning.
11128 			 */
11129 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11130 			    env->insn_processed - env->prev_insn_processed < 100)
11131 				add_new_state = false;
11132 			goto miss;
11133 		}
11134 		if (states_equal(env, &sl->state, cur)) {
11135 			sl->hit_cnt++;
11136 			/* reached equivalent register/stack state,
11137 			 * prune the search.
11138 			 * Registers read by the continuation are read by us.
11139 			 * If we have any write marks in env->cur_state, they
11140 			 * will prevent corresponding reads in the continuation
11141 			 * from reaching our parent (an explored_state).  Our
11142 			 * own state will get the read marks recorded, but
11143 			 * they'll be immediately forgotten as we're pruning
11144 			 * this state and will pop a new one.
11145 			 */
11146 			err = propagate_liveness(env, &sl->state, cur);
11147 
11148 			/* if previous state reached the exit with precision and
11149 			 * current state is equivalent to it (except precsion marks)
11150 			 * the precision needs to be propagated back in
11151 			 * the current state.
11152 			 */
11153 			err = err ? : push_jmp_history(env, cur);
11154 			err = err ? : propagate_precision(env, &sl->state);
11155 			if (err)
11156 				return err;
11157 			return 1;
11158 		}
11159 miss:
11160 		/* when new state is not going to be added do not increase miss count.
11161 		 * Otherwise several loop iterations will remove the state
11162 		 * recorded earlier. The goal of these heuristics is to have
11163 		 * states from some iterations of the loop (some in the beginning
11164 		 * and some at the end) to help pruning.
11165 		 */
11166 		if (add_new_state)
11167 			sl->miss_cnt++;
11168 		/* heuristic to determine whether this state is beneficial
11169 		 * to keep checking from state equivalence point of view.
11170 		 * Higher numbers increase max_states_per_insn and verification time,
11171 		 * but do not meaningfully decrease insn_processed.
11172 		 */
11173 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11174 			/* the state is unlikely to be useful. Remove it to
11175 			 * speed up verification
11176 			 */
11177 			*pprev = sl->next;
11178 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11179 				u32 br = sl->state.branches;
11180 
11181 				WARN_ONCE(br,
11182 					  "BUG live_done but branches_to_explore %d\n",
11183 					  br);
11184 				free_verifier_state(&sl->state, false);
11185 				kfree(sl);
11186 				env->peak_states--;
11187 			} else {
11188 				/* cannot free this state, since parentage chain may
11189 				 * walk it later. Add it for free_list instead to
11190 				 * be freed at the end of verification
11191 				 */
11192 				sl->next = env->free_list;
11193 				env->free_list = sl;
11194 			}
11195 			sl = *pprev;
11196 			continue;
11197 		}
11198 next:
11199 		pprev = &sl->next;
11200 		sl = *pprev;
11201 	}
11202 
11203 	if (env->max_states_per_insn < states_cnt)
11204 		env->max_states_per_insn = states_cnt;
11205 
11206 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11207 		return push_jmp_history(env, cur);
11208 
11209 	if (!add_new_state)
11210 		return push_jmp_history(env, cur);
11211 
11212 	/* There were no equivalent states, remember the current one.
11213 	 * Technically the current state is not proven to be safe yet,
11214 	 * but it will either reach outer most bpf_exit (which means it's safe)
11215 	 * or it will be rejected. When there are no loops the verifier won't be
11216 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11217 	 * again on the way to bpf_exit.
11218 	 * When looping the sl->state.branches will be > 0 and this state
11219 	 * will not be considered for equivalence until branches == 0.
11220 	 */
11221 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11222 	if (!new_sl)
11223 		return -ENOMEM;
11224 	env->total_states++;
11225 	env->peak_states++;
11226 	env->prev_jmps_processed = env->jmps_processed;
11227 	env->prev_insn_processed = env->insn_processed;
11228 
11229 	/* add new state to the head of linked list */
11230 	new = &new_sl->state;
11231 	err = copy_verifier_state(new, cur);
11232 	if (err) {
11233 		free_verifier_state(new, false);
11234 		kfree(new_sl);
11235 		return err;
11236 	}
11237 	new->insn_idx = insn_idx;
11238 	WARN_ONCE(new->branches != 1,
11239 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11240 
11241 	cur->parent = new;
11242 	cur->first_insn_idx = insn_idx;
11243 	clear_jmp_history(cur);
11244 	new_sl->next = *explored_state(env, insn_idx);
11245 	*explored_state(env, insn_idx) = new_sl;
11246 	/* connect new state to parentage chain. Current frame needs all
11247 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11248 	 * to the stack implicitly by JITs) so in callers' frames connect just
11249 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11250 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11251 	 * from callee with its full parentage chain, anyway.
11252 	 */
11253 	/* clear write marks in current state: the writes we did are not writes
11254 	 * our child did, so they don't screen off its reads from us.
11255 	 * (There are no read marks in current state, because reads always mark
11256 	 * their parent and current state never has children yet.  Only
11257 	 * explored_states can get read marks.)
11258 	 */
11259 	for (j = 0; j <= cur->curframe; j++) {
11260 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11261 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11262 		for (i = 0; i < BPF_REG_FP; i++)
11263 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11264 	}
11265 
11266 	/* all stack frames are accessible from callee, clear them all */
11267 	for (j = 0; j <= cur->curframe; j++) {
11268 		struct bpf_func_state *frame = cur->frame[j];
11269 		struct bpf_func_state *newframe = new->frame[j];
11270 
11271 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11272 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11273 			frame->stack[i].spilled_ptr.parent =
11274 						&newframe->stack[i].spilled_ptr;
11275 		}
11276 	}
11277 	return 0;
11278 }
11279 
11280 /* Return true if it's OK to have the same insn return a different type. */
11281 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11282 {
11283 	switch (base_type(type)) {
11284 	case PTR_TO_CTX:
11285 	case PTR_TO_SOCKET:
11286 	case PTR_TO_SOCK_COMMON:
11287 	case PTR_TO_TCP_SOCK:
11288 	case PTR_TO_XDP_SOCK:
11289 	case PTR_TO_BTF_ID:
11290 		return false;
11291 	default:
11292 		return true;
11293 	}
11294 }
11295 
11296 /* If an instruction was previously used with particular pointer types, then we
11297  * need to be careful to avoid cases such as the below, where it may be ok
11298  * for one branch accessing the pointer, but not ok for the other branch:
11299  *
11300  * R1 = sock_ptr
11301  * goto X;
11302  * ...
11303  * R1 = some_other_valid_ptr;
11304  * goto X;
11305  * ...
11306  * R2 = *(u32 *)(R1 + 0);
11307  */
11308 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11309 {
11310 	return src != prev && (!reg_type_mismatch_ok(src) ||
11311 			       !reg_type_mismatch_ok(prev));
11312 }
11313 
11314 static int do_check(struct bpf_verifier_env *env)
11315 {
11316 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11317 	struct bpf_verifier_state *state = env->cur_state;
11318 	struct bpf_insn *insns = env->prog->insnsi;
11319 	struct bpf_reg_state *regs;
11320 	int insn_cnt = env->prog->len;
11321 	bool do_print_state = false;
11322 	int prev_insn_idx = -1;
11323 
11324 	for (;;) {
11325 		struct bpf_insn *insn;
11326 		u8 class;
11327 		int err;
11328 
11329 		env->prev_insn_idx = prev_insn_idx;
11330 		if (env->insn_idx >= insn_cnt) {
11331 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11332 				env->insn_idx, insn_cnt);
11333 			return -EFAULT;
11334 		}
11335 
11336 		insn = &insns[env->insn_idx];
11337 		class = BPF_CLASS(insn->code);
11338 
11339 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11340 			verbose(env,
11341 				"BPF program is too large. Processed %d insn\n",
11342 				env->insn_processed);
11343 			return -E2BIG;
11344 		}
11345 
11346 		err = is_state_visited(env, env->insn_idx);
11347 		if (err < 0)
11348 			return err;
11349 		if (err == 1) {
11350 			/* found equivalent state, can prune the search */
11351 			if (env->log.level & BPF_LOG_LEVEL) {
11352 				if (do_print_state)
11353 					verbose(env, "\nfrom %d to %d%s: safe\n",
11354 						env->prev_insn_idx, env->insn_idx,
11355 						env->cur_state->speculative ?
11356 						" (speculative execution)" : "");
11357 				else
11358 					verbose(env, "%d: safe\n", env->insn_idx);
11359 			}
11360 			goto process_bpf_exit;
11361 		}
11362 
11363 		if (signal_pending(current))
11364 			return -EAGAIN;
11365 
11366 		if (need_resched())
11367 			cond_resched();
11368 
11369 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
11370 			verbose(env, "\nfrom %d to %d%s:",
11371 				env->prev_insn_idx, env->insn_idx,
11372 				env->cur_state->speculative ?
11373 				" (speculative execution)" : "");
11374 			print_verifier_state(env, state->frame[state->curframe], true);
11375 			do_print_state = false;
11376 		}
11377 
11378 		if (env->log.level & BPF_LOG_LEVEL) {
11379 			const struct bpf_insn_cbs cbs = {
11380 				.cb_call	= disasm_kfunc_name,
11381 				.cb_print	= verbose,
11382 				.private_data	= env,
11383 			};
11384 
11385 			if (verifier_state_scratched(env))
11386 				print_insn_state(env, state->frame[state->curframe]);
11387 
11388 			verbose_linfo(env, env->insn_idx, "; ");
11389 			env->prev_log_len = env->log.len_used;
11390 			verbose(env, "%d: ", env->insn_idx);
11391 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11392 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
11393 			env->prev_log_len = env->log.len_used;
11394 		}
11395 
11396 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11397 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11398 							   env->prev_insn_idx);
11399 			if (err)
11400 				return err;
11401 		}
11402 
11403 		regs = cur_regs(env);
11404 		sanitize_mark_insn_seen(env);
11405 		prev_insn_idx = env->insn_idx;
11406 
11407 		if (class == BPF_ALU || class == BPF_ALU64) {
11408 			err = check_alu_op(env, insn);
11409 			if (err)
11410 				return err;
11411 
11412 		} else if (class == BPF_LDX) {
11413 			enum bpf_reg_type *prev_src_type, src_reg_type;
11414 
11415 			/* check for reserved fields is already done */
11416 
11417 			/* check src operand */
11418 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11419 			if (err)
11420 				return err;
11421 
11422 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11423 			if (err)
11424 				return err;
11425 
11426 			src_reg_type = regs[insn->src_reg].type;
11427 
11428 			/* check that memory (src_reg + off) is readable,
11429 			 * the state of dst_reg will be updated by this func
11430 			 */
11431 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11432 					       insn->off, BPF_SIZE(insn->code),
11433 					       BPF_READ, insn->dst_reg, false);
11434 			if (err)
11435 				return err;
11436 
11437 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11438 
11439 			if (*prev_src_type == NOT_INIT) {
11440 				/* saw a valid insn
11441 				 * dst_reg = *(u32 *)(src_reg + off)
11442 				 * save type to validate intersecting paths
11443 				 */
11444 				*prev_src_type = src_reg_type;
11445 
11446 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11447 				/* ABuser program is trying to use the same insn
11448 				 * dst_reg = *(u32*) (src_reg + off)
11449 				 * with different pointer types:
11450 				 * src_reg == ctx in one branch and
11451 				 * src_reg == stack|map in some other branch.
11452 				 * Reject it.
11453 				 */
11454 				verbose(env, "same insn cannot be used with different pointers\n");
11455 				return -EINVAL;
11456 			}
11457 
11458 		} else if (class == BPF_STX) {
11459 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11460 
11461 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11462 				err = check_atomic(env, env->insn_idx, insn);
11463 				if (err)
11464 					return err;
11465 				env->insn_idx++;
11466 				continue;
11467 			}
11468 
11469 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11470 				verbose(env, "BPF_STX uses reserved fields\n");
11471 				return -EINVAL;
11472 			}
11473 
11474 			/* check src1 operand */
11475 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11476 			if (err)
11477 				return err;
11478 			/* check src2 operand */
11479 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11480 			if (err)
11481 				return err;
11482 
11483 			dst_reg_type = regs[insn->dst_reg].type;
11484 
11485 			/* check that memory (dst_reg + off) is writeable */
11486 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11487 					       insn->off, BPF_SIZE(insn->code),
11488 					       BPF_WRITE, insn->src_reg, false);
11489 			if (err)
11490 				return err;
11491 
11492 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11493 
11494 			if (*prev_dst_type == NOT_INIT) {
11495 				*prev_dst_type = dst_reg_type;
11496 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11497 				verbose(env, "same insn cannot be used with different pointers\n");
11498 				return -EINVAL;
11499 			}
11500 
11501 		} else if (class == BPF_ST) {
11502 			if (BPF_MODE(insn->code) != BPF_MEM ||
11503 			    insn->src_reg != BPF_REG_0) {
11504 				verbose(env, "BPF_ST uses reserved fields\n");
11505 				return -EINVAL;
11506 			}
11507 			/* check src operand */
11508 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11509 			if (err)
11510 				return err;
11511 
11512 			if (is_ctx_reg(env, insn->dst_reg)) {
11513 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11514 					insn->dst_reg,
11515 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11516 				return -EACCES;
11517 			}
11518 
11519 			/* check that memory (dst_reg + off) is writeable */
11520 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11521 					       insn->off, BPF_SIZE(insn->code),
11522 					       BPF_WRITE, -1, false);
11523 			if (err)
11524 				return err;
11525 
11526 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11527 			u8 opcode = BPF_OP(insn->code);
11528 
11529 			env->jmps_processed++;
11530 			if (opcode == BPF_CALL) {
11531 				if (BPF_SRC(insn->code) != BPF_K ||
11532 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11533 				     && insn->off != 0) ||
11534 				    (insn->src_reg != BPF_REG_0 &&
11535 				     insn->src_reg != BPF_PSEUDO_CALL &&
11536 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11537 				    insn->dst_reg != BPF_REG_0 ||
11538 				    class == BPF_JMP32) {
11539 					verbose(env, "BPF_CALL uses reserved fields\n");
11540 					return -EINVAL;
11541 				}
11542 
11543 				if (env->cur_state->active_spin_lock &&
11544 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11545 				     insn->imm != BPF_FUNC_spin_unlock)) {
11546 					verbose(env, "function calls are not allowed while holding a lock\n");
11547 					return -EINVAL;
11548 				}
11549 				if (insn->src_reg == BPF_PSEUDO_CALL)
11550 					err = check_func_call(env, insn, &env->insn_idx);
11551 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11552 					err = check_kfunc_call(env, insn);
11553 				else
11554 					err = check_helper_call(env, insn, &env->insn_idx);
11555 				if (err)
11556 					return err;
11557 			} else if (opcode == BPF_JA) {
11558 				if (BPF_SRC(insn->code) != BPF_K ||
11559 				    insn->imm != 0 ||
11560 				    insn->src_reg != BPF_REG_0 ||
11561 				    insn->dst_reg != BPF_REG_0 ||
11562 				    class == BPF_JMP32) {
11563 					verbose(env, "BPF_JA uses reserved fields\n");
11564 					return -EINVAL;
11565 				}
11566 
11567 				env->insn_idx += insn->off + 1;
11568 				continue;
11569 
11570 			} else if (opcode == BPF_EXIT) {
11571 				if (BPF_SRC(insn->code) != BPF_K ||
11572 				    insn->imm != 0 ||
11573 				    insn->src_reg != BPF_REG_0 ||
11574 				    insn->dst_reg != BPF_REG_0 ||
11575 				    class == BPF_JMP32) {
11576 					verbose(env, "BPF_EXIT uses reserved fields\n");
11577 					return -EINVAL;
11578 				}
11579 
11580 				if (env->cur_state->active_spin_lock) {
11581 					verbose(env, "bpf_spin_unlock is missing\n");
11582 					return -EINVAL;
11583 				}
11584 
11585 				if (state->curframe) {
11586 					/* exit from nested function */
11587 					err = prepare_func_exit(env, &env->insn_idx);
11588 					if (err)
11589 						return err;
11590 					do_print_state = true;
11591 					continue;
11592 				}
11593 
11594 				err = check_reference_leak(env);
11595 				if (err)
11596 					return err;
11597 
11598 				err = check_return_code(env);
11599 				if (err)
11600 					return err;
11601 process_bpf_exit:
11602 				mark_verifier_state_scratched(env);
11603 				update_branch_counts(env, env->cur_state);
11604 				err = pop_stack(env, &prev_insn_idx,
11605 						&env->insn_idx, pop_log);
11606 				if (err < 0) {
11607 					if (err != -ENOENT)
11608 						return err;
11609 					break;
11610 				} else {
11611 					do_print_state = true;
11612 					continue;
11613 				}
11614 			} else {
11615 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11616 				if (err)
11617 					return err;
11618 			}
11619 		} else if (class == BPF_LD) {
11620 			u8 mode = BPF_MODE(insn->code);
11621 
11622 			if (mode == BPF_ABS || mode == BPF_IND) {
11623 				err = check_ld_abs(env, insn);
11624 				if (err)
11625 					return err;
11626 
11627 			} else if (mode == BPF_IMM) {
11628 				err = check_ld_imm(env, insn);
11629 				if (err)
11630 					return err;
11631 
11632 				env->insn_idx++;
11633 				sanitize_mark_insn_seen(env);
11634 			} else {
11635 				verbose(env, "invalid BPF_LD mode\n");
11636 				return -EINVAL;
11637 			}
11638 		} else {
11639 			verbose(env, "unknown insn class %d\n", class);
11640 			return -EINVAL;
11641 		}
11642 
11643 		env->insn_idx++;
11644 	}
11645 
11646 	return 0;
11647 }
11648 
11649 static int find_btf_percpu_datasec(struct btf *btf)
11650 {
11651 	const struct btf_type *t;
11652 	const char *tname;
11653 	int i, n;
11654 
11655 	/*
11656 	 * Both vmlinux and module each have their own ".data..percpu"
11657 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11658 	 * types to look at only module's own BTF types.
11659 	 */
11660 	n = btf_nr_types(btf);
11661 	if (btf_is_module(btf))
11662 		i = btf_nr_types(btf_vmlinux);
11663 	else
11664 		i = 1;
11665 
11666 	for(; i < n; i++) {
11667 		t = btf_type_by_id(btf, i);
11668 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11669 			continue;
11670 
11671 		tname = btf_name_by_offset(btf, t->name_off);
11672 		if (!strcmp(tname, ".data..percpu"))
11673 			return i;
11674 	}
11675 
11676 	return -ENOENT;
11677 }
11678 
11679 /* replace pseudo btf_id with kernel symbol address */
11680 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11681 			       struct bpf_insn *insn,
11682 			       struct bpf_insn_aux_data *aux)
11683 {
11684 	const struct btf_var_secinfo *vsi;
11685 	const struct btf_type *datasec;
11686 	struct btf_mod_pair *btf_mod;
11687 	const struct btf_type *t;
11688 	const char *sym_name;
11689 	bool percpu = false;
11690 	u32 type, id = insn->imm;
11691 	struct btf *btf;
11692 	s32 datasec_id;
11693 	u64 addr;
11694 	int i, btf_fd, err;
11695 
11696 	btf_fd = insn[1].imm;
11697 	if (btf_fd) {
11698 		btf = btf_get_by_fd(btf_fd);
11699 		if (IS_ERR(btf)) {
11700 			verbose(env, "invalid module BTF object FD specified.\n");
11701 			return -EINVAL;
11702 		}
11703 	} else {
11704 		if (!btf_vmlinux) {
11705 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11706 			return -EINVAL;
11707 		}
11708 		btf = btf_vmlinux;
11709 		btf_get(btf);
11710 	}
11711 
11712 	t = btf_type_by_id(btf, id);
11713 	if (!t) {
11714 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11715 		err = -ENOENT;
11716 		goto err_put;
11717 	}
11718 
11719 	if (!btf_type_is_var(t)) {
11720 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11721 		err = -EINVAL;
11722 		goto err_put;
11723 	}
11724 
11725 	sym_name = btf_name_by_offset(btf, t->name_off);
11726 	addr = kallsyms_lookup_name(sym_name);
11727 	if (!addr) {
11728 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11729 			sym_name);
11730 		err = -ENOENT;
11731 		goto err_put;
11732 	}
11733 
11734 	datasec_id = find_btf_percpu_datasec(btf);
11735 	if (datasec_id > 0) {
11736 		datasec = btf_type_by_id(btf, datasec_id);
11737 		for_each_vsi(i, datasec, vsi) {
11738 			if (vsi->type == id) {
11739 				percpu = true;
11740 				break;
11741 			}
11742 		}
11743 	}
11744 
11745 	insn[0].imm = (u32)addr;
11746 	insn[1].imm = addr >> 32;
11747 
11748 	type = t->type;
11749 	t = btf_type_skip_modifiers(btf, type, NULL);
11750 	if (percpu) {
11751 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11752 		aux->btf_var.btf = btf;
11753 		aux->btf_var.btf_id = type;
11754 	} else if (!btf_type_is_struct(t)) {
11755 		const struct btf_type *ret;
11756 		const char *tname;
11757 		u32 tsize;
11758 
11759 		/* resolve the type size of ksym. */
11760 		ret = btf_resolve_size(btf, t, &tsize);
11761 		if (IS_ERR(ret)) {
11762 			tname = btf_name_by_offset(btf, t->name_off);
11763 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11764 				tname, PTR_ERR(ret));
11765 			err = -EINVAL;
11766 			goto err_put;
11767 		}
11768 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11769 		aux->btf_var.mem_size = tsize;
11770 	} else {
11771 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11772 		aux->btf_var.btf = btf;
11773 		aux->btf_var.btf_id = type;
11774 	}
11775 
11776 	/* check whether we recorded this BTF (and maybe module) already */
11777 	for (i = 0; i < env->used_btf_cnt; i++) {
11778 		if (env->used_btfs[i].btf == btf) {
11779 			btf_put(btf);
11780 			return 0;
11781 		}
11782 	}
11783 
11784 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11785 		err = -E2BIG;
11786 		goto err_put;
11787 	}
11788 
11789 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11790 	btf_mod->btf = btf;
11791 	btf_mod->module = NULL;
11792 
11793 	/* if we reference variables from kernel module, bump its refcount */
11794 	if (btf_is_module(btf)) {
11795 		btf_mod->module = btf_try_get_module(btf);
11796 		if (!btf_mod->module) {
11797 			err = -ENXIO;
11798 			goto err_put;
11799 		}
11800 	}
11801 
11802 	env->used_btf_cnt++;
11803 
11804 	return 0;
11805 err_put:
11806 	btf_put(btf);
11807 	return err;
11808 }
11809 
11810 static int check_map_prealloc(struct bpf_map *map)
11811 {
11812 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11813 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11814 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11815 		!(map->map_flags & BPF_F_NO_PREALLOC);
11816 }
11817 
11818 static bool is_tracing_prog_type(enum bpf_prog_type type)
11819 {
11820 	switch (type) {
11821 	case BPF_PROG_TYPE_KPROBE:
11822 	case BPF_PROG_TYPE_TRACEPOINT:
11823 	case BPF_PROG_TYPE_PERF_EVENT:
11824 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11825 		return true;
11826 	default:
11827 		return false;
11828 	}
11829 }
11830 
11831 static bool is_preallocated_map(struct bpf_map *map)
11832 {
11833 	if (!check_map_prealloc(map))
11834 		return false;
11835 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11836 		return false;
11837 	return true;
11838 }
11839 
11840 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11841 					struct bpf_map *map,
11842 					struct bpf_prog *prog)
11843 
11844 {
11845 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11846 	/*
11847 	 * Validate that trace type programs use preallocated hash maps.
11848 	 *
11849 	 * For programs attached to PERF events this is mandatory as the
11850 	 * perf NMI can hit any arbitrary code sequence.
11851 	 *
11852 	 * All other trace types using preallocated hash maps are unsafe as
11853 	 * well because tracepoint or kprobes can be inside locked regions
11854 	 * of the memory allocator or at a place where a recursion into the
11855 	 * memory allocator would see inconsistent state.
11856 	 *
11857 	 * On RT enabled kernels run-time allocation of all trace type
11858 	 * programs is strictly prohibited due to lock type constraints. On
11859 	 * !RT kernels it is allowed for backwards compatibility reasons for
11860 	 * now, but warnings are emitted so developers are made aware of
11861 	 * the unsafety and can fix their programs before this is enforced.
11862 	 */
11863 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11864 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11865 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11866 			return -EINVAL;
11867 		}
11868 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11869 			verbose(env, "trace type programs can only use preallocated hash map\n");
11870 			return -EINVAL;
11871 		}
11872 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11873 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11874 	}
11875 
11876 	if (map_value_has_spin_lock(map)) {
11877 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11878 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11879 			return -EINVAL;
11880 		}
11881 
11882 		if (is_tracing_prog_type(prog_type)) {
11883 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11884 			return -EINVAL;
11885 		}
11886 
11887 		if (prog->aux->sleepable) {
11888 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11889 			return -EINVAL;
11890 		}
11891 	}
11892 
11893 	if (map_value_has_timer(map)) {
11894 		if (is_tracing_prog_type(prog_type)) {
11895 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
11896 			return -EINVAL;
11897 		}
11898 	}
11899 
11900 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11901 	    !bpf_offload_prog_map_match(prog, map)) {
11902 		verbose(env, "offload device mismatch between prog and map\n");
11903 		return -EINVAL;
11904 	}
11905 
11906 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11907 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11908 		return -EINVAL;
11909 	}
11910 
11911 	if (prog->aux->sleepable)
11912 		switch (map->map_type) {
11913 		case BPF_MAP_TYPE_HASH:
11914 		case BPF_MAP_TYPE_LRU_HASH:
11915 		case BPF_MAP_TYPE_ARRAY:
11916 		case BPF_MAP_TYPE_PERCPU_HASH:
11917 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11918 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11919 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11920 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11921 			if (!is_preallocated_map(map)) {
11922 				verbose(env,
11923 					"Sleepable programs can only use preallocated maps\n");
11924 				return -EINVAL;
11925 			}
11926 			break;
11927 		case BPF_MAP_TYPE_RINGBUF:
11928 		case BPF_MAP_TYPE_INODE_STORAGE:
11929 		case BPF_MAP_TYPE_SK_STORAGE:
11930 		case BPF_MAP_TYPE_TASK_STORAGE:
11931 			break;
11932 		default:
11933 			verbose(env,
11934 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11935 			return -EINVAL;
11936 		}
11937 
11938 	return 0;
11939 }
11940 
11941 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11942 {
11943 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11944 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11945 }
11946 
11947 /* find and rewrite pseudo imm in ld_imm64 instructions:
11948  *
11949  * 1. if it accesses map FD, replace it with actual map pointer.
11950  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11951  *
11952  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11953  */
11954 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11955 {
11956 	struct bpf_insn *insn = env->prog->insnsi;
11957 	int insn_cnt = env->prog->len;
11958 	int i, j, err;
11959 
11960 	err = bpf_prog_calc_tag(env->prog);
11961 	if (err)
11962 		return err;
11963 
11964 	for (i = 0; i < insn_cnt; i++, insn++) {
11965 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11966 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11967 			verbose(env, "BPF_LDX uses reserved fields\n");
11968 			return -EINVAL;
11969 		}
11970 
11971 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11972 			struct bpf_insn_aux_data *aux;
11973 			struct bpf_map *map;
11974 			struct fd f;
11975 			u64 addr;
11976 			u32 fd;
11977 
11978 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11979 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11980 			    insn[1].off != 0) {
11981 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11982 				return -EINVAL;
11983 			}
11984 
11985 			if (insn[0].src_reg == 0)
11986 				/* valid generic load 64-bit imm */
11987 				goto next_insn;
11988 
11989 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11990 				aux = &env->insn_aux_data[i];
11991 				err = check_pseudo_btf_id(env, insn, aux);
11992 				if (err)
11993 					return err;
11994 				goto next_insn;
11995 			}
11996 
11997 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11998 				aux = &env->insn_aux_data[i];
11999 				aux->ptr_type = PTR_TO_FUNC;
12000 				goto next_insn;
12001 			}
12002 
12003 			/* In final convert_pseudo_ld_imm64() step, this is
12004 			 * converted into regular 64-bit imm load insn.
12005 			 */
12006 			switch (insn[0].src_reg) {
12007 			case BPF_PSEUDO_MAP_VALUE:
12008 			case BPF_PSEUDO_MAP_IDX_VALUE:
12009 				break;
12010 			case BPF_PSEUDO_MAP_FD:
12011 			case BPF_PSEUDO_MAP_IDX:
12012 				if (insn[1].imm == 0)
12013 					break;
12014 				fallthrough;
12015 			default:
12016 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12017 				return -EINVAL;
12018 			}
12019 
12020 			switch (insn[0].src_reg) {
12021 			case BPF_PSEUDO_MAP_IDX_VALUE:
12022 			case BPF_PSEUDO_MAP_IDX:
12023 				if (bpfptr_is_null(env->fd_array)) {
12024 					verbose(env, "fd_idx without fd_array is invalid\n");
12025 					return -EPROTO;
12026 				}
12027 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12028 							    insn[0].imm * sizeof(fd),
12029 							    sizeof(fd)))
12030 					return -EFAULT;
12031 				break;
12032 			default:
12033 				fd = insn[0].imm;
12034 				break;
12035 			}
12036 
12037 			f = fdget(fd);
12038 			map = __bpf_map_get(f);
12039 			if (IS_ERR(map)) {
12040 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12041 					insn[0].imm);
12042 				return PTR_ERR(map);
12043 			}
12044 
12045 			err = check_map_prog_compatibility(env, map, env->prog);
12046 			if (err) {
12047 				fdput(f);
12048 				return err;
12049 			}
12050 
12051 			aux = &env->insn_aux_data[i];
12052 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12053 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12054 				addr = (unsigned long)map;
12055 			} else {
12056 				u32 off = insn[1].imm;
12057 
12058 				if (off >= BPF_MAX_VAR_OFF) {
12059 					verbose(env, "direct value offset of %u is not allowed\n", off);
12060 					fdput(f);
12061 					return -EINVAL;
12062 				}
12063 
12064 				if (!map->ops->map_direct_value_addr) {
12065 					verbose(env, "no direct value access support for this map type\n");
12066 					fdput(f);
12067 					return -EINVAL;
12068 				}
12069 
12070 				err = map->ops->map_direct_value_addr(map, &addr, off);
12071 				if (err) {
12072 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12073 						map->value_size, off);
12074 					fdput(f);
12075 					return err;
12076 				}
12077 
12078 				aux->map_off = off;
12079 				addr += off;
12080 			}
12081 
12082 			insn[0].imm = (u32)addr;
12083 			insn[1].imm = addr >> 32;
12084 
12085 			/* check whether we recorded this map already */
12086 			for (j = 0; j < env->used_map_cnt; j++) {
12087 				if (env->used_maps[j] == map) {
12088 					aux->map_index = j;
12089 					fdput(f);
12090 					goto next_insn;
12091 				}
12092 			}
12093 
12094 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12095 				fdput(f);
12096 				return -E2BIG;
12097 			}
12098 
12099 			/* hold the map. If the program is rejected by verifier,
12100 			 * the map will be released by release_maps() or it
12101 			 * will be used by the valid program until it's unloaded
12102 			 * and all maps are released in free_used_maps()
12103 			 */
12104 			bpf_map_inc(map);
12105 
12106 			aux->map_index = env->used_map_cnt;
12107 			env->used_maps[env->used_map_cnt++] = map;
12108 
12109 			if (bpf_map_is_cgroup_storage(map) &&
12110 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12111 				verbose(env, "only one cgroup storage of each type is allowed\n");
12112 				fdput(f);
12113 				return -EBUSY;
12114 			}
12115 
12116 			fdput(f);
12117 next_insn:
12118 			insn++;
12119 			i++;
12120 			continue;
12121 		}
12122 
12123 		/* Basic sanity check before we invest more work here. */
12124 		if (!bpf_opcode_in_insntable(insn->code)) {
12125 			verbose(env, "unknown opcode %02x\n", insn->code);
12126 			return -EINVAL;
12127 		}
12128 	}
12129 
12130 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12131 	 * 'struct bpf_map *' into a register instead of user map_fd.
12132 	 * These pointers will be used later by verifier to validate map access.
12133 	 */
12134 	return 0;
12135 }
12136 
12137 /* drop refcnt of maps used by the rejected program */
12138 static void release_maps(struct bpf_verifier_env *env)
12139 {
12140 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12141 			     env->used_map_cnt);
12142 }
12143 
12144 /* drop refcnt of maps used by the rejected program */
12145 static void release_btfs(struct bpf_verifier_env *env)
12146 {
12147 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12148 			     env->used_btf_cnt);
12149 }
12150 
12151 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12152 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12153 {
12154 	struct bpf_insn *insn = env->prog->insnsi;
12155 	int insn_cnt = env->prog->len;
12156 	int i;
12157 
12158 	for (i = 0; i < insn_cnt; i++, insn++) {
12159 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12160 			continue;
12161 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12162 			continue;
12163 		insn->src_reg = 0;
12164 	}
12165 }
12166 
12167 /* single env->prog->insni[off] instruction was replaced with the range
12168  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12169  * [0, off) and [off, end) to new locations, so the patched range stays zero
12170  */
12171 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12172 				 struct bpf_insn_aux_data *new_data,
12173 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12174 {
12175 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12176 	struct bpf_insn *insn = new_prog->insnsi;
12177 	u32 old_seen = old_data[off].seen;
12178 	u32 prog_len;
12179 	int i;
12180 
12181 	/* aux info at OFF always needs adjustment, no matter fast path
12182 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12183 	 * original insn at old prog.
12184 	 */
12185 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12186 
12187 	if (cnt == 1)
12188 		return;
12189 	prog_len = new_prog->len;
12190 
12191 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12192 	memcpy(new_data + off + cnt - 1, old_data + off,
12193 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12194 	for (i = off; i < off + cnt - 1; i++) {
12195 		/* Expand insni[off]'s seen count to the patched range. */
12196 		new_data[i].seen = old_seen;
12197 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12198 	}
12199 	env->insn_aux_data = new_data;
12200 	vfree(old_data);
12201 }
12202 
12203 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12204 {
12205 	int i;
12206 
12207 	if (len == 1)
12208 		return;
12209 	/* NOTE: fake 'exit' subprog should be updated as well. */
12210 	for (i = 0; i <= env->subprog_cnt; i++) {
12211 		if (env->subprog_info[i].start <= off)
12212 			continue;
12213 		env->subprog_info[i].start += len - 1;
12214 	}
12215 }
12216 
12217 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12218 {
12219 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12220 	int i, sz = prog->aux->size_poke_tab;
12221 	struct bpf_jit_poke_descriptor *desc;
12222 
12223 	for (i = 0; i < sz; i++) {
12224 		desc = &tab[i];
12225 		if (desc->insn_idx <= off)
12226 			continue;
12227 		desc->insn_idx += len - 1;
12228 	}
12229 }
12230 
12231 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12232 					    const struct bpf_insn *patch, u32 len)
12233 {
12234 	struct bpf_prog *new_prog;
12235 	struct bpf_insn_aux_data *new_data = NULL;
12236 
12237 	if (len > 1) {
12238 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12239 					      sizeof(struct bpf_insn_aux_data)));
12240 		if (!new_data)
12241 			return NULL;
12242 	}
12243 
12244 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12245 	if (IS_ERR(new_prog)) {
12246 		if (PTR_ERR(new_prog) == -ERANGE)
12247 			verbose(env,
12248 				"insn %d cannot be patched due to 16-bit range\n",
12249 				env->insn_aux_data[off].orig_idx);
12250 		vfree(new_data);
12251 		return NULL;
12252 	}
12253 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12254 	adjust_subprog_starts(env, off, len);
12255 	adjust_poke_descs(new_prog, off, len);
12256 	return new_prog;
12257 }
12258 
12259 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12260 					      u32 off, u32 cnt)
12261 {
12262 	int i, j;
12263 
12264 	/* find first prog starting at or after off (first to remove) */
12265 	for (i = 0; i < env->subprog_cnt; i++)
12266 		if (env->subprog_info[i].start >= off)
12267 			break;
12268 	/* find first prog starting at or after off + cnt (first to stay) */
12269 	for (j = i; j < env->subprog_cnt; j++)
12270 		if (env->subprog_info[j].start >= off + cnt)
12271 			break;
12272 	/* if j doesn't start exactly at off + cnt, we are just removing
12273 	 * the front of previous prog
12274 	 */
12275 	if (env->subprog_info[j].start != off + cnt)
12276 		j--;
12277 
12278 	if (j > i) {
12279 		struct bpf_prog_aux *aux = env->prog->aux;
12280 		int move;
12281 
12282 		/* move fake 'exit' subprog as well */
12283 		move = env->subprog_cnt + 1 - j;
12284 
12285 		memmove(env->subprog_info + i,
12286 			env->subprog_info + j,
12287 			sizeof(*env->subprog_info) * move);
12288 		env->subprog_cnt -= j - i;
12289 
12290 		/* remove func_info */
12291 		if (aux->func_info) {
12292 			move = aux->func_info_cnt - j;
12293 
12294 			memmove(aux->func_info + i,
12295 				aux->func_info + j,
12296 				sizeof(*aux->func_info) * move);
12297 			aux->func_info_cnt -= j - i;
12298 			/* func_info->insn_off is set after all code rewrites,
12299 			 * in adjust_btf_func() - no need to adjust
12300 			 */
12301 		}
12302 	} else {
12303 		/* convert i from "first prog to remove" to "first to adjust" */
12304 		if (env->subprog_info[i].start == off)
12305 			i++;
12306 	}
12307 
12308 	/* update fake 'exit' subprog as well */
12309 	for (; i <= env->subprog_cnt; i++)
12310 		env->subprog_info[i].start -= cnt;
12311 
12312 	return 0;
12313 }
12314 
12315 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12316 				      u32 cnt)
12317 {
12318 	struct bpf_prog *prog = env->prog;
12319 	u32 i, l_off, l_cnt, nr_linfo;
12320 	struct bpf_line_info *linfo;
12321 
12322 	nr_linfo = prog->aux->nr_linfo;
12323 	if (!nr_linfo)
12324 		return 0;
12325 
12326 	linfo = prog->aux->linfo;
12327 
12328 	/* find first line info to remove, count lines to be removed */
12329 	for (i = 0; i < nr_linfo; i++)
12330 		if (linfo[i].insn_off >= off)
12331 			break;
12332 
12333 	l_off = i;
12334 	l_cnt = 0;
12335 	for (; i < nr_linfo; i++)
12336 		if (linfo[i].insn_off < off + cnt)
12337 			l_cnt++;
12338 		else
12339 			break;
12340 
12341 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12342 	 * last removed linfo.  prog is already modified, so prog->len == off
12343 	 * means no live instructions after (tail of the program was removed).
12344 	 */
12345 	if (prog->len != off && l_cnt &&
12346 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12347 		l_cnt--;
12348 		linfo[--i].insn_off = off + cnt;
12349 	}
12350 
12351 	/* remove the line info which refer to the removed instructions */
12352 	if (l_cnt) {
12353 		memmove(linfo + l_off, linfo + i,
12354 			sizeof(*linfo) * (nr_linfo - i));
12355 
12356 		prog->aux->nr_linfo -= l_cnt;
12357 		nr_linfo = prog->aux->nr_linfo;
12358 	}
12359 
12360 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12361 	for (i = l_off; i < nr_linfo; i++)
12362 		linfo[i].insn_off -= cnt;
12363 
12364 	/* fix up all subprogs (incl. 'exit') which start >= off */
12365 	for (i = 0; i <= env->subprog_cnt; i++)
12366 		if (env->subprog_info[i].linfo_idx > l_off) {
12367 			/* program may have started in the removed region but
12368 			 * may not be fully removed
12369 			 */
12370 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12371 				env->subprog_info[i].linfo_idx -= l_cnt;
12372 			else
12373 				env->subprog_info[i].linfo_idx = l_off;
12374 		}
12375 
12376 	return 0;
12377 }
12378 
12379 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12380 {
12381 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12382 	unsigned int orig_prog_len = env->prog->len;
12383 	int err;
12384 
12385 	if (bpf_prog_is_dev_bound(env->prog->aux))
12386 		bpf_prog_offload_remove_insns(env, off, cnt);
12387 
12388 	err = bpf_remove_insns(env->prog, off, cnt);
12389 	if (err)
12390 		return err;
12391 
12392 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12393 	if (err)
12394 		return err;
12395 
12396 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12397 	if (err)
12398 		return err;
12399 
12400 	memmove(aux_data + off,	aux_data + off + cnt,
12401 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12402 
12403 	return 0;
12404 }
12405 
12406 /* The verifier does more data flow analysis than llvm and will not
12407  * explore branches that are dead at run time. Malicious programs can
12408  * have dead code too. Therefore replace all dead at-run-time code
12409  * with 'ja -1'.
12410  *
12411  * Just nops are not optimal, e.g. if they would sit at the end of the
12412  * program and through another bug we would manage to jump there, then
12413  * we'd execute beyond program memory otherwise. Returning exception
12414  * code also wouldn't work since we can have subprogs where the dead
12415  * code could be located.
12416  */
12417 static void sanitize_dead_code(struct bpf_verifier_env *env)
12418 {
12419 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12420 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12421 	struct bpf_insn *insn = env->prog->insnsi;
12422 	const int insn_cnt = env->prog->len;
12423 	int i;
12424 
12425 	for (i = 0; i < insn_cnt; i++) {
12426 		if (aux_data[i].seen)
12427 			continue;
12428 		memcpy(insn + i, &trap, sizeof(trap));
12429 		aux_data[i].zext_dst = false;
12430 	}
12431 }
12432 
12433 static bool insn_is_cond_jump(u8 code)
12434 {
12435 	u8 op;
12436 
12437 	if (BPF_CLASS(code) == BPF_JMP32)
12438 		return true;
12439 
12440 	if (BPF_CLASS(code) != BPF_JMP)
12441 		return false;
12442 
12443 	op = BPF_OP(code);
12444 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12445 }
12446 
12447 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12448 {
12449 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12450 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12451 	struct bpf_insn *insn = env->prog->insnsi;
12452 	const int insn_cnt = env->prog->len;
12453 	int i;
12454 
12455 	for (i = 0; i < insn_cnt; i++, insn++) {
12456 		if (!insn_is_cond_jump(insn->code))
12457 			continue;
12458 
12459 		if (!aux_data[i + 1].seen)
12460 			ja.off = insn->off;
12461 		else if (!aux_data[i + 1 + insn->off].seen)
12462 			ja.off = 0;
12463 		else
12464 			continue;
12465 
12466 		if (bpf_prog_is_dev_bound(env->prog->aux))
12467 			bpf_prog_offload_replace_insn(env, i, &ja);
12468 
12469 		memcpy(insn, &ja, sizeof(ja));
12470 	}
12471 }
12472 
12473 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12474 {
12475 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12476 	int insn_cnt = env->prog->len;
12477 	int i, err;
12478 
12479 	for (i = 0; i < insn_cnt; i++) {
12480 		int j;
12481 
12482 		j = 0;
12483 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12484 			j++;
12485 		if (!j)
12486 			continue;
12487 
12488 		err = verifier_remove_insns(env, i, j);
12489 		if (err)
12490 			return err;
12491 		insn_cnt = env->prog->len;
12492 	}
12493 
12494 	return 0;
12495 }
12496 
12497 static int opt_remove_nops(struct bpf_verifier_env *env)
12498 {
12499 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12500 	struct bpf_insn *insn = env->prog->insnsi;
12501 	int insn_cnt = env->prog->len;
12502 	int i, err;
12503 
12504 	for (i = 0; i < insn_cnt; i++) {
12505 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12506 			continue;
12507 
12508 		err = verifier_remove_insns(env, i, 1);
12509 		if (err)
12510 			return err;
12511 		insn_cnt--;
12512 		i--;
12513 	}
12514 
12515 	return 0;
12516 }
12517 
12518 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12519 					 const union bpf_attr *attr)
12520 {
12521 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12522 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12523 	int i, patch_len, delta = 0, len = env->prog->len;
12524 	struct bpf_insn *insns = env->prog->insnsi;
12525 	struct bpf_prog *new_prog;
12526 	bool rnd_hi32;
12527 
12528 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12529 	zext_patch[1] = BPF_ZEXT_REG(0);
12530 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12531 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12532 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12533 	for (i = 0; i < len; i++) {
12534 		int adj_idx = i + delta;
12535 		struct bpf_insn insn;
12536 		int load_reg;
12537 
12538 		insn = insns[adj_idx];
12539 		load_reg = insn_def_regno(&insn);
12540 		if (!aux[adj_idx].zext_dst) {
12541 			u8 code, class;
12542 			u32 imm_rnd;
12543 
12544 			if (!rnd_hi32)
12545 				continue;
12546 
12547 			code = insn.code;
12548 			class = BPF_CLASS(code);
12549 			if (load_reg == -1)
12550 				continue;
12551 
12552 			/* NOTE: arg "reg" (the fourth one) is only used for
12553 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12554 			 *       here.
12555 			 */
12556 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12557 				if (class == BPF_LD &&
12558 				    BPF_MODE(code) == BPF_IMM)
12559 					i++;
12560 				continue;
12561 			}
12562 
12563 			/* ctx load could be transformed into wider load. */
12564 			if (class == BPF_LDX &&
12565 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12566 				continue;
12567 
12568 			imm_rnd = get_random_int();
12569 			rnd_hi32_patch[0] = insn;
12570 			rnd_hi32_patch[1].imm = imm_rnd;
12571 			rnd_hi32_patch[3].dst_reg = load_reg;
12572 			patch = rnd_hi32_patch;
12573 			patch_len = 4;
12574 			goto apply_patch_buffer;
12575 		}
12576 
12577 		/* Add in an zero-extend instruction if a) the JIT has requested
12578 		 * it or b) it's a CMPXCHG.
12579 		 *
12580 		 * The latter is because: BPF_CMPXCHG always loads a value into
12581 		 * R0, therefore always zero-extends. However some archs'
12582 		 * equivalent instruction only does this load when the
12583 		 * comparison is successful. This detail of CMPXCHG is
12584 		 * orthogonal to the general zero-extension behaviour of the
12585 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12586 		 */
12587 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12588 			continue;
12589 
12590 		if (WARN_ON(load_reg == -1)) {
12591 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12592 			return -EFAULT;
12593 		}
12594 
12595 		zext_patch[0] = insn;
12596 		zext_patch[1].dst_reg = load_reg;
12597 		zext_patch[1].src_reg = load_reg;
12598 		patch = zext_patch;
12599 		patch_len = 2;
12600 apply_patch_buffer:
12601 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12602 		if (!new_prog)
12603 			return -ENOMEM;
12604 		env->prog = new_prog;
12605 		insns = new_prog->insnsi;
12606 		aux = env->insn_aux_data;
12607 		delta += patch_len - 1;
12608 	}
12609 
12610 	return 0;
12611 }
12612 
12613 /* convert load instructions that access fields of a context type into a
12614  * sequence of instructions that access fields of the underlying structure:
12615  *     struct __sk_buff    -> struct sk_buff
12616  *     struct bpf_sock_ops -> struct sock
12617  */
12618 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12619 {
12620 	const struct bpf_verifier_ops *ops = env->ops;
12621 	int i, cnt, size, ctx_field_size, delta = 0;
12622 	const int insn_cnt = env->prog->len;
12623 	struct bpf_insn insn_buf[16], *insn;
12624 	u32 target_size, size_default, off;
12625 	struct bpf_prog *new_prog;
12626 	enum bpf_access_type type;
12627 	bool is_narrower_load;
12628 
12629 	if (ops->gen_prologue || env->seen_direct_write) {
12630 		if (!ops->gen_prologue) {
12631 			verbose(env, "bpf verifier is misconfigured\n");
12632 			return -EINVAL;
12633 		}
12634 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12635 					env->prog);
12636 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12637 			verbose(env, "bpf verifier is misconfigured\n");
12638 			return -EINVAL;
12639 		} else if (cnt) {
12640 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12641 			if (!new_prog)
12642 				return -ENOMEM;
12643 
12644 			env->prog = new_prog;
12645 			delta += cnt - 1;
12646 		}
12647 	}
12648 
12649 	if (bpf_prog_is_dev_bound(env->prog->aux))
12650 		return 0;
12651 
12652 	insn = env->prog->insnsi + delta;
12653 
12654 	for (i = 0; i < insn_cnt; i++, insn++) {
12655 		bpf_convert_ctx_access_t convert_ctx_access;
12656 		bool ctx_access;
12657 
12658 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12659 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12660 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12661 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12662 			type = BPF_READ;
12663 			ctx_access = true;
12664 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12665 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12666 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12667 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12668 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12669 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12670 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12671 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12672 			type = BPF_WRITE;
12673 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12674 		} else {
12675 			continue;
12676 		}
12677 
12678 		if (type == BPF_WRITE &&
12679 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12680 			struct bpf_insn patch[] = {
12681 				*insn,
12682 				BPF_ST_NOSPEC(),
12683 			};
12684 
12685 			cnt = ARRAY_SIZE(patch);
12686 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12687 			if (!new_prog)
12688 				return -ENOMEM;
12689 
12690 			delta    += cnt - 1;
12691 			env->prog = new_prog;
12692 			insn      = new_prog->insnsi + i + delta;
12693 			continue;
12694 		}
12695 
12696 		if (!ctx_access)
12697 			continue;
12698 
12699 		switch (env->insn_aux_data[i + delta].ptr_type) {
12700 		case PTR_TO_CTX:
12701 			if (!ops->convert_ctx_access)
12702 				continue;
12703 			convert_ctx_access = ops->convert_ctx_access;
12704 			break;
12705 		case PTR_TO_SOCKET:
12706 		case PTR_TO_SOCK_COMMON:
12707 			convert_ctx_access = bpf_sock_convert_ctx_access;
12708 			break;
12709 		case PTR_TO_TCP_SOCK:
12710 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12711 			break;
12712 		case PTR_TO_XDP_SOCK:
12713 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12714 			break;
12715 		case PTR_TO_BTF_ID:
12716 			if (type == BPF_READ) {
12717 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12718 					BPF_SIZE((insn)->code);
12719 				env->prog->aux->num_exentries++;
12720 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12721 				verbose(env, "Writes through BTF pointers are not allowed\n");
12722 				return -EINVAL;
12723 			}
12724 			continue;
12725 		default:
12726 			continue;
12727 		}
12728 
12729 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12730 		size = BPF_LDST_BYTES(insn);
12731 
12732 		/* If the read access is a narrower load of the field,
12733 		 * convert to a 4/8-byte load, to minimum program type specific
12734 		 * convert_ctx_access changes. If conversion is successful,
12735 		 * we will apply proper mask to the result.
12736 		 */
12737 		is_narrower_load = size < ctx_field_size;
12738 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12739 		off = insn->off;
12740 		if (is_narrower_load) {
12741 			u8 size_code;
12742 
12743 			if (type == BPF_WRITE) {
12744 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12745 				return -EINVAL;
12746 			}
12747 
12748 			size_code = BPF_H;
12749 			if (ctx_field_size == 4)
12750 				size_code = BPF_W;
12751 			else if (ctx_field_size == 8)
12752 				size_code = BPF_DW;
12753 
12754 			insn->off = off & ~(size_default - 1);
12755 			insn->code = BPF_LDX | BPF_MEM | size_code;
12756 		}
12757 
12758 		target_size = 0;
12759 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12760 					 &target_size);
12761 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12762 		    (ctx_field_size && !target_size)) {
12763 			verbose(env, "bpf verifier is misconfigured\n");
12764 			return -EINVAL;
12765 		}
12766 
12767 		if (is_narrower_load && size < target_size) {
12768 			u8 shift = bpf_ctx_narrow_access_offset(
12769 				off, size, size_default) * 8;
12770 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12771 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12772 				return -EINVAL;
12773 			}
12774 			if (ctx_field_size <= 4) {
12775 				if (shift)
12776 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12777 									insn->dst_reg,
12778 									shift);
12779 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12780 								(1 << size * 8) - 1);
12781 			} else {
12782 				if (shift)
12783 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12784 									insn->dst_reg,
12785 									shift);
12786 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12787 								(1ULL << size * 8) - 1);
12788 			}
12789 		}
12790 
12791 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12792 		if (!new_prog)
12793 			return -ENOMEM;
12794 
12795 		delta += cnt - 1;
12796 
12797 		/* keep walking new program and skip insns we just inserted */
12798 		env->prog = new_prog;
12799 		insn      = new_prog->insnsi + i + delta;
12800 	}
12801 
12802 	return 0;
12803 }
12804 
12805 static int jit_subprogs(struct bpf_verifier_env *env)
12806 {
12807 	struct bpf_prog *prog = env->prog, **func, *tmp;
12808 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12809 	struct bpf_map *map_ptr;
12810 	struct bpf_insn *insn;
12811 	void *old_bpf_func;
12812 	int err, num_exentries;
12813 
12814 	if (env->subprog_cnt <= 1)
12815 		return 0;
12816 
12817 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12818 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12819 			continue;
12820 
12821 		/* Upon error here we cannot fall back to interpreter but
12822 		 * need a hard reject of the program. Thus -EFAULT is
12823 		 * propagated in any case.
12824 		 */
12825 		subprog = find_subprog(env, i + insn->imm + 1);
12826 		if (subprog < 0) {
12827 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12828 				  i + insn->imm + 1);
12829 			return -EFAULT;
12830 		}
12831 		/* temporarily remember subprog id inside insn instead of
12832 		 * aux_data, since next loop will split up all insns into funcs
12833 		 */
12834 		insn->off = subprog;
12835 		/* remember original imm in case JIT fails and fallback
12836 		 * to interpreter will be needed
12837 		 */
12838 		env->insn_aux_data[i].call_imm = insn->imm;
12839 		/* point imm to __bpf_call_base+1 from JITs point of view */
12840 		insn->imm = 1;
12841 		if (bpf_pseudo_func(insn))
12842 			/* jit (e.g. x86_64) may emit fewer instructions
12843 			 * if it learns a u32 imm is the same as a u64 imm.
12844 			 * Force a non zero here.
12845 			 */
12846 			insn[1].imm = 1;
12847 	}
12848 
12849 	err = bpf_prog_alloc_jited_linfo(prog);
12850 	if (err)
12851 		goto out_undo_insn;
12852 
12853 	err = -ENOMEM;
12854 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12855 	if (!func)
12856 		goto out_undo_insn;
12857 
12858 	for (i = 0; i < env->subprog_cnt; i++) {
12859 		subprog_start = subprog_end;
12860 		subprog_end = env->subprog_info[i + 1].start;
12861 
12862 		len = subprog_end - subprog_start;
12863 		/* bpf_prog_run() doesn't call subprogs directly,
12864 		 * hence main prog stats include the runtime of subprogs.
12865 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12866 		 * func[i]->stats will never be accessed and stays NULL
12867 		 */
12868 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12869 		if (!func[i])
12870 			goto out_free;
12871 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12872 		       len * sizeof(struct bpf_insn));
12873 		func[i]->type = prog->type;
12874 		func[i]->len = len;
12875 		if (bpf_prog_calc_tag(func[i]))
12876 			goto out_free;
12877 		func[i]->is_func = 1;
12878 		func[i]->aux->func_idx = i;
12879 		/* Below members will be freed only at prog->aux */
12880 		func[i]->aux->btf = prog->aux->btf;
12881 		func[i]->aux->func_info = prog->aux->func_info;
12882 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12883 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12884 
12885 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12886 			struct bpf_jit_poke_descriptor *poke;
12887 
12888 			poke = &prog->aux->poke_tab[j];
12889 			if (poke->insn_idx < subprog_end &&
12890 			    poke->insn_idx >= subprog_start)
12891 				poke->aux = func[i]->aux;
12892 		}
12893 
12894 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12895 		 * Long term would need debug info to populate names
12896 		 */
12897 		func[i]->aux->name[0] = 'F';
12898 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12899 		func[i]->jit_requested = 1;
12900 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12901 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
12902 		func[i]->aux->linfo = prog->aux->linfo;
12903 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12904 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12905 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12906 		num_exentries = 0;
12907 		insn = func[i]->insnsi;
12908 		for (j = 0; j < func[i]->len; j++, insn++) {
12909 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12910 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12911 				num_exentries++;
12912 		}
12913 		func[i]->aux->num_exentries = num_exentries;
12914 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12915 		func[i] = bpf_int_jit_compile(func[i]);
12916 		if (!func[i]->jited) {
12917 			err = -ENOTSUPP;
12918 			goto out_free;
12919 		}
12920 		cond_resched();
12921 	}
12922 
12923 	/* at this point all bpf functions were successfully JITed
12924 	 * now populate all bpf_calls with correct addresses and
12925 	 * run last pass of JIT
12926 	 */
12927 	for (i = 0; i < env->subprog_cnt; i++) {
12928 		insn = func[i]->insnsi;
12929 		for (j = 0; j < func[i]->len; j++, insn++) {
12930 			if (bpf_pseudo_func(insn)) {
12931 				subprog = insn->off;
12932 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12933 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12934 				continue;
12935 			}
12936 			if (!bpf_pseudo_call(insn))
12937 				continue;
12938 			subprog = insn->off;
12939 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12940 		}
12941 
12942 		/* we use the aux data to keep a list of the start addresses
12943 		 * of the JITed images for each function in the program
12944 		 *
12945 		 * for some architectures, such as powerpc64, the imm field
12946 		 * might not be large enough to hold the offset of the start
12947 		 * address of the callee's JITed image from __bpf_call_base
12948 		 *
12949 		 * in such cases, we can lookup the start address of a callee
12950 		 * by using its subprog id, available from the off field of
12951 		 * the call instruction, as an index for this list
12952 		 */
12953 		func[i]->aux->func = func;
12954 		func[i]->aux->func_cnt = env->subprog_cnt;
12955 	}
12956 	for (i = 0; i < env->subprog_cnt; i++) {
12957 		old_bpf_func = func[i]->bpf_func;
12958 		tmp = bpf_int_jit_compile(func[i]);
12959 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12960 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12961 			err = -ENOTSUPP;
12962 			goto out_free;
12963 		}
12964 		cond_resched();
12965 	}
12966 
12967 	/* finally lock prog and jit images for all functions and
12968 	 * populate kallsysm
12969 	 */
12970 	for (i = 0; i < env->subprog_cnt; i++) {
12971 		bpf_prog_lock_ro(func[i]);
12972 		bpf_prog_kallsyms_add(func[i]);
12973 	}
12974 
12975 	/* Last step: make now unused interpreter insns from main
12976 	 * prog consistent for later dump requests, so they can
12977 	 * later look the same as if they were interpreted only.
12978 	 */
12979 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12980 		if (bpf_pseudo_func(insn)) {
12981 			insn[0].imm = env->insn_aux_data[i].call_imm;
12982 			insn[1].imm = insn->off;
12983 			insn->off = 0;
12984 			continue;
12985 		}
12986 		if (!bpf_pseudo_call(insn))
12987 			continue;
12988 		insn->off = env->insn_aux_data[i].call_imm;
12989 		subprog = find_subprog(env, i + insn->off + 1);
12990 		insn->imm = subprog;
12991 	}
12992 
12993 	prog->jited = 1;
12994 	prog->bpf_func = func[0]->bpf_func;
12995 	prog->aux->func = func;
12996 	prog->aux->func_cnt = env->subprog_cnt;
12997 	bpf_prog_jit_attempt_done(prog);
12998 	return 0;
12999 out_free:
13000 	/* We failed JIT'ing, so at this point we need to unregister poke
13001 	 * descriptors from subprogs, so that kernel is not attempting to
13002 	 * patch it anymore as we're freeing the subprog JIT memory.
13003 	 */
13004 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13005 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13006 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13007 	}
13008 	/* At this point we're guaranteed that poke descriptors are not
13009 	 * live anymore. We can just unlink its descriptor table as it's
13010 	 * released with the main prog.
13011 	 */
13012 	for (i = 0; i < env->subprog_cnt; i++) {
13013 		if (!func[i])
13014 			continue;
13015 		func[i]->aux->poke_tab = NULL;
13016 		bpf_jit_free(func[i]);
13017 	}
13018 	kfree(func);
13019 out_undo_insn:
13020 	/* cleanup main prog to be interpreted */
13021 	prog->jit_requested = 0;
13022 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13023 		if (!bpf_pseudo_call(insn))
13024 			continue;
13025 		insn->off = 0;
13026 		insn->imm = env->insn_aux_data[i].call_imm;
13027 	}
13028 	bpf_prog_jit_attempt_done(prog);
13029 	return err;
13030 }
13031 
13032 static int fixup_call_args(struct bpf_verifier_env *env)
13033 {
13034 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13035 	struct bpf_prog *prog = env->prog;
13036 	struct bpf_insn *insn = prog->insnsi;
13037 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13038 	int i, depth;
13039 #endif
13040 	int err = 0;
13041 
13042 	if (env->prog->jit_requested &&
13043 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13044 		err = jit_subprogs(env);
13045 		if (err == 0)
13046 			return 0;
13047 		if (err == -EFAULT)
13048 			return err;
13049 	}
13050 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13051 	if (has_kfunc_call) {
13052 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13053 		return -EINVAL;
13054 	}
13055 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13056 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13057 		 * have to be rejected, since interpreter doesn't support them yet.
13058 		 */
13059 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13060 		return -EINVAL;
13061 	}
13062 	for (i = 0; i < prog->len; i++, insn++) {
13063 		if (bpf_pseudo_func(insn)) {
13064 			/* When JIT fails the progs with callback calls
13065 			 * have to be rejected, since interpreter doesn't support them yet.
13066 			 */
13067 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13068 			return -EINVAL;
13069 		}
13070 
13071 		if (!bpf_pseudo_call(insn))
13072 			continue;
13073 		depth = get_callee_stack_depth(env, insn, i);
13074 		if (depth < 0)
13075 			return depth;
13076 		bpf_patch_call_args(insn, depth);
13077 	}
13078 	err = 0;
13079 #endif
13080 	return err;
13081 }
13082 
13083 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13084 			    struct bpf_insn *insn)
13085 {
13086 	const struct bpf_kfunc_desc *desc;
13087 
13088 	if (!insn->imm) {
13089 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13090 		return -EINVAL;
13091 	}
13092 
13093 	/* insn->imm has the btf func_id. Replace it with
13094 	 * an address (relative to __bpf_base_call).
13095 	 */
13096 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13097 	if (!desc) {
13098 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13099 			insn->imm);
13100 		return -EFAULT;
13101 	}
13102 
13103 	insn->imm = desc->imm;
13104 
13105 	return 0;
13106 }
13107 
13108 /* Do various post-verification rewrites in a single program pass.
13109  * These rewrites simplify JIT and interpreter implementations.
13110  */
13111 static int do_misc_fixups(struct bpf_verifier_env *env)
13112 {
13113 	struct bpf_prog *prog = env->prog;
13114 	enum bpf_attach_type eatype = prog->expected_attach_type;
13115 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
13116 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13117 	struct bpf_insn *insn = prog->insnsi;
13118 	const struct bpf_func_proto *fn;
13119 	const int insn_cnt = prog->len;
13120 	const struct bpf_map_ops *ops;
13121 	struct bpf_insn_aux_data *aux;
13122 	struct bpf_insn insn_buf[16];
13123 	struct bpf_prog *new_prog;
13124 	struct bpf_map *map_ptr;
13125 	int i, ret, cnt, delta = 0;
13126 
13127 	for (i = 0; i < insn_cnt; i++, insn++) {
13128 		/* Make divide-by-zero exceptions impossible. */
13129 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13130 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13131 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13132 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13133 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13134 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13135 			struct bpf_insn *patchlet;
13136 			struct bpf_insn chk_and_div[] = {
13137 				/* [R,W]x div 0 -> 0 */
13138 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13139 					     BPF_JNE | BPF_K, insn->src_reg,
13140 					     0, 2, 0),
13141 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13142 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13143 				*insn,
13144 			};
13145 			struct bpf_insn chk_and_mod[] = {
13146 				/* [R,W]x mod 0 -> [R,W]x */
13147 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13148 					     BPF_JEQ | BPF_K, insn->src_reg,
13149 					     0, 1 + (is64 ? 0 : 1), 0),
13150 				*insn,
13151 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13152 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13153 			};
13154 
13155 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13156 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13157 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13158 
13159 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13160 			if (!new_prog)
13161 				return -ENOMEM;
13162 
13163 			delta    += cnt - 1;
13164 			env->prog = prog = new_prog;
13165 			insn      = new_prog->insnsi + i + delta;
13166 			continue;
13167 		}
13168 
13169 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13170 		if (BPF_CLASS(insn->code) == BPF_LD &&
13171 		    (BPF_MODE(insn->code) == BPF_ABS ||
13172 		     BPF_MODE(insn->code) == BPF_IND)) {
13173 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13174 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13175 				verbose(env, "bpf verifier is misconfigured\n");
13176 				return -EINVAL;
13177 			}
13178 
13179 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13180 			if (!new_prog)
13181 				return -ENOMEM;
13182 
13183 			delta    += cnt - 1;
13184 			env->prog = prog = new_prog;
13185 			insn      = new_prog->insnsi + i + delta;
13186 			continue;
13187 		}
13188 
13189 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
13190 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13191 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13192 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13193 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13194 			struct bpf_insn *patch = &insn_buf[0];
13195 			bool issrc, isneg, isimm;
13196 			u32 off_reg;
13197 
13198 			aux = &env->insn_aux_data[i + delta];
13199 			if (!aux->alu_state ||
13200 			    aux->alu_state == BPF_ALU_NON_POINTER)
13201 				continue;
13202 
13203 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13204 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13205 				BPF_ALU_SANITIZE_SRC;
13206 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13207 
13208 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13209 			if (isimm) {
13210 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13211 			} else {
13212 				if (isneg)
13213 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13214 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13215 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13216 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13217 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13218 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13219 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13220 			}
13221 			if (!issrc)
13222 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13223 			insn->src_reg = BPF_REG_AX;
13224 			if (isneg)
13225 				insn->code = insn->code == code_add ?
13226 					     code_sub : code_add;
13227 			*patch++ = *insn;
13228 			if (issrc && isneg && !isimm)
13229 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13230 			cnt = patch - insn_buf;
13231 
13232 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13233 			if (!new_prog)
13234 				return -ENOMEM;
13235 
13236 			delta    += cnt - 1;
13237 			env->prog = prog = new_prog;
13238 			insn      = new_prog->insnsi + i + delta;
13239 			continue;
13240 		}
13241 
13242 		if (insn->code != (BPF_JMP | BPF_CALL))
13243 			continue;
13244 		if (insn->src_reg == BPF_PSEUDO_CALL)
13245 			continue;
13246 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13247 			ret = fixup_kfunc_call(env, insn);
13248 			if (ret)
13249 				return ret;
13250 			continue;
13251 		}
13252 
13253 		if (insn->imm == BPF_FUNC_get_route_realm)
13254 			prog->dst_needed = 1;
13255 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13256 			bpf_user_rnd_init_once();
13257 		if (insn->imm == BPF_FUNC_override_return)
13258 			prog->kprobe_override = 1;
13259 		if (insn->imm == BPF_FUNC_tail_call) {
13260 			/* If we tail call into other programs, we
13261 			 * cannot make any assumptions since they can
13262 			 * be replaced dynamically during runtime in
13263 			 * the program array.
13264 			 */
13265 			prog->cb_access = 1;
13266 			if (!allow_tail_call_in_subprogs(env))
13267 				prog->aux->stack_depth = MAX_BPF_STACK;
13268 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13269 
13270 			/* mark bpf_tail_call as different opcode to avoid
13271 			 * conditional branch in the interpreter for every normal
13272 			 * call and to prevent accidental JITing by JIT compiler
13273 			 * that doesn't support bpf_tail_call yet
13274 			 */
13275 			insn->imm = 0;
13276 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13277 
13278 			aux = &env->insn_aux_data[i + delta];
13279 			if (env->bpf_capable && !expect_blinding &&
13280 			    prog->jit_requested &&
13281 			    !bpf_map_key_poisoned(aux) &&
13282 			    !bpf_map_ptr_poisoned(aux) &&
13283 			    !bpf_map_ptr_unpriv(aux)) {
13284 				struct bpf_jit_poke_descriptor desc = {
13285 					.reason = BPF_POKE_REASON_TAIL_CALL,
13286 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13287 					.tail_call.key = bpf_map_key_immediate(aux),
13288 					.insn_idx = i + delta,
13289 				};
13290 
13291 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13292 				if (ret < 0) {
13293 					verbose(env, "adding tail call poke descriptor failed\n");
13294 					return ret;
13295 				}
13296 
13297 				insn->imm = ret + 1;
13298 				continue;
13299 			}
13300 
13301 			if (!bpf_map_ptr_unpriv(aux))
13302 				continue;
13303 
13304 			/* instead of changing every JIT dealing with tail_call
13305 			 * emit two extra insns:
13306 			 * if (index >= max_entries) goto out;
13307 			 * index &= array->index_mask;
13308 			 * to avoid out-of-bounds cpu speculation
13309 			 */
13310 			if (bpf_map_ptr_poisoned(aux)) {
13311 				verbose(env, "tail_call abusing map_ptr\n");
13312 				return -EINVAL;
13313 			}
13314 
13315 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13316 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13317 						  map_ptr->max_entries, 2);
13318 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13319 						    container_of(map_ptr,
13320 								 struct bpf_array,
13321 								 map)->index_mask);
13322 			insn_buf[2] = *insn;
13323 			cnt = 3;
13324 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13325 			if (!new_prog)
13326 				return -ENOMEM;
13327 
13328 			delta    += cnt - 1;
13329 			env->prog = prog = new_prog;
13330 			insn      = new_prog->insnsi + i + delta;
13331 			continue;
13332 		}
13333 
13334 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13335 			/* The verifier will process callback_fn as many times as necessary
13336 			 * with different maps and the register states prepared by
13337 			 * set_timer_callback_state will be accurate.
13338 			 *
13339 			 * The following use case is valid:
13340 			 *   map1 is shared by prog1, prog2, prog3.
13341 			 *   prog1 calls bpf_timer_init for some map1 elements
13342 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13343 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13344 			 *   prog3 calls bpf_timer_start for some map1 elements.
13345 			 *     Those that were not both bpf_timer_init-ed and
13346 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13347 			 */
13348 			struct bpf_insn ld_addrs[2] = {
13349 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13350 			};
13351 
13352 			insn_buf[0] = ld_addrs[0];
13353 			insn_buf[1] = ld_addrs[1];
13354 			insn_buf[2] = *insn;
13355 			cnt = 3;
13356 
13357 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13358 			if (!new_prog)
13359 				return -ENOMEM;
13360 
13361 			delta    += cnt - 1;
13362 			env->prog = prog = new_prog;
13363 			insn      = new_prog->insnsi + i + delta;
13364 			goto patch_call_imm;
13365 		}
13366 
13367 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13368 		 * and other inlining handlers are currently limited to 64 bit
13369 		 * only.
13370 		 */
13371 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13372 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13373 		     insn->imm == BPF_FUNC_map_update_elem ||
13374 		     insn->imm == BPF_FUNC_map_delete_elem ||
13375 		     insn->imm == BPF_FUNC_map_push_elem   ||
13376 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13377 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13378 		     insn->imm == BPF_FUNC_redirect_map    ||
13379 		     insn->imm == BPF_FUNC_for_each_map_elem)) {
13380 			aux = &env->insn_aux_data[i + delta];
13381 			if (bpf_map_ptr_poisoned(aux))
13382 				goto patch_call_imm;
13383 
13384 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13385 			ops = map_ptr->ops;
13386 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13387 			    ops->map_gen_lookup) {
13388 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13389 				if (cnt == -EOPNOTSUPP)
13390 					goto patch_map_ops_generic;
13391 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13392 					verbose(env, "bpf verifier is misconfigured\n");
13393 					return -EINVAL;
13394 				}
13395 
13396 				new_prog = bpf_patch_insn_data(env, i + delta,
13397 							       insn_buf, cnt);
13398 				if (!new_prog)
13399 					return -ENOMEM;
13400 
13401 				delta    += cnt - 1;
13402 				env->prog = prog = new_prog;
13403 				insn      = new_prog->insnsi + i + delta;
13404 				continue;
13405 			}
13406 
13407 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13408 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13409 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13410 				     (int (*)(struct bpf_map *map, void *key))NULL));
13411 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13412 				     (int (*)(struct bpf_map *map, void *key, void *value,
13413 					      u64 flags))NULL));
13414 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13415 				     (int (*)(struct bpf_map *map, void *value,
13416 					      u64 flags))NULL));
13417 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13418 				     (int (*)(struct bpf_map *map, void *value))NULL));
13419 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13420 				     (int (*)(struct bpf_map *map, void *value))NULL));
13421 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13422 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13423 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13424 				     (int (*)(struct bpf_map *map,
13425 					      bpf_callback_t callback_fn,
13426 					      void *callback_ctx,
13427 					      u64 flags))NULL));
13428 
13429 patch_map_ops_generic:
13430 			switch (insn->imm) {
13431 			case BPF_FUNC_map_lookup_elem:
13432 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13433 				continue;
13434 			case BPF_FUNC_map_update_elem:
13435 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13436 				continue;
13437 			case BPF_FUNC_map_delete_elem:
13438 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13439 				continue;
13440 			case BPF_FUNC_map_push_elem:
13441 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13442 				continue;
13443 			case BPF_FUNC_map_pop_elem:
13444 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13445 				continue;
13446 			case BPF_FUNC_map_peek_elem:
13447 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13448 				continue;
13449 			case BPF_FUNC_redirect_map:
13450 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13451 				continue;
13452 			case BPF_FUNC_for_each_map_elem:
13453 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13454 				continue;
13455 			}
13456 
13457 			goto patch_call_imm;
13458 		}
13459 
13460 		/* Implement bpf_jiffies64 inline. */
13461 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13462 		    insn->imm == BPF_FUNC_jiffies64) {
13463 			struct bpf_insn ld_jiffies_addr[2] = {
13464 				BPF_LD_IMM64(BPF_REG_0,
13465 					     (unsigned long)&jiffies),
13466 			};
13467 
13468 			insn_buf[0] = ld_jiffies_addr[0];
13469 			insn_buf[1] = ld_jiffies_addr[1];
13470 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13471 						  BPF_REG_0, 0);
13472 			cnt = 3;
13473 
13474 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13475 						       cnt);
13476 			if (!new_prog)
13477 				return -ENOMEM;
13478 
13479 			delta    += cnt - 1;
13480 			env->prog = prog = new_prog;
13481 			insn      = new_prog->insnsi + i + delta;
13482 			continue;
13483 		}
13484 
13485 		/* Implement bpf_get_func_arg inline. */
13486 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13487 		    insn->imm == BPF_FUNC_get_func_arg) {
13488 			/* Load nr_args from ctx - 8 */
13489 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13490 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
13491 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
13492 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
13493 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
13494 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13495 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
13496 			insn_buf[7] = BPF_JMP_A(1);
13497 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
13498 			cnt = 9;
13499 
13500 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13501 			if (!new_prog)
13502 				return -ENOMEM;
13503 
13504 			delta    += cnt - 1;
13505 			env->prog = prog = new_prog;
13506 			insn      = new_prog->insnsi + i + delta;
13507 			continue;
13508 		}
13509 
13510 		/* Implement bpf_get_func_ret inline. */
13511 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13512 		    insn->imm == BPF_FUNC_get_func_ret) {
13513 			if (eatype == BPF_TRACE_FEXIT ||
13514 			    eatype == BPF_MODIFY_RETURN) {
13515 				/* Load nr_args from ctx - 8 */
13516 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13517 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
13518 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
13519 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13520 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
13521 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
13522 				cnt = 6;
13523 			} else {
13524 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
13525 				cnt = 1;
13526 			}
13527 
13528 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13529 			if (!new_prog)
13530 				return -ENOMEM;
13531 
13532 			delta    += cnt - 1;
13533 			env->prog = prog = new_prog;
13534 			insn      = new_prog->insnsi + i + delta;
13535 			continue;
13536 		}
13537 
13538 		/* Implement get_func_arg_cnt inline. */
13539 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13540 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
13541 			/* Load nr_args from ctx - 8 */
13542 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13543 
13544 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13545 			if (!new_prog)
13546 				return -ENOMEM;
13547 
13548 			env->prog = prog = new_prog;
13549 			insn      = new_prog->insnsi + i + delta;
13550 			continue;
13551 		}
13552 
13553 		/* Implement bpf_get_func_ip inline. */
13554 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13555 		    insn->imm == BPF_FUNC_get_func_ip) {
13556 			/* Load IP address from ctx - 16 */
13557 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
13558 
13559 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13560 			if (!new_prog)
13561 				return -ENOMEM;
13562 
13563 			env->prog = prog = new_prog;
13564 			insn      = new_prog->insnsi + i + delta;
13565 			continue;
13566 		}
13567 
13568 patch_call_imm:
13569 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13570 		/* all functions that have prototype and verifier allowed
13571 		 * programs to call them, must be real in-kernel functions
13572 		 */
13573 		if (!fn->func) {
13574 			verbose(env,
13575 				"kernel subsystem misconfigured func %s#%d\n",
13576 				func_id_name(insn->imm), insn->imm);
13577 			return -EFAULT;
13578 		}
13579 		insn->imm = fn->func - __bpf_call_base;
13580 	}
13581 
13582 	/* Since poke tab is now finalized, publish aux to tracker. */
13583 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13584 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13585 		if (!map_ptr->ops->map_poke_track ||
13586 		    !map_ptr->ops->map_poke_untrack ||
13587 		    !map_ptr->ops->map_poke_run) {
13588 			verbose(env, "bpf verifier is misconfigured\n");
13589 			return -EINVAL;
13590 		}
13591 
13592 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13593 		if (ret < 0) {
13594 			verbose(env, "tracking tail call prog failed\n");
13595 			return ret;
13596 		}
13597 	}
13598 
13599 	sort_kfunc_descs_by_imm(env->prog);
13600 
13601 	return 0;
13602 }
13603 
13604 static void free_states(struct bpf_verifier_env *env)
13605 {
13606 	struct bpf_verifier_state_list *sl, *sln;
13607 	int i;
13608 
13609 	sl = env->free_list;
13610 	while (sl) {
13611 		sln = sl->next;
13612 		free_verifier_state(&sl->state, false);
13613 		kfree(sl);
13614 		sl = sln;
13615 	}
13616 	env->free_list = NULL;
13617 
13618 	if (!env->explored_states)
13619 		return;
13620 
13621 	for (i = 0; i < state_htab_size(env); i++) {
13622 		sl = env->explored_states[i];
13623 
13624 		while (sl) {
13625 			sln = sl->next;
13626 			free_verifier_state(&sl->state, false);
13627 			kfree(sl);
13628 			sl = sln;
13629 		}
13630 		env->explored_states[i] = NULL;
13631 	}
13632 }
13633 
13634 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13635 {
13636 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13637 	struct bpf_verifier_state *state;
13638 	struct bpf_reg_state *regs;
13639 	int ret, i;
13640 
13641 	env->prev_linfo = NULL;
13642 	env->pass_cnt++;
13643 
13644 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13645 	if (!state)
13646 		return -ENOMEM;
13647 	state->curframe = 0;
13648 	state->speculative = false;
13649 	state->branches = 1;
13650 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13651 	if (!state->frame[0]) {
13652 		kfree(state);
13653 		return -ENOMEM;
13654 	}
13655 	env->cur_state = state;
13656 	init_func_state(env, state->frame[0],
13657 			BPF_MAIN_FUNC /* callsite */,
13658 			0 /* frameno */,
13659 			subprog);
13660 
13661 	regs = state->frame[state->curframe]->regs;
13662 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13663 		ret = btf_prepare_func_args(env, subprog, regs);
13664 		if (ret)
13665 			goto out;
13666 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13667 			if (regs[i].type == PTR_TO_CTX)
13668 				mark_reg_known_zero(env, regs, i);
13669 			else if (regs[i].type == SCALAR_VALUE)
13670 				mark_reg_unknown(env, regs, i);
13671 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
13672 				const u32 mem_size = regs[i].mem_size;
13673 
13674 				mark_reg_known_zero(env, regs, i);
13675 				regs[i].mem_size = mem_size;
13676 				regs[i].id = ++env->id_gen;
13677 			}
13678 		}
13679 	} else {
13680 		/* 1st arg to a function */
13681 		regs[BPF_REG_1].type = PTR_TO_CTX;
13682 		mark_reg_known_zero(env, regs, BPF_REG_1);
13683 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13684 		if (ret == -EFAULT)
13685 			/* unlikely verifier bug. abort.
13686 			 * ret == 0 and ret < 0 are sadly acceptable for
13687 			 * main() function due to backward compatibility.
13688 			 * Like socket filter program may be written as:
13689 			 * int bpf_prog(struct pt_regs *ctx)
13690 			 * and never dereference that ctx in the program.
13691 			 * 'struct pt_regs' is a type mismatch for socket
13692 			 * filter that should be using 'struct __sk_buff'.
13693 			 */
13694 			goto out;
13695 	}
13696 
13697 	ret = do_check(env);
13698 out:
13699 	/* check for NULL is necessary, since cur_state can be freed inside
13700 	 * do_check() under memory pressure.
13701 	 */
13702 	if (env->cur_state) {
13703 		free_verifier_state(env->cur_state, true);
13704 		env->cur_state = NULL;
13705 	}
13706 	while (!pop_stack(env, NULL, NULL, false));
13707 	if (!ret && pop_log)
13708 		bpf_vlog_reset(&env->log, 0);
13709 	free_states(env);
13710 	return ret;
13711 }
13712 
13713 /* Verify all global functions in a BPF program one by one based on their BTF.
13714  * All global functions must pass verification. Otherwise the whole program is rejected.
13715  * Consider:
13716  * int bar(int);
13717  * int foo(int f)
13718  * {
13719  *    return bar(f);
13720  * }
13721  * int bar(int b)
13722  * {
13723  *    ...
13724  * }
13725  * foo() will be verified first for R1=any_scalar_value. During verification it
13726  * will be assumed that bar() already verified successfully and call to bar()
13727  * from foo() will be checked for type match only. Later bar() will be verified
13728  * independently to check that it's safe for R1=any_scalar_value.
13729  */
13730 static int do_check_subprogs(struct bpf_verifier_env *env)
13731 {
13732 	struct bpf_prog_aux *aux = env->prog->aux;
13733 	int i, ret;
13734 
13735 	if (!aux->func_info)
13736 		return 0;
13737 
13738 	for (i = 1; i < env->subprog_cnt; i++) {
13739 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13740 			continue;
13741 		env->insn_idx = env->subprog_info[i].start;
13742 		WARN_ON_ONCE(env->insn_idx == 0);
13743 		ret = do_check_common(env, i);
13744 		if (ret) {
13745 			return ret;
13746 		} else if (env->log.level & BPF_LOG_LEVEL) {
13747 			verbose(env,
13748 				"Func#%d is safe for any args that match its prototype\n",
13749 				i);
13750 		}
13751 	}
13752 	return 0;
13753 }
13754 
13755 static int do_check_main(struct bpf_verifier_env *env)
13756 {
13757 	int ret;
13758 
13759 	env->insn_idx = 0;
13760 	ret = do_check_common(env, 0);
13761 	if (!ret)
13762 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13763 	return ret;
13764 }
13765 
13766 
13767 static void print_verification_stats(struct bpf_verifier_env *env)
13768 {
13769 	int i;
13770 
13771 	if (env->log.level & BPF_LOG_STATS) {
13772 		verbose(env, "verification time %lld usec\n",
13773 			div_u64(env->verification_time, 1000));
13774 		verbose(env, "stack depth ");
13775 		for (i = 0; i < env->subprog_cnt; i++) {
13776 			u32 depth = env->subprog_info[i].stack_depth;
13777 
13778 			verbose(env, "%d", depth);
13779 			if (i + 1 < env->subprog_cnt)
13780 				verbose(env, "+");
13781 		}
13782 		verbose(env, "\n");
13783 	}
13784 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13785 		"total_states %d peak_states %d mark_read %d\n",
13786 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13787 		env->max_states_per_insn, env->total_states,
13788 		env->peak_states, env->longest_mark_read_walk);
13789 }
13790 
13791 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13792 {
13793 	const struct btf_type *t, *func_proto;
13794 	const struct bpf_struct_ops *st_ops;
13795 	const struct btf_member *member;
13796 	struct bpf_prog *prog = env->prog;
13797 	u32 btf_id, member_idx;
13798 	const char *mname;
13799 
13800 	if (!prog->gpl_compatible) {
13801 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13802 		return -EINVAL;
13803 	}
13804 
13805 	btf_id = prog->aux->attach_btf_id;
13806 	st_ops = bpf_struct_ops_find(btf_id);
13807 	if (!st_ops) {
13808 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13809 			btf_id);
13810 		return -ENOTSUPP;
13811 	}
13812 
13813 	t = st_ops->type;
13814 	member_idx = prog->expected_attach_type;
13815 	if (member_idx >= btf_type_vlen(t)) {
13816 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13817 			member_idx, st_ops->name);
13818 		return -EINVAL;
13819 	}
13820 
13821 	member = &btf_type_member(t)[member_idx];
13822 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13823 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13824 					       NULL);
13825 	if (!func_proto) {
13826 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13827 			mname, member_idx, st_ops->name);
13828 		return -EINVAL;
13829 	}
13830 
13831 	if (st_ops->check_member) {
13832 		int err = st_ops->check_member(t, member);
13833 
13834 		if (err) {
13835 			verbose(env, "attach to unsupported member %s of struct %s\n",
13836 				mname, st_ops->name);
13837 			return err;
13838 		}
13839 	}
13840 
13841 	prog->aux->attach_func_proto = func_proto;
13842 	prog->aux->attach_func_name = mname;
13843 	env->ops = st_ops->verifier_ops;
13844 
13845 	return 0;
13846 }
13847 #define SECURITY_PREFIX "security_"
13848 
13849 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13850 {
13851 	if (within_error_injection_list(addr) ||
13852 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13853 		return 0;
13854 
13855 	return -EINVAL;
13856 }
13857 
13858 /* list of non-sleepable functions that are otherwise on
13859  * ALLOW_ERROR_INJECTION list
13860  */
13861 BTF_SET_START(btf_non_sleepable_error_inject)
13862 /* Three functions below can be called from sleepable and non-sleepable context.
13863  * Assume non-sleepable from bpf safety point of view.
13864  */
13865 BTF_ID(func, __filemap_add_folio)
13866 BTF_ID(func, should_fail_alloc_page)
13867 BTF_ID(func, should_failslab)
13868 BTF_SET_END(btf_non_sleepable_error_inject)
13869 
13870 static int check_non_sleepable_error_inject(u32 btf_id)
13871 {
13872 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13873 }
13874 
13875 int bpf_check_attach_target(struct bpf_verifier_log *log,
13876 			    const struct bpf_prog *prog,
13877 			    const struct bpf_prog *tgt_prog,
13878 			    u32 btf_id,
13879 			    struct bpf_attach_target_info *tgt_info)
13880 {
13881 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13882 	const char prefix[] = "btf_trace_";
13883 	int ret = 0, subprog = -1, i;
13884 	const struct btf_type *t;
13885 	bool conservative = true;
13886 	const char *tname;
13887 	struct btf *btf;
13888 	long addr = 0;
13889 
13890 	if (!btf_id) {
13891 		bpf_log(log, "Tracing programs must provide btf_id\n");
13892 		return -EINVAL;
13893 	}
13894 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13895 	if (!btf) {
13896 		bpf_log(log,
13897 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13898 		return -EINVAL;
13899 	}
13900 	t = btf_type_by_id(btf, btf_id);
13901 	if (!t) {
13902 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13903 		return -EINVAL;
13904 	}
13905 	tname = btf_name_by_offset(btf, t->name_off);
13906 	if (!tname) {
13907 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13908 		return -EINVAL;
13909 	}
13910 	if (tgt_prog) {
13911 		struct bpf_prog_aux *aux = tgt_prog->aux;
13912 
13913 		for (i = 0; i < aux->func_info_cnt; i++)
13914 			if (aux->func_info[i].type_id == btf_id) {
13915 				subprog = i;
13916 				break;
13917 			}
13918 		if (subprog == -1) {
13919 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13920 			return -EINVAL;
13921 		}
13922 		conservative = aux->func_info_aux[subprog].unreliable;
13923 		if (prog_extension) {
13924 			if (conservative) {
13925 				bpf_log(log,
13926 					"Cannot replace static functions\n");
13927 				return -EINVAL;
13928 			}
13929 			if (!prog->jit_requested) {
13930 				bpf_log(log,
13931 					"Extension programs should be JITed\n");
13932 				return -EINVAL;
13933 			}
13934 		}
13935 		if (!tgt_prog->jited) {
13936 			bpf_log(log, "Can attach to only JITed progs\n");
13937 			return -EINVAL;
13938 		}
13939 		if (tgt_prog->type == prog->type) {
13940 			/* Cannot fentry/fexit another fentry/fexit program.
13941 			 * Cannot attach program extension to another extension.
13942 			 * It's ok to attach fentry/fexit to extension program.
13943 			 */
13944 			bpf_log(log, "Cannot recursively attach\n");
13945 			return -EINVAL;
13946 		}
13947 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13948 		    prog_extension &&
13949 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13950 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13951 			/* Program extensions can extend all program types
13952 			 * except fentry/fexit. The reason is the following.
13953 			 * The fentry/fexit programs are used for performance
13954 			 * analysis, stats and can be attached to any program
13955 			 * type except themselves. When extension program is
13956 			 * replacing XDP function it is necessary to allow
13957 			 * performance analysis of all functions. Both original
13958 			 * XDP program and its program extension. Hence
13959 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13960 			 * allowed. If extending of fentry/fexit was allowed it
13961 			 * would be possible to create long call chain
13962 			 * fentry->extension->fentry->extension beyond
13963 			 * reasonable stack size. Hence extending fentry is not
13964 			 * allowed.
13965 			 */
13966 			bpf_log(log, "Cannot extend fentry/fexit\n");
13967 			return -EINVAL;
13968 		}
13969 	} else {
13970 		if (prog_extension) {
13971 			bpf_log(log, "Cannot replace kernel functions\n");
13972 			return -EINVAL;
13973 		}
13974 	}
13975 
13976 	switch (prog->expected_attach_type) {
13977 	case BPF_TRACE_RAW_TP:
13978 		if (tgt_prog) {
13979 			bpf_log(log,
13980 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13981 			return -EINVAL;
13982 		}
13983 		if (!btf_type_is_typedef(t)) {
13984 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13985 				btf_id);
13986 			return -EINVAL;
13987 		}
13988 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13989 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13990 				btf_id, tname);
13991 			return -EINVAL;
13992 		}
13993 		tname += sizeof(prefix) - 1;
13994 		t = btf_type_by_id(btf, t->type);
13995 		if (!btf_type_is_ptr(t))
13996 			/* should never happen in valid vmlinux build */
13997 			return -EINVAL;
13998 		t = btf_type_by_id(btf, t->type);
13999 		if (!btf_type_is_func_proto(t))
14000 			/* should never happen in valid vmlinux build */
14001 			return -EINVAL;
14002 
14003 		break;
14004 	case BPF_TRACE_ITER:
14005 		if (!btf_type_is_func(t)) {
14006 			bpf_log(log, "attach_btf_id %u is not a function\n",
14007 				btf_id);
14008 			return -EINVAL;
14009 		}
14010 		t = btf_type_by_id(btf, t->type);
14011 		if (!btf_type_is_func_proto(t))
14012 			return -EINVAL;
14013 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14014 		if (ret)
14015 			return ret;
14016 		break;
14017 	default:
14018 		if (!prog_extension)
14019 			return -EINVAL;
14020 		fallthrough;
14021 	case BPF_MODIFY_RETURN:
14022 	case BPF_LSM_MAC:
14023 	case BPF_TRACE_FENTRY:
14024 	case BPF_TRACE_FEXIT:
14025 		if (!btf_type_is_func(t)) {
14026 			bpf_log(log, "attach_btf_id %u is not a function\n",
14027 				btf_id);
14028 			return -EINVAL;
14029 		}
14030 		if (prog_extension &&
14031 		    btf_check_type_match(log, prog, btf, t))
14032 			return -EINVAL;
14033 		t = btf_type_by_id(btf, t->type);
14034 		if (!btf_type_is_func_proto(t))
14035 			return -EINVAL;
14036 
14037 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14038 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14039 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14040 			return -EINVAL;
14041 
14042 		if (tgt_prog && conservative)
14043 			t = NULL;
14044 
14045 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14046 		if (ret < 0)
14047 			return ret;
14048 
14049 		if (tgt_prog) {
14050 			if (subprog == 0)
14051 				addr = (long) tgt_prog->bpf_func;
14052 			else
14053 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14054 		} else {
14055 			addr = kallsyms_lookup_name(tname);
14056 			if (!addr) {
14057 				bpf_log(log,
14058 					"The address of function %s cannot be found\n",
14059 					tname);
14060 				return -ENOENT;
14061 			}
14062 		}
14063 
14064 		if (prog->aux->sleepable) {
14065 			ret = -EINVAL;
14066 			switch (prog->type) {
14067 			case BPF_PROG_TYPE_TRACING:
14068 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
14069 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14070 				 */
14071 				if (!check_non_sleepable_error_inject(btf_id) &&
14072 				    within_error_injection_list(addr))
14073 					ret = 0;
14074 				break;
14075 			case BPF_PROG_TYPE_LSM:
14076 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
14077 				 * Only some of them are sleepable.
14078 				 */
14079 				if (bpf_lsm_is_sleepable_hook(btf_id))
14080 					ret = 0;
14081 				break;
14082 			default:
14083 				break;
14084 			}
14085 			if (ret) {
14086 				bpf_log(log, "%s is not sleepable\n", tname);
14087 				return ret;
14088 			}
14089 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
14090 			if (tgt_prog) {
14091 				bpf_log(log, "can't modify return codes of BPF programs\n");
14092 				return -EINVAL;
14093 			}
14094 			ret = check_attach_modify_return(addr, tname);
14095 			if (ret) {
14096 				bpf_log(log, "%s() is not modifiable\n", tname);
14097 				return ret;
14098 			}
14099 		}
14100 
14101 		break;
14102 	}
14103 	tgt_info->tgt_addr = addr;
14104 	tgt_info->tgt_name = tname;
14105 	tgt_info->tgt_type = t;
14106 	return 0;
14107 }
14108 
14109 BTF_SET_START(btf_id_deny)
14110 BTF_ID_UNUSED
14111 #ifdef CONFIG_SMP
14112 BTF_ID(func, migrate_disable)
14113 BTF_ID(func, migrate_enable)
14114 #endif
14115 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14116 BTF_ID(func, rcu_read_unlock_strict)
14117 #endif
14118 BTF_SET_END(btf_id_deny)
14119 
14120 static int check_attach_btf_id(struct bpf_verifier_env *env)
14121 {
14122 	struct bpf_prog *prog = env->prog;
14123 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
14124 	struct bpf_attach_target_info tgt_info = {};
14125 	u32 btf_id = prog->aux->attach_btf_id;
14126 	struct bpf_trampoline *tr;
14127 	int ret;
14128 	u64 key;
14129 
14130 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14131 		if (prog->aux->sleepable)
14132 			/* attach_btf_id checked to be zero already */
14133 			return 0;
14134 		verbose(env, "Syscall programs can only be sleepable\n");
14135 		return -EINVAL;
14136 	}
14137 
14138 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14139 	    prog->type != BPF_PROG_TYPE_LSM) {
14140 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
14141 		return -EINVAL;
14142 	}
14143 
14144 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14145 		return check_struct_ops_btf_id(env);
14146 
14147 	if (prog->type != BPF_PROG_TYPE_TRACING &&
14148 	    prog->type != BPF_PROG_TYPE_LSM &&
14149 	    prog->type != BPF_PROG_TYPE_EXT)
14150 		return 0;
14151 
14152 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14153 	if (ret)
14154 		return ret;
14155 
14156 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
14157 		/* to make freplace equivalent to their targets, they need to
14158 		 * inherit env->ops and expected_attach_type for the rest of the
14159 		 * verification
14160 		 */
14161 		env->ops = bpf_verifier_ops[tgt_prog->type];
14162 		prog->expected_attach_type = tgt_prog->expected_attach_type;
14163 	}
14164 
14165 	/* store info about the attachment target that will be used later */
14166 	prog->aux->attach_func_proto = tgt_info.tgt_type;
14167 	prog->aux->attach_func_name = tgt_info.tgt_name;
14168 
14169 	if (tgt_prog) {
14170 		prog->aux->saved_dst_prog_type = tgt_prog->type;
14171 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14172 	}
14173 
14174 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14175 		prog->aux->attach_btf_trace = true;
14176 		return 0;
14177 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14178 		if (!bpf_iter_prog_supported(prog))
14179 			return -EINVAL;
14180 		return 0;
14181 	}
14182 
14183 	if (prog->type == BPF_PROG_TYPE_LSM) {
14184 		ret = bpf_lsm_verify_prog(&env->log, prog);
14185 		if (ret < 0)
14186 			return ret;
14187 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
14188 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
14189 		return -EINVAL;
14190 	}
14191 
14192 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
14193 	tr = bpf_trampoline_get(key, &tgt_info);
14194 	if (!tr)
14195 		return -ENOMEM;
14196 
14197 	prog->aux->dst_trampoline = tr;
14198 	return 0;
14199 }
14200 
14201 struct btf *bpf_get_btf_vmlinux(void)
14202 {
14203 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14204 		mutex_lock(&bpf_verifier_lock);
14205 		if (!btf_vmlinux)
14206 			btf_vmlinux = btf_parse_vmlinux();
14207 		mutex_unlock(&bpf_verifier_lock);
14208 	}
14209 	return btf_vmlinux;
14210 }
14211 
14212 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
14213 {
14214 	u64 start_time = ktime_get_ns();
14215 	struct bpf_verifier_env *env;
14216 	struct bpf_verifier_log *log;
14217 	int i, len, ret = -EINVAL;
14218 	bool is_priv;
14219 
14220 	/* no program is valid */
14221 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14222 		return -EINVAL;
14223 
14224 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
14225 	 * allocate/free it every time bpf_check() is called
14226 	 */
14227 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
14228 	if (!env)
14229 		return -ENOMEM;
14230 	log = &env->log;
14231 
14232 	len = (*prog)->len;
14233 	env->insn_aux_data =
14234 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
14235 	ret = -ENOMEM;
14236 	if (!env->insn_aux_data)
14237 		goto err_free_env;
14238 	for (i = 0; i < len; i++)
14239 		env->insn_aux_data[i].orig_idx = i;
14240 	env->prog = *prog;
14241 	env->ops = bpf_verifier_ops[env->prog->type];
14242 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
14243 	is_priv = bpf_capable();
14244 
14245 	bpf_get_btf_vmlinux();
14246 
14247 	/* grab the mutex to protect few globals used by verifier */
14248 	if (!is_priv)
14249 		mutex_lock(&bpf_verifier_lock);
14250 
14251 	if (attr->log_level || attr->log_buf || attr->log_size) {
14252 		/* user requested verbose verifier output
14253 		 * and supplied buffer to store the verification trace
14254 		 */
14255 		log->level = attr->log_level;
14256 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14257 		log->len_total = attr->log_size;
14258 
14259 		/* log attributes have to be sane */
14260 		if (!bpf_verifier_log_attr_valid(log)) {
14261 			ret = -EINVAL;
14262 			goto err_unlock;
14263 		}
14264 	}
14265 
14266 	mark_verifier_state_clean(env);
14267 
14268 	if (IS_ERR(btf_vmlinux)) {
14269 		/* Either gcc or pahole or kernel are broken. */
14270 		verbose(env, "in-kernel BTF is malformed\n");
14271 		ret = PTR_ERR(btf_vmlinux);
14272 		goto skip_full_check;
14273 	}
14274 
14275 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14276 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
14277 		env->strict_alignment = true;
14278 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14279 		env->strict_alignment = false;
14280 
14281 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
14282 	env->allow_uninit_stack = bpf_allow_uninit_stack();
14283 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
14284 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
14285 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
14286 	env->bpf_capable = bpf_capable();
14287 
14288 	if (is_priv)
14289 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14290 
14291 	env->explored_states = kvcalloc(state_htab_size(env),
14292 				       sizeof(struct bpf_verifier_state_list *),
14293 				       GFP_USER);
14294 	ret = -ENOMEM;
14295 	if (!env->explored_states)
14296 		goto skip_full_check;
14297 
14298 	ret = add_subprog_and_kfunc(env);
14299 	if (ret < 0)
14300 		goto skip_full_check;
14301 
14302 	ret = check_subprogs(env);
14303 	if (ret < 0)
14304 		goto skip_full_check;
14305 
14306 	ret = check_btf_info(env, attr, uattr);
14307 	if (ret < 0)
14308 		goto skip_full_check;
14309 
14310 	ret = check_attach_btf_id(env);
14311 	if (ret)
14312 		goto skip_full_check;
14313 
14314 	ret = resolve_pseudo_ldimm64(env);
14315 	if (ret < 0)
14316 		goto skip_full_check;
14317 
14318 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
14319 		ret = bpf_prog_offload_verifier_prep(env->prog);
14320 		if (ret)
14321 			goto skip_full_check;
14322 	}
14323 
14324 	ret = check_cfg(env);
14325 	if (ret < 0)
14326 		goto skip_full_check;
14327 
14328 	ret = do_check_subprogs(env);
14329 	ret = ret ?: do_check_main(env);
14330 
14331 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14332 		ret = bpf_prog_offload_finalize(env);
14333 
14334 skip_full_check:
14335 	kvfree(env->explored_states);
14336 
14337 	if (ret == 0)
14338 		ret = check_max_stack_depth(env);
14339 
14340 	/* instruction rewrites happen after this point */
14341 	if (is_priv) {
14342 		if (ret == 0)
14343 			opt_hard_wire_dead_code_branches(env);
14344 		if (ret == 0)
14345 			ret = opt_remove_dead_code(env);
14346 		if (ret == 0)
14347 			ret = opt_remove_nops(env);
14348 	} else {
14349 		if (ret == 0)
14350 			sanitize_dead_code(env);
14351 	}
14352 
14353 	if (ret == 0)
14354 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14355 		ret = convert_ctx_accesses(env);
14356 
14357 	if (ret == 0)
14358 		ret = do_misc_fixups(env);
14359 
14360 	/* do 32-bit optimization after insn patching has done so those patched
14361 	 * insns could be handled correctly.
14362 	 */
14363 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14364 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14365 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14366 								     : false;
14367 	}
14368 
14369 	if (ret == 0)
14370 		ret = fixup_call_args(env);
14371 
14372 	env->verification_time = ktime_get_ns() - start_time;
14373 	print_verification_stats(env);
14374 	env->prog->aux->verified_insns = env->insn_processed;
14375 
14376 	if (log->level && bpf_verifier_log_full(log))
14377 		ret = -ENOSPC;
14378 	if (log->level && !log->ubuf) {
14379 		ret = -EFAULT;
14380 		goto err_release_maps;
14381 	}
14382 
14383 	if (ret)
14384 		goto err_release_maps;
14385 
14386 	if (env->used_map_cnt) {
14387 		/* if program passed verifier, update used_maps in bpf_prog_info */
14388 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14389 							  sizeof(env->used_maps[0]),
14390 							  GFP_KERNEL);
14391 
14392 		if (!env->prog->aux->used_maps) {
14393 			ret = -ENOMEM;
14394 			goto err_release_maps;
14395 		}
14396 
14397 		memcpy(env->prog->aux->used_maps, env->used_maps,
14398 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14399 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14400 	}
14401 	if (env->used_btf_cnt) {
14402 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14403 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14404 							  sizeof(env->used_btfs[0]),
14405 							  GFP_KERNEL);
14406 		if (!env->prog->aux->used_btfs) {
14407 			ret = -ENOMEM;
14408 			goto err_release_maps;
14409 		}
14410 
14411 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14412 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14413 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14414 	}
14415 	if (env->used_map_cnt || env->used_btf_cnt) {
14416 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14417 		 * bpf_ld_imm64 instructions
14418 		 */
14419 		convert_pseudo_ld_imm64(env);
14420 	}
14421 
14422 	adjust_btf_func(env);
14423 
14424 err_release_maps:
14425 	if (!env->prog->aux->used_maps)
14426 		/* if we didn't copy map pointers into bpf_prog_info, release
14427 		 * them now. Otherwise free_used_maps() will release them.
14428 		 */
14429 		release_maps(env);
14430 	if (!env->prog->aux->used_btfs)
14431 		release_btfs(env);
14432 
14433 	/* extension progs temporarily inherit the attach_type of their targets
14434 	   for verification purposes, so set it back to zero before returning
14435 	 */
14436 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14437 		env->prog->expected_attach_type = 0;
14438 
14439 	*prog = env->prog;
14440 err_unlock:
14441 	if (!is_priv)
14442 		mutex_unlock(&bpf_verifier_lock);
14443 	vfree(env->insn_aux_data);
14444 err_free_env:
14445 	kfree(env);
14446 	return ret;
14447 }
14448