xref: /openbmc/linux/kernel/bpf/verifier.c (revision 31e67366)
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/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25 
26 #include "disasm.h"
27 
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 	[_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38 
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all pathes through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns ether pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163 
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 	/* verifer state is 'st'
167 	 * before processing instruction 'insn_idx'
168 	 * and after processing instruction 'prev_insn_idx'
169 	 */
170 	struct bpf_verifier_state st;
171 	int insn_idx;
172 	int prev_insn_idx;
173 	struct bpf_verifier_stack_elem *next;
174 	/* length of verifier log at the time this state was pushed on stack */
175 	u32 log_pos;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
179 #define BPF_COMPLEXITY_LIMIT_STATES	64
180 
181 #define BPF_MAP_KEY_POISON	(1ULL << 63)
182 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
183 
184 #define BPF_MAP_PTR_UNPRIV	1UL
185 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
186 					  POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193 
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198 
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 			      const struct bpf_map *map, bool unpriv)
201 {
202 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 	unpriv |= bpf_map_ptr_unpriv(aux);
204 	aux->map_ptr_state = (unsigned long)map |
205 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207 
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212 
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217 
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222 
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 	bool poisoned = bpf_map_key_poisoned(aux);
226 
227 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230 
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233 	return insn->code == (BPF_JMP | BPF_CALL) &&
234 	       insn->src_reg == BPF_PSEUDO_CALL;
235 }
236 
237 struct bpf_call_arg_meta {
238 	struct bpf_map *map_ptr;
239 	bool raw_mode;
240 	bool pkt_access;
241 	int regno;
242 	int access_size;
243 	int mem_size;
244 	u64 msize_max_value;
245 	int ref_obj_id;
246 	int func_id;
247 	struct btf *btf;
248 	u32 btf_id;
249 	struct btf *ret_btf;
250 	u32 ret_btf_id;
251 };
252 
253 struct btf *btf_vmlinux;
254 
255 static DEFINE_MUTEX(bpf_verifier_lock);
256 
257 static const struct bpf_line_info *
258 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
259 {
260 	const struct bpf_line_info *linfo;
261 	const struct bpf_prog *prog;
262 	u32 i, nr_linfo;
263 
264 	prog = env->prog;
265 	nr_linfo = prog->aux->nr_linfo;
266 
267 	if (!nr_linfo || insn_off >= prog->len)
268 		return NULL;
269 
270 	linfo = prog->aux->linfo;
271 	for (i = 1; i < nr_linfo; i++)
272 		if (insn_off < linfo[i].insn_off)
273 			break;
274 
275 	return &linfo[i - 1];
276 }
277 
278 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
279 		       va_list args)
280 {
281 	unsigned int n;
282 
283 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
284 
285 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
286 		  "verifier log line truncated - local buffer too short\n");
287 
288 	n = min(log->len_total - log->len_used - 1, n);
289 	log->kbuf[n] = '\0';
290 
291 	if (log->level == BPF_LOG_KERNEL) {
292 		pr_err("BPF:%s\n", log->kbuf);
293 		return;
294 	}
295 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
296 		log->len_used += n;
297 	else
298 		log->ubuf = NULL;
299 }
300 
301 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
302 {
303 	char zero = 0;
304 
305 	if (!bpf_verifier_log_needed(log))
306 		return;
307 
308 	log->len_used = new_pos;
309 	if (put_user(zero, log->ubuf + new_pos))
310 		log->ubuf = NULL;
311 }
312 
313 /* log_level controls verbosity level of eBPF verifier.
314  * bpf_verifier_log_write() is used to dump the verification trace to the log,
315  * so the user can figure out what's wrong with the program
316  */
317 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
318 					   const char *fmt, ...)
319 {
320 	va_list args;
321 
322 	if (!bpf_verifier_log_needed(&env->log))
323 		return;
324 
325 	va_start(args, fmt);
326 	bpf_verifier_vlog(&env->log, fmt, args);
327 	va_end(args);
328 }
329 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
330 
331 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
332 {
333 	struct bpf_verifier_env *env = private_data;
334 	va_list args;
335 
336 	if (!bpf_verifier_log_needed(&env->log))
337 		return;
338 
339 	va_start(args, fmt);
340 	bpf_verifier_vlog(&env->log, fmt, args);
341 	va_end(args);
342 }
343 
344 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
345 			    const char *fmt, ...)
346 {
347 	va_list args;
348 
349 	if (!bpf_verifier_log_needed(log))
350 		return;
351 
352 	va_start(args, fmt);
353 	bpf_verifier_vlog(log, fmt, args);
354 	va_end(args);
355 }
356 
357 static const char *ltrim(const char *s)
358 {
359 	while (isspace(*s))
360 		s++;
361 
362 	return s;
363 }
364 
365 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
366 					 u32 insn_off,
367 					 const char *prefix_fmt, ...)
368 {
369 	const struct bpf_line_info *linfo;
370 
371 	if (!bpf_verifier_log_needed(&env->log))
372 		return;
373 
374 	linfo = find_linfo(env, insn_off);
375 	if (!linfo || linfo == env->prev_linfo)
376 		return;
377 
378 	if (prefix_fmt) {
379 		va_list args;
380 
381 		va_start(args, prefix_fmt);
382 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
383 		va_end(args);
384 	}
385 
386 	verbose(env, "%s\n",
387 		ltrim(btf_name_by_offset(env->prog->aux->btf,
388 					 linfo->line_off)));
389 
390 	env->prev_linfo = linfo;
391 }
392 
393 static bool type_is_pkt_pointer(enum bpf_reg_type type)
394 {
395 	return type == PTR_TO_PACKET ||
396 	       type == PTR_TO_PACKET_META;
397 }
398 
399 static bool type_is_sk_pointer(enum bpf_reg_type type)
400 {
401 	return type == PTR_TO_SOCKET ||
402 		type == PTR_TO_SOCK_COMMON ||
403 		type == PTR_TO_TCP_SOCK ||
404 		type == PTR_TO_XDP_SOCK;
405 }
406 
407 static bool reg_type_not_null(enum bpf_reg_type type)
408 {
409 	return type == PTR_TO_SOCKET ||
410 		type == PTR_TO_TCP_SOCK ||
411 		type == PTR_TO_MAP_VALUE ||
412 		type == PTR_TO_SOCK_COMMON;
413 }
414 
415 static bool reg_type_may_be_null(enum bpf_reg_type type)
416 {
417 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
418 	       type == PTR_TO_SOCKET_OR_NULL ||
419 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
420 	       type == PTR_TO_TCP_SOCK_OR_NULL ||
421 	       type == PTR_TO_BTF_ID_OR_NULL ||
422 	       type == PTR_TO_MEM_OR_NULL ||
423 	       type == PTR_TO_RDONLY_BUF_OR_NULL ||
424 	       type == PTR_TO_RDWR_BUF_OR_NULL;
425 }
426 
427 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
428 {
429 	return reg->type == PTR_TO_MAP_VALUE &&
430 		map_value_has_spin_lock(reg->map_ptr);
431 }
432 
433 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
434 {
435 	return type == PTR_TO_SOCKET ||
436 		type == PTR_TO_SOCKET_OR_NULL ||
437 		type == PTR_TO_TCP_SOCK ||
438 		type == PTR_TO_TCP_SOCK_OR_NULL ||
439 		type == PTR_TO_MEM ||
440 		type == PTR_TO_MEM_OR_NULL;
441 }
442 
443 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
444 {
445 	return type == ARG_PTR_TO_SOCK_COMMON;
446 }
447 
448 static bool arg_type_may_be_null(enum bpf_arg_type type)
449 {
450 	return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
451 	       type == ARG_PTR_TO_MEM_OR_NULL ||
452 	       type == ARG_PTR_TO_CTX_OR_NULL ||
453 	       type == ARG_PTR_TO_SOCKET_OR_NULL ||
454 	       type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
455 }
456 
457 /* Determine whether the function releases some resources allocated by another
458  * function call. The first reference type argument will be assumed to be
459  * released by release_reference().
460  */
461 static bool is_release_function(enum bpf_func_id func_id)
462 {
463 	return func_id == BPF_FUNC_sk_release ||
464 	       func_id == BPF_FUNC_ringbuf_submit ||
465 	       func_id == BPF_FUNC_ringbuf_discard;
466 }
467 
468 static bool may_be_acquire_function(enum bpf_func_id func_id)
469 {
470 	return func_id == BPF_FUNC_sk_lookup_tcp ||
471 		func_id == BPF_FUNC_sk_lookup_udp ||
472 		func_id == BPF_FUNC_skc_lookup_tcp ||
473 		func_id == BPF_FUNC_map_lookup_elem ||
474 	        func_id == BPF_FUNC_ringbuf_reserve;
475 }
476 
477 static bool is_acquire_function(enum bpf_func_id func_id,
478 				const struct bpf_map *map)
479 {
480 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481 
482 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 	    func_id == BPF_FUNC_sk_lookup_udp ||
484 	    func_id == BPF_FUNC_skc_lookup_tcp ||
485 	    func_id == BPF_FUNC_ringbuf_reserve)
486 		return true;
487 
488 	if (func_id == BPF_FUNC_map_lookup_elem &&
489 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
490 	     map_type == BPF_MAP_TYPE_SOCKHASH))
491 		return true;
492 
493 	return false;
494 }
495 
496 static bool is_ptr_cast_function(enum bpf_func_id func_id)
497 {
498 	return func_id == BPF_FUNC_tcp_sock ||
499 		func_id == BPF_FUNC_sk_fullsock ||
500 		func_id == BPF_FUNC_skc_to_tcp_sock ||
501 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
502 		func_id == BPF_FUNC_skc_to_udp6_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 /* string representation of 'enum bpf_reg_type' */
508 static const char * const reg_type_str[] = {
509 	[NOT_INIT]		= "?",
510 	[SCALAR_VALUE]		= "inv",
511 	[PTR_TO_CTX]		= "ctx",
512 	[CONST_PTR_TO_MAP]	= "map_ptr",
513 	[PTR_TO_MAP_VALUE]	= "map_value",
514 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
515 	[PTR_TO_STACK]		= "fp",
516 	[PTR_TO_PACKET]		= "pkt",
517 	[PTR_TO_PACKET_META]	= "pkt_meta",
518 	[PTR_TO_PACKET_END]	= "pkt_end",
519 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
520 	[PTR_TO_SOCKET]		= "sock",
521 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
522 	[PTR_TO_SOCK_COMMON]	= "sock_common",
523 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
524 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
525 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
526 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
527 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
528 	[PTR_TO_BTF_ID]		= "ptr_",
529 	[PTR_TO_BTF_ID_OR_NULL]	= "ptr_or_null_",
530 	[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
531 	[PTR_TO_MEM]		= "mem",
532 	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",
533 	[PTR_TO_RDONLY_BUF]	= "rdonly_buf",
534 	[PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
535 	[PTR_TO_RDWR_BUF]	= "rdwr_buf",
536 	[PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
537 };
538 
539 static char slot_type_char[] = {
540 	[STACK_INVALID]	= '?',
541 	[STACK_SPILL]	= 'r',
542 	[STACK_MISC]	= 'm',
543 	[STACK_ZERO]	= '0',
544 };
545 
546 static void print_liveness(struct bpf_verifier_env *env,
547 			   enum bpf_reg_liveness live)
548 {
549 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
550 	    verbose(env, "_");
551 	if (live & REG_LIVE_READ)
552 		verbose(env, "r");
553 	if (live & REG_LIVE_WRITTEN)
554 		verbose(env, "w");
555 	if (live & REG_LIVE_DONE)
556 		verbose(env, "D");
557 }
558 
559 static struct bpf_func_state *func(struct bpf_verifier_env *env,
560 				   const struct bpf_reg_state *reg)
561 {
562 	struct bpf_verifier_state *cur = env->cur_state;
563 
564 	return cur->frame[reg->frameno];
565 }
566 
567 static const char *kernel_type_name(const struct btf* btf, u32 id)
568 {
569 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
570 }
571 
572 static void print_verifier_state(struct bpf_verifier_env *env,
573 				 const struct bpf_func_state *state)
574 {
575 	const struct bpf_reg_state *reg;
576 	enum bpf_reg_type t;
577 	int i;
578 
579 	if (state->frameno)
580 		verbose(env, " frame%d:", state->frameno);
581 	for (i = 0; i < MAX_BPF_REG; i++) {
582 		reg = &state->regs[i];
583 		t = reg->type;
584 		if (t == NOT_INIT)
585 			continue;
586 		verbose(env, " R%d", i);
587 		print_liveness(env, reg->live);
588 		verbose(env, "=%s", reg_type_str[t]);
589 		if (t == SCALAR_VALUE && reg->precise)
590 			verbose(env, "P");
591 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
592 		    tnum_is_const(reg->var_off)) {
593 			/* reg->off should be 0 for SCALAR_VALUE */
594 			verbose(env, "%lld", reg->var_off.value + reg->off);
595 		} else {
596 			if (t == PTR_TO_BTF_ID ||
597 			    t == PTR_TO_BTF_ID_OR_NULL ||
598 			    t == PTR_TO_PERCPU_BTF_ID)
599 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
600 			verbose(env, "(id=%d", reg->id);
601 			if (reg_type_may_be_refcounted_or_null(t))
602 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
603 			if (t != SCALAR_VALUE)
604 				verbose(env, ",off=%d", reg->off);
605 			if (type_is_pkt_pointer(t))
606 				verbose(env, ",r=%d", reg->range);
607 			else if (t == CONST_PTR_TO_MAP ||
608 				 t == PTR_TO_MAP_VALUE ||
609 				 t == PTR_TO_MAP_VALUE_OR_NULL)
610 				verbose(env, ",ks=%d,vs=%d",
611 					reg->map_ptr->key_size,
612 					reg->map_ptr->value_size);
613 			if (tnum_is_const(reg->var_off)) {
614 				/* Typically an immediate SCALAR_VALUE, but
615 				 * could be a pointer whose offset is too big
616 				 * for reg->off
617 				 */
618 				verbose(env, ",imm=%llx", reg->var_off.value);
619 			} else {
620 				if (reg->smin_value != reg->umin_value &&
621 				    reg->smin_value != S64_MIN)
622 					verbose(env, ",smin_value=%lld",
623 						(long long)reg->smin_value);
624 				if (reg->smax_value != reg->umax_value &&
625 				    reg->smax_value != S64_MAX)
626 					verbose(env, ",smax_value=%lld",
627 						(long long)reg->smax_value);
628 				if (reg->umin_value != 0)
629 					verbose(env, ",umin_value=%llu",
630 						(unsigned long long)reg->umin_value);
631 				if (reg->umax_value != U64_MAX)
632 					verbose(env, ",umax_value=%llu",
633 						(unsigned long long)reg->umax_value);
634 				if (!tnum_is_unknown(reg->var_off)) {
635 					char tn_buf[48];
636 
637 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
638 					verbose(env, ",var_off=%s", tn_buf);
639 				}
640 				if (reg->s32_min_value != reg->smin_value &&
641 				    reg->s32_min_value != S32_MIN)
642 					verbose(env, ",s32_min_value=%d",
643 						(int)(reg->s32_min_value));
644 				if (reg->s32_max_value != reg->smax_value &&
645 				    reg->s32_max_value != S32_MAX)
646 					verbose(env, ",s32_max_value=%d",
647 						(int)(reg->s32_max_value));
648 				if (reg->u32_min_value != reg->umin_value &&
649 				    reg->u32_min_value != U32_MIN)
650 					verbose(env, ",u32_min_value=%d",
651 						(int)(reg->u32_min_value));
652 				if (reg->u32_max_value != reg->umax_value &&
653 				    reg->u32_max_value != U32_MAX)
654 					verbose(env, ",u32_max_value=%d",
655 						(int)(reg->u32_max_value));
656 			}
657 			verbose(env, ")");
658 		}
659 	}
660 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
661 		char types_buf[BPF_REG_SIZE + 1];
662 		bool valid = false;
663 		int j;
664 
665 		for (j = 0; j < BPF_REG_SIZE; j++) {
666 			if (state->stack[i].slot_type[j] != STACK_INVALID)
667 				valid = true;
668 			types_buf[j] = slot_type_char[
669 					state->stack[i].slot_type[j]];
670 		}
671 		types_buf[BPF_REG_SIZE] = 0;
672 		if (!valid)
673 			continue;
674 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
675 		print_liveness(env, state->stack[i].spilled_ptr.live);
676 		if (state->stack[i].slot_type[0] == STACK_SPILL) {
677 			reg = &state->stack[i].spilled_ptr;
678 			t = reg->type;
679 			verbose(env, "=%s", reg_type_str[t]);
680 			if (t == SCALAR_VALUE && reg->precise)
681 				verbose(env, "P");
682 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
683 				verbose(env, "%lld", reg->var_off.value + reg->off);
684 		} else {
685 			verbose(env, "=%s", types_buf);
686 		}
687 	}
688 	if (state->acquired_refs && state->refs[0].id) {
689 		verbose(env, " refs=%d", state->refs[0].id);
690 		for (i = 1; i < state->acquired_refs; i++)
691 			if (state->refs[i].id)
692 				verbose(env, ",%d", state->refs[i].id);
693 	}
694 	verbose(env, "\n");
695 }
696 
697 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
698 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
699 			       const struct bpf_func_state *src)	\
700 {									\
701 	if (!src->FIELD)						\
702 		return 0;						\
703 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
704 		/* internal bug, make state invalid to reject the program */ \
705 		memset(dst, 0, sizeof(*dst));				\
706 		return -EFAULT;						\
707 	}								\
708 	memcpy(dst->FIELD, src->FIELD,					\
709 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
710 	return 0;							\
711 }
712 /* copy_reference_state() */
713 COPY_STATE_FN(reference, acquired_refs, refs, 1)
714 /* copy_stack_state() */
715 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
716 #undef COPY_STATE_FN
717 
718 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
719 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
720 				  bool copy_old)			\
721 {									\
722 	u32 old_size = state->COUNT;					\
723 	struct bpf_##NAME##_state *new_##FIELD;				\
724 	int slot = size / SIZE;						\
725 									\
726 	if (size <= old_size || !size) {				\
727 		if (copy_old)						\
728 			return 0;					\
729 		state->COUNT = slot * SIZE;				\
730 		if (!size && old_size) {				\
731 			kfree(state->FIELD);				\
732 			state->FIELD = NULL;				\
733 		}							\
734 		return 0;						\
735 	}								\
736 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
737 				    GFP_KERNEL);			\
738 	if (!new_##FIELD)						\
739 		return -ENOMEM;						\
740 	if (copy_old) {							\
741 		if (state->FIELD)					\
742 			memcpy(new_##FIELD, state->FIELD,		\
743 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
744 		memset(new_##FIELD + old_size / SIZE, 0,		\
745 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
746 	}								\
747 	state->COUNT = slot * SIZE;					\
748 	kfree(state->FIELD);						\
749 	state->FIELD = new_##FIELD;					\
750 	return 0;							\
751 }
752 /* realloc_reference_state() */
753 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
754 /* realloc_stack_state() */
755 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
756 #undef REALLOC_STATE_FN
757 
758 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
759  * make it consume minimal amount of memory. check_stack_write() access from
760  * the program calls into realloc_func_state() to grow the stack size.
761  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
762  * which realloc_stack_state() copies over. It points to previous
763  * bpf_verifier_state which is never reallocated.
764  */
765 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
766 			      int refs_size, bool copy_old)
767 {
768 	int err = realloc_reference_state(state, refs_size, copy_old);
769 	if (err)
770 		return err;
771 	return realloc_stack_state(state, stack_size, copy_old);
772 }
773 
774 /* Acquire a pointer id from the env and update the state->refs to include
775  * this new pointer reference.
776  * On success, returns a valid pointer id to associate with the register
777  * On failure, returns a negative errno.
778  */
779 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
780 {
781 	struct bpf_func_state *state = cur_func(env);
782 	int new_ofs = state->acquired_refs;
783 	int id, err;
784 
785 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
786 	if (err)
787 		return err;
788 	id = ++env->id_gen;
789 	state->refs[new_ofs].id = id;
790 	state->refs[new_ofs].insn_idx = insn_idx;
791 
792 	return id;
793 }
794 
795 /* release function corresponding to acquire_reference_state(). Idempotent. */
796 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
797 {
798 	int i, last_idx;
799 
800 	last_idx = state->acquired_refs - 1;
801 	for (i = 0; i < state->acquired_refs; i++) {
802 		if (state->refs[i].id == ptr_id) {
803 			if (last_idx && i != last_idx)
804 				memcpy(&state->refs[i], &state->refs[last_idx],
805 				       sizeof(*state->refs));
806 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
807 			state->acquired_refs--;
808 			return 0;
809 		}
810 	}
811 	return -EINVAL;
812 }
813 
814 static int transfer_reference_state(struct bpf_func_state *dst,
815 				    struct bpf_func_state *src)
816 {
817 	int err = realloc_reference_state(dst, src->acquired_refs, false);
818 	if (err)
819 		return err;
820 	err = copy_reference_state(dst, src);
821 	if (err)
822 		return err;
823 	return 0;
824 }
825 
826 static void free_func_state(struct bpf_func_state *state)
827 {
828 	if (!state)
829 		return;
830 	kfree(state->refs);
831 	kfree(state->stack);
832 	kfree(state);
833 }
834 
835 static void clear_jmp_history(struct bpf_verifier_state *state)
836 {
837 	kfree(state->jmp_history);
838 	state->jmp_history = NULL;
839 	state->jmp_history_cnt = 0;
840 }
841 
842 static void free_verifier_state(struct bpf_verifier_state *state,
843 				bool free_self)
844 {
845 	int i;
846 
847 	for (i = 0; i <= state->curframe; i++) {
848 		free_func_state(state->frame[i]);
849 		state->frame[i] = NULL;
850 	}
851 	clear_jmp_history(state);
852 	if (free_self)
853 		kfree(state);
854 }
855 
856 /* copy verifier state from src to dst growing dst stack space
857  * when necessary to accommodate larger src stack
858  */
859 static int copy_func_state(struct bpf_func_state *dst,
860 			   const struct bpf_func_state *src)
861 {
862 	int err;
863 
864 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
865 				 false);
866 	if (err)
867 		return err;
868 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
869 	err = copy_reference_state(dst, src);
870 	if (err)
871 		return err;
872 	return copy_stack_state(dst, src);
873 }
874 
875 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
876 			       const struct bpf_verifier_state *src)
877 {
878 	struct bpf_func_state *dst;
879 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
880 	int i, err;
881 
882 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
883 		kfree(dst_state->jmp_history);
884 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
885 		if (!dst_state->jmp_history)
886 			return -ENOMEM;
887 	}
888 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
889 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
890 
891 	/* if dst has more stack frames then src frame, free them */
892 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
893 		free_func_state(dst_state->frame[i]);
894 		dst_state->frame[i] = NULL;
895 	}
896 	dst_state->speculative = src->speculative;
897 	dst_state->curframe = src->curframe;
898 	dst_state->active_spin_lock = src->active_spin_lock;
899 	dst_state->branches = src->branches;
900 	dst_state->parent = src->parent;
901 	dst_state->first_insn_idx = src->first_insn_idx;
902 	dst_state->last_insn_idx = src->last_insn_idx;
903 	for (i = 0; i <= src->curframe; i++) {
904 		dst = dst_state->frame[i];
905 		if (!dst) {
906 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
907 			if (!dst)
908 				return -ENOMEM;
909 			dst_state->frame[i] = dst;
910 		}
911 		err = copy_func_state(dst, src->frame[i]);
912 		if (err)
913 			return err;
914 	}
915 	return 0;
916 }
917 
918 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
919 {
920 	while (st) {
921 		u32 br = --st->branches;
922 
923 		/* WARN_ON(br > 1) technically makes sense here,
924 		 * but see comment in push_stack(), hence:
925 		 */
926 		WARN_ONCE((int)br < 0,
927 			  "BUG update_branch_counts:branches_to_explore=%d\n",
928 			  br);
929 		if (br)
930 			break;
931 		st = st->parent;
932 	}
933 }
934 
935 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
936 		     int *insn_idx, bool pop_log)
937 {
938 	struct bpf_verifier_state *cur = env->cur_state;
939 	struct bpf_verifier_stack_elem *elem, *head = env->head;
940 	int err;
941 
942 	if (env->head == NULL)
943 		return -ENOENT;
944 
945 	if (cur) {
946 		err = copy_verifier_state(cur, &head->st);
947 		if (err)
948 			return err;
949 	}
950 	if (pop_log)
951 		bpf_vlog_reset(&env->log, head->log_pos);
952 	if (insn_idx)
953 		*insn_idx = head->insn_idx;
954 	if (prev_insn_idx)
955 		*prev_insn_idx = head->prev_insn_idx;
956 	elem = head->next;
957 	free_verifier_state(&head->st, false);
958 	kfree(head);
959 	env->head = elem;
960 	env->stack_size--;
961 	return 0;
962 }
963 
964 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
965 					     int insn_idx, int prev_insn_idx,
966 					     bool speculative)
967 {
968 	struct bpf_verifier_state *cur = env->cur_state;
969 	struct bpf_verifier_stack_elem *elem;
970 	int err;
971 
972 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
973 	if (!elem)
974 		goto err;
975 
976 	elem->insn_idx = insn_idx;
977 	elem->prev_insn_idx = prev_insn_idx;
978 	elem->next = env->head;
979 	elem->log_pos = env->log.len_used;
980 	env->head = elem;
981 	env->stack_size++;
982 	err = copy_verifier_state(&elem->st, cur);
983 	if (err)
984 		goto err;
985 	elem->st.speculative |= speculative;
986 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
987 		verbose(env, "The sequence of %d jumps is too complex.\n",
988 			env->stack_size);
989 		goto err;
990 	}
991 	if (elem->st.parent) {
992 		++elem->st.parent->branches;
993 		/* WARN_ON(branches > 2) technically makes sense here,
994 		 * but
995 		 * 1. speculative states will bump 'branches' for non-branch
996 		 * instructions
997 		 * 2. is_state_visited() heuristics may decide not to create
998 		 * a new state for a sequence of branches and all such current
999 		 * and cloned states will be pointing to a single parent state
1000 		 * which might have large 'branches' count.
1001 		 */
1002 	}
1003 	return &elem->st;
1004 err:
1005 	free_verifier_state(env->cur_state, true);
1006 	env->cur_state = NULL;
1007 	/* pop all elements and return */
1008 	while (!pop_stack(env, NULL, NULL, false));
1009 	return NULL;
1010 }
1011 
1012 #define CALLER_SAVED_REGS 6
1013 static const int caller_saved[CALLER_SAVED_REGS] = {
1014 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1015 };
1016 
1017 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1018 				struct bpf_reg_state *reg);
1019 
1020 /* This helper doesn't clear reg->id */
1021 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1022 {
1023 	reg->var_off = tnum_const(imm);
1024 	reg->smin_value = (s64)imm;
1025 	reg->smax_value = (s64)imm;
1026 	reg->umin_value = imm;
1027 	reg->umax_value = imm;
1028 
1029 	reg->s32_min_value = (s32)imm;
1030 	reg->s32_max_value = (s32)imm;
1031 	reg->u32_min_value = (u32)imm;
1032 	reg->u32_max_value = (u32)imm;
1033 }
1034 
1035 /* Mark the unknown part of a register (variable offset or scalar value) as
1036  * known to have the value @imm.
1037  */
1038 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1039 {
1040 	/* Clear id, off, and union(map_ptr, range) */
1041 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1042 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1043 	___mark_reg_known(reg, imm);
1044 }
1045 
1046 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1047 {
1048 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1049 	reg->s32_min_value = (s32)imm;
1050 	reg->s32_max_value = (s32)imm;
1051 	reg->u32_min_value = (u32)imm;
1052 	reg->u32_max_value = (u32)imm;
1053 }
1054 
1055 /* Mark the 'variable offset' part of a register as zero.  This should be
1056  * used only on registers holding a pointer type.
1057  */
1058 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1059 {
1060 	__mark_reg_known(reg, 0);
1061 }
1062 
1063 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1064 {
1065 	__mark_reg_known(reg, 0);
1066 	reg->type = SCALAR_VALUE;
1067 }
1068 
1069 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1070 				struct bpf_reg_state *regs, u32 regno)
1071 {
1072 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1073 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1074 		/* Something bad happened, let's kill all regs */
1075 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1076 			__mark_reg_not_init(env, regs + regno);
1077 		return;
1078 	}
1079 	__mark_reg_known_zero(regs + regno);
1080 }
1081 
1082 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1083 {
1084 	switch (reg->type) {
1085 	case PTR_TO_MAP_VALUE_OR_NULL: {
1086 		const struct bpf_map *map = reg->map_ptr;
1087 
1088 		if (map->inner_map_meta) {
1089 			reg->type = CONST_PTR_TO_MAP;
1090 			reg->map_ptr = map->inner_map_meta;
1091 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1092 			reg->type = PTR_TO_XDP_SOCK;
1093 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1094 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1095 			reg->type = PTR_TO_SOCKET;
1096 		} else {
1097 			reg->type = PTR_TO_MAP_VALUE;
1098 		}
1099 		break;
1100 	}
1101 	case PTR_TO_SOCKET_OR_NULL:
1102 		reg->type = PTR_TO_SOCKET;
1103 		break;
1104 	case PTR_TO_SOCK_COMMON_OR_NULL:
1105 		reg->type = PTR_TO_SOCK_COMMON;
1106 		break;
1107 	case PTR_TO_TCP_SOCK_OR_NULL:
1108 		reg->type = PTR_TO_TCP_SOCK;
1109 		break;
1110 	case PTR_TO_BTF_ID_OR_NULL:
1111 		reg->type = PTR_TO_BTF_ID;
1112 		break;
1113 	case PTR_TO_MEM_OR_NULL:
1114 		reg->type = PTR_TO_MEM;
1115 		break;
1116 	case PTR_TO_RDONLY_BUF_OR_NULL:
1117 		reg->type = PTR_TO_RDONLY_BUF;
1118 		break;
1119 	case PTR_TO_RDWR_BUF_OR_NULL:
1120 		reg->type = PTR_TO_RDWR_BUF;
1121 		break;
1122 	default:
1123 		WARN_ON("unknown nullable register type");
1124 	}
1125 }
1126 
1127 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1128 {
1129 	return type_is_pkt_pointer(reg->type);
1130 }
1131 
1132 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1133 {
1134 	return reg_is_pkt_pointer(reg) ||
1135 	       reg->type == PTR_TO_PACKET_END;
1136 }
1137 
1138 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1139 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1140 				    enum bpf_reg_type which)
1141 {
1142 	/* The register can already have a range from prior markings.
1143 	 * This is fine as long as it hasn't been advanced from its
1144 	 * origin.
1145 	 */
1146 	return reg->type == which &&
1147 	       reg->id == 0 &&
1148 	       reg->off == 0 &&
1149 	       tnum_equals_const(reg->var_off, 0);
1150 }
1151 
1152 /* Reset the min/max bounds of a register */
1153 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1154 {
1155 	reg->smin_value = S64_MIN;
1156 	reg->smax_value = S64_MAX;
1157 	reg->umin_value = 0;
1158 	reg->umax_value = U64_MAX;
1159 
1160 	reg->s32_min_value = S32_MIN;
1161 	reg->s32_max_value = S32_MAX;
1162 	reg->u32_min_value = 0;
1163 	reg->u32_max_value = U32_MAX;
1164 }
1165 
1166 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1167 {
1168 	reg->smin_value = S64_MIN;
1169 	reg->smax_value = S64_MAX;
1170 	reg->umin_value = 0;
1171 	reg->umax_value = U64_MAX;
1172 }
1173 
1174 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1175 {
1176 	reg->s32_min_value = S32_MIN;
1177 	reg->s32_max_value = S32_MAX;
1178 	reg->u32_min_value = 0;
1179 	reg->u32_max_value = U32_MAX;
1180 }
1181 
1182 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1183 {
1184 	struct tnum var32_off = tnum_subreg(reg->var_off);
1185 
1186 	/* min signed is max(sign bit) | min(other bits) */
1187 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1188 			var32_off.value | (var32_off.mask & S32_MIN));
1189 	/* max signed is min(sign bit) | max(other bits) */
1190 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1191 			var32_off.value | (var32_off.mask & S32_MAX));
1192 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1193 	reg->u32_max_value = min(reg->u32_max_value,
1194 				 (u32)(var32_off.value | var32_off.mask));
1195 }
1196 
1197 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1198 {
1199 	/* min signed is max(sign bit) | min(other bits) */
1200 	reg->smin_value = max_t(s64, reg->smin_value,
1201 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1202 	/* max signed is min(sign bit) | max(other bits) */
1203 	reg->smax_value = min_t(s64, reg->smax_value,
1204 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1205 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1206 	reg->umax_value = min(reg->umax_value,
1207 			      reg->var_off.value | reg->var_off.mask);
1208 }
1209 
1210 static void __update_reg_bounds(struct bpf_reg_state *reg)
1211 {
1212 	__update_reg32_bounds(reg);
1213 	__update_reg64_bounds(reg);
1214 }
1215 
1216 /* Uses signed min/max values to inform unsigned, and vice-versa */
1217 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1218 {
1219 	/* Learn sign from signed bounds.
1220 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1221 	 * are the same, so combine.  This works even in the negative case, e.g.
1222 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1223 	 */
1224 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1225 		reg->s32_min_value = reg->u32_min_value =
1226 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1227 		reg->s32_max_value = reg->u32_max_value =
1228 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1229 		return;
1230 	}
1231 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1232 	 * boundary, so we must be careful.
1233 	 */
1234 	if ((s32)reg->u32_max_value >= 0) {
1235 		/* Positive.  We can't learn anything from the smin, but smax
1236 		 * is positive, hence safe.
1237 		 */
1238 		reg->s32_min_value = reg->u32_min_value;
1239 		reg->s32_max_value = reg->u32_max_value =
1240 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1241 	} else if ((s32)reg->u32_min_value < 0) {
1242 		/* Negative.  We can't learn anything from the smax, but smin
1243 		 * is negative, hence safe.
1244 		 */
1245 		reg->s32_min_value = reg->u32_min_value =
1246 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1247 		reg->s32_max_value = reg->u32_max_value;
1248 	}
1249 }
1250 
1251 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1252 {
1253 	/* Learn sign from signed bounds.
1254 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1255 	 * are the same, so combine.  This works even in the negative case, e.g.
1256 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1257 	 */
1258 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1259 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1260 							  reg->umin_value);
1261 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1262 							  reg->umax_value);
1263 		return;
1264 	}
1265 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1266 	 * boundary, so we must be careful.
1267 	 */
1268 	if ((s64)reg->umax_value >= 0) {
1269 		/* Positive.  We can't learn anything from the smin, but smax
1270 		 * is positive, hence safe.
1271 		 */
1272 		reg->smin_value = reg->umin_value;
1273 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1274 							  reg->umax_value);
1275 	} else if ((s64)reg->umin_value < 0) {
1276 		/* Negative.  We can't learn anything from the smax, but smin
1277 		 * is negative, hence safe.
1278 		 */
1279 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1280 							  reg->umin_value);
1281 		reg->smax_value = reg->umax_value;
1282 	}
1283 }
1284 
1285 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1286 {
1287 	__reg32_deduce_bounds(reg);
1288 	__reg64_deduce_bounds(reg);
1289 }
1290 
1291 /* Attempts to improve var_off based on unsigned min/max information */
1292 static void __reg_bound_offset(struct bpf_reg_state *reg)
1293 {
1294 	struct tnum var64_off = tnum_intersect(reg->var_off,
1295 					       tnum_range(reg->umin_value,
1296 							  reg->umax_value));
1297 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1298 						tnum_range(reg->u32_min_value,
1299 							   reg->u32_max_value));
1300 
1301 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1302 }
1303 
1304 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1305 {
1306 	reg->umin_value = reg->u32_min_value;
1307 	reg->umax_value = reg->u32_max_value;
1308 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1309 	 * but must be positive otherwise set to worse case bounds
1310 	 * and refine later from tnum.
1311 	 */
1312 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1313 		reg->smax_value = reg->s32_max_value;
1314 	else
1315 		reg->smax_value = U32_MAX;
1316 	if (reg->s32_min_value >= 0)
1317 		reg->smin_value = reg->s32_min_value;
1318 	else
1319 		reg->smin_value = 0;
1320 }
1321 
1322 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1323 {
1324 	/* special case when 64-bit register has upper 32-bit register
1325 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1326 	 * allowing us to use 32-bit bounds directly,
1327 	 */
1328 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1329 		__reg_assign_32_into_64(reg);
1330 	} else {
1331 		/* Otherwise the best we can do is push lower 32bit known and
1332 		 * unknown bits into register (var_off set from jmp logic)
1333 		 * then learn as much as possible from the 64-bit tnum
1334 		 * known and unknown bits. The previous smin/smax bounds are
1335 		 * invalid here because of jmp32 compare so mark them unknown
1336 		 * so they do not impact tnum bounds calculation.
1337 		 */
1338 		__mark_reg64_unbounded(reg);
1339 		__update_reg_bounds(reg);
1340 	}
1341 
1342 	/* Intersecting with the old var_off might have improved our bounds
1343 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1344 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1345 	 */
1346 	__reg_deduce_bounds(reg);
1347 	__reg_bound_offset(reg);
1348 	__update_reg_bounds(reg);
1349 }
1350 
1351 static bool __reg64_bound_s32(s64 a)
1352 {
1353 	return a > S32_MIN && a < S32_MAX;
1354 }
1355 
1356 static bool __reg64_bound_u32(u64 a)
1357 {
1358 	if (a > U32_MIN && a < U32_MAX)
1359 		return true;
1360 	return false;
1361 }
1362 
1363 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1364 {
1365 	__mark_reg32_unbounded(reg);
1366 
1367 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1368 		reg->s32_min_value = (s32)reg->smin_value;
1369 		reg->s32_max_value = (s32)reg->smax_value;
1370 	}
1371 	if (__reg64_bound_u32(reg->umin_value))
1372 		reg->u32_min_value = (u32)reg->umin_value;
1373 	if (__reg64_bound_u32(reg->umax_value))
1374 		reg->u32_max_value = (u32)reg->umax_value;
1375 
1376 	/* Intersecting with the old var_off might have improved our bounds
1377 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1378 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1379 	 */
1380 	__reg_deduce_bounds(reg);
1381 	__reg_bound_offset(reg);
1382 	__update_reg_bounds(reg);
1383 }
1384 
1385 /* Mark a register as having a completely unknown (scalar) value. */
1386 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1387 			       struct bpf_reg_state *reg)
1388 {
1389 	/*
1390 	 * Clear type, id, off, and union(map_ptr, range) and
1391 	 * padding between 'type' and union
1392 	 */
1393 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1394 	reg->type = SCALAR_VALUE;
1395 	reg->var_off = tnum_unknown;
1396 	reg->frameno = 0;
1397 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1398 	__mark_reg_unbounded(reg);
1399 }
1400 
1401 static void mark_reg_unknown(struct bpf_verifier_env *env,
1402 			     struct bpf_reg_state *regs, u32 regno)
1403 {
1404 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1405 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1406 		/* Something bad happened, let's kill all regs except FP */
1407 		for (regno = 0; regno < BPF_REG_FP; regno++)
1408 			__mark_reg_not_init(env, regs + regno);
1409 		return;
1410 	}
1411 	__mark_reg_unknown(env, regs + regno);
1412 }
1413 
1414 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1415 				struct bpf_reg_state *reg)
1416 {
1417 	__mark_reg_unknown(env, reg);
1418 	reg->type = NOT_INIT;
1419 }
1420 
1421 static void mark_reg_not_init(struct bpf_verifier_env *env,
1422 			      struct bpf_reg_state *regs, u32 regno)
1423 {
1424 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1425 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1426 		/* Something bad happened, let's kill all regs except FP */
1427 		for (regno = 0; regno < BPF_REG_FP; regno++)
1428 			__mark_reg_not_init(env, regs + regno);
1429 		return;
1430 	}
1431 	__mark_reg_not_init(env, regs + regno);
1432 }
1433 
1434 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1435 			    struct bpf_reg_state *regs, u32 regno,
1436 			    enum bpf_reg_type reg_type,
1437 			    struct btf *btf, u32 btf_id)
1438 {
1439 	if (reg_type == SCALAR_VALUE) {
1440 		mark_reg_unknown(env, regs, regno);
1441 		return;
1442 	}
1443 	mark_reg_known_zero(env, regs, regno);
1444 	regs[regno].type = PTR_TO_BTF_ID;
1445 	regs[regno].btf = btf;
1446 	regs[regno].btf_id = btf_id;
1447 }
1448 
1449 #define DEF_NOT_SUBREG	(0)
1450 static void init_reg_state(struct bpf_verifier_env *env,
1451 			   struct bpf_func_state *state)
1452 {
1453 	struct bpf_reg_state *regs = state->regs;
1454 	int i;
1455 
1456 	for (i = 0; i < MAX_BPF_REG; i++) {
1457 		mark_reg_not_init(env, regs, i);
1458 		regs[i].live = REG_LIVE_NONE;
1459 		regs[i].parent = NULL;
1460 		regs[i].subreg_def = DEF_NOT_SUBREG;
1461 	}
1462 
1463 	/* frame pointer */
1464 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1465 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1466 	regs[BPF_REG_FP].frameno = state->frameno;
1467 }
1468 
1469 #define BPF_MAIN_FUNC (-1)
1470 static void init_func_state(struct bpf_verifier_env *env,
1471 			    struct bpf_func_state *state,
1472 			    int callsite, int frameno, int subprogno)
1473 {
1474 	state->callsite = callsite;
1475 	state->frameno = frameno;
1476 	state->subprogno = subprogno;
1477 	init_reg_state(env, state);
1478 }
1479 
1480 enum reg_arg_type {
1481 	SRC_OP,		/* register is used as source operand */
1482 	DST_OP,		/* register is used as destination operand */
1483 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1484 };
1485 
1486 static int cmp_subprogs(const void *a, const void *b)
1487 {
1488 	return ((struct bpf_subprog_info *)a)->start -
1489 	       ((struct bpf_subprog_info *)b)->start;
1490 }
1491 
1492 static int find_subprog(struct bpf_verifier_env *env, int off)
1493 {
1494 	struct bpf_subprog_info *p;
1495 
1496 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1497 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1498 	if (!p)
1499 		return -ENOENT;
1500 	return p - env->subprog_info;
1501 
1502 }
1503 
1504 static int add_subprog(struct bpf_verifier_env *env, int off)
1505 {
1506 	int insn_cnt = env->prog->len;
1507 	int ret;
1508 
1509 	if (off >= insn_cnt || off < 0) {
1510 		verbose(env, "call to invalid destination\n");
1511 		return -EINVAL;
1512 	}
1513 	ret = find_subprog(env, off);
1514 	if (ret >= 0)
1515 		return 0;
1516 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1517 		verbose(env, "too many subprograms\n");
1518 		return -E2BIG;
1519 	}
1520 	env->subprog_info[env->subprog_cnt++].start = off;
1521 	sort(env->subprog_info, env->subprog_cnt,
1522 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1523 	return 0;
1524 }
1525 
1526 static int check_subprogs(struct bpf_verifier_env *env)
1527 {
1528 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1529 	struct bpf_subprog_info *subprog = env->subprog_info;
1530 	struct bpf_insn *insn = env->prog->insnsi;
1531 	int insn_cnt = env->prog->len;
1532 
1533 	/* Add entry function. */
1534 	ret = add_subprog(env, 0);
1535 	if (ret < 0)
1536 		return ret;
1537 
1538 	/* determine subprog starts. The end is one before the next starts */
1539 	for (i = 0; i < insn_cnt; i++) {
1540 		if (!bpf_pseudo_call(insn + i))
1541 			continue;
1542 		if (!env->bpf_capable) {
1543 			verbose(env,
1544 				"function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1545 			return -EPERM;
1546 		}
1547 		ret = add_subprog(env, i + insn[i].imm + 1);
1548 		if (ret < 0)
1549 			return ret;
1550 	}
1551 
1552 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1553 	 * logic. 'subprog_cnt' should not be increased.
1554 	 */
1555 	subprog[env->subprog_cnt].start = insn_cnt;
1556 
1557 	if (env->log.level & BPF_LOG_LEVEL2)
1558 		for (i = 0; i < env->subprog_cnt; i++)
1559 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1560 
1561 	/* now check that all jumps are within the same subprog */
1562 	subprog_start = subprog[cur_subprog].start;
1563 	subprog_end = subprog[cur_subprog + 1].start;
1564 	for (i = 0; i < insn_cnt; i++) {
1565 		u8 code = insn[i].code;
1566 
1567 		if (code == (BPF_JMP | BPF_CALL) &&
1568 		    insn[i].imm == BPF_FUNC_tail_call &&
1569 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1570 			subprog[cur_subprog].has_tail_call = true;
1571 		if (BPF_CLASS(code) == BPF_LD &&
1572 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1573 			subprog[cur_subprog].has_ld_abs = true;
1574 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1575 			goto next;
1576 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1577 			goto next;
1578 		off = i + insn[i].off + 1;
1579 		if (off < subprog_start || off >= subprog_end) {
1580 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1581 			return -EINVAL;
1582 		}
1583 next:
1584 		if (i == subprog_end - 1) {
1585 			/* to avoid fall-through from one subprog into another
1586 			 * the last insn of the subprog should be either exit
1587 			 * or unconditional jump back
1588 			 */
1589 			if (code != (BPF_JMP | BPF_EXIT) &&
1590 			    code != (BPF_JMP | BPF_JA)) {
1591 				verbose(env, "last insn is not an exit or jmp\n");
1592 				return -EINVAL;
1593 			}
1594 			subprog_start = subprog_end;
1595 			cur_subprog++;
1596 			if (cur_subprog < env->subprog_cnt)
1597 				subprog_end = subprog[cur_subprog + 1].start;
1598 		}
1599 	}
1600 	return 0;
1601 }
1602 
1603 /* Parentage chain of this register (or stack slot) should take care of all
1604  * issues like callee-saved registers, stack slot allocation time, etc.
1605  */
1606 static int mark_reg_read(struct bpf_verifier_env *env,
1607 			 const struct bpf_reg_state *state,
1608 			 struct bpf_reg_state *parent, u8 flag)
1609 {
1610 	bool writes = parent == state->parent; /* Observe write marks */
1611 	int cnt = 0;
1612 
1613 	while (parent) {
1614 		/* if read wasn't screened by an earlier write ... */
1615 		if (writes && state->live & REG_LIVE_WRITTEN)
1616 			break;
1617 		if (parent->live & REG_LIVE_DONE) {
1618 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1619 				reg_type_str[parent->type],
1620 				parent->var_off.value, parent->off);
1621 			return -EFAULT;
1622 		}
1623 		/* The first condition is more likely to be true than the
1624 		 * second, checked it first.
1625 		 */
1626 		if ((parent->live & REG_LIVE_READ) == flag ||
1627 		    parent->live & REG_LIVE_READ64)
1628 			/* The parentage chain never changes and
1629 			 * this parent was already marked as LIVE_READ.
1630 			 * There is no need to keep walking the chain again and
1631 			 * keep re-marking all parents as LIVE_READ.
1632 			 * This case happens when the same register is read
1633 			 * multiple times without writes into it in-between.
1634 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1635 			 * then no need to set the weak REG_LIVE_READ32.
1636 			 */
1637 			break;
1638 		/* ... then we depend on parent's value */
1639 		parent->live |= flag;
1640 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1641 		if (flag == REG_LIVE_READ64)
1642 			parent->live &= ~REG_LIVE_READ32;
1643 		state = parent;
1644 		parent = state->parent;
1645 		writes = true;
1646 		cnt++;
1647 	}
1648 
1649 	if (env->longest_mark_read_walk < cnt)
1650 		env->longest_mark_read_walk = cnt;
1651 	return 0;
1652 }
1653 
1654 /* This function is supposed to be used by the following 32-bit optimization
1655  * code only. It returns TRUE if the source or destination register operates
1656  * on 64-bit, otherwise return FALSE.
1657  */
1658 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1659 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1660 {
1661 	u8 code, class, op;
1662 
1663 	code = insn->code;
1664 	class = BPF_CLASS(code);
1665 	op = BPF_OP(code);
1666 	if (class == BPF_JMP) {
1667 		/* BPF_EXIT for "main" will reach here. Return TRUE
1668 		 * conservatively.
1669 		 */
1670 		if (op == BPF_EXIT)
1671 			return true;
1672 		if (op == BPF_CALL) {
1673 			/* BPF to BPF call will reach here because of marking
1674 			 * caller saved clobber with DST_OP_NO_MARK for which we
1675 			 * don't care the register def because they are anyway
1676 			 * marked as NOT_INIT already.
1677 			 */
1678 			if (insn->src_reg == BPF_PSEUDO_CALL)
1679 				return false;
1680 			/* Helper call will reach here because of arg type
1681 			 * check, conservatively return TRUE.
1682 			 */
1683 			if (t == SRC_OP)
1684 				return true;
1685 
1686 			return false;
1687 		}
1688 	}
1689 
1690 	if (class == BPF_ALU64 || class == BPF_JMP ||
1691 	    /* BPF_END always use BPF_ALU class. */
1692 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1693 		return true;
1694 
1695 	if (class == BPF_ALU || class == BPF_JMP32)
1696 		return false;
1697 
1698 	if (class == BPF_LDX) {
1699 		if (t != SRC_OP)
1700 			return BPF_SIZE(code) == BPF_DW;
1701 		/* LDX source must be ptr. */
1702 		return true;
1703 	}
1704 
1705 	if (class == BPF_STX) {
1706 		if (reg->type != SCALAR_VALUE)
1707 			return true;
1708 		return BPF_SIZE(code) == BPF_DW;
1709 	}
1710 
1711 	if (class == BPF_LD) {
1712 		u8 mode = BPF_MODE(code);
1713 
1714 		/* LD_IMM64 */
1715 		if (mode == BPF_IMM)
1716 			return true;
1717 
1718 		/* Both LD_IND and LD_ABS return 32-bit data. */
1719 		if (t != SRC_OP)
1720 			return  false;
1721 
1722 		/* Implicit ctx ptr. */
1723 		if (regno == BPF_REG_6)
1724 			return true;
1725 
1726 		/* Explicit source could be any width. */
1727 		return true;
1728 	}
1729 
1730 	if (class == BPF_ST)
1731 		/* The only source register for BPF_ST is a ptr. */
1732 		return true;
1733 
1734 	/* Conservatively return true at default. */
1735 	return true;
1736 }
1737 
1738 /* Return TRUE if INSN doesn't have explicit value define. */
1739 static bool insn_no_def(struct bpf_insn *insn)
1740 {
1741 	u8 class = BPF_CLASS(insn->code);
1742 
1743 	return (class == BPF_JMP || class == BPF_JMP32 ||
1744 		class == BPF_STX || class == BPF_ST);
1745 }
1746 
1747 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1748 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1749 {
1750 	if (insn_no_def(insn))
1751 		return false;
1752 
1753 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1754 }
1755 
1756 static void mark_insn_zext(struct bpf_verifier_env *env,
1757 			   struct bpf_reg_state *reg)
1758 {
1759 	s32 def_idx = reg->subreg_def;
1760 
1761 	if (def_idx == DEF_NOT_SUBREG)
1762 		return;
1763 
1764 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1765 	/* The dst will be zero extended, so won't be sub-register anymore. */
1766 	reg->subreg_def = DEF_NOT_SUBREG;
1767 }
1768 
1769 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1770 			 enum reg_arg_type t)
1771 {
1772 	struct bpf_verifier_state *vstate = env->cur_state;
1773 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1774 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1775 	struct bpf_reg_state *reg, *regs = state->regs;
1776 	bool rw64;
1777 
1778 	if (regno >= MAX_BPF_REG) {
1779 		verbose(env, "R%d is invalid\n", regno);
1780 		return -EINVAL;
1781 	}
1782 
1783 	reg = &regs[regno];
1784 	rw64 = is_reg64(env, insn, regno, reg, t);
1785 	if (t == SRC_OP) {
1786 		/* check whether register used as source operand can be read */
1787 		if (reg->type == NOT_INIT) {
1788 			verbose(env, "R%d !read_ok\n", regno);
1789 			return -EACCES;
1790 		}
1791 		/* We don't need to worry about FP liveness because it's read-only */
1792 		if (regno == BPF_REG_FP)
1793 			return 0;
1794 
1795 		if (rw64)
1796 			mark_insn_zext(env, reg);
1797 
1798 		return mark_reg_read(env, reg, reg->parent,
1799 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1800 	} else {
1801 		/* check whether register used as dest operand can be written to */
1802 		if (regno == BPF_REG_FP) {
1803 			verbose(env, "frame pointer is read only\n");
1804 			return -EACCES;
1805 		}
1806 		reg->live |= REG_LIVE_WRITTEN;
1807 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1808 		if (t == DST_OP)
1809 			mark_reg_unknown(env, regs, regno);
1810 	}
1811 	return 0;
1812 }
1813 
1814 /* for any branch, call, exit record the history of jmps in the given state */
1815 static int push_jmp_history(struct bpf_verifier_env *env,
1816 			    struct bpf_verifier_state *cur)
1817 {
1818 	u32 cnt = cur->jmp_history_cnt;
1819 	struct bpf_idx_pair *p;
1820 
1821 	cnt++;
1822 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1823 	if (!p)
1824 		return -ENOMEM;
1825 	p[cnt - 1].idx = env->insn_idx;
1826 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1827 	cur->jmp_history = p;
1828 	cur->jmp_history_cnt = cnt;
1829 	return 0;
1830 }
1831 
1832 /* Backtrack one insn at a time. If idx is not at the top of recorded
1833  * history then previous instruction came from straight line execution.
1834  */
1835 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1836 			     u32 *history)
1837 {
1838 	u32 cnt = *history;
1839 
1840 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1841 		i = st->jmp_history[cnt - 1].prev_idx;
1842 		(*history)--;
1843 	} else {
1844 		i--;
1845 	}
1846 	return i;
1847 }
1848 
1849 /* For given verifier state backtrack_insn() is called from the last insn to
1850  * the first insn. Its purpose is to compute a bitmask of registers and
1851  * stack slots that needs precision in the parent verifier state.
1852  */
1853 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1854 			  u32 *reg_mask, u64 *stack_mask)
1855 {
1856 	const struct bpf_insn_cbs cbs = {
1857 		.cb_print	= verbose,
1858 		.private_data	= env,
1859 	};
1860 	struct bpf_insn *insn = env->prog->insnsi + idx;
1861 	u8 class = BPF_CLASS(insn->code);
1862 	u8 opcode = BPF_OP(insn->code);
1863 	u8 mode = BPF_MODE(insn->code);
1864 	u32 dreg = 1u << insn->dst_reg;
1865 	u32 sreg = 1u << insn->src_reg;
1866 	u32 spi;
1867 
1868 	if (insn->code == 0)
1869 		return 0;
1870 	if (env->log.level & BPF_LOG_LEVEL) {
1871 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1872 		verbose(env, "%d: ", idx);
1873 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1874 	}
1875 
1876 	if (class == BPF_ALU || class == BPF_ALU64) {
1877 		if (!(*reg_mask & dreg))
1878 			return 0;
1879 		if (opcode == BPF_MOV) {
1880 			if (BPF_SRC(insn->code) == BPF_X) {
1881 				/* dreg = sreg
1882 				 * dreg needs precision after this insn
1883 				 * sreg needs precision before this insn
1884 				 */
1885 				*reg_mask &= ~dreg;
1886 				*reg_mask |= sreg;
1887 			} else {
1888 				/* dreg = K
1889 				 * dreg needs precision after this insn.
1890 				 * Corresponding register is already marked
1891 				 * as precise=true in this verifier state.
1892 				 * No further markings in parent are necessary
1893 				 */
1894 				*reg_mask &= ~dreg;
1895 			}
1896 		} else {
1897 			if (BPF_SRC(insn->code) == BPF_X) {
1898 				/* dreg += sreg
1899 				 * both dreg and sreg need precision
1900 				 * before this insn
1901 				 */
1902 				*reg_mask |= sreg;
1903 			} /* else dreg += K
1904 			   * dreg still needs precision before this insn
1905 			   */
1906 		}
1907 	} else if (class == BPF_LDX) {
1908 		if (!(*reg_mask & dreg))
1909 			return 0;
1910 		*reg_mask &= ~dreg;
1911 
1912 		/* scalars can only be spilled into stack w/o losing precision.
1913 		 * Load from any other memory can be zero extended.
1914 		 * The desire to keep that precision is already indicated
1915 		 * by 'precise' mark in corresponding register of this state.
1916 		 * No further tracking necessary.
1917 		 */
1918 		if (insn->src_reg != BPF_REG_FP)
1919 			return 0;
1920 		if (BPF_SIZE(insn->code) != BPF_DW)
1921 			return 0;
1922 
1923 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1924 		 * that [fp - off] slot contains scalar that needs to be
1925 		 * tracked with precision
1926 		 */
1927 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1928 		if (spi >= 64) {
1929 			verbose(env, "BUG spi %d\n", spi);
1930 			WARN_ONCE(1, "verifier backtracking bug");
1931 			return -EFAULT;
1932 		}
1933 		*stack_mask |= 1ull << spi;
1934 	} else if (class == BPF_STX || class == BPF_ST) {
1935 		if (*reg_mask & dreg)
1936 			/* stx & st shouldn't be using _scalar_ dst_reg
1937 			 * to access memory. It means backtracking
1938 			 * encountered a case of pointer subtraction.
1939 			 */
1940 			return -ENOTSUPP;
1941 		/* scalars can only be spilled into stack */
1942 		if (insn->dst_reg != BPF_REG_FP)
1943 			return 0;
1944 		if (BPF_SIZE(insn->code) != BPF_DW)
1945 			return 0;
1946 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1947 		if (spi >= 64) {
1948 			verbose(env, "BUG spi %d\n", spi);
1949 			WARN_ONCE(1, "verifier backtracking bug");
1950 			return -EFAULT;
1951 		}
1952 		if (!(*stack_mask & (1ull << spi)))
1953 			return 0;
1954 		*stack_mask &= ~(1ull << spi);
1955 		if (class == BPF_STX)
1956 			*reg_mask |= sreg;
1957 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1958 		if (opcode == BPF_CALL) {
1959 			if (insn->src_reg == BPF_PSEUDO_CALL)
1960 				return -ENOTSUPP;
1961 			/* regular helper call sets R0 */
1962 			*reg_mask &= ~1;
1963 			if (*reg_mask & 0x3f) {
1964 				/* if backtracing was looking for registers R1-R5
1965 				 * they should have been found already.
1966 				 */
1967 				verbose(env, "BUG regs %x\n", *reg_mask);
1968 				WARN_ONCE(1, "verifier backtracking bug");
1969 				return -EFAULT;
1970 			}
1971 		} else if (opcode == BPF_EXIT) {
1972 			return -ENOTSUPP;
1973 		}
1974 	} else if (class == BPF_LD) {
1975 		if (!(*reg_mask & dreg))
1976 			return 0;
1977 		*reg_mask &= ~dreg;
1978 		/* It's ld_imm64 or ld_abs or ld_ind.
1979 		 * For ld_imm64 no further tracking of precision
1980 		 * into parent is necessary
1981 		 */
1982 		if (mode == BPF_IND || mode == BPF_ABS)
1983 			/* to be analyzed */
1984 			return -ENOTSUPP;
1985 	}
1986 	return 0;
1987 }
1988 
1989 /* the scalar precision tracking algorithm:
1990  * . at the start all registers have precise=false.
1991  * . scalar ranges are tracked as normal through alu and jmp insns.
1992  * . once precise value of the scalar register is used in:
1993  *   .  ptr + scalar alu
1994  *   . if (scalar cond K|scalar)
1995  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1996  *   backtrack through the verifier states and mark all registers and
1997  *   stack slots with spilled constants that these scalar regisers
1998  *   should be precise.
1999  * . during state pruning two registers (or spilled stack slots)
2000  *   are equivalent if both are not precise.
2001  *
2002  * Note the verifier cannot simply walk register parentage chain,
2003  * since many different registers and stack slots could have been
2004  * used to compute single precise scalar.
2005  *
2006  * The approach of starting with precise=true for all registers and then
2007  * backtrack to mark a register as not precise when the verifier detects
2008  * that program doesn't care about specific value (e.g., when helper
2009  * takes register as ARG_ANYTHING parameter) is not safe.
2010  *
2011  * It's ok to walk single parentage chain of the verifier states.
2012  * It's possible that this backtracking will go all the way till 1st insn.
2013  * All other branches will be explored for needing precision later.
2014  *
2015  * The backtracking needs to deal with cases like:
2016  *   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)
2017  * r9 -= r8
2018  * r5 = r9
2019  * if r5 > 0x79f goto pc+7
2020  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2021  * r5 += 1
2022  * ...
2023  * call bpf_perf_event_output#25
2024  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2025  *
2026  * and this case:
2027  * r6 = 1
2028  * call foo // uses callee's r6 inside to compute r0
2029  * r0 += r6
2030  * if r0 == 0 goto
2031  *
2032  * to track above reg_mask/stack_mask needs to be independent for each frame.
2033  *
2034  * Also if parent's curframe > frame where backtracking started,
2035  * the verifier need to mark registers in both frames, otherwise callees
2036  * may incorrectly prune callers. This is similar to
2037  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2038  *
2039  * For now backtracking falls back into conservative marking.
2040  */
2041 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2042 				     struct bpf_verifier_state *st)
2043 {
2044 	struct bpf_func_state *func;
2045 	struct bpf_reg_state *reg;
2046 	int i, j;
2047 
2048 	/* big hammer: mark all scalars precise in this path.
2049 	 * pop_stack may still get !precise scalars.
2050 	 */
2051 	for (; st; st = st->parent)
2052 		for (i = 0; i <= st->curframe; i++) {
2053 			func = st->frame[i];
2054 			for (j = 0; j < BPF_REG_FP; j++) {
2055 				reg = &func->regs[j];
2056 				if (reg->type != SCALAR_VALUE)
2057 					continue;
2058 				reg->precise = true;
2059 			}
2060 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2061 				if (func->stack[j].slot_type[0] != STACK_SPILL)
2062 					continue;
2063 				reg = &func->stack[j].spilled_ptr;
2064 				if (reg->type != SCALAR_VALUE)
2065 					continue;
2066 				reg->precise = true;
2067 			}
2068 		}
2069 }
2070 
2071 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2072 				  int spi)
2073 {
2074 	struct bpf_verifier_state *st = env->cur_state;
2075 	int first_idx = st->first_insn_idx;
2076 	int last_idx = env->insn_idx;
2077 	struct bpf_func_state *func;
2078 	struct bpf_reg_state *reg;
2079 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2080 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2081 	bool skip_first = true;
2082 	bool new_marks = false;
2083 	int i, err;
2084 
2085 	if (!env->bpf_capable)
2086 		return 0;
2087 
2088 	func = st->frame[st->curframe];
2089 	if (regno >= 0) {
2090 		reg = &func->regs[regno];
2091 		if (reg->type != SCALAR_VALUE) {
2092 			WARN_ONCE(1, "backtracing misuse");
2093 			return -EFAULT;
2094 		}
2095 		if (!reg->precise)
2096 			new_marks = true;
2097 		else
2098 			reg_mask = 0;
2099 		reg->precise = true;
2100 	}
2101 
2102 	while (spi >= 0) {
2103 		if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2104 			stack_mask = 0;
2105 			break;
2106 		}
2107 		reg = &func->stack[spi].spilled_ptr;
2108 		if (reg->type != SCALAR_VALUE) {
2109 			stack_mask = 0;
2110 			break;
2111 		}
2112 		if (!reg->precise)
2113 			new_marks = true;
2114 		else
2115 			stack_mask = 0;
2116 		reg->precise = true;
2117 		break;
2118 	}
2119 
2120 	if (!new_marks)
2121 		return 0;
2122 	if (!reg_mask && !stack_mask)
2123 		return 0;
2124 	for (;;) {
2125 		DECLARE_BITMAP(mask, 64);
2126 		u32 history = st->jmp_history_cnt;
2127 
2128 		if (env->log.level & BPF_LOG_LEVEL)
2129 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2130 		for (i = last_idx;;) {
2131 			if (skip_first) {
2132 				err = 0;
2133 				skip_first = false;
2134 			} else {
2135 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2136 			}
2137 			if (err == -ENOTSUPP) {
2138 				mark_all_scalars_precise(env, st);
2139 				return 0;
2140 			} else if (err) {
2141 				return err;
2142 			}
2143 			if (!reg_mask && !stack_mask)
2144 				/* Found assignment(s) into tracked register in this state.
2145 				 * Since this state is already marked, just return.
2146 				 * Nothing to be tracked further in the parent state.
2147 				 */
2148 				return 0;
2149 			if (i == first_idx)
2150 				break;
2151 			i = get_prev_insn_idx(st, i, &history);
2152 			if (i >= env->prog->len) {
2153 				/* This can happen if backtracking reached insn 0
2154 				 * and there are still reg_mask or stack_mask
2155 				 * to backtrack.
2156 				 * It means the backtracking missed the spot where
2157 				 * particular register was initialized with a constant.
2158 				 */
2159 				verbose(env, "BUG backtracking idx %d\n", i);
2160 				WARN_ONCE(1, "verifier backtracking bug");
2161 				return -EFAULT;
2162 			}
2163 		}
2164 		st = st->parent;
2165 		if (!st)
2166 			break;
2167 
2168 		new_marks = false;
2169 		func = st->frame[st->curframe];
2170 		bitmap_from_u64(mask, reg_mask);
2171 		for_each_set_bit(i, mask, 32) {
2172 			reg = &func->regs[i];
2173 			if (reg->type != SCALAR_VALUE) {
2174 				reg_mask &= ~(1u << i);
2175 				continue;
2176 			}
2177 			if (!reg->precise)
2178 				new_marks = true;
2179 			reg->precise = true;
2180 		}
2181 
2182 		bitmap_from_u64(mask, stack_mask);
2183 		for_each_set_bit(i, mask, 64) {
2184 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2185 				/* the sequence of instructions:
2186 				 * 2: (bf) r3 = r10
2187 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2188 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2189 				 * doesn't contain jmps. It's backtracked
2190 				 * as a single block.
2191 				 * During backtracking insn 3 is not recognized as
2192 				 * stack access, so at the end of backtracking
2193 				 * stack slot fp-8 is still marked in stack_mask.
2194 				 * However the parent state may not have accessed
2195 				 * fp-8 and it's "unallocated" stack space.
2196 				 * In such case fallback to conservative.
2197 				 */
2198 				mark_all_scalars_precise(env, st);
2199 				return 0;
2200 			}
2201 
2202 			if (func->stack[i].slot_type[0] != STACK_SPILL) {
2203 				stack_mask &= ~(1ull << i);
2204 				continue;
2205 			}
2206 			reg = &func->stack[i].spilled_ptr;
2207 			if (reg->type != SCALAR_VALUE) {
2208 				stack_mask &= ~(1ull << i);
2209 				continue;
2210 			}
2211 			if (!reg->precise)
2212 				new_marks = true;
2213 			reg->precise = true;
2214 		}
2215 		if (env->log.level & BPF_LOG_LEVEL) {
2216 			print_verifier_state(env, func);
2217 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2218 				new_marks ? "didn't have" : "already had",
2219 				reg_mask, stack_mask);
2220 		}
2221 
2222 		if (!reg_mask && !stack_mask)
2223 			break;
2224 		if (!new_marks)
2225 			break;
2226 
2227 		last_idx = st->last_insn_idx;
2228 		first_idx = st->first_insn_idx;
2229 	}
2230 	return 0;
2231 }
2232 
2233 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2234 {
2235 	return __mark_chain_precision(env, regno, -1);
2236 }
2237 
2238 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2239 {
2240 	return __mark_chain_precision(env, -1, spi);
2241 }
2242 
2243 static bool is_spillable_regtype(enum bpf_reg_type type)
2244 {
2245 	switch (type) {
2246 	case PTR_TO_MAP_VALUE:
2247 	case PTR_TO_MAP_VALUE_OR_NULL:
2248 	case PTR_TO_STACK:
2249 	case PTR_TO_CTX:
2250 	case PTR_TO_PACKET:
2251 	case PTR_TO_PACKET_META:
2252 	case PTR_TO_PACKET_END:
2253 	case PTR_TO_FLOW_KEYS:
2254 	case CONST_PTR_TO_MAP:
2255 	case PTR_TO_SOCKET:
2256 	case PTR_TO_SOCKET_OR_NULL:
2257 	case PTR_TO_SOCK_COMMON:
2258 	case PTR_TO_SOCK_COMMON_OR_NULL:
2259 	case PTR_TO_TCP_SOCK:
2260 	case PTR_TO_TCP_SOCK_OR_NULL:
2261 	case PTR_TO_XDP_SOCK:
2262 	case PTR_TO_BTF_ID:
2263 	case PTR_TO_BTF_ID_OR_NULL:
2264 	case PTR_TO_RDONLY_BUF:
2265 	case PTR_TO_RDONLY_BUF_OR_NULL:
2266 	case PTR_TO_RDWR_BUF:
2267 	case PTR_TO_RDWR_BUF_OR_NULL:
2268 	case PTR_TO_PERCPU_BTF_ID:
2269 	case PTR_TO_MEM:
2270 	case PTR_TO_MEM_OR_NULL:
2271 		return true;
2272 	default:
2273 		return false;
2274 	}
2275 }
2276 
2277 /* Does this register contain a constant zero? */
2278 static bool register_is_null(struct bpf_reg_state *reg)
2279 {
2280 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2281 }
2282 
2283 static bool register_is_const(struct bpf_reg_state *reg)
2284 {
2285 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2286 }
2287 
2288 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2289 {
2290 	return tnum_is_unknown(reg->var_off) &&
2291 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2292 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2293 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2294 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2295 }
2296 
2297 static bool register_is_bounded(struct bpf_reg_state *reg)
2298 {
2299 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2300 }
2301 
2302 static bool __is_pointer_value(bool allow_ptr_leaks,
2303 			       const struct bpf_reg_state *reg)
2304 {
2305 	if (allow_ptr_leaks)
2306 		return false;
2307 
2308 	return reg->type != SCALAR_VALUE;
2309 }
2310 
2311 static void save_register_state(struct bpf_func_state *state,
2312 				int spi, struct bpf_reg_state *reg)
2313 {
2314 	int i;
2315 
2316 	state->stack[spi].spilled_ptr = *reg;
2317 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2318 
2319 	for (i = 0; i < BPF_REG_SIZE; i++)
2320 		state->stack[spi].slot_type[i] = STACK_SPILL;
2321 }
2322 
2323 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2324  * stack boundary and alignment are checked in check_mem_access()
2325  */
2326 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2327 				       /* stack frame we're writing to */
2328 				       struct bpf_func_state *state,
2329 				       int off, int size, int value_regno,
2330 				       int insn_idx)
2331 {
2332 	struct bpf_func_state *cur; /* state of the current function */
2333 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2334 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2335 	struct bpf_reg_state *reg = NULL;
2336 
2337 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2338 				 state->acquired_refs, true);
2339 	if (err)
2340 		return err;
2341 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2342 	 * so it's aligned access and [off, off + size) are within stack limits
2343 	 */
2344 	if (!env->allow_ptr_leaks &&
2345 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2346 	    size != BPF_REG_SIZE) {
2347 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2348 		return -EACCES;
2349 	}
2350 
2351 	cur = env->cur_state->frame[env->cur_state->curframe];
2352 	if (value_regno >= 0)
2353 		reg = &cur->regs[value_regno];
2354 
2355 	if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2356 	    !register_is_null(reg) && env->bpf_capable) {
2357 		if (dst_reg != BPF_REG_FP) {
2358 			/* The backtracking logic can only recognize explicit
2359 			 * stack slot address like [fp - 8]. Other spill of
2360 			 * scalar via different register has to be conervative.
2361 			 * Backtrack from here and mark all registers as precise
2362 			 * that contributed into 'reg' being a constant.
2363 			 */
2364 			err = mark_chain_precision(env, value_regno);
2365 			if (err)
2366 				return err;
2367 		}
2368 		save_register_state(state, spi, reg);
2369 	} else if (reg && is_spillable_regtype(reg->type)) {
2370 		/* register containing pointer is being spilled into stack */
2371 		if (size != BPF_REG_SIZE) {
2372 			verbose_linfo(env, insn_idx, "; ");
2373 			verbose(env, "invalid size of register spill\n");
2374 			return -EACCES;
2375 		}
2376 
2377 		if (state != cur && reg->type == PTR_TO_STACK) {
2378 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2379 			return -EINVAL;
2380 		}
2381 
2382 		if (!env->bypass_spec_v4) {
2383 			bool sanitize = false;
2384 
2385 			if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2386 			    register_is_const(&state->stack[spi].spilled_ptr))
2387 				sanitize = true;
2388 			for (i = 0; i < BPF_REG_SIZE; i++)
2389 				if (state->stack[spi].slot_type[i] == STACK_MISC) {
2390 					sanitize = true;
2391 					break;
2392 				}
2393 			if (sanitize) {
2394 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2395 				int soff = (-spi - 1) * BPF_REG_SIZE;
2396 
2397 				/* detected reuse of integer stack slot with a pointer
2398 				 * which means either llvm is reusing stack slot or
2399 				 * an attacker is trying to exploit CVE-2018-3639
2400 				 * (speculative store bypass)
2401 				 * Have to sanitize that slot with preemptive
2402 				 * store of zero.
2403 				 */
2404 				if (*poff && *poff != soff) {
2405 					/* disallow programs where single insn stores
2406 					 * into two different stack slots, since verifier
2407 					 * cannot sanitize them
2408 					 */
2409 					verbose(env,
2410 						"insn %d cannot access two stack slots fp%d and fp%d",
2411 						insn_idx, *poff, soff);
2412 					return -EINVAL;
2413 				}
2414 				*poff = soff;
2415 			}
2416 		}
2417 		save_register_state(state, spi, reg);
2418 	} else {
2419 		u8 type = STACK_MISC;
2420 
2421 		/* regular write of data into stack destroys any spilled ptr */
2422 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2423 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2424 		if (state->stack[spi].slot_type[0] == STACK_SPILL)
2425 			for (i = 0; i < BPF_REG_SIZE; i++)
2426 				state->stack[spi].slot_type[i] = STACK_MISC;
2427 
2428 		/* only mark the slot as written if all 8 bytes were written
2429 		 * otherwise read propagation may incorrectly stop too soon
2430 		 * when stack slots are partially written.
2431 		 * This heuristic means that read propagation will be
2432 		 * conservative, since it will add reg_live_read marks
2433 		 * to stack slots all the way to first state when programs
2434 		 * writes+reads less than 8 bytes
2435 		 */
2436 		if (size == BPF_REG_SIZE)
2437 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2438 
2439 		/* when we zero initialize stack slots mark them as such */
2440 		if (reg && register_is_null(reg)) {
2441 			/* backtracking doesn't work for STACK_ZERO yet. */
2442 			err = mark_chain_precision(env, value_regno);
2443 			if (err)
2444 				return err;
2445 			type = STACK_ZERO;
2446 		}
2447 
2448 		/* Mark slots affected by this stack write. */
2449 		for (i = 0; i < size; i++)
2450 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2451 				type;
2452 	}
2453 	return 0;
2454 }
2455 
2456 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2457  * known to contain a variable offset.
2458  * This function checks whether the write is permitted and conservatively
2459  * tracks the effects of the write, considering that each stack slot in the
2460  * dynamic range is potentially written to.
2461  *
2462  * 'off' includes 'regno->off'.
2463  * 'value_regno' can be -1, meaning that an unknown value is being written to
2464  * the stack.
2465  *
2466  * Spilled pointers in range are not marked as written because we don't know
2467  * what's going to be actually written. This means that read propagation for
2468  * future reads cannot be terminated by this write.
2469  *
2470  * For privileged programs, uninitialized stack slots are considered
2471  * initialized by this write (even though we don't know exactly what offsets
2472  * are going to be written to). The idea is that we don't want the verifier to
2473  * reject future reads that access slots written to through variable offsets.
2474  */
2475 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2476 				     /* func where register points to */
2477 				     struct bpf_func_state *state,
2478 				     int ptr_regno, int off, int size,
2479 				     int value_regno, int insn_idx)
2480 {
2481 	struct bpf_func_state *cur; /* state of the current function */
2482 	int min_off, max_off;
2483 	int i, err;
2484 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2485 	bool writing_zero = false;
2486 	/* set if the fact that we're writing a zero is used to let any
2487 	 * stack slots remain STACK_ZERO
2488 	 */
2489 	bool zero_used = false;
2490 
2491 	cur = env->cur_state->frame[env->cur_state->curframe];
2492 	ptr_reg = &cur->regs[ptr_regno];
2493 	min_off = ptr_reg->smin_value + off;
2494 	max_off = ptr_reg->smax_value + off + size;
2495 	if (value_regno >= 0)
2496 		value_reg = &cur->regs[value_regno];
2497 	if (value_reg && register_is_null(value_reg))
2498 		writing_zero = true;
2499 
2500 	err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2501 				 state->acquired_refs, true);
2502 	if (err)
2503 		return err;
2504 
2505 
2506 	/* Variable offset writes destroy any spilled pointers in range. */
2507 	for (i = min_off; i < max_off; i++) {
2508 		u8 new_type, *stype;
2509 		int slot, spi;
2510 
2511 		slot = -i - 1;
2512 		spi = slot / BPF_REG_SIZE;
2513 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2514 
2515 		if (!env->allow_ptr_leaks
2516 				&& *stype != NOT_INIT
2517 				&& *stype != SCALAR_VALUE) {
2518 			/* Reject the write if there's are spilled pointers in
2519 			 * range. If we didn't reject here, the ptr status
2520 			 * would be erased below (even though not all slots are
2521 			 * actually overwritten), possibly opening the door to
2522 			 * leaks.
2523 			 */
2524 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2525 				insn_idx, i);
2526 			return -EINVAL;
2527 		}
2528 
2529 		/* Erase all spilled pointers. */
2530 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2531 
2532 		/* Update the slot type. */
2533 		new_type = STACK_MISC;
2534 		if (writing_zero && *stype == STACK_ZERO) {
2535 			new_type = STACK_ZERO;
2536 			zero_used = true;
2537 		}
2538 		/* If the slot is STACK_INVALID, we check whether it's OK to
2539 		 * pretend that it will be initialized by this write. The slot
2540 		 * might not actually be written to, and so if we mark it as
2541 		 * initialized future reads might leak uninitialized memory.
2542 		 * For privileged programs, we will accept such reads to slots
2543 		 * that may or may not be written because, if we're reject
2544 		 * them, the error would be too confusing.
2545 		 */
2546 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2547 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2548 					insn_idx, i);
2549 			return -EINVAL;
2550 		}
2551 		*stype = new_type;
2552 	}
2553 	if (zero_used) {
2554 		/* backtracking doesn't work for STACK_ZERO yet. */
2555 		err = mark_chain_precision(env, value_regno);
2556 		if (err)
2557 			return err;
2558 	}
2559 	return 0;
2560 }
2561 
2562 /* When register 'dst_regno' is assigned some values from stack[min_off,
2563  * max_off), we set the register's type according to the types of the
2564  * respective stack slots. If all the stack values are known to be zeros, then
2565  * so is the destination reg. Otherwise, the register is considered to be
2566  * SCALAR. This function does not deal with register filling; the caller must
2567  * ensure that all spilled registers in the stack range have been marked as
2568  * read.
2569  */
2570 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2571 				/* func where src register points to */
2572 				struct bpf_func_state *ptr_state,
2573 				int min_off, int max_off, int dst_regno)
2574 {
2575 	struct bpf_verifier_state *vstate = env->cur_state;
2576 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2577 	int i, slot, spi;
2578 	u8 *stype;
2579 	int zeros = 0;
2580 
2581 	for (i = min_off; i < max_off; i++) {
2582 		slot = -i - 1;
2583 		spi = slot / BPF_REG_SIZE;
2584 		stype = ptr_state->stack[spi].slot_type;
2585 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2586 			break;
2587 		zeros++;
2588 	}
2589 	if (zeros == max_off - min_off) {
2590 		/* any access_size read into register is zero extended,
2591 		 * so the whole register == const_zero
2592 		 */
2593 		__mark_reg_const_zero(&state->regs[dst_regno]);
2594 		/* backtracking doesn't support STACK_ZERO yet,
2595 		 * so mark it precise here, so that later
2596 		 * backtracking can stop here.
2597 		 * Backtracking may not need this if this register
2598 		 * doesn't participate in pointer adjustment.
2599 		 * Forward propagation of precise flag is not
2600 		 * necessary either. This mark is only to stop
2601 		 * backtracking. Any register that contributed
2602 		 * to const 0 was marked precise before spill.
2603 		 */
2604 		state->regs[dst_regno].precise = true;
2605 	} else {
2606 		/* have read misc data from the stack */
2607 		mark_reg_unknown(env, state->regs, dst_regno);
2608 	}
2609 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2610 }
2611 
2612 /* Read the stack at 'off' and put the results into the register indicated by
2613  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2614  * spilled reg.
2615  *
2616  * 'dst_regno' can be -1, meaning that the read value is not going to a
2617  * register.
2618  *
2619  * The access is assumed to be within the current stack bounds.
2620  */
2621 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2622 				      /* func where src register points to */
2623 				      struct bpf_func_state *reg_state,
2624 				      int off, int size, int dst_regno)
2625 {
2626 	struct bpf_verifier_state *vstate = env->cur_state;
2627 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2628 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2629 	struct bpf_reg_state *reg;
2630 	u8 *stype;
2631 
2632 	stype = reg_state->stack[spi].slot_type;
2633 	reg = &reg_state->stack[spi].spilled_ptr;
2634 
2635 	if (stype[0] == STACK_SPILL) {
2636 		if (size != BPF_REG_SIZE) {
2637 			if (reg->type != SCALAR_VALUE) {
2638 				verbose_linfo(env, env->insn_idx, "; ");
2639 				verbose(env, "invalid size of register fill\n");
2640 				return -EACCES;
2641 			}
2642 			if (dst_regno >= 0) {
2643 				mark_reg_unknown(env, state->regs, dst_regno);
2644 				state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2645 			}
2646 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2647 			return 0;
2648 		}
2649 		for (i = 1; i < BPF_REG_SIZE; i++) {
2650 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2651 				verbose(env, "corrupted spill memory\n");
2652 				return -EACCES;
2653 			}
2654 		}
2655 
2656 		if (dst_regno >= 0) {
2657 			/* restore register state from stack */
2658 			state->regs[dst_regno] = *reg;
2659 			/* mark reg as written since spilled pointer state likely
2660 			 * has its liveness marks cleared by is_state_visited()
2661 			 * which resets stack/reg liveness for state transitions
2662 			 */
2663 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2664 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2665 			/* If dst_regno==-1, the caller is asking us whether
2666 			 * it is acceptable to use this value as a SCALAR_VALUE
2667 			 * (e.g. for XADD).
2668 			 * We must not allow unprivileged callers to do that
2669 			 * with spilled pointers.
2670 			 */
2671 			verbose(env, "leaking pointer from stack off %d\n",
2672 				off);
2673 			return -EACCES;
2674 		}
2675 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2676 	} else {
2677 		u8 type;
2678 
2679 		for (i = 0; i < size; i++) {
2680 			type = stype[(slot - i) % BPF_REG_SIZE];
2681 			if (type == STACK_MISC)
2682 				continue;
2683 			if (type == STACK_ZERO)
2684 				continue;
2685 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2686 				off, i, size);
2687 			return -EACCES;
2688 		}
2689 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2690 		if (dst_regno >= 0)
2691 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2692 	}
2693 	return 0;
2694 }
2695 
2696 enum stack_access_src {
2697 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2698 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
2699 };
2700 
2701 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2702 					 int regno, int off, int access_size,
2703 					 bool zero_size_allowed,
2704 					 enum stack_access_src type,
2705 					 struct bpf_call_arg_meta *meta);
2706 
2707 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2708 {
2709 	return cur_regs(env) + regno;
2710 }
2711 
2712 /* Read the stack at 'ptr_regno + off' and put the result into the register
2713  * 'dst_regno'.
2714  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2715  * but not its variable offset.
2716  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2717  *
2718  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2719  * filling registers (i.e. reads of spilled register cannot be detected when
2720  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2721  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2722  * offset; for a fixed offset check_stack_read_fixed_off should be used
2723  * instead.
2724  */
2725 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2726 				    int ptr_regno, int off, int size, int dst_regno)
2727 {
2728 	/* The state of the source register. */
2729 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2730 	struct bpf_func_state *ptr_state = func(env, reg);
2731 	int err;
2732 	int min_off, max_off;
2733 
2734 	/* Note that we pass a NULL meta, so raw access will not be permitted.
2735 	 */
2736 	err = check_stack_range_initialized(env, ptr_regno, off, size,
2737 					    false, ACCESS_DIRECT, NULL);
2738 	if (err)
2739 		return err;
2740 
2741 	min_off = reg->smin_value + off;
2742 	max_off = reg->smax_value + off;
2743 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2744 	return 0;
2745 }
2746 
2747 /* check_stack_read dispatches to check_stack_read_fixed_off or
2748  * check_stack_read_var_off.
2749  *
2750  * The caller must ensure that the offset falls within the allocated stack
2751  * bounds.
2752  *
2753  * 'dst_regno' is a register which will receive the value from the stack. It
2754  * can be -1, meaning that the read value is not going to a register.
2755  */
2756 static int check_stack_read(struct bpf_verifier_env *env,
2757 			    int ptr_regno, int off, int size,
2758 			    int dst_regno)
2759 {
2760 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2761 	struct bpf_func_state *state = func(env, reg);
2762 	int err;
2763 	/* Some accesses are only permitted with a static offset. */
2764 	bool var_off = !tnum_is_const(reg->var_off);
2765 
2766 	/* The offset is required to be static when reads don't go to a
2767 	 * register, in order to not leak pointers (see
2768 	 * check_stack_read_fixed_off).
2769 	 */
2770 	if (dst_regno < 0 && var_off) {
2771 		char tn_buf[48];
2772 
2773 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2774 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2775 			tn_buf, off, size);
2776 		return -EACCES;
2777 	}
2778 	/* Variable offset is prohibited for unprivileged mode for simplicity
2779 	 * since it requires corresponding support in Spectre masking for stack
2780 	 * ALU. See also retrieve_ptr_limit().
2781 	 */
2782 	if (!env->bypass_spec_v1 && var_off) {
2783 		char tn_buf[48];
2784 
2785 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2786 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2787 				ptr_regno, tn_buf);
2788 		return -EACCES;
2789 	}
2790 
2791 	if (!var_off) {
2792 		off += reg->var_off.value;
2793 		err = check_stack_read_fixed_off(env, state, off, size,
2794 						 dst_regno);
2795 	} else {
2796 		/* Variable offset stack reads need more conservative handling
2797 		 * than fixed offset ones. Note that dst_regno >= 0 on this
2798 		 * branch.
2799 		 */
2800 		err = check_stack_read_var_off(env, ptr_regno, off, size,
2801 					       dst_regno);
2802 	}
2803 	return err;
2804 }
2805 
2806 
2807 /* check_stack_write dispatches to check_stack_write_fixed_off or
2808  * check_stack_write_var_off.
2809  *
2810  * 'ptr_regno' is the register used as a pointer into the stack.
2811  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2812  * 'value_regno' is the register whose value we're writing to the stack. It can
2813  * be -1, meaning that we're not writing from a register.
2814  *
2815  * The caller must ensure that the offset falls within the maximum stack size.
2816  */
2817 static int check_stack_write(struct bpf_verifier_env *env,
2818 			     int ptr_regno, int off, int size,
2819 			     int value_regno, int insn_idx)
2820 {
2821 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2822 	struct bpf_func_state *state = func(env, reg);
2823 	int err;
2824 
2825 	if (tnum_is_const(reg->var_off)) {
2826 		off += reg->var_off.value;
2827 		err = check_stack_write_fixed_off(env, state, off, size,
2828 						  value_regno, insn_idx);
2829 	} else {
2830 		/* Variable offset stack reads need more conservative handling
2831 		 * than fixed offset ones.
2832 		 */
2833 		err = check_stack_write_var_off(env, state,
2834 						ptr_regno, off, size,
2835 						value_regno, insn_idx);
2836 	}
2837 	return err;
2838 }
2839 
2840 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2841 				 int off, int size, enum bpf_access_type type)
2842 {
2843 	struct bpf_reg_state *regs = cur_regs(env);
2844 	struct bpf_map *map = regs[regno].map_ptr;
2845 	u32 cap = bpf_map_flags_to_cap(map);
2846 
2847 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2848 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2849 			map->value_size, off, size);
2850 		return -EACCES;
2851 	}
2852 
2853 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2854 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2855 			map->value_size, off, size);
2856 		return -EACCES;
2857 	}
2858 
2859 	return 0;
2860 }
2861 
2862 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2863 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2864 			      int off, int size, u32 mem_size,
2865 			      bool zero_size_allowed)
2866 {
2867 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2868 	struct bpf_reg_state *reg;
2869 
2870 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2871 		return 0;
2872 
2873 	reg = &cur_regs(env)[regno];
2874 	switch (reg->type) {
2875 	case PTR_TO_MAP_VALUE:
2876 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2877 			mem_size, off, size);
2878 		break;
2879 	case PTR_TO_PACKET:
2880 	case PTR_TO_PACKET_META:
2881 	case PTR_TO_PACKET_END:
2882 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2883 			off, size, regno, reg->id, off, mem_size);
2884 		break;
2885 	case PTR_TO_MEM:
2886 	default:
2887 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2888 			mem_size, off, size);
2889 	}
2890 
2891 	return -EACCES;
2892 }
2893 
2894 /* check read/write into a memory region with possible variable offset */
2895 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2896 				   int off, int size, u32 mem_size,
2897 				   bool zero_size_allowed)
2898 {
2899 	struct bpf_verifier_state *vstate = env->cur_state;
2900 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2901 	struct bpf_reg_state *reg = &state->regs[regno];
2902 	int err;
2903 
2904 	/* We may have adjusted the register pointing to memory region, so we
2905 	 * need to try adding each of min_value and max_value to off
2906 	 * to make sure our theoretical access will be safe.
2907 	 */
2908 	if (env->log.level & BPF_LOG_LEVEL)
2909 		print_verifier_state(env, state);
2910 
2911 	/* The minimum value is only important with signed
2912 	 * comparisons where we can't assume the floor of a
2913 	 * value is 0.  If we are using signed variables for our
2914 	 * index'es we need to make sure that whatever we use
2915 	 * will have a set floor within our range.
2916 	 */
2917 	if (reg->smin_value < 0 &&
2918 	    (reg->smin_value == S64_MIN ||
2919 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2920 	      reg->smin_value + off < 0)) {
2921 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2922 			regno);
2923 		return -EACCES;
2924 	}
2925 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
2926 				 mem_size, zero_size_allowed);
2927 	if (err) {
2928 		verbose(env, "R%d min value is outside of the allowed memory range\n",
2929 			regno);
2930 		return err;
2931 	}
2932 
2933 	/* If we haven't set a max value then we need to bail since we can't be
2934 	 * sure we won't do bad things.
2935 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
2936 	 */
2937 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2938 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2939 			regno);
2940 		return -EACCES;
2941 	}
2942 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
2943 				 mem_size, zero_size_allowed);
2944 	if (err) {
2945 		verbose(env, "R%d max value is outside of the allowed memory range\n",
2946 			regno);
2947 		return err;
2948 	}
2949 
2950 	return 0;
2951 }
2952 
2953 /* check read/write into a map element with possible variable offset */
2954 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2955 			    int off, int size, bool zero_size_allowed)
2956 {
2957 	struct bpf_verifier_state *vstate = env->cur_state;
2958 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2959 	struct bpf_reg_state *reg = &state->regs[regno];
2960 	struct bpf_map *map = reg->map_ptr;
2961 	int err;
2962 
2963 	err = check_mem_region_access(env, regno, off, size, map->value_size,
2964 				      zero_size_allowed);
2965 	if (err)
2966 		return err;
2967 
2968 	if (map_value_has_spin_lock(map)) {
2969 		u32 lock = map->spin_lock_off;
2970 
2971 		/* if any part of struct bpf_spin_lock can be touched by
2972 		 * load/store reject this program.
2973 		 * To check that [x1, x2) overlaps with [y1, y2)
2974 		 * it is sufficient to check x1 < y2 && y1 < x2.
2975 		 */
2976 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2977 		     lock < reg->umax_value + off + size) {
2978 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2979 			return -EACCES;
2980 		}
2981 	}
2982 	return err;
2983 }
2984 
2985 #define MAX_PACKET_OFF 0xffff
2986 
2987 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2988 {
2989 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2990 }
2991 
2992 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2993 				       const struct bpf_call_arg_meta *meta,
2994 				       enum bpf_access_type t)
2995 {
2996 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2997 
2998 	switch (prog_type) {
2999 	/* Program types only with direct read access go here! */
3000 	case BPF_PROG_TYPE_LWT_IN:
3001 	case BPF_PROG_TYPE_LWT_OUT:
3002 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3003 	case BPF_PROG_TYPE_SK_REUSEPORT:
3004 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3005 	case BPF_PROG_TYPE_CGROUP_SKB:
3006 		if (t == BPF_WRITE)
3007 			return false;
3008 		fallthrough;
3009 
3010 	/* Program types with direct read + write access go here! */
3011 	case BPF_PROG_TYPE_SCHED_CLS:
3012 	case BPF_PROG_TYPE_SCHED_ACT:
3013 	case BPF_PROG_TYPE_XDP:
3014 	case BPF_PROG_TYPE_LWT_XMIT:
3015 	case BPF_PROG_TYPE_SK_SKB:
3016 	case BPF_PROG_TYPE_SK_MSG:
3017 		if (meta)
3018 			return meta->pkt_access;
3019 
3020 		env->seen_direct_write = true;
3021 		return true;
3022 
3023 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3024 		if (t == BPF_WRITE)
3025 			env->seen_direct_write = true;
3026 
3027 		return true;
3028 
3029 	default:
3030 		return false;
3031 	}
3032 }
3033 
3034 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3035 			       int size, bool zero_size_allowed)
3036 {
3037 	struct bpf_reg_state *regs = cur_regs(env);
3038 	struct bpf_reg_state *reg = &regs[regno];
3039 	int err;
3040 
3041 	/* We may have added a variable offset to the packet pointer; but any
3042 	 * reg->range we have comes after that.  We are only checking the fixed
3043 	 * offset.
3044 	 */
3045 
3046 	/* We don't allow negative numbers, because we aren't tracking enough
3047 	 * detail to prove they're safe.
3048 	 */
3049 	if (reg->smin_value < 0) {
3050 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3051 			regno);
3052 		return -EACCES;
3053 	}
3054 
3055 	err = reg->range < 0 ? -EINVAL :
3056 	      __check_mem_access(env, regno, off, size, reg->range,
3057 				 zero_size_allowed);
3058 	if (err) {
3059 		verbose(env, "R%d offset is outside of the packet\n", regno);
3060 		return err;
3061 	}
3062 
3063 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3064 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3065 	 * otherwise find_good_pkt_pointers would have refused to set range info
3066 	 * that __check_mem_access would have rejected this pkt access.
3067 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3068 	 */
3069 	env->prog->aux->max_pkt_offset =
3070 		max_t(u32, env->prog->aux->max_pkt_offset,
3071 		      off + reg->umax_value + size - 1);
3072 
3073 	return err;
3074 }
3075 
3076 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3077 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3078 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3079 			    struct btf **btf, u32 *btf_id)
3080 {
3081 	struct bpf_insn_access_aux info = {
3082 		.reg_type = *reg_type,
3083 		.log = &env->log,
3084 	};
3085 
3086 	if (env->ops->is_valid_access &&
3087 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3088 		/* A non zero info.ctx_field_size indicates that this field is a
3089 		 * candidate for later verifier transformation to load the whole
3090 		 * field and then apply a mask when accessed with a narrower
3091 		 * access than actual ctx access size. A zero info.ctx_field_size
3092 		 * will only allow for whole field access and rejects any other
3093 		 * type of narrower access.
3094 		 */
3095 		*reg_type = info.reg_type;
3096 
3097 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3098 			*btf = info.btf;
3099 			*btf_id = info.btf_id;
3100 		} else {
3101 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3102 		}
3103 		/* remember the offset of last byte accessed in ctx */
3104 		if (env->prog->aux->max_ctx_offset < off + size)
3105 			env->prog->aux->max_ctx_offset = off + size;
3106 		return 0;
3107 	}
3108 
3109 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3110 	return -EACCES;
3111 }
3112 
3113 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3114 				  int size)
3115 {
3116 	if (size < 0 || off < 0 ||
3117 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3118 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3119 			off, size);
3120 		return -EACCES;
3121 	}
3122 	return 0;
3123 }
3124 
3125 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3126 			     u32 regno, int off, int size,
3127 			     enum bpf_access_type t)
3128 {
3129 	struct bpf_reg_state *regs = cur_regs(env);
3130 	struct bpf_reg_state *reg = &regs[regno];
3131 	struct bpf_insn_access_aux info = {};
3132 	bool valid;
3133 
3134 	if (reg->smin_value < 0) {
3135 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3136 			regno);
3137 		return -EACCES;
3138 	}
3139 
3140 	switch (reg->type) {
3141 	case PTR_TO_SOCK_COMMON:
3142 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3143 		break;
3144 	case PTR_TO_SOCKET:
3145 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3146 		break;
3147 	case PTR_TO_TCP_SOCK:
3148 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3149 		break;
3150 	case PTR_TO_XDP_SOCK:
3151 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3152 		break;
3153 	default:
3154 		valid = false;
3155 	}
3156 
3157 
3158 	if (valid) {
3159 		env->insn_aux_data[insn_idx].ctx_field_size =
3160 			info.ctx_field_size;
3161 		return 0;
3162 	}
3163 
3164 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3165 		regno, reg_type_str[reg->type], off, size);
3166 
3167 	return -EACCES;
3168 }
3169 
3170 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3171 {
3172 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3173 }
3174 
3175 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3176 {
3177 	const struct bpf_reg_state *reg = reg_state(env, regno);
3178 
3179 	return reg->type == PTR_TO_CTX;
3180 }
3181 
3182 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3183 {
3184 	const struct bpf_reg_state *reg = reg_state(env, regno);
3185 
3186 	return type_is_sk_pointer(reg->type);
3187 }
3188 
3189 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3190 {
3191 	const struct bpf_reg_state *reg = reg_state(env, regno);
3192 
3193 	return type_is_pkt_pointer(reg->type);
3194 }
3195 
3196 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3197 {
3198 	const struct bpf_reg_state *reg = reg_state(env, regno);
3199 
3200 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3201 	return reg->type == PTR_TO_FLOW_KEYS;
3202 }
3203 
3204 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3205 				   const struct bpf_reg_state *reg,
3206 				   int off, int size, bool strict)
3207 {
3208 	struct tnum reg_off;
3209 	int ip_align;
3210 
3211 	/* Byte size accesses are always allowed. */
3212 	if (!strict || size == 1)
3213 		return 0;
3214 
3215 	/* For platforms that do not have a Kconfig enabling
3216 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3217 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3218 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3219 	 * to this code only in strict mode where we want to emulate
3220 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3221 	 * unconditional IP align value of '2'.
3222 	 */
3223 	ip_align = 2;
3224 
3225 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3226 	if (!tnum_is_aligned(reg_off, size)) {
3227 		char tn_buf[48];
3228 
3229 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3230 		verbose(env,
3231 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3232 			ip_align, tn_buf, reg->off, off, size);
3233 		return -EACCES;
3234 	}
3235 
3236 	return 0;
3237 }
3238 
3239 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3240 				       const struct bpf_reg_state *reg,
3241 				       const char *pointer_desc,
3242 				       int off, int size, bool strict)
3243 {
3244 	struct tnum reg_off;
3245 
3246 	/* Byte size accesses are always allowed. */
3247 	if (!strict || size == 1)
3248 		return 0;
3249 
3250 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3251 	if (!tnum_is_aligned(reg_off, size)) {
3252 		char tn_buf[48];
3253 
3254 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3255 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3256 			pointer_desc, tn_buf, reg->off, off, size);
3257 		return -EACCES;
3258 	}
3259 
3260 	return 0;
3261 }
3262 
3263 static int check_ptr_alignment(struct bpf_verifier_env *env,
3264 			       const struct bpf_reg_state *reg, int off,
3265 			       int size, bool strict_alignment_once)
3266 {
3267 	bool strict = env->strict_alignment || strict_alignment_once;
3268 	const char *pointer_desc = "";
3269 
3270 	switch (reg->type) {
3271 	case PTR_TO_PACKET:
3272 	case PTR_TO_PACKET_META:
3273 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3274 		 * right in front, treat it the very same way.
3275 		 */
3276 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3277 	case PTR_TO_FLOW_KEYS:
3278 		pointer_desc = "flow keys ";
3279 		break;
3280 	case PTR_TO_MAP_VALUE:
3281 		pointer_desc = "value ";
3282 		break;
3283 	case PTR_TO_CTX:
3284 		pointer_desc = "context ";
3285 		break;
3286 	case PTR_TO_STACK:
3287 		pointer_desc = "stack ";
3288 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3289 		 * and check_stack_read_fixed_off() relies on stack accesses being
3290 		 * aligned.
3291 		 */
3292 		strict = true;
3293 		break;
3294 	case PTR_TO_SOCKET:
3295 		pointer_desc = "sock ";
3296 		break;
3297 	case PTR_TO_SOCK_COMMON:
3298 		pointer_desc = "sock_common ";
3299 		break;
3300 	case PTR_TO_TCP_SOCK:
3301 		pointer_desc = "tcp_sock ";
3302 		break;
3303 	case PTR_TO_XDP_SOCK:
3304 		pointer_desc = "xdp_sock ";
3305 		break;
3306 	default:
3307 		break;
3308 	}
3309 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3310 					   strict);
3311 }
3312 
3313 static int update_stack_depth(struct bpf_verifier_env *env,
3314 			      const struct bpf_func_state *func,
3315 			      int off)
3316 {
3317 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3318 
3319 	if (stack >= -off)
3320 		return 0;
3321 
3322 	/* update known max for given subprogram */
3323 	env->subprog_info[func->subprogno].stack_depth = -off;
3324 	return 0;
3325 }
3326 
3327 /* starting from main bpf function walk all instructions of the function
3328  * and recursively walk all callees that given function can call.
3329  * Ignore jump and exit insns.
3330  * Since recursion is prevented by check_cfg() this algorithm
3331  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3332  */
3333 static int check_max_stack_depth(struct bpf_verifier_env *env)
3334 {
3335 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3336 	struct bpf_subprog_info *subprog = env->subprog_info;
3337 	struct bpf_insn *insn = env->prog->insnsi;
3338 	bool tail_call_reachable = false;
3339 	int ret_insn[MAX_CALL_FRAMES];
3340 	int ret_prog[MAX_CALL_FRAMES];
3341 	int j;
3342 
3343 process_func:
3344 	/* protect against potential stack overflow that might happen when
3345 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3346 	 * depth for such case down to 256 so that the worst case scenario
3347 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3348 	 * 8k).
3349 	 *
3350 	 * To get the idea what might happen, see an example:
3351 	 * func1 -> sub rsp, 128
3352 	 *  subfunc1 -> sub rsp, 256
3353 	 *  tailcall1 -> add rsp, 256
3354 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3355 	 *   subfunc2 -> sub rsp, 64
3356 	 *   subfunc22 -> sub rsp, 128
3357 	 *   tailcall2 -> add rsp, 128
3358 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3359 	 *
3360 	 * tailcall will unwind the current stack frame but it will not get rid
3361 	 * of caller's stack as shown on the example above.
3362 	 */
3363 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3364 		verbose(env,
3365 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3366 			depth);
3367 		return -EACCES;
3368 	}
3369 	/* round up to 32-bytes, since this is granularity
3370 	 * of interpreter stack size
3371 	 */
3372 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3373 	if (depth > MAX_BPF_STACK) {
3374 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3375 			frame + 1, depth);
3376 		return -EACCES;
3377 	}
3378 continue_func:
3379 	subprog_end = subprog[idx + 1].start;
3380 	for (; i < subprog_end; i++) {
3381 		if (!bpf_pseudo_call(insn + i))
3382 			continue;
3383 		/* remember insn and function to return to */
3384 		ret_insn[frame] = i + 1;
3385 		ret_prog[frame] = idx;
3386 
3387 		/* find the callee */
3388 		i = i + insn[i].imm + 1;
3389 		idx = find_subprog(env, i);
3390 		if (idx < 0) {
3391 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3392 				  i);
3393 			return -EFAULT;
3394 		}
3395 
3396 		if (subprog[idx].has_tail_call)
3397 			tail_call_reachable = true;
3398 
3399 		frame++;
3400 		if (frame >= MAX_CALL_FRAMES) {
3401 			verbose(env, "the call stack of %d frames is too deep !\n",
3402 				frame);
3403 			return -E2BIG;
3404 		}
3405 		goto process_func;
3406 	}
3407 	/* if tail call got detected across bpf2bpf calls then mark each of the
3408 	 * currently present subprog frames as tail call reachable subprogs;
3409 	 * this info will be utilized by JIT so that we will be preserving the
3410 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3411 	 */
3412 	if (tail_call_reachable)
3413 		for (j = 0; j < frame; j++)
3414 			subprog[ret_prog[j]].tail_call_reachable = true;
3415 
3416 	/* end of for() loop means the last insn of the 'subprog'
3417 	 * was reached. Doesn't matter whether it was JA or EXIT
3418 	 */
3419 	if (frame == 0)
3420 		return 0;
3421 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3422 	frame--;
3423 	i = ret_insn[frame];
3424 	idx = ret_prog[frame];
3425 	goto continue_func;
3426 }
3427 
3428 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3429 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3430 				  const struct bpf_insn *insn, int idx)
3431 {
3432 	int start = idx + insn->imm + 1, subprog;
3433 
3434 	subprog = find_subprog(env, start);
3435 	if (subprog < 0) {
3436 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3437 			  start);
3438 		return -EFAULT;
3439 	}
3440 	return env->subprog_info[subprog].stack_depth;
3441 }
3442 #endif
3443 
3444 int check_ctx_reg(struct bpf_verifier_env *env,
3445 		  const struct bpf_reg_state *reg, int regno)
3446 {
3447 	/* Access to ctx or passing it to a helper is only allowed in
3448 	 * its original, unmodified form.
3449 	 */
3450 
3451 	if (reg->off) {
3452 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3453 			regno, reg->off);
3454 		return -EACCES;
3455 	}
3456 
3457 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3458 		char tn_buf[48];
3459 
3460 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3461 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3462 		return -EACCES;
3463 	}
3464 
3465 	return 0;
3466 }
3467 
3468 static int __check_buffer_access(struct bpf_verifier_env *env,
3469 				 const char *buf_info,
3470 				 const struct bpf_reg_state *reg,
3471 				 int regno, int off, int size)
3472 {
3473 	if (off < 0) {
3474 		verbose(env,
3475 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3476 			regno, buf_info, off, size);
3477 		return -EACCES;
3478 	}
3479 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3480 		char tn_buf[48];
3481 
3482 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3483 		verbose(env,
3484 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3485 			regno, off, tn_buf);
3486 		return -EACCES;
3487 	}
3488 
3489 	return 0;
3490 }
3491 
3492 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3493 				  const struct bpf_reg_state *reg,
3494 				  int regno, int off, int size)
3495 {
3496 	int err;
3497 
3498 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3499 	if (err)
3500 		return err;
3501 
3502 	if (off + size > env->prog->aux->max_tp_access)
3503 		env->prog->aux->max_tp_access = off + size;
3504 
3505 	return 0;
3506 }
3507 
3508 static int check_buffer_access(struct bpf_verifier_env *env,
3509 			       const struct bpf_reg_state *reg,
3510 			       int regno, int off, int size,
3511 			       bool zero_size_allowed,
3512 			       const char *buf_info,
3513 			       u32 *max_access)
3514 {
3515 	int err;
3516 
3517 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3518 	if (err)
3519 		return err;
3520 
3521 	if (off + size > *max_access)
3522 		*max_access = off + size;
3523 
3524 	return 0;
3525 }
3526 
3527 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3528 static void zext_32_to_64(struct bpf_reg_state *reg)
3529 {
3530 	reg->var_off = tnum_subreg(reg->var_off);
3531 	__reg_assign_32_into_64(reg);
3532 }
3533 
3534 /* truncate register to smaller size (in bytes)
3535  * must be called with size < BPF_REG_SIZE
3536  */
3537 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3538 {
3539 	u64 mask;
3540 
3541 	/* clear high bits in bit representation */
3542 	reg->var_off = tnum_cast(reg->var_off, size);
3543 
3544 	/* fix arithmetic bounds */
3545 	mask = ((u64)1 << (size * 8)) - 1;
3546 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3547 		reg->umin_value &= mask;
3548 		reg->umax_value &= mask;
3549 	} else {
3550 		reg->umin_value = 0;
3551 		reg->umax_value = mask;
3552 	}
3553 	reg->smin_value = reg->umin_value;
3554 	reg->smax_value = reg->umax_value;
3555 
3556 	/* If size is smaller than 32bit register the 32bit register
3557 	 * values are also truncated so we push 64-bit bounds into
3558 	 * 32-bit bounds. Above were truncated < 32-bits already.
3559 	 */
3560 	if (size >= 4)
3561 		return;
3562 	__reg_combine_64_into_32(reg);
3563 }
3564 
3565 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3566 {
3567 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3568 }
3569 
3570 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3571 {
3572 	void *ptr;
3573 	u64 addr;
3574 	int err;
3575 
3576 	err = map->ops->map_direct_value_addr(map, &addr, off);
3577 	if (err)
3578 		return err;
3579 	ptr = (void *)(long)addr + off;
3580 
3581 	switch (size) {
3582 	case sizeof(u8):
3583 		*val = (u64)*(u8 *)ptr;
3584 		break;
3585 	case sizeof(u16):
3586 		*val = (u64)*(u16 *)ptr;
3587 		break;
3588 	case sizeof(u32):
3589 		*val = (u64)*(u32 *)ptr;
3590 		break;
3591 	case sizeof(u64):
3592 		*val = *(u64 *)ptr;
3593 		break;
3594 	default:
3595 		return -EINVAL;
3596 	}
3597 	return 0;
3598 }
3599 
3600 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3601 				   struct bpf_reg_state *regs,
3602 				   int regno, int off, int size,
3603 				   enum bpf_access_type atype,
3604 				   int value_regno)
3605 {
3606 	struct bpf_reg_state *reg = regs + regno;
3607 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3608 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3609 	u32 btf_id;
3610 	int ret;
3611 
3612 	if (off < 0) {
3613 		verbose(env,
3614 			"R%d is ptr_%s invalid negative access: off=%d\n",
3615 			regno, tname, off);
3616 		return -EACCES;
3617 	}
3618 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3619 		char tn_buf[48];
3620 
3621 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3622 		verbose(env,
3623 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3624 			regno, tname, off, tn_buf);
3625 		return -EACCES;
3626 	}
3627 
3628 	if (env->ops->btf_struct_access) {
3629 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3630 						  off, size, atype, &btf_id);
3631 	} else {
3632 		if (atype != BPF_READ) {
3633 			verbose(env, "only read is supported\n");
3634 			return -EACCES;
3635 		}
3636 
3637 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3638 					atype, &btf_id);
3639 	}
3640 
3641 	if (ret < 0)
3642 		return ret;
3643 
3644 	if (atype == BPF_READ && value_regno >= 0)
3645 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3646 
3647 	return 0;
3648 }
3649 
3650 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3651 				   struct bpf_reg_state *regs,
3652 				   int regno, int off, int size,
3653 				   enum bpf_access_type atype,
3654 				   int value_regno)
3655 {
3656 	struct bpf_reg_state *reg = regs + regno;
3657 	struct bpf_map *map = reg->map_ptr;
3658 	const struct btf_type *t;
3659 	const char *tname;
3660 	u32 btf_id;
3661 	int ret;
3662 
3663 	if (!btf_vmlinux) {
3664 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3665 		return -ENOTSUPP;
3666 	}
3667 
3668 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3669 		verbose(env, "map_ptr access not supported for map type %d\n",
3670 			map->map_type);
3671 		return -ENOTSUPP;
3672 	}
3673 
3674 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3675 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3676 
3677 	if (!env->allow_ptr_to_map_access) {
3678 		verbose(env,
3679 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3680 			tname);
3681 		return -EPERM;
3682 	}
3683 
3684 	if (off < 0) {
3685 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3686 			regno, tname, off);
3687 		return -EACCES;
3688 	}
3689 
3690 	if (atype != BPF_READ) {
3691 		verbose(env, "only read from %s is supported\n", tname);
3692 		return -EACCES;
3693 	}
3694 
3695 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3696 	if (ret < 0)
3697 		return ret;
3698 
3699 	if (value_regno >= 0)
3700 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3701 
3702 	return 0;
3703 }
3704 
3705 /* Check that the stack access at the given offset is within bounds. The
3706  * maximum valid offset is -1.
3707  *
3708  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3709  * -state->allocated_stack for reads.
3710  */
3711 static int check_stack_slot_within_bounds(int off,
3712 					  struct bpf_func_state *state,
3713 					  enum bpf_access_type t)
3714 {
3715 	int min_valid_off;
3716 
3717 	if (t == BPF_WRITE)
3718 		min_valid_off = -MAX_BPF_STACK;
3719 	else
3720 		min_valid_off = -state->allocated_stack;
3721 
3722 	if (off < min_valid_off || off > -1)
3723 		return -EACCES;
3724 	return 0;
3725 }
3726 
3727 /* Check that the stack access at 'regno + off' falls within the maximum stack
3728  * bounds.
3729  *
3730  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3731  */
3732 static int check_stack_access_within_bounds(
3733 		struct bpf_verifier_env *env,
3734 		int regno, int off, int access_size,
3735 		enum stack_access_src src, enum bpf_access_type type)
3736 {
3737 	struct bpf_reg_state *regs = cur_regs(env);
3738 	struct bpf_reg_state *reg = regs + regno;
3739 	struct bpf_func_state *state = func(env, reg);
3740 	int min_off, max_off;
3741 	int err;
3742 	char *err_extra;
3743 
3744 	if (src == ACCESS_HELPER)
3745 		/* We don't know if helpers are reading or writing (or both). */
3746 		err_extra = " indirect access to";
3747 	else if (type == BPF_READ)
3748 		err_extra = " read from";
3749 	else
3750 		err_extra = " write to";
3751 
3752 	if (tnum_is_const(reg->var_off)) {
3753 		min_off = reg->var_off.value + off;
3754 		if (access_size > 0)
3755 			max_off = min_off + access_size - 1;
3756 		else
3757 			max_off = min_off;
3758 	} else {
3759 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3760 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
3761 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3762 				err_extra, regno);
3763 			return -EACCES;
3764 		}
3765 		min_off = reg->smin_value + off;
3766 		if (access_size > 0)
3767 			max_off = reg->smax_value + off + access_size - 1;
3768 		else
3769 			max_off = min_off;
3770 	}
3771 
3772 	err = check_stack_slot_within_bounds(min_off, state, type);
3773 	if (!err)
3774 		err = check_stack_slot_within_bounds(max_off, state, type);
3775 
3776 	if (err) {
3777 		if (tnum_is_const(reg->var_off)) {
3778 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3779 				err_extra, regno, off, access_size);
3780 		} else {
3781 			char tn_buf[48];
3782 
3783 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3784 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3785 				err_extra, regno, tn_buf, access_size);
3786 		}
3787 	}
3788 	return err;
3789 }
3790 
3791 /* check whether memory at (regno + off) is accessible for t = (read | write)
3792  * if t==write, value_regno is a register which value is stored into memory
3793  * if t==read, value_regno is a register which will receive the value from memory
3794  * if t==write && value_regno==-1, some unknown value is stored into memory
3795  * if t==read && value_regno==-1, don't care what we read from memory
3796  */
3797 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3798 			    int off, int bpf_size, enum bpf_access_type t,
3799 			    int value_regno, bool strict_alignment_once)
3800 {
3801 	struct bpf_reg_state *regs = cur_regs(env);
3802 	struct bpf_reg_state *reg = regs + regno;
3803 	struct bpf_func_state *state;
3804 	int size, err = 0;
3805 
3806 	size = bpf_size_to_bytes(bpf_size);
3807 	if (size < 0)
3808 		return size;
3809 
3810 	/* alignment checks will add in reg->off themselves */
3811 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3812 	if (err)
3813 		return err;
3814 
3815 	/* for access checks, reg->off is just part of off */
3816 	off += reg->off;
3817 
3818 	if (reg->type == PTR_TO_MAP_VALUE) {
3819 		if (t == BPF_WRITE && value_regno >= 0 &&
3820 		    is_pointer_value(env, value_regno)) {
3821 			verbose(env, "R%d leaks addr into map\n", value_regno);
3822 			return -EACCES;
3823 		}
3824 		err = check_map_access_type(env, regno, off, size, t);
3825 		if (err)
3826 			return err;
3827 		err = check_map_access(env, regno, off, size, false);
3828 		if (!err && t == BPF_READ && value_regno >= 0) {
3829 			struct bpf_map *map = reg->map_ptr;
3830 
3831 			/* if map is read-only, track its contents as scalars */
3832 			if (tnum_is_const(reg->var_off) &&
3833 			    bpf_map_is_rdonly(map) &&
3834 			    map->ops->map_direct_value_addr) {
3835 				int map_off = off + reg->var_off.value;
3836 				u64 val = 0;
3837 
3838 				err = bpf_map_direct_read(map, map_off, size,
3839 							  &val);
3840 				if (err)
3841 					return err;
3842 
3843 				regs[value_regno].type = SCALAR_VALUE;
3844 				__mark_reg_known(&regs[value_regno], val);
3845 			} else {
3846 				mark_reg_unknown(env, regs, value_regno);
3847 			}
3848 		}
3849 	} else if (reg->type == PTR_TO_MEM) {
3850 		if (t == BPF_WRITE && value_regno >= 0 &&
3851 		    is_pointer_value(env, value_regno)) {
3852 			verbose(env, "R%d leaks addr into mem\n", value_regno);
3853 			return -EACCES;
3854 		}
3855 		err = check_mem_region_access(env, regno, off, size,
3856 					      reg->mem_size, false);
3857 		if (!err && t == BPF_READ && value_regno >= 0)
3858 			mark_reg_unknown(env, regs, value_regno);
3859 	} else if (reg->type == PTR_TO_CTX) {
3860 		enum bpf_reg_type reg_type = SCALAR_VALUE;
3861 		struct btf *btf = NULL;
3862 		u32 btf_id = 0;
3863 
3864 		if (t == BPF_WRITE && value_regno >= 0 &&
3865 		    is_pointer_value(env, value_regno)) {
3866 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
3867 			return -EACCES;
3868 		}
3869 
3870 		err = check_ctx_reg(env, reg, regno);
3871 		if (err < 0)
3872 			return err;
3873 
3874 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
3875 		if (err)
3876 			verbose_linfo(env, insn_idx, "; ");
3877 		if (!err && t == BPF_READ && value_regno >= 0) {
3878 			/* ctx access returns either a scalar, or a
3879 			 * PTR_TO_PACKET[_META,_END]. In the latter
3880 			 * case, we know the offset is zero.
3881 			 */
3882 			if (reg_type == SCALAR_VALUE) {
3883 				mark_reg_unknown(env, regs, value_regno);
3884 			} else {
3885 				mark_reg_known_zero(env, regs,
3886 						    value_regno);
3887 				if (reg_type_may_be_null(reg_type))
3888 					regs[value_regno].id = ++env->id_gen;
3889 				/* A load of ctx field could have different
3890 				 * actual load size with the one encoded in the
3891 				 * insn. When the dst is PTR, it is for sure not
3892 				 * a sub-register.
3893 				 */
3894 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3895 				if (reg_type == PTR_TO_BTF_ID ||
3896 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
3897 					regs[value_regno].btf = btf;
3898 					regs[value_regno].btf_id = btf_id;
3899 				}
3900 			}
3901 			regs[value_regno].type = reg_type;
3902 		}
3903 
3904 	} else if (reg->type == PTR_TO_STACK) {
3905 		/* Basic bounds checks. */
3906 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3907 		if (err)
3908 			return err;
3909 
3910 		state = func(env, reg);
3911 		err = update_stack_depth(env, state, off);
3912 		if (err)
3913 			return err;
3914 
3915 		if (t == BPF_READ)
3916 			err = check_stack_read(env, regno, off, size,
3917 					       value_regno);
3918 		else
3919 			err = check_stack_write(env, regno, off, size,
3920 						value_regno, insn_idx);
3921 	} else if (reg_is_pkt_pointer(reg)) {
3922 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3923 			verbose(env, "cannot write into packet\n");
3924 			return -EACCES;
3925 		}
3926 		if (t == BPF_WRITE && value_regno >= 0 &&
3927 		    is_pointer_value(env, value_regno)) {
3928 			verbose(env, "R%d leaks addr into packet\n",
3929 				value_regno);
3930 			return -EACCES;
3931 		}
3932 		err = check_packet_access(env, regno, off, size, false);
3933 		if (!err && t == BPF_READ && value_regno >= 0)
3934 			mark_reg_unknown(env, regs, value_regno);
3935 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
3936 		if (t == BPF_WRITE && value_regno >= 0 &&
3937 		    is_pointer_value(env, value_regno)) {
3938 			verbose(env, "R%d leaks addr into flow keys\n",
3939 				value_regno);
3940 			return -EACCES;
3941 		}
3942 
3943 		err = check_flow_keys_access(env, off, size);
3944 		if (!err && t == BPF_READ && value_regno >= 0)
3945 			mark_reg_unknown(env, regs, value_regno);
3946 	} else if (type_is_sk_pointer(reg->type)) {
3947 		if (t == BPF_WRITE) {
3948 			verbose(env, "R%d cannot write into %s\n",
3949 				regno, reg_type_str[reg->type]);
3950 			return -EACCES;
3951 		}
3952 		err = check_sock_access(env, insn_idx, regno, off, size, t);
3953 		if (!err && value_regno >= 0)
3954 			mark_reg_unknown(env, regs, value_regno);
3955 	} else if (reg->type == PTR_TO_TP_BUFFER) {
3956 		err = check_tp_buffer_access(env, reg, regno, off, size);
3957 		if (!err && t == BPF_READ && value_regno >= 0)
3958 			mark_reg_unknown(env, regs, value_regno);
3959 	} else if (reg->type == PTR_TO_BTF_ID) {
3960 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3961 					      value_regno);
3962 	} else if (reg->type == CONST_PTR_TO_MAP) {
3963 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3964 					      value_regno);
3965 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
3966 		if (t == BPF_WRITE) {
3967 			verbose(env, "R%d cannot write into %s\n",
3968 				regno, reg_type_str[reg->type]);
3969 			return -EACCES;
3970 		}
3971 		err = check_buffer_access(env, reg, regno, off, size, false,
3972 					  "rdonly",
3973 					  &env->prog->aux->max_rdonly_access);
3974 		if (!err && value_regno >= 0)
3975 			mark_reg_unknown(env, regs, value_regno);
3976 	} else if (reg->type == PTR_TO_RDWR_BUF) {
3977 		err = check_buffer_access(env, reg, regno, off, size, false,
3978 					  "rdwr",
3979 					  &env->prog->aux->max_rdwr_access);
3980 		if (!err && t == BPF_READ && value_regno >= 0)
3981 			mark_reg_unknown(env, regs, value_regno);
3982 	} else {
3983 		verbose(env, "R%d invalid mem access '%s'\n", regno,
3984 			reg_type_str[reg->type]);
3985 		return -EACCES;
3986 	}
3987 
3988 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3989 	    regs[value_regno].type == SCALAR_VALUE) {
3990 		/* b/h/w load zero-extends, mark upper bits as known 0 */
3991 		coerce_reg_to_size(&regs[value_regno], size);
3992 	}
3993 	return err;
3994 }
3995 
3996 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3997 {
3998 	int load_reg;
3999 	int err;
4000 
4001 	switch (insn->imm) {
4002 	case BPF_ADD:
4003 	case BPF_ADD | BPF_FETCH:
4004 	case BPF_AND:
4005 	case BPF_AND | BPF_FETCH:
4006 	case BPF_OR:
4007 	case BPF_OR | BPF_FETCH:
4008 	case BPF_XOR:
4009 	case BPF_XOR | BPF_FETCH:
4010 	case BPF_XCHG:
4011 	case BPF_CMPXCHG:
4012 		break;
4013 	default:
4014 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4015 		return -EINVAL;
4016 	}
4017 
4018 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4019 		verbose(env, "invalid atomic operand size\n");
4020 		return -EINVAL;
4021 	}
4022 
4023 	/* check src1 operand */
4024 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4025 	if (err)
4026 		return err;
4027 
4028 	/* check src2 operand */
4029 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4030 	if (err)
4031 		return err;
4032 
4033 	if (insn->imm == BPF_CMPXCHG) {
4034 		/* Check comparison of R0 with memory location */
4035 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4036 		if (err)
4037 			return err;
4038 	}
4039 
4040 	if (is_pointer_value(env, insn->src_reg)) {
4041 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4042 		return -EACCES;
4043 	}
4044 
4045 	if (is_ctx_reg(env, insn->dst_reg) ||
4046 	    is_pkt_reg(env, insn->dst_reg) ||
4047 	    is_flow_key_reg(env, insn->dst_reg) ||
4048 	    is_sk_reg(env, insn->dst_reg)) {
4049 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4050 			insn->dst_reg,
4051 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4052 		return -EACCES;
4053 	}
4054 
4055 	if (insn->imm & BPF_FETCH) {
4056 		if (insn->imm == BPF_CMPXCHG)
4057 			load_reg = BPF_REG_0;
4058 		else
4059 			load_reg = insn->src_reg;
4060 
4061 		/* check and record load of old value */
4062 		err = check_reg_arg(env, load_reg, DST_OP);
4063 		if (err)
4064 			return err;
4065 	} else {
4066 		/* This instruction accesses a memory location but doesn't
4067 		 * actually load it into a register.
4068 		 */
4069 		load_reg = -1;
4070 	}
4071 
4072 	/* check whether we can read the memory */
4073 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4074 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4075 	if (err)
4076 		return err;
4077 
4078 	/* check whether we can write into the same memory */
4079 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4080 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4081 	if (err)
4082 		return err;
4083 
4084 	return 0;
4085 }
4086 
4087 /* When register 'regno' is used to read the stack (either directly or through
4088  * a helper function) make sure that it's within stack boundary and, depending
4089  * on the access type, that all elements of the stack are initialized.
4090  *
4091  * 'off' includes 'regno->off', but not its dynamic part (if any).
4092  *
4093  * All registers that have been spilled on the stack in the slots within the
4094  * read offsets are marked as read.
4095  */
4096 static int check_stack_range_initialized(
4097 		struct bpf_verifier_env *env, int regno, int off,
4098 		int access_size, bool zero_size_allowed,
4099 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4100 {
4101 	struct bpf_reg_state *reg = reg_state(env, regno);
4102 	struct bpf_func_state *state = func(env, reg);
4103 	int err, min_off, max_off, i, j, slot, spi;
4104 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4105 	enum bpf_access_type bounds_check_type;
4106 	/* Some accesses can write anything into the stack, others are
4107 	 * read-only.
4108 	 */
4109 	bool clobber = false;
4110 
4111 	if (access_size == 0 && !zero_size_allowed) {
4112 		verbose(env, "invalid zero-sized read\n");
4113 		return -EACCES;
4114 	}
4115 
4116 	if (type == ACCESS_HELPER) {
4117 		/* The bounds checks for writes are more permissive than for
4118 		 * reads. However, if raw_mode is not set, we'll do extra
4119 		 * checks below.
4120 		 */
4121 		bounds_check_type = BPF_WRITE;
4122 		clobber = true;
4123 	} else {
4124 		bounds_check_type = BPF_READ;
4125 	}
4126 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4127 					       type, bounds_check_type);
4128 	if (err)
4129 		return err;
4130 
4131 
4132 	if (tnum_is_const(reg->var_off)) {
4133 		min_off = max_off = reg->var_off.value + off;
4134 	} else {
4135 		/* Variable offset is prohibited for unprivileged mode for
4136 		 * simplicity since it requires corresponding support in
4137 		 * Spectre masking for stack ALU.
4138 		 * See also retrieve_ptr_limit().
4139 		 */
4140 		if (!env->bypass_spec_v1) {
4141 			char tn_buf[48];
4142 
4143 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4144 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4145 				regno, err_extra, tn_buf);
4146 			return -EACCES;
4147 		}
4148 		/* Only initialized buffer on stack is allowed to be accessed
4149 		 * with variable offset. With uninitialized buffer it's hard to
4150 		 * guarantee that whole memory is marked as initialized on
4151 		 * helper return since specific bounds are unknown what may
4152 		 * cause uninitialized stack leaking.
4153 		 */
4154 		if (meta && meta->raw_mode)
4155 			meta = NULL;
4156 
4157 		min_off = reg->smin_value + off;
4158 		max_off = reg->smax_value + off;
4159 	}
4160 
4161 	if (meta && meta->raw_mode) {
4162 		meta->access_size = access_size;
4163 		meta->regno = regno;
4164 		return 0;
4165 	}
4166 
4167 	for (i = min_off; i < max_off + access_size; i++) {
4168 		u8 *stype;
4169 
4170 		slot = -i - 1;
4171 		spi = slot / BPF_REG_SIZE;
4172 		if (state->allocated_stack <= slot)
4173 			goto err;
4174 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4175 		if (*stype == STACK_MISC)
4176 			goto mark;
4177 		if (*stype == STACK_ZERO) {
4178 			if (clobber) {
4179 				/* helper can write anything into the stack */
4180 				*stype = STACK_MISC;
4181 			}
4182 			goto mark;
4183 		}
4184 
4185 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4186 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4187 			goto mark;
4188 
4189 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4190 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4191 		     env->allow_ptr_leaks)) {
4192 			if (clobber) {
4193 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4194 				for (j = 0; j < BPF_REG_SIZE; j++)
4195 					state->stack[spi].slot_type[j] = STACK_MISC;
4196 			}
4197 			goto mark;
4198 		}
4199 
4200 err:
4201 		if (tnum_is_const(reg->var_off)) {
4202 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4203 				err_extra, regno, min_off, i - min_off, access_size);
4204 		} else {
4205 			char tn_buf[48];
4206 
4207 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4208 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4209 				err_extra, regno, tn_buf, i - min_off, access_size);
4210 		}
4211 		return -EACCES;
4212 mark:
4213 		/* reading any byte out of 8-byte 'spill_slot' will cause
4214 		 * the whole slot to be marked as 'read'
4215 		 */
4216 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4217 			      state->stack[spi].spilled_ptr.parent,
4218 			      REG_LIVE_READ64);
4219 	}
4220 	return update_stack_depth(env, state, min_off);
4221 }
4222 
4223 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4224 				   int access_size, bool zero_size_allowed,
4225 				   struct bpf_call_arg_meta *meta)
4226 {
4227 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4228 
4229 	switch (reg->type) {
4230 	case PTR_TO_PACKET:
4231 	case PTR_TO_PACKET_META:
4232 		return check_packet_access(env, regno, reg->off, access_size,
4233 					   zero_size_allowed);
4234 	case PTR_TO_MAP_VALUE:
4235 		if (check_map_access_type(env, regno, reg->off, access_size,
4236 					  meta && meta->raw_mode ? BPF_WRITE :
4237 					  BPF_READ))
4238 			return -EACCES;
4239 		return check_map_access(env, regno, reg->off, access_size,
4240 					zero_size_allowed);
4241 	case PTR_TO_MEM:
4242 		return check_mem_region_access(env, regno, reg->off,
4243 					       access_size, reg->mem_size,
4244 					       zero_size_allowed);
4245 	case PTR_TO_RDONLY_BUF:
4246 		if (meta && meta->raw_mode)
4247 			return -EACCES;
4248 		return check_buffer_access(env, reg, regno, reg->off,
4249 					   access_size, zero_size_allowed,
4250 					   "rdonly",
4251 					   &env->prog->aux->max_rdonly_access);
4252 	case PTR_TO_RDWR_BUF:
4253 		return check_buffer_access(env, reg, regno, reg->off,
4254 					   access_size, zero_size_allowed,
4255 					   "rdwr",
4256 					   &env->prog->aux->max_rdwr_access);
4257 	case PTR_TO_STACK:
4258 		return check_stack_range_initialized(
4259 				env,
4260 				regno, reg->off, access_size,
4261 				zero_size_allowed, ACCESS_HELPER, meta);
4262 	default: /* scalar_value or invalid ptr */
4263 		/* Allow zero-byte read from NULL, regardless of pointer type */
4264 		if (zero_size_allowed && access_size == 0 &&
4265 		    register_is_null(reg))
4266 			return 0;
4267 
4268 		verbose(env, "R%d type=%s expected=%s\n", regno,
4269 			reg_type_str[reg->type],
4270 			reg_type_str[PTR_TO_STACK]);
4271 		return -EACCES;
4272 	}
4273 }
4274 
4275 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4276 		   u32 regno, u32 mem_size)
4277 {
4278 	if (register_is_null(reg))
4279 		return 0;
4280 
4281 	if (reg_type_may_be_null(reg->type)) {
4282 		/* Assuming that the register contains a value check if the memory
4283 		 * access is safe. Temporarily save and restore the register's state as
4284 		 * the conversion shouldn't be visible to a caller.
4285 		 */
4286 		const struct bpf_reg_state saved_reg = *reg;
4287 		int rv;
4288 
4289 		mark_ptr_not_null_reg(reg);
4290 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4291 		*reg = saved_reg;
4292 		return rv;
4293 	}
4294 
4295 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4296 }
4297 
4298 /* Implementation details:
4299  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4300  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4301  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4302  * value_or_null->value transition, since the verifier only cares about
4303  * the range of access to valid map value pointer and doesn't care about actual
4304  * address of the map element.
4305  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4306  * reg->id > 0 after value_or_null->value transition. By doing so
4307  * two bpf_map_lookups will be considered two different pointers that
4308  * point to different bpf_spin_locks.
4309  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4310  * dead-locks.
4311  * Since only one bpf_spin_lock is allowed the checks are simpler than
4312  * reg_is_refcounted() logic. The verifier needs to remember only
4313  * one spin_lock instead of array of acquired_refs.
4314  * cur_state->active_spin_lock remembers which map value element got locked
4315  * and clears it after bpf_spin_unlock.
4316  */
4317 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4318 			     bool is_lock)
4319 {
4320 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4321 	struct bpf_verifier_state *cur = env->cur_state;
4322 	bool is_const = tnum_is_const(reg->var_off);
4323 	struct bpf_map *map = reg->map_ptr;
4324 	u64 val = reg->var_off.value;
4325 
4326 	if (!is_const) {
4327 		verbose(env,
4328 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4329 			regno);
4330 		return -EINVAL;
4331 	}
4332 	if (!map->btf) {
4333 		verbose(env,
4334 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4335 			map->name);
4336 		return -EINVAL;
4337 	}
4338 	if (!map_value_has_spin_lock(map)) {
4339 		if (map->spin_lock_off == -E2BIG)
4340 			verbose(env,
4341 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4342 				map->name);
4343 		else if (map->spin_lock_off == -ENOENT)
4344 			verbose(env,
4345 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4346 				map->name);
4347 		else
4348 			verbose(env,
4349 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4350 				map->name);
4351 		return -EINVAL;
4352 	}
4353 	if (map->spin_lock_off != val + reg->off) {
4354 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4355 			val + reg->off);
4356 		return -EINVAL;
4357 	}
4358 	if (is_lock) {
4359 		if (cur->active_spin_lock) {
4360 			verbose(env,
4361 				"Locking two bpf_spin_locks are not allowed\n");
4362 			return -EINVAL;
4363 		}
4364 		cur->active_spin_lock = reg->id;
4365 	} else {
4366 		if (!cur->active_spin_lock) {
4367 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4368 			return -EINVAL;
4369 		}
4370 		if (cur->active_spin_lock != reg->id) {
4371 			verbose(env, "bpf_spin_unlock of different lock\n");
4372 			return -EINVAL;
4373 		}
4374 		cur->active_spin_lock = 0;
4375 	}
4376 	return 0;
4377 }
4378 
4379 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4380 {
4381 	return type == ARG_PTR_TO_MEM ||
4382 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4383 	       type == ARG_PTR_TO_UNINIT_MEM;
4384 }
4385 
4386 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4387 {
4388 	return type == ARG_CONST_SIZE ||
4389 	       type == ARG_CONST_SIZE_OR_ZERO;
4390 }
4391 
4392 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4393 {
4394 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4395 }
4396 
4397 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4398 {
4399 	return type == ARG_PTR_TO_INT ||
4400 	       type == ARG_PTR_TO_LONG;
4401 }
4402 
4403 static int int_ptr_type_to_size(enum bpf_arg_type type)
4404 {
4405 	if (type == ARG_PTR_TO_INT)
4406 		return sizeof(u32);
4407 	else if (type == ARG_PTR_TO_LONG)
4408 		return sizeof(u64);
4409 
4410 	return -EINVAL;
4411 }
4412 
4413 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4414 				 const struct bpf_call_arg_meta *meta,
4415 				 enum bpf_arg_type *arg_type)
4416 {
4417 	if (!meta->map_ptr) {
4418 		/* kernel subsystem misconfigured verifier */
4419 		verbose(env, "invalid map_ptr to access map->type\n");
4420 		return -EACCES;
4421 	}
4422 
4423 	switch (meta->map_ptr->map_type) {
4424 	case BPF_MAP_TYPE_SOCKMAP:
4425 	case BPF_MAP_TYPE_SOCKHASH:
4426 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4427 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4428 		} else {
4429 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4430 			return -EINVAL;
4431 		}
4432 		break;
4433 
4434 	default:
4435 		break;
4436 	}
4437 	return 0;
4438 }
4439 
4440 struct bpf_reg_types {
4441 	const enum bpf_reg_type types[10];
4442 	u32 *btf_id;
4443 };
4444 
4445 static const struct bpf_reg_types map_key_value_types = {
4446 	.types = {
4447 		PTR_TO_STACK,
4448 		PTR_TO_PACKET,
4449 		PTR_TO_PACKET_META,
4450 		PTR_TO_MAP_VALUE,
4451 	},
4452 };
4453 
4454 static const struct bpf_reg_types sock_types = {
4455 	.types = {
4456 		PTR_TO_SOCK_COMMON,
4457 		PTR_TO_SOCKET,
4458 		PTR_TO_TCP_SOCK,
4459 		PTR_TO_XDP_SOCK,
4460 	},
4461 };
4462 
4463 #ifdef CONFIG_NET
4464 static const struct bpf_reg_types btf_id_sock_common_types = {
4465 	.types = {
4466 		PTR_TO_SOCK_COMMON,
4467 		PTR_TO_SOCKET,
4468 		PTR_TO_TCP_SOCK,
4469 		PTR_TO_XDP_SOCK,
4470 		PTR_TO_BTF_ID,
4471 	},
4472 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4473 };
4474 #endif
4475 
4476 static const struct bpf_reg_types mem_types = {
4477 	.types = {
4478 		PTR_TO_STACK,
4479 		PTR_TO_PACKET,
4480 		PTR_TO_PACKET_META,
4481 		PTR_TO_MAP_VALUE,
4482 		PTR_TO_MEM,
4483 		PTR_TO_RDONLY_BUF,
4484 		PTR_TO_RDWR_BUF,
4485 	},
4486 };
4487 
4488 static const struct bpf_reg_types int_ptr_types = {
4489 	.types = {
4490 		PTR_TO_STACK,
4491 		PTR_TO_PACKET,
4492 		PTR_TO_PACKET_META,
4493 		PTR_TO_MAP_VALUE,
4494 	},
4495 };
4496 
4497 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4498 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4499 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4500 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4501 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4502 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4503 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4504 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4505 
4506 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4507 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4508 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4509 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4510 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
4511 	[ARG_CONST_SIZE]		= &scalar_types,
4512 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4513 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4514 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4515 	[ARG_PTR_TO_CTX]		= &context_types,
4516 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
4517 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4518 #ifdef CONFIG_NET
4519 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4520 #endif
4521 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4522 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
4523 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4524 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4525 	[ARG_PTR_TO_MEM]		= &mem_types,
4526 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
4527 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4528 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4529 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
4530 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4531 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4532 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4533 };
4534 
4535 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4536 			  enum bpf_arg_type arg_type,
4537 			  const u32 *arg_btf_id)
4538 {
4539 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4540 	enum bpf_reg_type expected, type = reg->type;
4541 	const struct bpf_reg_types *compatible;
4542 	int i, j;
4543 
4544 	compatible = compatible_reg_types[arg_type];
4545 	if (!compatible) {
4546 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4547 		return -EFAULT;
4548 	}
4549 
4550 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4551 		expected = compatible->types[i];
4552 		if (expected == NOT_INIT)
4553 			break;
4554 
4555 		if (type == expected)
4556 			goto found;
4557 	}
4558 
4559 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4560 	for (j = 0; j + 1 < i; j++)
4561 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4562 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4563 	return -EACCES;
4564 
4565 found:
4566 	if (type == PTR_TO_BTF_ID) {
4567 		if (!arg_btf_id) {
4568 			if (!compatible->btf_id) {
4569 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4570 				return -EFAULT;
4571 			}
4572 			arg_btf_id = compatible->btf_id;
4573 		}
4574 
4575 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4576 					  btf_vmlinux, *arg_btf_id)) {
4577 			verbose(env, "R%d is of type %s but %s is expected\n",
4578 				regno, kernel_type_name(reg->btf, reg->btf_id),
4579 				kernel_type_name(btf_vmlinux, *arg_btf_id));
4580 			return -EACCES;
4581 		}
4582 
4583 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4584 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4585 				regno);
4586 			return -EACCES;
4587 		}
4588 	}
4589 
4590 	return 0;
4591 }
4592 
4593 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4594 			  struct bpf_call_arg_meta *meta,
4595 			  const struct bpf_func_proto *fn)
4596 {
4597 	u32 regno = BPF_REG_1 + arg;
4598 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4599 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4600 	enum bpf_reg_type type = reg->type;
4601 	int err = 0;
4602 
4603 	if (arg_type == ARG_DONTCARE)
4604 		return 0;
4605 
4606 	err = check_reg_arg(env, regno, SRC_OP);
4607 	if (err)
4608 		return err;
4609 
4610 	if (arg_type == ARG_ANYTHING) {
4611 		if (is_pointer_value(env, regno)) {
4612 			verbose(env, "R%d leaks addr into helper function\n",
4613 				regno);
4614 			return -EACCES;
4615 		}
4616 		return 0;
4617 	}
4618 
4619 	if (type_is_pkt_pointer(type) &&
4620 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4621 		verbose(env, "helper access to the packet is not allowed\n");
4622 		return -EACCES;
4623 	}
4624 
4625 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4626 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4627 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4628 		err = resolve_map_arg_type(env, meta, &arg_type);
4629 		if (err)
4630 			return err;
4631 	}
4632 
4633 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4634 		/* A NULL register has a SCALAR_VALUE type, so skip
4635 		 * type checking.
4636 		 */
4637 		goto skip_type_check;
4638 
4639 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4640 	if (err)
4641 		return err;
4642 
4643 	if (type == PTR_TO_CTX) {
4644 		err = check_ctx_reg(env, reg, regno);
4645 		if (err < 0)
4646 			return err;
4647 	}
4648 
4649 skip_type_check:
4650 	if (reg->ref_obj_id) {
4651 		if (meta->ref_obj_id) {
4652 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4653 				regno, reg->ref_obj_id,
4654 				meta->ref_obj_id);
4655 			return -EFAULT;
4656 		}
4657 		meta->ref_obj_id = reg->ref_obj_id;
4658 	}
4659 
4660 	if (arg_type == ARG_CONST_MAP_PTR) {
4661 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4662 		meta->map_ptr = reg->map_ptr;
4663 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4664 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4665 		 * check that [key, key + map->key_size) are within
4666 		 * stack limits and initialized
4667 		 */
4668 		if (!meta->map_ptr) {
4669 			/* in function declaration map_ptr must come before
4670 			 * map_key, so that it's verified and known before
4671 			 * we have to check map_key here. Otherwise it means
4672 			 * that kernel subsystem misconfigured verifier
4673 			 */
4674 			verbose(env, "invalid map_ptr to access map->key\n");
4675 			return -EACCES;
4676 		}
4677 		err = check_helper_mem_access(env, regno,
4678 					      meta->map_ptr->key_size, false,
4679 					      NULL);
4680 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4681 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4682 		    !register_is_null(reg)) ||
4683 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4684 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4685 		 * check [value, value + map->value_size) validity
4686 		 */
4687 		if (!meta->map_ptr) {
4688 			/* kernel subsystem misconfigured verifier */
4689 			verbose(env, "invalid map_ptr to access map->value\n");
4690 			return -EACCES;
4691 		}
4692 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4693 		err = check_helper_mem_access(env, regno,
4694 					      meta->map_ptr->value_size, false,
4695 					      meta);
4696 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4697 		if (!reg->btf_id) {
4698 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4699 			return -EACCES;
4700 		}
4701 		meta->ret_btf = reg->btf;
4702 		meta->ret_btf_id = reg->btf_id;
4703 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4704 		if (meta->func_id == BPF_FUNC_spin_lock) {
4705 			if (process_spin_lock(env, regno, true))
4706 				return -EACCES;
4707 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4708 			if (process_spin_lock(env, regno, false))
4709 				return -EACCES;
4710 		} else {
4711 			verbose(env, "verifier internal error\n");
4712 			return -EFAULT;
4713 		}
4714 	} else if (arg_type_is_mem_ptr(arg_type)) {
4715 		/* The access to this pointer is only checked when we hit the
4716 		 * next is_mem_size argument below.
4717 		 */
4718 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4719 	} else if (arg_type_is_mem_size(arg_type)) {
4720 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4721 
4722 		/* This is used to refine r0 return value bounds for helpers
4723 		 * that enforce this value as an upper bound on return values.
4724 		 * See do_refine_retval_range() for helpers that can refine
4725 		 * the return value. C type of helper is u32 so we pull register
4726 		 * bound from umax_value however, if negative verifier errors
4727 		 * out. Only upper bounds can be learned because retval is an
4728 		 * int type and negative retvals are allowed.
4729 		 */
4730 		meta->msize_max_value = reg->umax_value;
4731 
4732 		/* The register is SCALAR_VALUE; the access check
4733 		 * happens using its boundaries.
4734 		 */
4735 		if (!tnum_is_const(reg->var_off))
4736 			/* For unprivileged variable accesses, disable raw
4737 			 * mode so that the program is required to
4738 			 * initialize all the memory that the helper could
4739 			 * just partially fill up.
4740 			 */
4741 			meta = NULL;
4742 
4743 		if (reg->smin_value < 0) {
4744 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4745 				regno);
4746 			return -EACCES;
4747 		}
4748 
4749 		if (reg->umin_value == 0) {
4750 			err = check_helper_mem_access(env, regno - 1, 0,
4751 						      zero_size_allowed,
4752 						      meta);
4753 			if (err)
4754 				return err;
4755 		}
4756 
4757 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4758 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4759 				regno);
4760 			return -EACCES;
4761 		}
4762 		err = check_helper_mem_access(env, regno - 1,
4763 					      reg->umax_value,
4764 					      zero_size_allowed, meta);
4765 		if (!err)
4766 			err = mark_chain_precision(env, regno);
4767 	} else if (arg_type_is_alloc_size(arg_type)) {
4768 		if (!tnum_is_const(reg->var_off)) {
4769 			verbose(env, "R%d is not a known constant'\n",
4770 				regno);
4771 			return -EACCES;
4772 		}
4773 		meta->mem_size = reg->var_off.value;
4774 	} else if (arg_type_is_int_ptr(arg_type)) {
4775 		int size = int_ptr_type_to_size(arg_type);
4776 
4777 		err = check_helper_mem_access(env, regno, size, false, meta);
4778 		if (err)
4779 			return err;
4780 		err = check_ptr_alignment(env, reg, 0, size, true);
4781 	}
4782 
4783 	return err;
4784 }
4785 
4786 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4787 {
4788 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4789 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4790 
4791 	if (func_id != BPF_FUNC_map_update_elem)
4792 		return false;
4793 
4794 	/* It's not possible to get access to a locked struct sock in these
4795 	 * contexts, so updating is safe.
4796 	 */
4797 	switch (type) {
4798 	case BPF_PROG_TYPE_TRACING:
4799 		if (eatype == BPF_TRACE_ITER)
4800 			return true;
4801 		break;
4802 	case BPF_PROG_TYPE_SOCKET_FILTER:
4803 	case BPF_PROG_TYPE_SCHED_CLS:
4804 	case BPF_PROG_TYPE_SCHED_ACT:
4805 	case BPF_PROG_TYPE_XDP:
4806 	case BPF_PROG_TYPE_SK_REUSEPORT:
4807 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4808 	case BPF_PROG_TYPE_SK_LOOKUP:
4809 		return true;
4810 	default:
4811 		break;
4812 	}
4813 
4814 	verbose(env, "cannot update sockmap in this context\n");
4815 	return false;
4816 }
4817 
4818 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4819 {
4820 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4821 }
4822 
4823 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4824 					struct bpf_map *map, int func_id)
4825 {
4826 	if (!map)
4827 		return 0;
4828 
4829 	/* We need a two way check, first is from map perspective ... */
4830 	switch (map->map_type) {
4831 	case BPF_MAP_TYPE_PROG_ARRAY:
4832 		if (func_id != BPF_FUNC_tail_call)
4833 			goto error;
4834 		break;
4835 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4836 		if (func_id != BPF_FUNC_perf_event_read &&
4837 		    func_id != BPF_FUNC_perf_event_output &&
4838 		    func_id != BPF_FUNC_skb_output &&
4839 		    func_id != BPF_FUNC_perf_event_read_value &&
4840 		    func_id != BPF_FUNC_xdp_output)
4841 			goto error;
4842 		break;
4843 	case BPF_MAP_TYPE_RINGBUF:
4844 		if (func_id != BPF_FUNC_ringbuf_output &&
4845 		    func_id != BPF_FUNC_ringbuf_reserve &&
4846 		    func_id != BPF_FUNC_ringbuf_submit &&
4847 		    func_id != BPF_FUNC_ringbuf_discard &&
4848 		    func_id != BPF_FUNC_ringbuf_query)
4849 			goto error;
4850 		break;
4851 	case BPF_MAP_TYPE_STACK_TRACE:
4852 		if (func_id != BPF_FUNC_get_stackid)
4853 			goto error;
4854 		break;
4855 	case BPF_MAP_TYPE_CGROUP_ARRAY:
4856 		if (func_id != BPF_FUNC_skb_under_cgroup &&
4857 		    func_id != BPF_FUNC_current_task_under_cgroup)
4858 			goto error;
4859 		break;
4860 	case BPF_MAP_TYPE_CGROUP_STORAGE:
4861 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4862 		if (func_id != BPF_FUNC_get_local_storage)
4863 			goto error;
4864 		break;
4865 	case BPF_MAP_TYPE_DEVMAP:
4866 	case BPF_MAP_TYPE_DEVMAP_HASH:
4867 		if (func_id != BPF_FUNC_redirect_map &&
4868 		    func_id != BPF_FUNC_map_lookup_elem)
4869 			goto error;
4870 		break;
4871 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
4872 	 * appear.
4873 	 */
4874 	case BPF_MAP_TYPE_CPUMAP:
4875 		if (func_id != BPF_FUNC_redirect_map)
4876 			goto error;
4877 		break;
4878 	case BPF_MAP_TYPE_XSKMAP:
4879 		if (func_id != BPF_FUNC_redirect_map &&
4880 		    func_id != BPF_FUNC_map_lookup_elem)
4881 			goto error;
4882 		break;
4883 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4884 	case BPF_MAP_TYPE_HASH_OF_MAPS:
4885 		if (func_id != BPF_FUNC_map_lookup_elem)
4886 			goto error;
4887 		break;
4888 	case BPF_MAP_TYPE_SOCKMAP:
4889 		if (func_id != BPF_FUNC_sk_redirect_map &&
4890 		    func_id != BPF_FUNC_sock_map_update &&
4891 		    func_id != BPF_FUNC_map_delete_elem &&
4892 		    func_id != BPF_FUNC_msg_redirect_map &&
4893 		    func_id != BPF_FUNC_sk_select_reuseport &&
4894 		    func_id != BPF_FUNC_map_lookup_elem &&
4895 		    !may_update_sockmap(env, func_id))
4896 			goto error;
4897 		break;
4898 	case BPF_MAP_TYPE_SOCKHASH:
4899 		if (func_id != BPF_FUNC_sk_redirect_hash &&
4900 		    func_id != BPF_FUNC_sock_hash_update &&
4901 		    func_id != BPF_FUNC_map_delete_elem &&
4902 		    func_id != BPF_FUNC_msg_redirect_hash &&
4903 		    func_id != BPF_FUNC_sk_select_reuseport &&
4904 		    func_id != BPF_FUNC_map_lookup_elem &&
4905 		    !may_update_sockmap(env, func_id))
4906 			goto error;
4907 		break;
4908 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4909 		if (func_id != BPF_FUNC_sk_select_reuseport)
4910 			goto error;
4911 		break;
4912 	case BPF_MAP_TYPE_QUEUE:
4913 	case BPF_MAP_TYPE_STACK:
4914 		if (func_id != BPF_FUNC_map_peek_elem &&
4915 		    func_id != BPF_FUNC_map_pop_elem &&
4916 		    func_id != BPF_FUNC_map_push_elem)
4917 			goto error;
4918 		break;
4919 	case BPF_MAP_TYPE_SK_STORAGE:
4920 		if (func_id != BPF_FUNC_sk_storage_get &&
4921 		    func_id != BPF_FUNC_sk_storage_delete)
4922 			goto error;
4923 		break;
4924 	case BPF_MAP_TYPE_INODE_STORAGE:
4925 		if (func_id != BPF_FUNC_inode_storage_get &&
4926 		    func_id != BPF_FUNC_inode_storage_delete)
4927 			goto error;
4928 		break;
4929 	case BPF_MAP_TYPE_TASK_STORAGE:
4930 		if (func_id != BPF_FUNC_task_storage_get &&
4931 		    func_id != BPF_FUNC_task_storage_delete)
4932 			goto error;
4933 		break;
4934 	default:
4935 		break;
4936 	}
4937 
4938 	/* ... and second from the function itself. */
4939 	switch (func_id) {
4940 	case BPF_FUNC_tail_call:
4941 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4942 			goto error;
4943 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4944 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4945 			return -EINVAL;
4946 		}
4947 		break;
4948 	case BPF_FUNC_perf_event_read:
4949 	case BPF_FUNC_perf_event_output:
4950 	case BPF_FUNC_perf_event_read_value:
4951 	case BPF_FUNC_skb_output:
4952 	case BPF_FUNC_xdp_output:
4953 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4954 			goto error;
4955 		break;
4956 	case BPF_FUNC_get_stackid:
4957 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4958 			goto error;
4959 		break;
4960 	case BPF_FUNC_current_task_under_cgroup:
4961 	case BPF_FUNC_skb_under_cgroup:
4962 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4963 			goto error;
4964 		break;
4965 	case BPF_FUNC_redirect_map:
4966 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4967 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4968 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
4969 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
4970 			goto error;
4971 		break;
4972 	case BPF_FUNC_sk_redirect_map:
4973 	case BPF_FUNC_msg_redirect_map:
4974 	case BPF_FUNC_sock_map_update:
4975 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4976 			goto error;
4977 		break;
4978 	case BPF_FUNC_sk_redirect_hash:
4979 	case BPF_FUNC_msg_redirect_hash:
4980 	case BPF_FUNC_sock_hash_update:
4981 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4982 			goto error;
4983 		break;
4984 	case BPF_FUNC_get_local_storage:
4985 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4986 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4987 			goto error;
4988 		break;
4989 	case BPF_FUNC_sk_select_reuseport:
4990 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4991 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4992 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
4993 			goto error;
4994 		break;
4995 	case BPF_FUNC_map_peek_elem:
4996 	case BPF_FUNC_map_pop_elem:
4997 	case BPF_FUNC_map_push_elem:
4998 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4999 		    map->map_type != BPF_MAP_TYPE_STACK)
5000 			goto error;
5001 		break;
5002 	case BPF_FUNC_sk_storage_get:
5003 	case BPF_FUNC_sk_storage_delete:
5004 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5005 			goto error;
5006 		break;
5007 	case BPF_FUNC_inode_storage_get:
5008 	case BPF_FUNC_inode_storage_delete:
5009 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5010 			goto error;
5011 		break;
5012 	case BPF_FUNC_task_storage_get:
5013 	case BPF_FUNC_task_storage_delete:
5014 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5015 			goto error;
5016 		break;
5017 	default:
5018 		break;
5019 	}
5020 
5021 	return 0;
5022 error:
5023 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5024 		map->map_type, func_id_name(func_id), func_id);
5025 	return -EINVAL;
5026 }
5027 
5028 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5029 {
5030 	int count = 0;
5031 
5032 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5033 		count++;
5034 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5035 		count++;
5036 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5037 		count++;
5038 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5039 		count++;
5040 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5041 		count++;
5042 
5043 	/* We only support one arg being in raw mode at the moment,
5044 	 * which is sufficient for the helper functions we have
5045 	 * right now.
5046 	 */
5047 	return count <= 1;
5048 }
5049 
5050 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5051 				    enum bpf_arg_type arg_next)
5052 {
5053 	return (arg_type_is_mem_ptr(arg_curr) &&
5054 	        !arg_type_is_mem_size(arg_next)) ||
5055 	       (!arg_type_is_mem_ptr(arg_curr) &&
5056 		arg_type_is_mem_size(arg_next));
5057 }
5058 
5059 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5060 {
5061 	/* bpf_xxx(..., buf, len) call will access 'len'
5062 	 * bytes from memory 'buf'. Both arg types need
5063 	 * to be paired, so make sure there's no buggy
5064 	 * helper function specification.
5065 	 */
5066 	if (arg_type_is_mem_size(fn->arg1_type) ||
5067 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5068 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5069 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5070 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5071 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5072 		return false;
5073 
5074 	return true;
5075 }
5076 
5077 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5078 {
5079 	int count = 0;
5080 
5081 	if (arg_type_may_be_refcounted(fn->arg1_type))
5082 		count++;
5083 	if (arg_type_may_be_refcounted(fn->arg2_type))
5084 		count++;
5085 	if (arg_type_may_be_refcounted(fn->arg3_type))
5086 		count++;
5087 	if (arg_type_may_be_refcounted(fn->arg4_type))
5088 		count++;
5089 	if (arg_type_may_be_refcounted(fn->arg5_type))
5090 		count++;
5091 
5092 	/* A reference acquiring function cannot acquire
5093 	 * another refcounted ptr.
5094 	 */
5095 	if (may_be_acquire_function(func_id) && count)
5096 		return false;
5097 
5098 	/* We only support one arg being unreferenced at the moment,
5099 	 * which is sufficient for the helper functions we have right now.
5100 	 */
5101 	return count <= 1;
5102 }
5103 
5104 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5105 {
5106 	int i;
5107 
5108 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5109 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5110 			return false;
5111 
5112 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5113 			return false;
5114 	}
5115 
5116 	return true;
5117 }
5118 
5119 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5120 {
5121 	return check_raw_mode_ok(fn) &&
5122 	       check_arg_pair_ok(fn) &&
5123 	       check_btf_id_ok(fn) &&
5124 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5125 }
5126 
5127 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5128  * are now invalid, so turn them into unknown SCALAR_VALUE.
5129  */
5130 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5131 				     struct bpf_func_state *state)
5132 {
5133 	struct bpf_reg_state *regs = state->regs, *reg;
5134 	int i;
5135 
5136 	for (i = 0; i < MAX_BPF_REG; i++)
5137 		if (reg_is_pkt_pointer_any(&regs[i]))
5138 			mark_reg_unknown(env, regs, i);
5139 
5140 	bpf_for_each_spilled_reg(i, state, reg) {
5141 		if (!reg)
5142 			continue;
5143 		if (reg_is_pkt_pointer_any(reg))
5144 			__mark_reg_unknown(env, reg);
5145 	}
5146 }
5147 
5148 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5149 {
5150 	struct bpf_verifier_state *vstate = env->cur_state;
5151 	int i;
5152 
5153 	for (i = 0; i <= vstate->curframe; i++)
5154 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5155 }
5156 
5157 enum {
5158 	AT_PKT_END = -1,
5159 	BEYOND_PKT_END = -2,
5160 };
5161 
5162 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5163 {
5164 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5165 	struct bpf_reg_state *reg = &state->regs[regn];
5166 
5167 	if (reg->type != PTR_TO_PACKET)
5168 		/* PTR_TO_PACKET_META is not supported yet */
5169 		return;
5170 
5171 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5172 	 * How far beyond pkt_end it goes is unknown.
5173 	 * if (!range_open) it's the case of pkt >= pkt_end
5174 	 * if (range_open) it's the case of pkt > pkt_end
5175 	 * hence this pointer is at least 1 byte bigger than pkt_end
5176 	 */
5177 	if (range_open)
5178 		reg->range = BEYOND_PKT_END;
5179 	else
5180 		reg->range = AT_PKT_END;
5181 }
5182 
5183 static void release_reg_references(struct bpf_verifier_env *env,
5184 				   struct bpf_func_state *state,
5185 				   int ref_obj_id)
5186 {
5187 	struct bpf_reg_state *regs = state->regs, *reg;
5188 	int i;
5189 
5190 	for (i = 0; i < MAX_BPF_REG; i++)
5191 		if (regs[i].ref_obj_id == ref_obj_id)
5192 			mark_reg_unknown(env, regs, i);
5193 
5194 	bpf_for_each_spilled_reg(i, state, reg) {
5195 		if (!reg)
5196 			continue;
5197 		if (reg->ref_obj_id == ref_obj_id)
5198 			__mark_reg_unknown(env, reg);
5199 	}
5200 }
5201 
5202 /* The pointer with the specified id has released its reference to kernel
5203  * resources. Identify all copies of the same pointer and clear the reference.
5204  */
5205 static int release_reference(struct bpf_verifier_env *env,
5206 			     int ref_obj_id)
5207 {
5208 	struct bpf_verifier_state *vstate = env->cur_state;
5209 	int err;
5210 	int i;
5211 
5212 	err = release_reference_state(cur_func(env), ref_obj_id);
5213 	if (err)
5214 		return err;
5215 
5216 	for (i = 0; i <= vstate->curframe; i++)
5217 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5218 
5219 	return 0;
5220 }
5221 
5222 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5223 				    struct bpf_reg_state *regs)
5224 {
5225 	int i;
5226 
5227 	/* after the call registers r0 - r5 were scratched */
5228 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5229 		mark_reg_not_init(env, regs, caller_saved[i]);
5230 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5231 	}
5232 }
5233 
5234 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5235 			   int *insn_idx)
5236 {
5237 	struct bpf_verifier_state *state = env->cur_state;
5238 	struct bpf_func_info_aux *func_info_aux;
5239 	struct bpf_func_state *caller, *callee;
5240 	int i, err, subprog, target_insn;
5241 	bool is_global = false;
5242 
5243 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5244 		verbose(env, "the call stack of %d frames is too deep\n",
5245 			state->curframe + 2);
5246 		return -E2BIG;
5247 	}
5248 
5249 	target_insn = *insn_idx + insn->imm;
5250 	subprog = find_subprog(env, target_insn + 1);
5251 	if (subprog < 0) {
5252 		verbose(env, "verifier bug. No program starts at insn %d\n",
5253 			target_insn + 1);
5254 		return -EFAULT;
5255 	}
5256 
5257 	caller = state->frame[state->curframe];
5258 	if (state->frame[state->curframe + 1]) {
5259 		verbose(env, "verifier bug. Frame %d already allocated\n",
5260 			state->curframe + 1);
5261 		return -EFAULT;
5262 	}
5263 
5264 	func_info_aux = env->prog->aux->func_info_aux;
5265 	if (func_info_aux)
5266 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5267 	err = btf_check_func_arg_match(env, subprog, caller->regs);
5268 	if (err == -EFAULT)
5269 		return err;
5270 	if (is_global) {
5271 		if (err) {
5272 			verbose(env, "Caller passes invalid args into func#%d\n",
5273 				subprog);
5274 			return err;
5275 		} else {
5276 			if (env->log.level & BPF_LOG_LEVEL)
5277 				verbose(env,
5278 					"Func#%d is global and valid. Skipping.\n",
5279 					subprog);
5280 			clear_caller_saved_regs(env, caller->regs);
5281 
5282 			/* All global functions return a 64-bit SCALAR_VALUE */
5283 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5284 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5285 
5286 			/* continue with next insn after call */
5287 			return 0;
5288 		}
5289 	}
5290 
5291 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5292 	if (!callee)
5293 		return -ENOMEM;
5294 	state->frame[state->curframe + 1] = callee;
5295 
5296 	/* callee cannot access r0, r6 - r9 for reading and has to write
5297 	 * into its own stack before reading from it.
5298 	 * callee can read/write into caller's stack
5299 	 */
5300 	init_func_state(env, callee,
5301 			/* remember the callsite, it will be used by bpf_exit */
5302 			*insn_idx /* callsite */,
5303 			state->curframe + 1 /* frameno within this callchain */,
5304 			subprog /* subprog number within this prog */);
5305 
5306 	/* Transfer references to the callee */
5307 	err = transfer_reference_state(callee, caller);
5308 	if (err)
5309 		return err;
5310 
5311 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5312 	 * pointers, which connects us up to the liveness chain
5313 	 */
5314 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5315 		callee->regs[i] = caller->regs[i];
5316 
5317 	clear_caller_saved_regs(env, caller->regs);
5318 
5319 	/* only increment it after check_reg_arg() finished */
5320 	state->curframe++;
5321 
5322 	/* and go analyze first insn of the callee */
5323 	*insn_idx = target_insn;
5324 
5325 	if (env->log.level & BPF_LOG_LEVEL) {
5326 		verbose(env, "caller:\n");
5327 		print_verifier_state(env, caller);
5328 		verbose(env, "callee:\n");
5329 		print_verifier_state(env, callee);
5330 	}
5331 	return 0;
5332 }
5333 
5334 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5335 {
5336 	struct bpf_verifier_state *state = env->cur_state;
5337 	struct bpf_func_state *caller, *callee;
5338 	struct bpf_reg_state *r0;
5339 	int err;
5340 
5341 	callee = state->frame[state->curframe];
5342 	r0 = &callee->regs[BPF_REG_0];
5343 	if (r0->type == PTR_TO_STACK) {
5344 		/* technically it's ok to return caller's stack pointer
5345 		 * (or caller's caller's pointer) back to the caller,
5346 		 * since these pointers are valid. Only current stack
5347 		 * pointer will be invalid as soon as function exits,
5348 		 * but let's be conservative
5349 		 */
5350 		verbose(env, "cannot return stack pointer to the caller\n");
5351 		return -EINVAL;
5352 	}
5353 
5354 	state->curframe--;
5355 	caller = state->frame[state->curframe];
5356 	/* return to the caller whatever r0 had in the callee */
5357 	caller->regs[BPF_REG_0] = *r0;
5358 
5359 	/* Transfer references to the caller */
5360 	err = transfer_reference_state(caller, callee);
5361 	if (err)
5362 		return err;
5363 
5364 	*insn_idx = callee->callsite + 1;
5365 	if (env->log.level & BPF_LOG_LEVEL) {
5366 		verbose(env, "returning from callee:\n");
5367 		print_verifier_state(env, callee);
5368 		verbose(env, "to caller at %d:\n", *insn_idx);
5369 		print_verifier_state(env, caller);
5370 	}
5371 	/* clear everything in the callee */
5372 	free_func_state(callee);
5373 	state->frame[state->curframe + 1] = NULL;
5374 	return 0;
5375 }
5376 
5377 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5378 				   int func_id,
5379 				   struct bpf_call_arg_meta *meta)
5380 {
5381 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5382 
5383 	if (ret_type != RET_INTEGER ||
5384 	    (func_id != BPF_FUNC_get_stack &&
5385 	     func_id != BPF_FUNC_probe_read_str &&
5386 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5387 	     func_id != BPF_FUNC_probe_read_user_str))
5388 		return;
5389 
5390 	ret_reg->smax_value = meta->msize_max_value;
5391 	ret_reg->s32_max_value = meta->msize_max_value;
5392 	ret_reg->smin_value = -MAX_ERRNO;
5393 	ret_reg->s32_min_value = -MAX_ERRNO;
5394 	__reg_deduce_bounds(ret_reg);
5395 	__reg_bound_offset(ret_reg);
5396 	__update_reg_bounds(ret_reg);
5397 }
5398 
5399 static int
5400 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5401 		int func_id, int insn_idx)
5402 {
5403 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5404 	struct bpf_map *map = meta->map_ptr;
5405 
5406 	if (func_id != BPF_FUNC_tail_call &&
5407 	    func_id != BPF_FUNC_map_lookup_elem &&
5408 	    func_id != BPF_FUNC_map_update_elem &&
5409 	    func_id != BPF_FUNC_map_delete_elem &&
5410 	    func_id != BPF_FUNC_map_push_elem &&
5411 	    func_id != BPF_FUNC_map_pop_elem &&
5412 	    func_id != BPF_FUNC_map_peek_elem)
5413 		return 0;
5414 
5415 	if (map == NULL) {
5416 		verbose(env, "kernel subsystem misconfigured verifier\n");
5417 		return -EINVAL;
5418 	}
5419 
5420 	/* In case of read-only, some additional restrictions
5421 	 * need to be applied in order to prevent altering the
5422 	 * state of the map from program side.
5423 	 */
5424 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5425 	    (func_id == BPF_FUNC_map_delete_elem ||
5426 	     func_id == BPF_FUNC_map_update_elem ||
5427 	     func_id == BPF_FUNC_map_push_elem ||
5428 	     func_id == BPF_FUNC_map_pop_elem)) {
5429 		verbose(env, "write into map forbidden\n");
5430 		return -EACCES;
5431 	}
5432 
5433 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5434 		bpf_map_ptr_store(aux, meta->map_ptr,
5435 				  !meta->map_ptr->bypass_spec_v1);
5436 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5437 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5438 				  !meta->map_ptr->bypass_spec_v1);
5439 	return 0;
5440 }
5441 
5442 static int
5443 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5444 		int func_id, int insn_idx)
5445 {
5446 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5447 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5448 	struct bpf_map *map = meta->map_ptr;
5449 	struct tnum range;
5450 	u64 val;
5451 	int err;
5452 
5453 	if (func_id != BPF_FUNC_tail_call)
5454 		return 0;
5455 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5456 		verbose(env, "kernel subsystem misconfigured verifier\n");
5457 		return -EINVAL;
5458 	}
5459 
5460 	range = tnum_range(0, map->max_entries - 1);
5461 	reg = &regs[BPF_REG_3];
5462 
5463 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5464 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5465 		return 0;
5466 	}
5467 
5468 	err = mark_chain_precision(env, BPF_REG_3);
5469 	if (err)
5470 		return err;
5471 
5472 	val = reg->var_off.value;
5473 	if (bpf_map_key_unseen(aux))
5474 		bpf_map_key_store(aux, val);
5475 	else if (!bpf_map_key_poisoned(aux) &&
5476 		  bpf_map_key_immediate(aux) != val)
5477 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5478 	return 0;
5479 }
5480 
5481 static int check_reference_leak(struct bpf_verifier_env *env)
5482 {
5483 	struct bpf_func_state *state = cur_func(env);
5484 	int i;
5485 
5486 	for (i = 0; i < state->acquired_refs; i++) {
5487 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5488 			state->refs[i].id, state->refs[i].insn_idx);
5489 	}
5490 	return state->acquired_refs ? -EINVAL : 0;
5491 }
5492 
5493 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5494 {
5495 	const struct bpf_func_proto *fn = NULL;
5496 	struct bpf_reg_state *regs;
5497 	struct bpf_call_arg_meta meta;
5498 	bool changes_data;
5499 	int i, err;
5500 
5501 	/* find function prototype */
5502 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5503 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5504 			func_id);
5505 		return -EINVAL;
5506 	}
5507 
5508 	if (env->ops->get_func_proto)
5509 		fn = env->ops->get_func_proto(func_id, env->prog);
5510 	if (!fn) {
5511 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5512 			func_id);
5513 		return -EINVAL;
5514 	}
5515 
5516 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5517 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5518 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5519 		return -EINVAL;
5520 	}
5521 
5522 	if (fn->allowed && !fn->allowed(env->prog)) {
5523 		verbose(env, "helper call is not allowed in probe\n");
5524 		return -EINVAL;
5525 	}
5526 
5527 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5528 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5529 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5530 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5531 			func_id_name(func_id), func_id);
5532 		return -EINVAL;
5533 	}
5534 
5535 	memset(&meta, 0, sizeof(meta));
5536 	meta.pkt_access = fn->pkt_access;
5537 
5538 	err = check_func_proto(fn, func_id);
5539 	if (err) {
5540 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5541 			func_id_name(func_id), func_id);
5542 		return err;
5543 	}
5544 
5545 	meta.func_id = func_id;
5546 	/* check args */
5547 	for (i = 0; i < 5; i++) {
5548 		err = check_func_arg(env, i, &meta, fn);
5549 		if (err)
5550 			return err;
5551 	}
5552 
5553 	err = record_func_map(env, &meta, func_id, insn_idx);
5554 	if (err)
5555 		return err;
5556 
5557 	err = record_func_key(env, &meta, func_id, insn_idx);
5558 	if (err)
5559 		return err;
5560 
5561 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5562 	 * is inferred from register state.
5563 	 */
5564 	for (i = 0; i < meta.access_size; i++) {
5565 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5566 				       BPF_WRITE, -1, false);
5567 		if (err)
5568 			return err;
5569 	}
5570 
5571 	if (func_id == BPF_FUNC_tail_call) {
5572 		err = check_reference_leak(env);
5573 		if (err) {
5574 			verbose(env, "tail_call would lead to reference leak\n");
5575 			return err;
5576 		}
5577 	} else if (is_release_function(func_id)) {
5578 		err = release_reference(env, meta.ref_obj_id);
5579 		if (err) {
5580 			verbose(env, "func %s#%d reference has not been acquired before\n",
5581 				func_id_name(func_id), func_id);
5582 			return err;
5583 		}
5584 	}
5585 
5586 	regs = cur_regs(env);
5587 
5588 	/* check that flags argument in get_local_storage(map, flags) is 0,
5589 	 * this is required because get_local_storage() can't return an error.
5590 	 */
5591 	if (func_id == BPF_FUNC_get_local_storage &&
5592 	    !register_is_null(&regs[BPF_REG_2])) {
5593 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5594 		return -EINVAL;
5595 	}
5596 
5597 	/* reset caller saved regs */
5598 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5599 		mark_reg_not_init(env, regs, caller_saved[i]);
5600 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5601 	}
5602 
5603 	/* helper call returns 64-bit value. */
5604 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5605 
5606 	/* update return register (already marked as written above) */
5607 	if (fn->ret_type == RET_INTEGER) {
5608 		/* sets type to SCALAR_VALUE */
5609 		mark_reg_unknown(env, regs, BPF_REG_0);
5610 	} else if (fn->ret_type == RET_VOID) {
5611 		regs[BPF_REG_0].type = NOT_INIT;
5612 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5613 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5614 		/* There is no offset yet applied, variable or fixed */
5615 		mark_reg_known_zero(env, regs, BPF_REG_0);
5616 		/* remember map_ptr, so that check_map_access()
5617 		 * can check 'value_size' boundary of memory access
5618 		 * to map element returned from bpf_map_lookup_elem()
5619 		 */
5620 		if (meta.map_ptr == NULL) {
5621 			verbose(env,
5622 				"kernel subsystem misconfigured verifier\n");
5623 			return -EINVAL;
5624 		}
5625 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5626 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5627 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5628 			if (map_value_has_spin_lock(meta.map_ptr))
5629 				regs[BPF_REG_0].id = ++env->id_gen;
5630 		} else {
5631 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5632 		}
5633 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5634 		mark_reg_known_zero(env, regs, BPF_REG_0);
5635 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5636 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5637 		mark_reg_known_zero(env, regs, BPF_REG_0);
5638 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5639 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5640 		mark_reg_known_zero(env, regs, BPF_REG_0);
5641 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5642 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5643 		mark_reg_known_zero(env, regs, BPF_REG_0);
5644 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5645 		regs[BPF_REG_0].mem_size = meta.mem_size;
5646 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5647 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5648 		const struct btf_type *t;
5649 
5650 		mark_reg_known_zero(env, regs, BPF_REG_0);
5651 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5652 		if (!btf_type_is_struct(t)) {
5653 			u32 tsize;
5654 			const struct btf_type *ret;
5655 			const char *tname;
5656 
5657 			/* resolve the type size of ksym. */
5658 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5659 			if (IS_ERR(ret)) {
5660 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5661 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5662 					tname, PTR_ERR(ret));
5663 				return -EINVAL;
5664 			}
5665 			regs[BPF_REG_0].type =
5666 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5667 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5668 			regs[BPF_REG_0].mem_size = tsize;
5669 		} else {
5670 			regs[BPF_REG_0].type =
5671 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5672 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5673 			regs[BPF_REG_0].btf = meta.ret_btf;
5674 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5675 		}
5676 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5677 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
5678 		int ret_btf_id;
5679 
5680 		mark_reg_known_zero(env, regs, BPF_REG_0);
5681 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5682 						     PTR_TO_BTF_ID :
5683 						     PTR_TO_BTF_ID_OR_NULL;
5684 		ret_btf_id = *fn->ret_btf_id;
5685 		if (ret_btf_id == 0) {
5686 			verbose(env, "invalid return type %d of func %s#%d\n",
5687 				fn->ret_type, func_id_name(func_id), func_id);
5688 			return -EINVAL;
5689 		}
5690 		/* current BPF helper definitions are only coming from
5691 		 * built-in code with type IDs from  vmlinux BTF
5692 		 */
5693 		regs[BPF_REG_0].btf = btf_vmlinux;
5694 		regs[BPF_REG_0].btf_id = ret_btf_id;
5695 	} else {
5696 		verbose(env, "unknown return type %d of func %s#%d\n",
5697 			fn->ret_type, func_id_name(func_id), func_id);
5698 		return -EINVAL;
5699 	}
5700 
5701 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
5702 		regs[BPF_REG_0].id = ++env->id_gen;
5703 
5704 	if (is_ptr_cast_function(func_id)) {
5705 		/* For release_reference() */
5706 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5707 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5708 		int id = acquire_reference_state(env, insn_idx);
5709 
5710 		if (id < 0)
5711 			return id;
5712 		/* For mark_ptr_or_null_reg() */
5713 		regs[BPF_REG_0].id = id;
5714 		/* For release_reference() */
5715 		regs[BPF_REG_0].ref_obj_id = id;
5716 	}
5717 
5718 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5719 
5720 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5721 	if (err)
5722 		return err;
5723 
5724 	if ((func_id == BPF_FUNC_get_stack ||
5725 	     func_id == BPF_FUNC_get_task_stack) &&
5726 	    !env->prog->has_callchain_buf) {
5727 		const char *err_str;
5728 
5729 #ifdef CONFIG_PERF_EVENTS
5730 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5731 		err_str = "cannot get callchain buffer for func %s#%d\n";
5732 #else
5733 		err = -ENOTSUPP;
5734 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5735 #endif
5736 		if (err) {
5737 			verbose(env, err_str, func_id_name(func_id), func_id);
5738 			return err;
5739 		}
5740 
5741 		env->prog->has_callchain_buf = true;
5742 	}
5743 
5744 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5745 		env->prog->call_get_stack = true;
5746 
5747 	if (changes_data)
5748 		clear_all_pkt_pointers(env);
5749 	return 0;
5750 }
5751 
5752 static bool signed_add_overflows(s64 a, s64 b)
5753 {
5754 	/* Do the add in u64, where overflow is well-defined */
5755 	s64 res = (s64)((u64)a + (u64)b);
5756 
5757 	if (b < 0)
5758 		return res > a;
5759 	return res < a;
5760 }
5761 
5762 static bool signed_add32_overflows(s32 a, s32 b)
5763 {
5764 	/* Do the add in u32, where overflow is well-defined */
5765 	s32 res = (s32)((u32)a + (u32)b);
5766 
5767 	if (b < 0)
5768 		return res > a;
5769 	return res < a;
5770 }
5771 
5772 static bool signed_sub_overflows(s64 a, s64 b)
5773 {
5774 	/* Do the sub in u64, where overflow is well-defined */
5775 	s64 res = (s64)((u64)a - (u64)b);
5776 
5777 	if (b < 0)
5778 		return res < a;
5779 	return res > a;
5780 }
5781 
5782 static bool signed_sub32_overflows(s32 a, s32 b)
5783 {
5784 	/* Do the sub in u32, where overflow is well-defined */
5785 	s32 res = (s32)((u32)a - (u32)b);
5786 
5787 	if (b < 0)
5788 		return res < a;
5789 	return res > a;
5790 }
5791 
5792 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5793 				  const struct bpf_reg_state *reg,
5794 				  enum bpf_reg_type type)
5795 {
5796 	bool known = tnum_is_const(reg->var_off);
5797 	s64 val = reg->var_off.value;
5798 	s64 smin = reg->smin_value;
5799 
5800 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5801 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5802 			reg_type_str[type], val);
5803 		return false;
5804 	}
5805 
5806 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5807 		verbose(env, "%s pointer offset %d is not allowed\n",
5808 			reg_type_str[type], reg->off);
5809 		return false;
5810 	}
5811 
5812 	if (smin == S64_MIN) {
5813 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5814 			reg_type_str[type]);
5815 		return false;
5816 	}
5817 
5818 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5819 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5820 			smin, reg_type_str[type]);
5821 		return false;
5822 	}
5823 
5824 	return true;
5825 }
5826 
5827 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5828 {
5829 	return &env->insn_aux_data[env->insn_idx];
5830 }
5831 
5832 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5833 			      u32 *ptr_limit, u8 opcode, bool off_is_neg)
5834 {
5835 	bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
5836 			    (opcode == BPF_SUB && !off_is_neg);
5837 	u32 off;
5838 
5839 	switch (ptr_reg->type) {
5840 	case PTR_TO_STACK:
5841 		/* Indirect variable offset stack access is prohibited in
5842 		 * unprivileged mode so it's not handled here.
5843 		 */
5844 		off = ptr_reg->off + ptr_reg->var_off.value;
5845 		if (mask_to_left)
5846 			*ptr_limit = MAX_BPF_STACK + off;
5847 		else
5848 			*ptr_limit = -off;
5849 		return 0;
5850 	case PTR_TO_MAP_VALUE:
5851 		if (mask_to_left) {
5852 			*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5853 		} else {
5854 			off = ptr_reg->smin_value + ptr_reg->off;
5855 			*ptr_limit = ptr_reg->map_ptr->value_size - off;
5856 		}
5857 		return 0;
5858 	default:
5859 		return -EINVAL;
5860 	}
5861 }
5862 
5863 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5864 				    const struct bpf_insn *insn)
5865 {
5866 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5867 }
5868 
5869 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5870 				       u32 alu_state, u32 alu_limit)
5871 {
5872 	/* If we arrived here from different branches with different
5873 	 * state or limits to sanitize, then this won't work.
5874 	 */
5875 	if (aux->alu_state &&
5876 	    (aux->alu_state != alu_state ||
5877 	     aux->alu_limit != alu_limit))
5878 		return -EACCES;
5879 
5880 	/* Corresponding fixup done in fixup_bpf_calls(). */
5881 	aux->alu_state = alu_state;
5882 	aux->alu_limit = alu_limit;
5883 	return 0;
5884 }
5885 
5886 static int sanitize_val_alu(struct bpf_verifier_env *env,
5887 			    struct bpf_insn *insn)
5888 {
5889 	struct bpf_insn_aux_data *aux = cur_aux(env);
5890 
5891 	if (can_skip_alu_sanitation(env, insn))
5892 		return 0;
5893 
5894 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5895 }
5896 
5897 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5898 			    struct bpf_insn *insn,
5899 			    const struct bpf_reg_state *ptr_reg,
5900 			    struct bpf_reg_state *dst_reg,
5901 			    bool off_is_neg)
5902 {
5903 	struct bpf_verifier_state *vstate = env->cur_state;
5904 	struct bpf_insn_aux_data *aux = cur_aux(env);
5905 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
5906 	u8 opcode = BPF_OP(insn->code);
5907 	u32 alu_state, alu_limit;
5908 	struct bpf_reg_state tmp;
5909 	bool ret;
5910 
5911 	if (can_skip_alu_sanitation(env, insn))
5912 		return 0;
5913 
5914 	/* We already marked aux for masking from non-speculative
5915 	 * paths, thus we got here in the first place. We only care
5916 	 * to explore bad access from here.
5917 	 */
5918 	if (vstate->speculative)
5919 		goto do_sim;
5920 
5921 	alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5922 	alu_state |= ptr_is_dst_reg ?
5923 		     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5924 
5925 	if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5926 		return 0;
5927 	if (update_alu_sanitation_state(aux, alu_state, alu_limit))
5928 		return -EACCES;
5929 do_sim:
5930 	/* Simulate and find potential out-of-bounds access under
5931 	 * speculative execution from truncation as a result of
5932 	 * masking when off was not within expected range. If off
5933 	 * sits in dst, then we temporarily need to move ptr there
5934 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5935 	 * for cases where we use K-based arithmetic in one direction
5936 	 * and truncated reg-based in the other in order to explore
5937 	 * bad access.
5938 	 */
5939 	if (!ptr_is_dst_reg) {
5940 		tmp = *dst_reg;
5941 		*dst_reg = *ptr_reg;
5942 	}
5943 	ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
5944 	if (!ptr_is_dst_reg && ret)
5945 		*dst_reg = tmp;
5946 	return !ret ? -EFAULT : 0;
5947 }
5948 
5949 /* check that stack access falls within stack limits and that 'reg' doesn't
5950  * have a variable offset.
5951  *
5952  * Variable offset is prohibited for unprivileged mode for simplicity since it
5953  * requires corresponding support in Spectre masking for stack ALU.  See also
5954  * retrieve_ptr_limit().
5955  *
5956  *
5957  * 'off' includes 'reg->off'.
5958  */
5959 static int check_stack_access_for_ptr_arithmetic(
5960 				struct bpf_verifier_env *env,
5961 				int regno,
5962 				const struct bpf_reg_state *reg,
5963 				int off)
5964 {
5965 	if (!tnum_is_const(reg->var_off)) {
5966 		char tn_buf[48];
5967 
5968 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5969 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5970 			regno, tn_buf, off);
5971 		return -EACCES;
5972 	}
5973 
5974 	if (off >= 0 || off < -MAX_BPF_STACK) {
5975 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
5976 			"prohibited for !root; off=%d\n", regno, off);
5977 		return -EACCES;
5978 	}
5979 
5980 	return 0;
5981 }
5982 
5983 
5984 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5985  * Caller should also handle BPF_MOV case separately.
5986  * If we return -EACCES, caller may want to try again treating pointer as a
5987  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
5988  */
5989 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5990 				   struct bpf_insn *insn,
5991 				   const struct bpf_reg_state *ptr_reg,
5992 				   const struct bpf_reg_state *off_reg)
5993 {
5994 	struct bpf_verifier_state *vstate = env->cur_state;
5995 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5996 	struct bpf_reg_state *regs = state->regs, *dst_reg;
5997 	bool known = tnum_is_const(off_reg->var_off);
5998 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5999 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6000 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6001 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6002 	u32 dst = insn->dst_reg, src = insn->src_reg;
6003 	u8 opcode = BPF_OP(insn->code);
6004 	int ret;
6005 
6006 	dst_reg = &regs[dst];
6007 
6008 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6009 	    smin_val > smax_val || umin_val > umax_val) {
6010 		/* Taint dst register if offset had invalid bounds derived from
6011 		 * e.g. dead branches.
6012 		 */
6013 		__mark_reg_unknown(env, dst_reg);
6014 		return 0;
6015 	}
6016 
6017 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6018 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6019 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6020 			__mark_reg_unknown(env, dst_reg);
6021 			return 0;
6022 		}
6023 
6024 		verbose(env,
6025 			"R%d 32-bit pointer arithmetic prohibited\n",
6026 			dst);
6027 		return -EACCES;
6028 	}
6029 
6030 	switch (ptr_reg->type) {
6031 	case PTR_TO_MAP_VALUE_OR_NULL:
6032 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6033 			dst, reg_type_str[ptr_reg->type]);
6034 		return -EACCES;
6035 	case CONST_PTR_TO_MAP:
6036 		/* smin_val represents the known value */
6037 		if (known && smin_val == 0 && opcode == BPF_ADD)
6038 			break;
6039 		fallthrough;
6040 	case PTR_TO_PACKET_END:
6041 	case PTR_TO_SOCKET:
6042 	case PTR_TO_SOCKET_OR_NULL:
6043 	case PTR_TO_SOCK_COMMON:
6044 	case PTR_TO_SOCK_COMMON_OR_NULL:
6045 	case PTR_TO_TCP_SOCK:
6046 	case PTR_TO_TCP_SOCK_OR_NULL:
6047 	case PTR_TO_XDP_SOCK:
6048 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6049 			dst, reg_type_str[ptr_reg->type]);
6050 		return -EACCES;
6051 	case PTR_TO_MAP_VALUE:
6052 		if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6053 			verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6054 				off_reg == dst_reg ? dst : src);
6055 			return -EACCES;
6056 		}
6057 		fallthrough;
6058 	default:
6059 		break;
6060 	}
6061 
6062 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6063 	 * The id may be overwritten later if we create a new variable offset.
6064 	 */
6065 	dst_reg->type = ptr_reg->type;
6066 	dst_reg->id = ptr_reg->id;
6067 
6068 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6069 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6070 		return -EINVAL;
6071 
6072 	/* pointer types do not carry 32-bit bounds at the moment. */
6073 	__mark_reg32_unbounded(dst_reg);
6074 
6075 	switch (opcode) {
6076 	case BPF_ADD:
6077 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6078 		if (ret < 0) {
6079 			verbose(env, "R%d tried to add from different maps or paths\n", dst);
6080 			return ret;
6081 		}
6082 		/* We can take a fixed offset as long as it doesn't overflow
6083 		 * the s32 'off' field
6084 		 */
6085 		if (known && (ptr_reg->off + smin_val ==
6086 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6087 			/* pointer += K.  Accumulate it into fixed offset */
6088 			dst_reg->smin_value = smin_ptr;
6089 			dst_reg->smax_value = smax_ptr;
6090 			dst_reg->umin_value = umin_ptr;
6091 			dst_reg->umax_value = umax_ptr;
6092 			dst_reg->var_off = ptr_reg->var_off;
6093 			dst_reg->off = ptr_reg->off + smin_val;
6094 			dst_reg->raw = ptr_reg->raw;
6095 			break;
6096 		}
6097 		/* A new variable offset is created.  Note that off_reg->off
6098 		 * == 0, since it's a scalar.
6099 		 * dst_reg gets the pointer type and since some positive
6100 		 * integer value was added to the pointer, give it a new 'id'
6101 		 * if it's a PTR_TO_PACKET.
6102 		 * this creates a new 'base' pointer, off_reg (variable) gets
6103 		 * added into the variable offset, and we copy the fixed offset
6104 		 * from ptr_reg.
6105 		 */
6106 		if (signed_add_overflows(smin_ptr, smin_val) ||
6107 		    signed_add_overflows(smax_ptr, smax_val)) {
6108 			dst_reg->smin_value = S64_MIN;
6109 			dst_reg->smax_value = S64_MAX;
6110 		} else {
6111 			dst_reg->smin_value = smin_ptr + smin_val;
6112 			dst_reg->smax_value = smax_ptr + smax_val;
6113 		}
6114 		if (umin_ptr + umin_val < umin_ptr ||
6115 		    umax_ptr + umax_val < umax_ptr) {
6116 			dst_reg->umin_value = 0;
6117 			dst_reg->umax_value = U64_MAX;
6118 		} else {
6119 			dst_reg->umin_value = umin_ptr + umin_val;
6120 			dst_reg->umax_value = umax_ptr + umax_val;
6121 		}
6122 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6123 		dst_reg->off = ptr_reg->off;
6124 		dst_reg->raw = ptr_reg->raw;
6125 		if (reg_is_pkt_pointer(ptr_reg)) {
6126 			dst_reg->id = ++env->id_gen;
6127 			/* something was added to pkt_ptr, set range to zero */
6128 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6129 		}
6130 		break;
6131 	case BPF_SUB:
6132 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6133 		if (ret < 0) {
6134 			verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6135 			return ret;
6136 		}
6137 		if (dst_reg == off_reg) {
6138 			/* scalar -= pointer.  Creates an unknown scalar */
6139 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6140 				dst);
6141 			return -EACCES;
6142 		}
6143 		/* We don't allow subtraction from FP, because (according to
6144 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6145 		 * be able to deal with it.
6146 		 */
6147 		if (ptr_reg->type == PTR_TO_STACK) {
6148 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6149 				dst);
6150 			return -EACCES;
6151 		}
6152 		if (known && (ptr_reg->off - smin_val ==
6153 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6154 			/* pointer -= K.  Subtract it from fixed offset */
6155 			dst_reg->smin_value = smin_ptr;
6156 			dst_reg->smax_value = smax_ptr;
6157 			dst_reg->umin_value = umin_ptr;
6158 			dst_reg->umax_value = umax_ptr;
6159 			dst_reg->var_off = ptr_reg->var_off;
6160 			dst_reg->id = ptr_reg->id;
6161 			dst_reg->off = ptr_reg->off - smin_val;
6162 			dst_reg->raw = ptr_reg->raw;
6163 			break;
6164 		}
6165 		/* A new variable offset is created.  If the subtrahend is known
6166 		 * nonnegative, then any reg->range we had before is still good.
6167 		 */
6168 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6169 		    signed_sub_overflows(smax_ptr, smin_val)) {
6170 			/* Overflow possible, we know nothing */
6171 			dst_reg->smin_value = S64_MIN;
6172 			dst_reg->smax_value = S64_MAX;
6173 		} else {
6174 			dst_reg->smin_value = smin_ptr - smax_val;
6175 			dst_reg->smax_value = smax_ptr - smin_val;
6176 		}
6177 		if (umin_ptr < umax_val) {
6178 			/* Overflow possible, we know nothing */
6179 			dst_reg->umin_value = 0;
6180 			dst_reg->umax_value = U64_MAX;
6181 		} else {
6182 			/* Cannot overflow (as long as bounds are consistent) */
6183 			dst_reg->umin_value = umin_ptr - umax_val;
6184 			dst_reg->umax_value = umax_ptr - umin_val;
6185 		}
6186 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6187 		dst_reg->off = ptr_reg->off;
6188 		dst_reg->raw = ptr_reg->raw;
6189 		if (reg_is_pkt_pointer(ptr_reg)) {
6190 			dst_reg->id = ++env->id_gen;
6191 			/* something was added to pkt_ptr, set range to zero */
6192 			if (smin_val < 0)
6193 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6194 		}
6195 		break;
6196 	case BPF_AND:
6197 	case BPF_OR:
6198 	case BPF_XOR:
6199 		/* bitwise ops on pointers are troublesome, prohibit. */
6200 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6201 			dst, bpf_alu_string[opcode >> 4]);
6202 		return -EACCES;
6203 	default:
6204 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6205 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6206 			dst, bpf_alu_string[opcode >> 4]);
6207 		return -EACCES;
6208 	}
6209 
6210 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6211 		return -EINVAL;
6212 
6213 	__update_reg_bounds(dst_reg);
6214 	__reg_deduce_bounds(dst_reg);
6215 	__reg_bound_offset(dst_reg);
6216 
6217 	/* For unprivileged we require that resulting offset must be in bounds
6218 	 * in order to be able to sanitize access later on.
6219 	 */
6220 	if (!env->bypass_spec_v1) {
6221 		if (dst_reg->type == PTR_TO_MAP_VALUE &&
6222 		    check_map_access(env, dst, dst_reg->off, 1, false)) {
6223 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6224 				"prohibited for !root\n", dst);
6225 			return -EACCES;
6226 		} else if (dst_reg->type == PTR_TO_STACK &&
6227 			   check_stack_access_for_ptr_arithmetic(
6228 				   env, dst, dst_reg, dst_reg->off +
6229 				   dst_reg->var_off.value)) {
6230 			return -EACCES;
6231 		}
6232 	}
6233 
6234 	return 0;
6235 }
6236 
6237 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6238 				 struct bpf_reg_state *src_reg)
6239 {
6240 	s32 smin_val = src_reg->s32_min_value;
6241 	s32 smax_val = src_reg->s32_max_value;
6242 	u32 umin_val = src_reg->u32_min_value;
6243 	u32 umax_val = src_reg->u32_max_value;
6244 
6245 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6246 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6247 		dst_reg->s32_min_value = S32_MIN;
6248 		dst_reg->s32_max_value = S32_MAX;
6249 	} else {
6250 		dst_reg->s32_min_value += smin_val;
6251 		dst_reg->s32_max_value += smax_val;
6252 	}
6253 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6254 	    dst_reg->u32_max_value + umax_val < umax_val) {
6255 		dst_reg->u32_min_value = 0;
6256 		dst_reg->u32_max_value = U32_MAX;
6257 	} else {
6258 		dst_reg->u32_min_value += umin_val;
6259 		dst_reg->u32_max_value += umax_val;
6260 	}
6261 }
6262 
6263 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6264 			       struct bpf_reg_state *src_reg)
6265 {
6266 	s64 smin_val = src_reg->smin_value;
6267 	s64 smax_val = src_reg->smax_value;
6268 	u64 umin_val = src_reg->umin_value;
6269 	u64 umax_val = src_reg->umax_value;
6270 
6271 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6272 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6273 		dst_reg->smin_value = S64_MIN;
6274 		dst_reg->smax_value = S64_MAX;
6275 	} else {
6276 		dst_reg->smin_value += smin_val;
6277 		dst_reg->smax_value += smax_val;
6278 	}
6279 	if (dst_reg->umin_value + umin_val < umin_val ||
6280 	    dst_reg->umax_value + umax_val < umax_val) {
6281 		dst_reg->umin_value = 0;
6282 		dst_reg->umax_value = U64_MAX;
6283 	} else {
6284 		dst_reg->umin_value += umin_val;
6285 		dst_reg->umax_value += umax_val;
6286 	}
6287 }
6288 
6289 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6290 				 struct bpf_reg_state *src_reg)
6291 {
6292 	s32 smin_val = src_reg->s32_min_value;
6293 	s32 smax_val = src_reg->s32_max_value;
6294 	u32 umin_val = src_reg->u32_min_value;
6295 	u32 umax_val = src_reg->u32_max_value;
6296 
6297 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6298 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6299 		/* Overflow possible, we know nothing */
6300 		dst_reg->s32_min_value = S32_MIN;
6301 		dst_reg->s32_max_value = S32_MAX;
6302 	} else {
6303 		dst_reg->s32_min_value -= smax_val;
6304 		dst_reg->s32_max_value -= smin_val;
6305 	}
6306 	if (dst_reg->u32_min_value < umax_val) {
6307 		/* Overflow possible, we know nothing */
6308 		dst_reg->u32_min_value = 0;
6309 		dst_reg->u32_max_value = U32_MAX;
6310 	} else {
6311 		/* Cannot overflow (as long as bounds are consistent) */
6312 		dst_reg->u32_min_value -= umax_val;
6313 		dst_reg->u32_max_value -= umin_val;
6314 	}
6315 }
6316 
6317 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6318 			       struct bpf_reg_state *src_reg)
6319 {
6320 	s64 smin_val = src_reg->smin_value;
6321 	s64 smax_val = src_reg->smax_value;
6322 	u64 umin_val = src_reg->umin_value;
6323 	u64 umax_val = src_reg->umax_value;
6324 
6325 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6326 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6327 		/* Overflow possible, we know nothing */
6328 		dst_reg->smin_value = S64_MIN;
6329 		dst_reg->smax_value = S64_MAX;
6330 	} else {
6331 		dst_reg->smin_value -= smax_val;
6332 		dst_reg->smax_value -= smin_val;
6333 	}
6334 	if (dst_reg->umin_value < umax_val) {
6335 		/* Overflow possible, we know nothing */
6336 		dst_reg->umin_value = 0;
6337 		dst_reg->umax_value = U64_MAX;
6338 	} else {
6339 		/* Cannot overflow (as long as bounds are consistent) */
6340 		dst_reg->umin_value -= umax_val;
6341 		dst_reg->umax_value -= umin_val;
6342 	}
6343 }
6344 
6345 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6346 				 struct bpf_reg_state *src_reg)
6347 {
6348 	s32 smin_val = src_reg->s32_min_value;
6349 	u32 umin_val = src_reg->u32_min_value;
6350 	u32 umax_val = src_reg->u32_max_value;
6351 
6352 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6353 		/* Ain't nobody got time to multiply that sign */
6354 		__mark_reg32_unbounded(dst_reg);
6355 		return;
6356 	}
6357 	/* Both values are positive, so we can work with unsigned and
6358 	 * copy the result to signed (unless it exceeds S32_MAX).
6359 	 */
6360 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6361 		/* Potential overflow, we know nothing */
6362 		__mark_reg32_unbounded(dst_reg);
6363 		return;
6364 	}
6365 	dst_reg->u32_min_value *= umin_val;
6366 	dst_reg->u32_max_value *= umax_val;
6367 	if (dst_reg->u32_max_value > S32_MAX) {
6368 		/* Overflow possible, we know nothing */
6369 		dst_reg->s32_min_value = S32_MIN;
6370 		dst_reg->s32_max_value = S32_MAX;
6371 	} else {
6372 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6373 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6374 	}
6375 }
6376 
6377 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6378 			       struct bpf_reg_state *src_reg)
6379 {
6380 	s64 smin_val = src_reg->smin_value;
6381 	u64 umin_val = src_reg->umin_value;
6382 	u64 umax_val = src_reg->umax_value;
6383 
6384 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6385 		/* Ain't nobody got time to multiply that sign */
6386 		__mark_reg64_unbounded(dst_reg);
6387 		return;
6388 	}
6389 	/* Both values are positive, so we can work with unsigned and
6390 	 * copy the result to signed (unless it exceeds S64_MAX).
6391 	 */
6392 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6393 		/* Potential overflow, we know nothing */
6394 		__mark_reg64_unbounded(dst_reg);
6395 		return;
6396 	}
6397 	dst_reg->umin_value *= umin_val;
6398 	dst_reg->umax_value *= umax_val;
6399 	if (dst_reg->umax_value > S64_MAX) {
6400 		/* Overflow possible, we know nothing */
6401 		dst_reg->smin_value = S64_MIN;
6402 		dst_reg->smax_value = S64_MAX;
6403 	} else {
6404 		dst_reg->smin_value = dst_reg->umin_value;
6405 		dst_reg->smax_value = dst_reg->umax_value;
6406 	}
6407 }
6408 
6409 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6410 				 struct bpf_reg_state *src_reg)
6411 {
6412 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6413 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6414 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6415 	s32 smin_val = src_reg->s32_min_value;
6416 	u32 umax_val = src_reg->u32_max_value;
6417 
6418 	/* Assuming scalar64_min_max_and will be called so its safe
6419 	 * to skip updating register for known 32-bit case.
6420 	 */
6421 	if (src_known && dst_known)
6422 		return;
6423 
6424 	/* We get our minimum from the var_off, since that's inherently
6425 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6426 	 */
6427 	dst_reg->u32_min_value = var32_off.value;
6428 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6429 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6430 		/* Lose signed bounds when ANDing negative numbers,
6431 		 * ain't nobody got time for that.
6432 		 */
6433 		dst_reg->s32_min_value = S32_MIN;
6434 		dst_reg->s32_max_value = S32_MAX;
6435 	} else {
6436 		/* ANDing two positives gives a positive, so safe to
6437 		 * cast result into s64.
6438 		 */
6439 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6440 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6441 	}
6442 
6443 }
6444 
6445 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6446 			       struct bpf_reg_state *src_reg)
6447 {
6448 	bool src_known = tnum_is_const(src_reg->var_off);
6449 	bool dst_known = tnum_is_const(dst_reg->var_off);
6450 	s64 smin_val = src_reg->smin_value;
6451 	u64 umax_val = src_reg->umax_value;
6452 
6453 	if (src_known && dst_known) {
6454 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6455 		return;
6456 	}
6457 
6458 	/* We get our minimum from the var_off, since that's inherently
6459 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6460 	 */
6461 	dst_reg->umin_value = dst_reg->var_off.value;
6462 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6463 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6464 		/* Lose signed bounds when ANDing negative numbers,
6465 		 * ain't nobody got time for that.
6466 		 */
6467 		dst_reg->smin_value = S64_MIN;
6468 		dst_reg->smax_value = S64_MAX;
6469 	} else {
6470 		/* ANDing two positives gives a positive, so safe to
6471 		 * cast result into s64.
6472 		 */
6473 		dst_reg->smin_value = dst_reg->umin_value;
6474 		dst_reg->smax_value = dst_reg->umax_value;
6475 	}
6476 	/* We may learn something more from the var_off */
6477 	__update_reg_bounds(dst_reg);
6478 }
6479 
6480 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6481 				struct bpf_reg_state *src_reg)
6482 {
6483 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6484 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6485 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6486 	s32 smin_val = src_reg->s32_min_value;
6487 	u32 umin_val = src_reg->u32_min_value;
6488 
6489 	/* Assuming scalar64_min_max_or will be called so it is safe
6490 	 * to skip updating register for known case.
6491 	 */
6492 	if (src_known && dst_known)
6493 		return;
6494 
6495 	/* We get our maximum from the var_off, and our minimum is the
6496 	 * maximum of the operands' minima
6497 	 */
6498 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6499 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6500 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6501 		/* Lose signed bounds when ORing negative numbers,
6502 		 * ain't nobody got time for that.
6503 		 */
6504 		dst_reg->s32_min_value = S32_MIN;
6505 		dst_reg->s32_max_value = S32_MAX;
6506 	} else {
6507 		/* ORing two positives gives a positive, so safe to
6508 		 * cast result into s64.
6509 		 */
6510 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6511 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6512 	}
6513 }
6514 
6515 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6516 			      struct bpf_reg_state *src_reg)
6517 {
6518 	bool src_known = tnum_is_const(src_reg->var_off);
6519 	bool dst_known = tnum_is_const(dst_reg->var_off);
6520 	s64 smin_val = src_reg->smin_value;
6521 	u64 umin_val = src_reg->umin_value;
6522 
6523 	if (src_known && dst_known) {
6524 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6525 		return;
6526 	}
6527 
6528 	/* We get our maximum from the var_off, and our minimum is the
6529 	 * maximum of the operands' minima
6530 	 */
6531 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6532 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6533 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6534 		/* Lose signed bounds when ORing negative numbers,
6535 		 * ain't nobody got time for that.
6536 		 */
6537 		dst_reg->smin_value = S64_MIN;
6538 		dst_reg->smax_value = S64_MAX;
6539 	} else {
6540 		/* ORing two positives gives a positive, so safe to
6541 		 * cast result into s64.
6542 		 */
6543 		dst_reg->smin_value = dst_reg->umin_value;
6544 		dst_reg->smax_value = dst_reg->umax_value;
6545 	}
6546 	/* We may learn something more from the var_off */
6547 	__update_reg_bounds(dst_reg);
6548 }
6549 
6550 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6551 				 struct bpf_reg_state *src_reg)
6552 {
6553 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6554 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6555 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6556 	s32 smin_val = src_reg->s32_min_value;
6557 
6558 	/* Assuming scalar64_min_max_xor will be called so it is safe
6559 	 * to skip updating register for known case.
6560 	 */
6561 	if (src_known && dst_known)
6562 		return;
6563 
6564 	/* We get both minimum and maximum from the var32_off. */
6565 	dst_reg->u32_min_value = var32_off.value;
6566 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6567 
6568 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6569 		/* XORing two positive sign numbers gives a positive,
6570 		 * so safe to cast u32 result into s32.
6571 		 */
6572 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6573 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6574 	} else {
6575 		dst_reg->s32_min_value = S32_MIN;
6576 		dst_reg->s32_max_value = S32_MAX;
6577 	}
6578 }
6579 
6580 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6581 			       struct bpf_reg_state *src_reg)
6582 {
6583 	bool src_known = tnum_is_const(src_reg->var_off);
6584 	bool dst_known = tnum_is_const(dst_reg->var_off);
6585 	s64 smin_val = src_reg->smin_value;
6586 
6587 	if (src_known && dst_known) {
6588 		/* dst_reg->var_off.value has been updated earlier */
6589 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6590 		return;
6591 	}
6592 
6593 	/* We get both minimum and maximum from the var_off. */
6594 	dst_reg->umin_value = dst_reg->var_off.value;
6595 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6596 
6597 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6598 		/* XORing two positive sign numbers gives a positive,
6599 		 * so safe to cast u64 result into s64.
6600 		 */
6601 		dst_reg->smin_value = dst_reg->umin_value;
6602 		dst_reg->smax_value = dst_reg->umax_value;
6603 	} else {
6604 		dst_reg->smin_value = S64_MIN;
6605 		dst_reg->smax_value = S64_MAX;
6606 	}
6607 
6608 	__update_reg_bounds(dst_reg);
6609 }
6610 
6611 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6612 				   u64 umin_val, u64 umax_val)
6613 {
6614 	/* We lose all sign bit information (except what we can pick
6615 	 * up from var_off)
6616 	 */
6617 	dst_reg->s32_min_value = S32_MIN;
6618 	dst_reg->s32_max_value = S32_MAX;
6619 	/* If we might shift our top bit out, then we know nothing */
6620 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6621 		dst_reg->u32_min_value = 0;
6622 		dst_reg->u32_max_value = U32_MAX;
6623 	} else {
6624 		dst_reg->u32_min_value <<= umin_val;
6625 		dst_reg->u32_max_value <<= umax_val;
6626 	}
6627 }
6628 
6629 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6630 				 struct bpf_reg_state *src_reg)
6631 {
6632 	u32 umax_val = src_reg->u32_max_value;
6633 	u32 umin_val = src_reg->u32_min_value;
6634 	/* u32 alu operation will zext upper bits */
6635 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6636 
6637 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6638 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6639 	/* Not required but being careful mark reg64 bounds as unknown so
6640 	 * that we are forced to pick them up from tnum and zext later and
6641 	 * if some path skips this step we are still safe.
6642 	 */
6643 	__mark_reg64_unbounded(dst_reg);
6644 	__update_reg32_bounds(dst_reg);
6645 }
6646 
6647 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6648 				   u64 umin_val, u64 umax_val)
6649 {
6650 	/* Special case <<32 because it is a common compiler pattern to sign
6651 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6652 	 * positive we know this shift will also be positive so we can track
6653 	 * bounds correctly. Otherwise we lose all sign bit information except
6654 	 * what we can pick up from var_off. Perhaps we can generalize this
6655 	 * later to shifts of any length.
6656 	 */
6657 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6658 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6659 	else
6660 		dst_reg->smax_value = S64_MAX;
6661 
6662 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6663 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6664 	else
6665 		dst_reg->smin_value = S64_MIN;
6666 
6667 	/* If we might shift our top bit out, then we know nothing */
6668 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6669 		dst_reg->umin_value = 0;
6670 		dst_reg->umax_value = U64_MAX;
6671 	} else {
6672 		dst_reg->umin_value <<= umin_val;
6673 		dst_reg->umax_value <<= umax_val;
6674 	}
6675 }
6676 
6677 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6678 			       struct bpf_reg_state *src_reg)
6679 {
6680 	u64 umax_val = src_reg->umax_value;
6681 	u64 umin_val = src_reg->umin_value;
6682 
6683 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6684 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6685 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6686 
6687 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6688 	/* We may learn something more from the var_off */
6689 	__update_reg_bounds(dst_reg);
6690 }
6691 
6692 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6693 				 struct bpf_reg_state *src_reg)
6694 {
6695 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6696 	u32 umax_val = src_reg->u32_max_value;
6697 	u32 umin_val = src_reg->u32_min_value;
6698 
6699 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6700 	 * be negative, then either:
6701 	 * 1) src_reg might be zero, so the sign bit of the result is
6702 	 *    unknown, so we lose our signed bounds
6703 	 * 2) it's known negative, thus the unsigned bounds capture the
6704 	 *    signed bounds
6705 	 * 3) the signed bounds cross zero, so they tell us nothing
6706 	 *    about the result
6707 	 * If the value in dst_reg is known nonnegative, then again the
6708 	 * unsigned bounds capture the signed bounds.
6709 	 * Thus, in all cases it suffices to blow away our signed bounds
6710 	 * and rely on inferring new ones from the unsigned bounds and
6711 	 * var_off of the result.
6712 	 */
6713 	dst_reg->s32_min_value = S32_MIN;
6714 	dst_reg->s32_max_value = S32_MAX;
6715 
6716 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6717 	dst_reg->u32_min_value >>= umax_val;
6718 	dst_reg->u32_max_value >>= umin_val;
6719 
6720 	__mark_reg64_unbounded(dst_reg);
6721 	__update_reg32_bounds(dst_reg);
6722 }
6723 
6724 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6725 			       struct bpf_reg_state *src_reg)
6726 {
6727 	u64 umax_val = src_reg->umax_value;
6728 	u64 umin_val = src_reg->umin_value;
6729 
6730 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6731 	 * be negative, then either:
6732 	 * 1) src_reg might be zero, so the sign bit of the result is
6733 	 *    unknown, so we lose our signed bounds
6734 	 * 2) it's known negative, thus the unsigned bounds capture the
6735 	 *    signed bounds
6736 	 * 3) the signed bounds cross zero, so they tell us nothing
6737 	 *    about the result
6738 	 * If the value in dst_reg is known nonnegative, then again the
6739 	 * unsigned bounds capture the signed bounds.
6740 	 * Thus, in all cases it suffices to blow away our signed bounds
6741 	 * and rely on inferring new ones from the unsigned bounds and
6742 	 * var_off of the result.
6743 	 */
6744 	dst_reg->smin_value = S64_MIN;
6745 	dst_reg->smax_value = S64_MAX;
6746 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6747 	dst_reg->umin_value >>= umax_val;
6748 	dst_reg->umax_value >>= umin_val;
6749 
6750 	/* Its not easy to operate on alu32 bounds here because it depends
6751 	 * on bits being shifted in. Take easy way out and mark unbounded
6752 	 * so we can recalculate later from tnum.
6753 	 */
6754 	__mark_reg32_unbounded(dst_reg);
6755 	__update_reg_bounds(dst_reg);
6756 }
6757 
6758 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6759 				  struct bpf_reg_state *src_reg)
6760 {
6761 	u64 umin_val = src_reg->u32_min_value;
6762 
6763 	/* Upon reaching here, src_known is true and
6764 	 * umax_val is equal to umin_val.
6765 	 */
6766 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6767 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6768 
6769 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6770 
6771 	/* blow away the dst_reg umin_value/umax_value and rely on
6772 	 * dst_reg var_off to refine the result.
6773 	 */
6774 	dst_reg->u32_min_value = 0;
6775 	dst_reg->u32_max_value = U32_MAX;
6776 
6777 	__mark_reg64_unbounded(dst_reg);
6778 	__update_reg32_bounds(dst_reg);
6779 }
6780 
6781 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6782 				struct bpf_reg_state *src_reg)
6783 {
6784 	u64 umin_val = src_reg->umin_value;
6785 
6786 	/* Upon reaching here, src_known is true and umax_val is equal
6787 	 * to umin_val.
6788 	 */
6789 	dst_reg->smin_value >>= umin_val;
6790 	dst_reg->smax_value >>= umin_val;
6791 
6792 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6793 
6794 	/* blow away the dst_reg umin_value/umax_value and rely on
6795 	 * dst_reg var_off to refine the result.
6796 	 */
6797 	dst_reg->umin_value = 0;
6798 	dst_reg->umax_value = U64_MAX;
6799 
6800 	/* Its not easy to operate on alu32 bounds here because it depends
6801 	 * on bits being shifted in from upper 32-bits. Take easy way out
6802 	 * and mark unbounded so we can recalculate later from tnum.
6803 	 */
6804 	__mark_reg32_unbounded(dst_reg);
6805 	__update_reg_bounds(dst_reg);
6806 }
6807 
6808 /* WARNING: This function does calculations on 64-bit values, but the actual
6809  * execution may occur on 32-bit values. Therefore, things like bitshifts
6810  * need extra checks in the 32-bit case.
6811  */
6812 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6813 				      struct bpf_insn *insn,
6814 				      struct bpf_reg_state *dst_reg,
6815 				      struct bpf_reg_state src_reg)
6816 {
6817 	struct bpf_reg_state *regs = cur_regs(env);
6818 	u8 opcode = BPF_OP(insn->code);
6819 	bool src_known;
6820 	s64 smin_val, smax_val;
6821 	u64 umin_val, umax_val;
6822 	s32 s32_min_val, s32_max_val;
6823 	u32 u32_min_val, u32_max_val;
6824 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6825 	u32 dst = insn->dst_reg;
6826 	int ret;
6827 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6828 
6829 	smin_val = src_reg.smin_value;
6830 	smax_val = src_reg.smax_value;
6831 	umin_val = src_reg.umin_value;
6832 	umax_val = src_reg.umax_value;
6833 
6834 	s32_min_val = src_reg.s32_min_value;
6835 	s32_max_val = src_reg.s32_max_value;
6836 	u32_min_val = src_reg.u32_min_value;
6837 	u32_max_val = src_reg.u32_max_value;
6838 
6839 	if (alu32) {
6840 		src_known = tnum_subreg_is_const(src_reg.var_off);
6841 		if ((src_known &&
6842 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6843 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6844 			/* Taint dst register if offset had invalid bounds
6845 			 * derived from e.g. dead branches.
6846 			 */
6847 			__mark_reg_unknown(env, dst_reg);
6848 			return 0;
6849 		}
6850 	} else {
6851 		src_known = tnum_is_const(src_reg.var_off);
6852 		if ((src_known &&
6853 		     (smin_val != smax_val || umin_val != umax_val)) ||
6854 		    smin_val > smax_val || umin_val > umax_val) {
6855 			/* Taint dst register if offset had invalid bounds
6856 			 * derived from e.g. dead branches.
6857 			 */
6858 			__mark_reg_unknown(env, dst_reg);
6859 			return 0;
6860 		}
6861 	}
6862 
6863 	if (!src_known &&
6864 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6865 		__mark_reg_unknown(env, dst_reg);
6866 		return 0;
6867 	}
6868 
6869 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6870 	 * There are two classes of instructions: The first class we track both
6871 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
6872 	 * greatest amount of precision when alu operations are mixed with jmp32
6873 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6874 	 * and BPF_OR. This is possible because these ops have fairly easy to
6875 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6876 	 * See alu32 verifier tests for examples. The second class of
6877 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6878 	 * with regards to tracking sign/unsigned bounds because the bits may
6879 	 * cross subreg boundaries in the alu64 case. When this happens we mark
6880 	 * the reg unbounded in the subreg bound space and use the resulting
6881 	 * tnum to calculate an approximation of the sign/unsigned bounds.
6882 	 */
6883 	switch (opcode) {
6884 	case BPF_ADD:
6885 		ret = sanitize_val_alu(env, insn);
6886 		if (ret < 0) {
6887 			verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6888 			return ret;
6889 		}
6890 		scalar32_min_max_add(dst_reg, &src_reg);
6891 		scalar_min_max_add(dst_reg, &src_reg);
6892 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6893 		break;
6894 	case BPF_SUB:
6895 		ret = sanitize_val_alu(env, insn);
6896 		if (ret < 0) {
6897 			verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6898 			return ret;
6899 		}
6900 		scalar32_min_max_sub(dst_reg, &src_reg);
6901 		scalar_min_max_sub(dst_reg, &src_reg);
6902 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6903 		break;
6904 	case BPF_MUL:
6905 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6906 		scalar32_min_max_mul(dst_reg, &src_reg);
6907 		scalar_min_max_mul(dst_reg, &src_reg);
6908 		break;
6909 	case BPF_AND:
6910 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6911 		scalar32_min_max_and(dst_reg, &src_reg);
6912 		scalar_min_max_and(dst_reg, &src_reg);
6913 		break;
6914 	case BPF_OR:
6915 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6916 		scalar32_min_max_or(dst_reg, &src_reg);
6917 		scalar_min_max_or(dst_reg, &src_reg);
6918 		break;
6919 	case BPF_XOR:
6920 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6921 		scalar32_min_max_xor(dst_reg, &src_reg);
6922 		scalar_min_max_xor(dst_reg, &src_reg);
6923 		break;
6924 	case BPF_LSH:
6925 		if (umax_val >= insn_bitness) {
6926 			/* Shifts greater than 31 or 63 are undefined.
6927 			 * This includes shifts by a negative number.
6928 			 */
6929 			mark_reg_unknown(env, regs, insn->dst_reg);
6930 			break;
6931 		}
6932 		if (alu32)
6933 			scalar32_min_max_lsh(dst_reg, &src_reg);
6934 		else
6935 			scalar_min_max_lsh(dst_reg, &src_reg);
6936 		break;
6937 	case BPF_RSH:
6938 		if (umax_val >= insn_bitness) {
6939 			/* Shifts greater than 31 or 63 are undefined.
6940 			 * This includes shifts by a negative number.
6941 			 */
6942 			mark_reg_unknown(env, regs, insn->dst_reg);
6943 			break;
6944 		}
6945 		if (alu32)
6946 			scalar32_min_max_rsh(dst_reg, &src_reg);
6947 		else
6948 			scalar_min_max_rsh(dst_reg, &src_reg);
6949 		break;
6950 	case BPF_ARSH:
6951 		if (umax_val >= insn_bitness) {
6952 			/* Shifts greater than 31 or 63 are undefined.
6953 			 * This includes shifts by a negative number.
6954 			 */
6955 			mark_reg_unknown(env, regs, insn->dst_reg);
6956 			break;
6957 		}
6958 		if (alu32)
6959 			scalar32_min_max_arsh(dst_reg, &src_reg);
6960 		else
6961 			scalar_min_max_arsh(dst_reg, &src_reg);
6962 		break;
6963 	default:
6964 		mark_reg_unknown(env, regs, insn->dst_reg);
6965 		break;
6966 	}
6967 
6968 	/* ALU32 ops are zero extended into 64bit register */
6969 	if (alu32)
6970 		zext_32_to_64(dst_reg);
6971 
6972 	__update_reg_bounds(dst_reg);
6973 	__reg_deduce_bounds(dst_reg);
6974 	__reg_bound_offset(dst_reg);
6975 	return 0;
6976 }
6977 
6978 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6979  * and var_off.
6980  */
6981 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6982 				   struct bpf_insn *insn)
6983 {
6984 	struct bpf_verifier_state *vstate = env->cur_state;
6985 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6986 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
6987 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6988 	u8 opcode = BPF_OP(insn->code);
6989 	int err;
6990 
6991 	dst_reg = &regs[insn->dst_reg];
6992 	src_reg = NULL;
6993 	if (dst_reg->type != SCALAR_VALUE)
6994 		ptr_reg = dst_reg;
6995 	else
6996 		/* Make sure ID is cleared otherwise dst_reg min/max could be
6997 		 * incorrectly propagated into other registers by find_equal_scalars()
6998 		 */
6999 		dst_reg->id = 0;
7000 	if (BPF_SRC(insn->code) == BPF_X) {
7001 		src_reg = &regs[insn->src_reg];
7002 		if (src_reg->type != SCALAR_VALUE) {
7003 			if (dst_reg->type != SCALAR_VALUE) {
7004 				/* Combining two pointers by any ALU op yields
7005 				 * an arbitrary scalar. Disallow all math except
7006 				 * pointer subtraction
7007 				 */
7008 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7009 					mark_reg_unknown(env, regs, insn->dst_reg);
7010 					return 0;
7011 				}
7012 				verbose(env, "R%d pointer %s pointer prohibited\n",
7013 					insn->dst_reg,
7014 					bpf_alu_string[opcode >> 4]);
7015 				return -EACCES;
7016 			} else {
7017 				/* scalar += pointer
7018 				 * This is legal, but we have to reverse our
7019 				 * src/dest handling in computing the range
7020 				 */
7021 				err = mark_chain_precision(env, insn->dst_reg);
7022 				if (err)
7023 					return err;
7024 				return adjust_ptr_min_max_vals(env, insn,
7025 							       src_reg, dst_reg);
7026 			}
7027 		} else if (ptr_reg) {
7028 			/* pointer += scalar */
7029 			err = mark_chain_precision(env, insn->src_reg);
7030 			if (err)
7031 				return err;
7032 			return adjust_ptr_min_max_vals(env, insn,
7033 						       dst_reg, src_reg);
7034 		}
7035 	} else {
7036 		/* Pretend the src is a reg with a known value, since we only
7037 		 * need to be able to read from this state.
7038 		 */
7039 		off_reg.type = SCALAR_VALUE;
7040 		__mark_reg_known(&off_reg, insn->imm);
7041 		src_reg = &off_reg;
7042 		if (ptr_reg) /* pointer += K */
7043 			return adjust_ptr_min_max_vals(env, insn,
7044 						       ptr_reg, src_reg);
7045 	}
7046 
7047 	/* Got here implies adding two SCALAR_VALUEs */
7048 	if (WARN_ON_ONCE(ptr_reg)) {
7049 		print_verifier_state(env, state);
7050 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7051 		return -EINVAL;
7052 	}
7053 	if (WARN_ON(!src_reg)) {
7054 		print_verifier_state(env, state);
7055 		verbose(env, "verifier internal error: no src_reg\n");
7056 		return -EINVAL;
7057 	}
7058 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7059 }
7060 
7061 /* check validity of 32-bit and 64-bit arithmetic operations */
7062 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7063 {
7064 	struct bpf_reg_state *regs = cur_regs(env);
7065 	u8 opcode = BPF_OP(insn->code);
7066 	int err;
7067 
7068 	if (opcode == BPF_END || opcode == BPF_NEG) {
7069 		if (opcode == BPF_NEG) {
7070 			if (BPF_SRC(insn->code) != 0 ||
7071 			    insn->src_reg != BPF_REG_0 ||
7072 			    insn->off != 0 || insn->imm != 0) {
7073 				verbose(env, "BPF_NEG uses reserved fields\n");
7074 				return -EINVAL;
7075 			}
7076 		} else {
7077 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7078 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7079 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7080 				verbose(env, "BPF_END uses reserved fields\n");
7081 				return -EINVAL;
7082 			}
7083 		}
7084 
7085 		/* check src operand */
7086 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7087 		if (err)
7088 			return err;
7089 
7090 		if (is_pointer_value(env, insn->dst_reg)) {
7091 			verbose(env, "R%d pointer arithmetic prohibited\n",
7092 				insn->dst_reg);
7093 			return -EACCES;
7094 		}
7095 
7096 		/* check dest operand */
7097 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7098 		if (err)
7099 			return err;
7100 
7101 	} else if (opcode == BPF_MOV) {
7102 
7103 		if (BPF_SRC(insn->code) == BPF_X) {
7104 			if (insn->imm != 0 || insn->off != 0) {
7105 				verbose(env, "BPF_MOV uses reserved fields\n");
7106 				return -EINVAL;
7107 			}
7108 
7109 			/* check src operand */
7110 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7111 			if (err)
7112 				return err;
7113 		} else {
7114 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7115 				verbose(env, "BPF_MOV uses reserved fields\n");
7116 				return -EINVAL;
7117 			}
7118 		}
7119 
7120 		/* check dest operand, mark as required later */
7121 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7122 		if (err)
7123 			return err;
7124 
7125 		if (BPF_SRC(insn->code) == BPF_X) {
7126 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7127 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7128 
7129 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7130 				/* case: R1 = R2
7131 				 * copy register state to dest reg
7132 				 */
7133 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7134 					/* Assign src and dst registers the same ID
7135 					 * that will be used by find_equal_scalars()
7136 					 * to propagate min/max range.
7137 					 */
7138 					src_reg->id = ++env->id_gen;
7139 				*dst_reg = *src_reg;
7140 				dst_reg->live |= REG_LIVE_WRITTEN;
7141 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7142 			} else {
7143 				/* R1 = (u32) R2 */
7144 				if (is_pointer_value(env, insn->src_reg)) {
7145 					verbose(env,
7146 						"R%d partial copy of pointer\n",
7147 						insn->src_reg);
7148 					return -EACCES;
7149 				} else if (src_reg->type == SCALAR_VALUE) {
7150 					*dst_reg = *src_reg;
7151 					/* Make sure ID is cleared otherwise
7152 					 * dst_reg min/max could be incorrectly
7153 					 * propagated into src_reg by find_equal_scalars()
7154 					 */
7155 					dst_reg->id = 0;
7156 					dst_reg->live |= REG_LIVE_WRITTEN;
7157 					dst_reg->subreg_def = env->insn_idx + 1;
7158 				} else {
7159 					mark_reg_unknown(env, regs,
7160 							 insn->dst_reg);
7161 				}
7162 				zext_32_to_64(dst_reg);
7163 			}
7164 		} else {
7165 			/* case: R = imm
7166 			 * remember the value we stored into this reg
7167 			 */
7168 			/* clear any state __mark_reg_known doesn't set */
7169 			mark_reg_unknown(env, regs, insn->dst_reg);
7170 			regs[insn->dst_reg].type = SCALAR_VALUE;
7171 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7172 				__mark_reg_known(regs + insn->dst_reg,
7173 						 insn->imm);
7174 			} else {
7175 				__mark_reg_known(regs + insn->dst_reg,
7176 						 (u32)insn->imm);
7177 			}
7178 		}
7179 
7180 	} else if (opcode > BPF_END) {
7181 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7182 		return -EINVAL;
7183 
7184 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7185 
7186 		if (BPF_SRC(insn->code) == BPF_X) {
7187 			if (insn->imm != 0 || insn->off != 0) {
7188 				verbose(env, "BPF_ALU uses reserved fields\n");
7189 				return -EINVAL;
7190 			}
7191 			/* check src1 operand */
7192 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7193 			if (err)
7194 				return err;
7195 		} else {
7196 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7197 				verbose(env, "BPF_ALU uses reserved fields\n");
7198 				return -EINVAL;
7199 			}
7200 		}
7201 
7202 		/* check src2 operand */
7203 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7204 		if (err)
7205 			return err;
7206 
7207 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7208 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7209 			verbose(env, "div by zero\n");
7210 			return -EINVAL;
7211 		}
7212 
7213 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7214 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7215 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7216 
7217 			if (insn->imm < 0 || insn->imm >= size) {
7218 				verbose(env, "invalid shift %d\n", insn->imm);
7219 				return -EINVAL;
7220 			}
7221 		}
7222 
7223 		/* check dest operand */
7224 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7225 		if (err)
7226 			return err;
7227 
7228 		return adjust_reg_min_max_vals(env, insn);
7229 	}
7230 
7231 	return 0;
7232 }
7233 
7234 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7235 				     struct bpf_reg_state *dst_reg,
7236 				     enum bpf_reg_type type, int new_range)
7237 {
7238 	struct bpf_reg_state *reg;
7239 	int i;
7240 
7241 	for (i = 0; i < MAX_BPF_REG; i++) {
7242 		reg = &state->regs[i];
7243 		if (reg->type == type && reg->id == dst_reg->id)
7244 			/* keep the maximum range already checked */
7245 			reg->range = max(reg->range, new_range);
7246 	}
7247 
7248 	bpf_for_each_spilled_reg(i, state, reg) {
7249 		if (!reg)
7250 			continue;
7251 		if (reg->type == type && reg->id == dst_reg->id)
7252 			reg->range = max(reg->range, new_range);
7253 	}
7254 }
7255 
7256 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7257 				   struct bpf_reg_state *dst_reg,
7258 				   enum bpf_reg_type type,
7259 				   bool range_right_open)
7260 {
7261 	int new_range, i;
7262 
7263 	if (dst_reg->off < 0 ||
7264 	    (dst_reg->off == 0 && range_right_open))
7265 		/* This doesn't give us any range */
7266 		return;
7267 
7268 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7269 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7270 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7271 		 * than pkt_end, but that's because it's also less than pkt.
7272 		 */
7273 		return;
7274 
7275 	new_range = dst_reg->off;
7276 	if (range_right_open)
7277 		new_range--;
7278 
7279 	/* Examples for register markings:
7280 	 *
7281 	 * pkt_data in dst register:
7282 	 *
7283 	 *   r2 = r3;
7284 	 *   r2 += 8;
7285 	 *   if (r2 > pkt_end) goto <handle exception>
7286 	 *   <access okay>
7287 	 *
7288 	 *   r2 = r3;
7289 	 *   r2 += 8;
7290 	 *   if (r2 < pkt_end) goto <access okay>
7291 	 *   <handle exception>
7292 	 *
7293 	 *   Where:
7294 	 *     r2 == dst_reg, pkt_end == src_reg
7295 	 *     r2=pkt(id=n,off=8,r=0)
7296 	 *     r3=pkt(id=n,off=0,r=0)
7297 	 *
7298 	 * pkt_data in src register:
7299 	 *
7300 	 *   r2 = r3;
7301 	 *   r2 += 8;
7302 	 *   if (pkt_end >= r2) goto <access okay>
7303 	 *   <handle exception>
7304 	 *
7305 	 *   r2 = r3;
7306 	 *   r2 += 8;
7307 	 *   if (pkt_end <= r2) goto <handle exception>
7308 	 *   <access okay>
7309 	 *
7310 	 *   Where:
7311 	 *     pkt_end == dst_reg, r2 == src_reg
7312 	 *     r2=pkt(id=n,off=8,r=0)
7313 	 *     r3=pkt(id=n,off=0,r=0)
7314 	 *
7315 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7316 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7317 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7318 	 * the check.
7319 	 */
7320 
7321 	/* If our ids match, then we must have the same max_value.  And we
7322 	 * don't care about the other reg's fixed offset, since if it's too big
7323 	 * the range won't allow anything.
7324 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7325 	 */
7326 	for (i = 0; i <= vstate->curframe; i++)
7327 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7328 					 new_range);
7329 }
7330 
7331 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7332 {
7333 	struct tnum subreg = tnum_subreg(reg->var_off);
7334 	s32 sval = (s32)val;
7335 
7336 	switch (opcode) {
7337 	case BPF_JEQ:
7338 		if (tnum_is_const(subreg))
7339 			return !!tnum_equals_const(subreg, val);
7340 		break;
7341 	case BPF_JNE:
7342 		if (tnum_is_const(subreg))
7343 			return !tnum_equals_const(subreg, val);
7344 		break;
7345 	case BPF_JSET:
7346 		if ((~subreg.mask & subreg.value) & val)
7347 			return 1;
7348 		if (!((subreg.mask | subreg.value) & val))
7349 			return 0;
7350 		break;
7351 	case BPF_JGT:
7352 		if (reg->u32_min_value > val)
7353 			return 1;
7354 		else if (reg->u32_max_value <= val)
7355 			return 0;
7356 		break;
7357 	case BPF_JSGT:
7358 		if (reg->s32_min_value > sval)
7359 			return 1;
7360 		else if (reg->s32_max_value <= sval)
7361 			return 0;
7362 		break;
7363 	case BPF_JLT:
7364 		if (reg->u32_max_value < val)
7365 			return 1;
7366 		else if (reg->u32_min_value >= val)
7367 			return 0;
7368 		break;
7369 	case BPF_JSLT:
7370 		if (reg->s32_max_value < sval)
7371 			return 1;
7372 		else if (reg->s32_min_value >= sval)
7373 			return 0;
7374 		break;
7375 	case BPF_JGE:
7376 		if (reg->u32_min_value >= val)
7377 			return 1;
7378 		else if (reg->u32_max_value < val)
7379 			return 0;
7380 		break;
7381 	case BPF_JSGE:
7382 		if (reg->s32_min_value >= sval)
7383 			return 1;
7384 		else if (reg->s32_max_value < sval)
7385 			return 0;
7386 		break;
7387 	case BPF_JLE:
7388 		if (reg->u32_max_value <= val)
7389 			return 1;
7390 		else if (reg->u32_min_value > val)
7391 			return 0;
7392 		break;
7393 	case BPF_JSLE:
7394 		if (reg->s32_max_value <= sval)
7395 			return 1;
7396 		else if (reg->s32_min_value > sval)
7397 			return 0;
7398 		break;
7399 	}
7400 
7401 	return -1;
7402 }
7403 
7404 
7405 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7406 {
7407 	s64 sval = (s64)val;
7408 
7409 	switch (opcode) {
7410 	case BPF_JEQ:
7411 		if (tnum_is_const(reg->var_off))
7412 			return !!tnum_equals_const(reg->var_off, val);
7413 		break;
7414 	case BPF_JNE:
7415 		if (tnum_is_const(reg->var_off))
7416 			return !tnum_equals_const(reg->var_off, val);
7417 		break;
7418 	case BPF_JSET:
7419 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7420 			return 1;
7421 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7422 			return 0;
7423 		break;
7424 	case BPF_JGT:
7425 		if (reg->umin_value > val)
7426 			return 1;
7427 		else if (reg->umax_value <= val)
7428 			return 0;
7429 		break;
7430 	case BPF_JSGT:
7431 		if (reg->smin_value > sval)
7432 			return 1;
7433 		else if (reg->smax_value <= sval)
7434 			return 0;
7435 		break;
7436 	case BPF_JLT:
7437 		if (reg->umax_value < val)
7438 			return 1;
7439 		else if (reg->umin_value >= val)
7440 			return 0;
7441 		break;
7442 	case BPF_JSLT:
7443 		if (reg->smax_value < sval)
7444 			return 1;
7445 		else if (reg->smin_value >= sval)
7446 			return 0;
7447 		break;
7448 	case BPF_JGE:
7449 		if (reg->umin_value >= val)
7450 			return 1;
7451 		else if (reg->umax_value < val)
7452 			return 0;
7453 		break;
7454 	case BPF_JSGE:
7455 		if (reg->smin_value >= sval)
7456 			return 1;
7457 		else if (reg->smax_value < sval)
7458 			return 0;
7459 		break;
7460 	case BPF_JLE:
7461 		if (reg->umax_value <= val)
7462 			return 1;
7463 		else if (reg->umin_value > val)
7464 			return 0;
7465 		break;
7466 	case BPF_JSLE:
7467 		if (reg->smax_value <= sval)
7468 			return 1;
7469 		else if (reg->smin_value > sval)
7470 			return 0;
7471 		break;
7472 	}
7473 
7474 	return -1;
7475 }
7476 
7477 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7478  * and return:
7479  *  1 - branch will be taken and "goto target" will be executed
7480  *  0 - branch will not be taken and fall-through to next insn
7481  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7482  *      range [0,10]
7483  */
7484 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7485 			   bool is_jmp32)
7486 {
7487 	if (__is_pointer_value(false, reg)) {
7488 		if (!reg_type_not_null(reg->type))
7489 			return -1;
7490 
7491 		/* If pointer is valid tests against zero will fail so we can
7492 		 * use this to direct branch taken.
7493 		 */
7494 		if (val != 0)
7495 			return -1;
7496 
7497 		switch (opcode) {
7498 		case BPF_JEQ:
7499 			return 0;
7500 		case BPF_JNE:
7501 			return 1;
7502 		default:
7503 			return -1;
7504 		}
7505 	}
7506 
7507 	if (is_jmp32)
7508 		return is_branch32_taken(reg, val, opcode);
7509 	return is_branch64_taken(reg, val, opcode);
7510 }
7511 
7512 static int flip_opcode(u32 opcode)
7513 {
7514 	/* How can we transform "a <op> b" into "b <op> a"? */
7515 	static const u8 opcode_flip[16] = {
7516 		/* these stay the same */
7517 		[BPF_JEQ  >> 4] = BPF_JEQ,
7518 		[BPF_JNE  >> 4] = BPF_JNE,
7519 		[BPF_JSET >> 4] = BPF_JSET,
7520 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7521 		[BPF_JGE  >> 4] = BPF_JLE,
7522 		[BPF_JGT  >> 4] = BPF_JLT,
7523 		[BPF_JLE  >> 4] = BPF_JGE,
7524 		[BPF_JLT  >> 4] = BPF_JGT,
7525 		[BPF_JSGE >> 4] = BPF_JSLE,
7526 		[BPF_JSGT >> 4] = BPF_JSLT,
7527 		[BPF_JSLE >> 4] = BPF_JSGE,
7528 		[BPF_JSLT >> 4] = BPF_JSGT
7529 	};
7530 	return opcode_flip[opcode >> 4];
7531 }
7532 
7533 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7534 				   struct bpf_reg_state *src_reg,
7535 				   u8 opcode)
7536 {
7537 	struct bpf_reg_state *pkt;
7538 
7539 	if (src_reg->type == PTR_TO_PACKET_END) {
7540 		pkt = dst_reg;
7541 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7542 		pkt = src_reg;
7543 		opcode = flip_opcode(opcode);
7544 	} else {
7545 		return -1;
7546 	}
7547 
7548 	if (pkt->range >= 0)
7549 		return -1;
7550 
7551 	switch (opcode) {
7552 	case BPF_JLE:
7553 		/* pkt <= pkt_end */
7554 		fallthrough;
7555 	case BPF_JGT:
7556 		/* pkt > pkt_end */
7557 		if (pkt->range == BEYOND_PKT_END)
7558 			/* pkt has at last one extra byte beyond pkt_end */
7559 			return opcode == BPF_JGT;
7560 		break;
7561 	case BPF_JLT:
7562 		/* pkt < pkt_end */
7563 		fallthrough;
7564 	case BPF_JGE:
7565 		/* pkt >= pkt_end */
7566 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7567 			return opcode == BPF_JGE;
7568 		break;
7569 	}
7570 	return -1;
7571 }
7572 
7573 /* Adjusts the register min/max values in the case that the dst_reg is the
7574  * variable register that we are working on, and src_reg is a constant or we're
7575  * simply doing a BPF_K check.
7576  * In JEQ/JNE cases we also adjust the var_off values.
7577  */
7578 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7579 			    struct bpf_reg_state *false_reg,
7580 			    u64 val, u32 val32,
7581 			    u8 opcode, bool is_jmp32)
7582 {
7583 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7584 	struct tnum false_64off = false_reg->var_off;
7585 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7586 	struct tnum true_64off = true_reg->var_off;
7587 	s64 sval = (s64)val;
7588 	s32 sval32 = (s32)val32;
7589 
7590 	/* If the dst_reg is a pointer, we can't learn anything about its
7591 	 * variable offset from the compare (unless src_reg were a pointer into
7592 	 * the same object, but we don't bother with that.
7593 	 * Since false_reg and true_reg have the same type by construction, we
7594 	 * only need to check one of them for pointerness.
7595 	 */
7596 	if (__is_pointer_value(false, false_reg))
7597 		return;
7598 
7599 	switch (opcode) {
7600 	case BPF_JEQ:
7601 	case BPF_JNE:
7602 	{
7603 		struct bpf_reg_state *reg =
7604 			opcode == BPF_JEQ ? true_reg : false_reg;
7605 
7606 		/* JEQ/JNE comparison doesn't change the register equivalence.
7607 		 * r1 = r2;
7608 		 * if (r1 == 42) goto label;
7609 		 * ...
7610 		 * label: // here both r1 and r2 are known to be 42.
7611 		 *
7612 		 * Hence when marking register as known preserve it's ID.
7613 		 */
7614 		if (is_jmp32)
7615 			__mark_reg32_known(reg, val32);
7616 		else
7617 			___mark_reg_known(reg, val);
7618 		break;
7619 	}
7620 	case BPF_JSET:
7621 		if (is_jmp32) {
7622 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7623 			if (is_power_of_2(val32))
7624 				true_32off = tnum_or(true_32off,
7625 						     tnum_const(val32));
7626 		} else {
7627 			false_64off = tnum_and(false_64off, tnum_const(~val));
7628 			if (is_power_of_2(val))
7629 				true_64off = tnum_or(true_64off,
7630 						     tnum_const(val));
7631 		}
7632 		break;
7633 	case BPF_JGE:
7634 	case BPF_JGT:
7635 	{
7636 		if (is_jmp32) {
7637 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7638 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7639 
7640 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7641 						       false_umax);
7642 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7643 						      true_umin);
7644 		} else {
7645 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7646 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7647 
7648 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7649 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7650 		}
7651 		break;
7652 	}
7653 	case BPF_JSGE:
7654 	case BPF_JSGT:
7655 	{
7656 		if (is_jmp32) {
7657 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7658 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7659 
7660 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7661 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7662 		} else {
7663 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7664 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7665 
7666 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7667 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7668 		}
7669 		break;
7670 	}
7671 	case BPF_JLE:
7672 	case BPF_JLT:
7673 	{
7674 		if (is_jmp32) {
7675 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7676 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7677 
7678 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7679 						       false_umin);
7680 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7681 						      true_umax);
7682 		} else {
7683 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7684 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7685 
7686 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7687 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7688 		}
7689 		break;
7690 	}
7691 	case BPF_JSLE:
7692 	case BPF_JSLT:
7693 	{
7694 		if (is_jmp32) {
7695 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7696 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7697 
7698 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7699 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7700 		} else {
7701 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7702 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7703 
7704 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7705 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7706 		}
7707 		break;
7708 	}
7709 	default:
7710 		return;
7711 	}
7712 
7713 	if (is_jmp32) {
7714 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7715 					     tnum_subreg(false_32off));
7716 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7717 					    tnum_subreg(true_32off));
7718 		__reg_combine_32_into_64(false_reg);
7719 		__reg_combine_32_into_64(true_reg);
7720 	} else {
7721 		false_reg->var_off = false_64off;
7722 		true_reg->var_off = true_64off;
7723 		__reg_combine_64_into_32(false_reg);
7724 		__reg_combine_64_into_32(true_reg);
7725 	}
7726 }
7727 
7728 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7729  * the variable reg.
7730  */
7731 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7732 				struct bpf_reg_state *false_reg,
7733 				u64 val, u32 val32,
7734 				u8 opcode, bool is_jmp32)
7735 {
7736 	opcode = flip_opcode(opcode);
7737 	/* This uses zero as "not present in table"; luckily the zero opcode,
7738 	 * BPF_JA, can't get here.
7739 	 */
7740 	if (opcode)
7741 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7742 }
7743 
7744 /* Regs are known to be equal, so intersect their min/max/var_off */
7745 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7746 				  struct bpf_reg_state *dst_reg)
7747 {
7748 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7749 							dst_reg->umin_value);
7750 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7751 							dst_reg->umax_value);
7752 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7753 							dst_reg->smin_value);
7754 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7755 							dst_reg->smax_value);
7756 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7757 							     dst_reg->var_off);
7758 	/* We might have learned new bounds from the var_off. */
7759 	__update_reg_bounds(src_reg);
7760 	__update_reg_bounds(dst_reg);
7761 	/* We might have learned something about the sign bit. */
7762 	__reg_deduce_bounds(src_reg);
7763 	__reg_deduce_bounds(dst_reg);
7764 	/* We might have learned some bits from the bounds. */
7765 	__reg_bound_offset(src_reg);
7766 	__reg_bound_offset(dst_reg);
7767 	/* Intersecting with the old var_off might have improved our bounds
7768 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7769 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
7770 	 */
7771 	__update_reg_bounds(src_reg);
7772 	__update_reg_bounds(dst_reg);
7773 }
7774 
7775 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7776 				struct bpf_reg_state *true_dst,
7777 				struct bpf_reg_state *false_src,
7778 				struct bpf_reg_state *false_dst,
7779 				u8 opcode)
7780 {
7781 	switch (opcode) {
7782 	case BPF_JEQ:
7783 		__reg_combine_min_max(true_src, true_dst);
7784 		break;
7785 	case BPF_JNE:
7786 		__reg_combine_min_max(false_src, false_dst);
7787 		break;
7788 	}
7789 }
7790 
7791 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7792 				 struct bpf_reg_state *reg, u32 id,
7793 				 bool is_null)
7794 {
7795 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
7796 	    !WARN_ON_ONCE(!reg->id)) {
7797 		/* Old offset (both fixed and variable parts) should
7798 		 * have been known-zero, because we don't allow pointer
7799 		 * arithmetic on pointers that might be NULL.
7800 		 */
7801 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7802 				 !tnum_equals_const(reg->var_off, 0) ||
7803 				 reg->off)) {
7804 			__mark_reg_known_zero(reg);
7805 			reg->off = 0;
7806 		}
7807 		if (is_null) {
7808 			reg->type = SCALAR_VALUE;
7809 			/* We don't need id and ref_obj_id from this point
7810 			 * onwards anymore, thus we should better reset it,
7811 			 * so that state pruning has chances to take effect.
7812 			 */
7813 			reg->id = 0;
7814 			reg->ref_obj_id = 0;
7815 
7816 			return;
7817 		}
7818 
7819 		mark_ptr_not_null_reg(reg);
7820 
7821 		if (!reg_may_point_to_spin_lock(reg)) {
7822 			/* For not-NULL ptr, reg->ref_obj_id will be reset
7823 			 * in release_reg_references().
7824 			 *
7825 			 * reg->id is still used by spin_lock ptr. Other
7826 			 * than spin_lock ptr type, reg->id can be reset.
7827 			 */
7828 			reg->id = 0;
7829 		}
7830 	}
7831 }
7832 
7833 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7834 				    bool is_null)
7835 {
7836 	struct bpf_reg_state *reg;
7837 	int i;
7838 
7839 	for (i = 0; i < MAX_BPF_REG; i++)
7840 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7841 
7842 	bpf_for_each_spilled_reg(i, state, reg) {
7843 		if (!reg)
7844 			continue;
7845 		mark_ptr_or_null_reg(state, reg, id, is_null);
7846 	}
7847 }
7848 
7849 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7850  * be folded together at some point.
7851  */
7852 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7853 				  bool is_null)
7854 {
7855 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7856 	struct bpf_reg_state *regs = state->regs;
7857 	u32 ref_obj_id = regs[regno].ref_obj_id;
7858 	u32 id = regs[regno].id;
7859 	int i;
7860 
7861 	if (ref_obj_id && ref_obj_id == id && is_null)
7862 		/* regs[regno] is in the " == NULL" branch.
7863 		 * No one could have freed the reference state before
7864 		 * doing the NULL check.
7865 		 */
7866 		WARN_ON_ONCE(release_reference_state(state, id));
7867 
7868 	for (i = 0; i <= vstate->curframe; i++)
7869 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7870 }
7871 
7872 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7873 				   struct bpf_reg_state *dst_reg,
7874 				   struct bpf_reg_state *src_reg,
7875 				   struct bpf_verifier_state *this_branch,
7876 				   struct bpf_verifier_state *other_branch)
7877 {
7878 	if (BPF_SRC(insn->code) != BPF_X)
7879 		return false;
7880 
7881 	/* Pointers are always 64-bit. */
7882 	if (BPF_CLASS(insn->code) == BPF_JMP32)
7883 		return false;
7884 
7885 	switch (BPF_OP(insn->code)) {
7886 	case BPF_JGT:
7887 		if ((dst_reg->type == PTR_TO_PACKET &&
7888 		     src_reg->type == PTR_TO_PACKET_END) ||
7889 		    (dst_reg->type == PTR_TO_PACKET_META &&
7890 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7891 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7892 			find_good_pkt_pointers(this_branch, dst_reg,
7893 					       dst_reg->type, false);
7894 			mark_pkt_end(other_branch, insn->dst_reg, true);
7895 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7896 			    src_reg->type == PTR_TO_PACKET) ||
7897 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7898 			    src_reg->type == PTR_TO_PACKET_META)) {
7899 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
7900 			find_good_pkt_pointers(other_branch, src_reg,
7901 					       src_reg->type, true);
7902 			mark_pkt_end(this_branch, insn->src_reg, false);
7903 		} else {
7904 			return false;
7905 		}
7906 		break;
7907 	case BPF_JLT:
7908 		if ((dst_reg->type == PTR_TO_PACKET &&
7909 		     src_reg->type == PTR_TO_PACKET_END) ||
7910 		    (dst_reg->type == PTR_TO_PACKET_META &&
7911 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7912 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7913 			find_good_pkt_pointers(other_branch, dst_reg,
7914 					       dst_reg->type, true);
7915 			mark_pkt_end(this_branch, insn->dst_reg, false);
7916 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7917 			    src_reg->type == PTR_TO_PACKET) ||
7918 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7919 			    src_reg->type == PTR_TO_PACKET_META)) {
7920 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
7921 			find_good_pkt_pointers(this_branch, src_reg,
7922 					       src_reg->type, false);
7923 			mark_pkt_end(other_branch, insn->src_reg, true);
7924 		} else {
7925 			return false;
7926 		}
7927 		break;
7928 	case BPF_JGE:
7929 		if ((dst_reg->type == PTR_TO_PACKET &&
7930 		     src_reg->type == PTR_TO_PACKET_END) ||
7931 		    (dst_reg->type == PTR_TO_PACKET_META &&
7932 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7933 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7934 			find_good_pkt_pointers(this_branch, dst_reg,
7935 					       dst_reg->type, true);
7936 			mark_pkt_end(other_branch, insn->dst_reg, false);
7937 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7938 			    src_reg->type == PTR_TO_PACKET) ||
7939 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7940 			    src_reg->type == PTR_TO_PACKET_META)) {
7941 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7942 			find_good_pkt_pointers(other_branch, src_reg,
7943 					       src_reg->type, false);
7944 			mark_pkt_end(this_branch, insn->src_reg, true);
7945 		} else {
7946 			return false;
7947 		}
7948 		break;
7949 	case BPF_JLE:
7950 		if ((dst_reg->type == PTR_TO_PACKET &&
7951 		     src_reg->type == PTR_TO_PACKET_END) ||
7952 		    (dst_reg->type == PTR_TO_PACKET_META &&
7953 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7954 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7955 			find_good_pkt_pointers(other_branch, dst_reg,
7956 					       dst_reg->type, false);
7957 			mark_pkt_end(this_branch, insn->dst_reg, true);
7958 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7959 			    src_reg->type == PTR_TO_PACKET) ||
7960 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7961 			    src_reg->type == PTR_TO_PACKET_META)) {
7962 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7963 			find_good_pkt_pointers(this_branch, src_reg,
7964 					       src_reg->type, true);
7965 			mark_pkt_end(other_branch, insn->src_reg, false);
7966 		} else {
7967 			return false;
7968 		}
7969 		break;
7970 	default:
7971 		return false;
7972 	}
7973 
7974 	return true;
7975 }
7976 
7977 static void find_equal_scalars(struct bpf_verifier_state *vstate,
7978 			       struct bpf_reg_state *known_reg)
7979 {
7980 	struct bpf_func_state *state;
7981 	struct bpf_reg_state *reg;
7982 	int i, j;
7983 
7984 	for (i = 0; i <= vstate->curframe; i++) {
7985 		state = vstate->frame[i];
7986 		for (j = 0; j < MAX_BPF_REG; j++) {
7987 			reg = &state->regs[j];
7988 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7989 				*reg = *known_reg;
7990 		}
7991 
7992 		bpf_for_each_spilled_reg(j, state, reg) {
7993 			if (!reg)
7994 				continue;
7995 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7996 				*reg = *known_reg;
7997 		}
7998 	}
7999 }
8000 
8001 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8002 			     struct bpf_insn *insn, int *insn_idx)
8003 {
8004 	struct bpf_verifier_state *this_branch = env->cur_state;
8005 	struct bpf_verifier_state *other_branch;
8006 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8007 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8008 	u8 opcode = BPF_OP(insn->code);
8009 	bool is_jmp32;
8010 	int pred = -1;
8011 	int err;
8012 
8013 	/* Only conditional jumps are expected to reach here. */
8014 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8015 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8016 		return -EINVAL;
8017 	}
8018 
8019 	if (BPF_SRC(insn->code) == BPF_X) {
8020 		if (insn->imm != 0) {
8021 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8022 			return -EINVAL;
8023 		}
8024 
8025 		/* check src1 operand */
8026 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8027 		if (err)
8028 			return err;
8029 
8030 		if (is_pointer_value(env, insn->src_reg)) {
8031 			verbose(env, "R%d pointer comparison prohibited\n",
8032 				insn->src_reg);
8033 			return -EACCES;
8034 		}
8035 		src_reg = &regs[insn->src_reg];
8036 	} else {
8037 		if (insn->src_reg != BPF_REG_0) {
8038 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8039 			return -EINVAL;
8040 		}
8041 	}
8042 
8043 	/* check src2 operand */
8044 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8045 	if (err)
8046 		return err;
8047 
8048 	dst_reg = &regs[insn->dst_reg];
8049 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8050 
8051 	if (BPF_SRC(insn->code) == BPF_K) {
8052 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8053 	} else if (src_reg->type == SCALAR_VALUE &&
8054 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8055 		pred = is_branch_taken(dst_reg,
8056 				       tnum_subreg(src_reg->var_off).value,
8057 				       opcode,
8058 				       is_jmp32);
8059 	} else if (src_reg->type == SCALAR_VALUE &&
8060 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8061 		pred = is_branch_taken(dst_reg,
8062 				       src_reg->var_off.value,
8063 				       opcode,
8064 				       is_jmp32);
8065 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8066 		   reg_is_pkt_pointer_any(src_reg) &&
8067 		   !is_jmp32) {
8068 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8069 	}
8070 
8071 	if (pred >= 0) {
8072 		/* If we get here with a dst_reg pointer type it is because
8073 		 * above is_branch_taken() special cased the 0 comparison.
8074 		 */
8075 		if (!__is_pointer_value(false, dst_reg))
8076 			err = mark_chain_precision(env, insn->dst_reg);
8077 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8078 		    !__is_pointer_value(false, src_reg))
8079 			err = mark_chain_precision(env, insn->src_reg);
8080 		if (err)
8081 			return err;
8082 	}
8083 	if (pred == 1) {
8084 		/* only follow the goto, ignore fall-through */
8085 		*insn_idx += insn->off;
8086 		return 0;
8087 	} else if (pred == 0) {
8088 		/* only follow fall-through branch, since
8089 		 * that's where the program will go
8090 		 */
8091 		return 0;
8092 	}
8093 
8094 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8095 				  false);
8096 	if (!other_branch)
8097 		return -EFAULT;
8098 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8099 
8100 	/* detect if we are comparing against a constant value so we can adjust
8101 	 * our min/max values for our dst register.
8102 	 * this is only legit if both are scalars (or pointers to the same
8103 	 * object, I suppose, but we don't support that right now), because
8104 	 * otherwise the different base pointers mean the offsets aren't
8105 	 * comparable.
8106 	 */
8107 	if (BPF_SRC(insn->code) == BPF_X) {
8108 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8109 
8110 		if (dst_reg->type == SCALAR_VALUE &&
8111 		    src_reg->type == SCALAR_VALUE) {
8112 			if (tnum_is_const(src_reg->var_off) ||
8113 			    (is_jmp32 &&
8114 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8115 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8116 						dst_reg,
8117 						src_reg->var_off.value,
8118 						tnum_subreg(src_reg->var_off).value,
8119 						opcode, is_jmp32);
8120 			else if (tnum_is_const(dst_reg->var_off) ||
8121 				 (is_jmp32 &&
8122 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8123 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8124 						    src_reg,
8125 						    dst_reg->var_off.value,
8126 						    tnum_subreg(dst_reg->var_off).value,
8127 						    opcode, is_jmp32);
8128 			else if (!is_jmp32 &&
8129 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8130 				/* Comparing for equality, we can combine knowledge */
8131 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8132 						    &other_branch_regs[insn->dst_reg],
8133 						    src_reg, dst_reg, opcode);
8134 			if (src_reg->id &&
8135 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8136 				find_equal_scalars(this_branch, src_reg);
8137 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8138 			}
8139 
8140 		}
8141 	} else if (dst_reg->type == SCALAR_VALUE) {
8142 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8143 					dst_reg, insn->imm, (u32)insn->imm,
8144 					opcode, is_jmp32);
8145 	}
8146 
8147 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8148 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8149 		find_equal_scalars(this_branch, dst_reg);
8150 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8151 	}
8152 
8153 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8154 	 * NOTE: these optimizations below are related with pointer comparison
8155 	 *       which will never be JMP32.
8156 	 */
8157 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8158 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8159 	    reg_type_may_be_null(dst_reg->type)) {
8160 		/* Mark all identical registers in each branch as either
8161 		 * safe or unknown depending R == 0 or R != 0 conditional.
8162 		 */
8163 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8164 				      opcode == BPF_JNE);
8165 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8166 				      opcode == BPF_JEQ);
8167 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8168 					   this_branch, other_branch) &&
8169 		   is_pointer_value(env, insn->dst_reg)) {
8170 		verbose(env, "R%d pointer comparison prohibited\n",
8171 			insn->dst_reg);
8172 		return -EACCES;
8173 	}
8174 	if (env->log.level & BPF_LOG_LEVEL)
8175 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8176 	return 0;
8177 }
8178 
8179 /* verify BPF_LD_IMM64 instruction */
8180 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8181 {
8182 	struct bpf_insn_aux_data *aux = cur_aux(env);
8183 	struct bpf_reg_state *regs = cur_regs(env);
8184 	struct bpf_reg_state *dst_reg;
8185 	struct bpf_map *map;
8186 	int err;
8187 
8188 	if (BPF_SIZE(insn->code) != BPF_DW) {
8189 		verbose(env, "invalid BPF_LD_IMM insn\n");
8190 		return -EINVAL;
8191 	}
8192 	if (insn->off != 0) {
8193 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8194 		return -EINVAL;
8195 	}
8196 
8197 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8198 	if (err)
8199 		return err;
8200 
8201 	dst_reg = &regs[insn->dst_reg];
8202 	if (insn->src_reg == 0) {
8203 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8204 
8205 		dst_reg->type = SCALAR_VALUE;
8206 		__mark_reg_known(&regs[insn->dst_reg], imm);
8207 		return 0;
8208 	}
8209 
8210 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8211 		mark_reg_known_zero(env, regs, insn->dst_reg);
8212 
8213 		dst_reg->type = aux->btf_var.reg_type;
8214 		switch (dst_reg->type) {
8215 		case PTR_TO_MEM:
8216 			dst_reg->mem_size = aux->btf_var.mem_size;
8217 			break;
8218 		case PTR_TO_BTF_ID:
8219 		case PTR_TO_PERCPU_BTF_ID:
8220 			dst_reg->btf = aux->btf_var.btf;
8221 			dst_reg->btf_id = aux->btf_var.btf_id;
8222 			break;
8223 		default:
8224 			verbose(env, "bpf verifier is misconfigured\n");
8225 			return -EFAULT;
8226 		}
8227 		return 0;
8228 	}
8229 
8230 	map = env->used_maps[aux->map_index];
8231 	mark_reg_known_zero(env, regs, insn->dst_reg);
8232 	dst_reg->map_ptr = map;
8233 
8234 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8235 		dst_reg->type = PTR_TO_MAP_VALUE;
8236 		dst_reg->off = aux->map_off;
8237 		if (map_value_has_spin_lock(map))
8238 			dst_reg->id = ++env->id_gen;
8239 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8240 		dst_reg->type = CONST_PTR_TO_MAP;
8241 	} else {
8242 		verbose(env, "bpf verifier is misconfigured\n");
8243 		return -EINVAL;
8244 	}
8245 
8246 	return 0;
8247 }
8248 
8249 static bool may_access_skb(enum bpf_prog_type type)
8250 {
8251 	switch (type) {
8252 	case BPF_PROG_TYPE_SOCKET_FILTER:
8253 	case BPF_PROG_TYPE_SCHED_CLS:
8254 	case BPF_PROG_TYPE_SCHED_ACT:
8255 		return true;
8256 	default:
8257 		return false;
8258 	}
8259 }
8260 
8261 /* verify safety of LD_ABS|LD_IND instructions:
8262  * - they can only appear in the programs where ctx == skb
8263  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8264  *   preserve R6-R9, and store return value into R0
8265  *
8266  * Implicit input:
8267  *   ctx == skb == R6 == CTX
8268  *
8269  * Explicit input:
8270  *   SRC == any register
8271  *   IMM == 32-bit immediate
8272  *
8273  * Output:
8274  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8275  */
8276 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8277 {
8278 	struct bpf_reg_state *regs = cur_regs(env);
8279 	static const int ctx_reg = BPF_REG_6;
8280 	u8 mode = BPF_MODE(insn->code);
8281 	int i, err;
8282 
8283 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8284 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8285 		return -EINVAL;
8286 	}
8287 
8288 	if (!env->ops->gen_ld_abs) {
8289 		verbose(env, "bpf verifier is misconfigured\n");
8290 		return -EINVAL;
8291 	}
8292 
8293 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8294 	    BPF_SIZE(insn->code) == BPF_DW ||
8295 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8296 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8297 		return -EINVAL;
8298 	}
8299 
8300 	/* check whether implicit source operand (register R6) is readable */
8301 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8302 	if (err)
8303 		return err;
8304 
8305 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8306 	 * gen_ld_abs() may terminate the program at runtime, leading to
8307 	 * reference leak.
8308 	 */
8309 	err = check_reference_leak(env);
8310 	if (err) {
8311 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8312 		return err;
8313 	}
8314 
8315 	if (env->cur_state->active_spin_lock) {
8316 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8317 		return -EINVAL;
8318 	}
8319 
8320 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8321 		verbose(env,
8322 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8323 		return -EINVAL;
8324 	}
8325 
8326 	if (mode == BPF_IND) {
8327 		/* check explicit source operand */
8328 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8329 		if (err)
8330 			return err;
8331 	}
8332 
8333 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8334 	if (err < 0)
8335 		return err;
8336 
8337 	/* reset caller saved regs to unreadable */
8338 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8339 		mark_reg_not_init(env, regs, caller_saved[i]);
8340 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8341 	}
8342 
8343 	/* mark destination R0 register as readable, since it contains
8344 	 * the value fetched from the packet.
8345 	 * Already marked as written above.
8346 	 */
8347 	mark_reg_unknown(env, regs, BPF_REG_0);
8348 	/* ld_abs load up to 32-bit skb data. */
8349 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8350 	return 0;
8351 }
8352 
8353 static int check_return_code(struct bpf_verifier_env *env)
8354 {
8355 	struct tnum enforce_attach_type_range = tnum_unknown;
8356 	const struct bpf_prog *prog = env->prog;
8357 	struct bpf_reg_state *reg;
8358 	struct tnum range = tnum_range(0, 1);
8359 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8360 	int err;
8361 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8362 
8363 	/* LSM and struct_ops func-ptr's return type could be "void" */
8364 	if (!is_subprog &&
8365 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8366 	     prog_type == BPF_PROG_TYPE_LSM) &&
8367 	    !prog->aux->attach_func_proto->type)
8368 		return 0;
8369 
8370 	/* eBPF calling convetion is such that R0 is used
8371 	 * to return the value from eBPF program.
8372 	 * Make sure that it's readable at this time
8373 	 * of bpf_exit, which means that program wrote
8374 	 * something into it earlier
8375 	 */
8376 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8377 	if (err)
8378 		return err;
8379 
8380 	if (is_pointer_value(env, BPF_REG_0)) {
8381 		verbose(env, "R0 leaks addr as return value\n");
8382 		return -EACCES;
8383 	}
8384 
8385 	reg = cur_regs(env) + BPF_REG_0;
8386 	if (is_subprog) {
8387 		if (reg->type != SCALAR_VALUE) {
8388 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8389 				reg_type_str[reg->type]);
8390 			return -EINVAL;
8391 		}
8392 		return 0;
8393 	}
8394 
8395 	switch (prog_type) {
8396 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8397 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8398 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8399 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8400 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8401 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8402 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8403 			range = tnum_range(1, 1);
8404 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8405 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8406 			range = tnum_range(0, 3);
8407 		break;
8408 	case BPF_PROG_TYPE_CGROUP_SKB:
8409 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8410 			range = tnum_range(0, 3);
8411 			enforce_attach_type_range = tnum_range(2, 3);
8412 		}
8413 		break;
8414 	case BPF_PROG_TYPE_CGROUP_SOCK:
8415 	case BPF_PROG_TYPE_SOCK_OPS:
8416 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8417 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8418 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8419 		break;
8420 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8421 		if (!env->prog->aux->attach_btf_id)
8422 			return 0;
8423 		range = tnum_const(0);
8424 		break;
8425 	case BPF_PROG_TYPE_TRACING:
8426 		switch (env->prog->expected_attach_type) {
8427 		case BPF_TRACE_FENTRY:
8428 		case BPF_TRACE_FEXIT:
8429 			range = tnum_const(0);
8430 			break;
8431 		case BPF_TRACE_RAW_TP:
8432 		case BPF_MODIFY_RETURN:
8433 			return 0;
8434 		case BPF_TRACE_ITER:
8435 			break;
8436 		default:
8437 			return -ENOTSUPP;
8438 		}
8439 		break;
8440 	case BPF_PROG_TYPE_SK_LOOKUP:
8441 		range = tnum_range(SK_DROP, SK_PASS);
8442 		break;
8443 	case BPF_PROG_TYPE_EXT:
8444 		/* freplace program can return anything as its return value
8445 		 * depends on the to-be-replaced kernel func or bpf program.
8446 		 */
8447 	default:
8448 		return 0;
8449 	}
8450 
8451 	if (reg->type != SCALAR_VALUE) {
8452 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8453 			reg_type_str[reg->type]);
8454 		return -EINVAL;
8455 	}
8456 
8457 	if (!tnum_in(range, reg->var_off)) {
8458 		char tn_buf[48];
8459 
8460 		verbose(env, "At program exit the register R0 ");
8461 		if (!tnum_is_unknown(reg->var_off)) {
8462 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8463 			verbose(env, "has value %s", tn_buf);
8464 		} else {
8465 			verbose(env, "has unknown scalar value");
8466 		}
8467 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8468 		verbose(env, " should have been in %s\n", tn_buf);
8469 		return -EINVAL;
8470 	}
8471 
8472 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8473 	    tnum_in(enforce_attach_type_range, reg->var_off))
8474 		env->prog->enforce_expected_attach_type = 1;
8475 	return 0;
8476 }
8477 
8478 /* non-recursive DFS pseudo code
8479  * 1  procedure DFS-iterative(G,v):
8480  * 2      label v as discovered
8481  * 3      let S be a stack
8482  * 4      S.push(v)
8483  * 5      while S is not empty
8484  * 6            t <- S.pop()
8485  * 7            if t is what we're looking for:
8486  * 8                return t
8487  * 9            for all edges e in G.adjacentEdges(t) do
8488  * 10               if edge e is already labelled
8489  * 11                   continue with the next edge
8490  * 12               w <- G.adjacentVertex(t,e)
8491  * 13               if vertex w is not discovered and not explored
8492  * 14                   label e as tree-edge
8493  * 15                   label w as discovered
8494  * 16                   S.push(w)
8495  * 17                   continue at 5
8496  * 18               else if vertex w is discovered
8497  * 19                   label e as back-edge
8498  * 20               else
8499  * 21                   // vertex w is explored
8500  * 22                   label e as forward- or cross-edge
8501  * 23           label t as explored
8502  * 24           S.pop()
8503  *
8504  * convention:
8505  * 0x10 - discovered
8506  * 0x11 - discovered and fall-through edge labelled
8507  * 0x12 - discovered and fall-through and branch edges labelled
8508  * 0x20 - explored
8509  */
8510 
8511 enum {
8512 	DISCOVERED = 0x10,
8513 	EXPLORED = 0x20,
8514 	FALLTHROUGH = 1,
8515 	BRANCH = 2,
8516 };
8517 
8518 static u32 state_htab_size(struct bpf_verifier_env *env)
8519 {
8520 	return env->prog->len;
8521 }
8522 
8523 static struct bpf_verifier_state_list **explored_state(
8524 					struct bpf_verifier_env *env,
8525 					int idx)
8526 {
8527 	struct bpf_verifier_state *cur = env->cur_state;
8528 	struct bpf_func_state *state = cur->frame[cur->curframe];
8529 
8530 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8531 }
8532 
8533 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8534 {
8535 	env->insn_aux_data[idx].prune_point = true;
8536 }
8537 
8538 enum {
8539 	DONE_EXPLORING = 0,
8540 	KEEP_EXPLORING = 1,
8541 };
8542 
8543 /* t, w, e - match pseudo-code above:
8544  * t - index of current instruction
8545  * w - next instruction
8546  * e - edge
8547  */
8548 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8549 		     bool loop_ok)
8550 {
8551 	int *insn_stack = env->cfg.insn_stack;
8552 	int *insn_state = env->cfg.insn_state;
8553 
8554 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8555 		return DONE_EXPLORING;
8556 
8557 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8558 		return DONE_EXPLORING;
8559 
8560 	if (w < 0 || w >= env->prog->len) {
8561 		verbose_linfo(env, t, "%d: ", t);
8562 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8563 		return -EINVAL;
8564 	}
8565 
8566 	if (e == BRANCH)
8567 		/* mark branch target for state pruning */
8568 		init_explored_state(env, w);
8569 
8570 	if (insn_state[w] == 0) {
8571 		/* tree-edge */
8572 		insn_state[t] = DISCOVERED | e;
8573 		insn_state[w] = DISCOVERED;
8574 		if (env->cfg.cur_stack >= env->prog->len)
8575 			return -E2BIG;
8576 		insn_stack[env->cfg.cur_stack++] = w;
8577 		return KEEP_EXPLORING;
8578 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8579 		if (loop_ok && env->bpf_capable)
8580 			return DONE_EXPLORING;
8581 		verbose_linfo(env, t, "%d: ", t);
8582 		verbose_linfo(env, w, "%d: ", w);
8583 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8584 		return -EINVAL;
8585 	} else if (insn_state[w] == EXPLORED) {
8586 		/* forward- or cross-edge */
8587 		insn_state[t] = DISCOVERED | e;
8588 	} else {
8589 		verbose(env, "insn state internal bug\n");
8590 		return -EFAULT;
8591 	}
8592 	return DONE_EXPLORING;
8593 }
8594 
8595 /* Visits the instruction at index t and returns one of the following:
8596  *  < 0 - an error occurred
8597  *  DONE_EXPLORING - the instruction was fully explored
8598  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
8599  */
8600 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8601 {
8602 	struct bpf_insn *insns = env->prog->insnsi;
8603 	int ret;
8604 
8605 	/* All non-branch instructions have a single fall-through edge. */
8606 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8607 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
8608 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
8609 
8610 	switch (BPF_OP(insns[t].code)) {
8611 	case BPF_EXIT:
8612 		return DONE_EXPLORING;
8613 
8614 	case BPF_CALL:
8615 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8616 		if (ret)
8617 			return ret;
8618 
8619 		if (t + 1 < insn_cnt)
8620 			init_explored_state(env, t + 1);
8621 		if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8622 			init_explored_state(env, t);
8623 			ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8624 					env, false);
8625 		}
8626 		return ret;
8627 
8628 	case BPF_JA:
8629 		if (BPF_SRC(insns[t].code) != BPF_K)
8630 			return -EINVAL;
8631 
8632 		/* unconditional jump with single edge */
8633 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8634 				true);
8635 		if (ret)
8636 			return ret;
8637 
8638 		/* unconditional jmp is not a good pruning point,
8639 		 * but it's marked, since backtracking needs
8640 		 * to record jmp history in is_state_visited().
8641 		 */
8642 		init_explored_state(env, t + insns[t].off + 1);
8643 		/* tell verifier to check for equivalent states
8644 		 * after every call and jump
8645 		 */
8646 		if (t + 1 < insn_cnt)
8647 			init_explored_state(env, t + 1);
8648 
8649 		return ret;
8650 
8651 	default:
8652 		/* conditional jump with two edges */
8653 		init_explored_state(env, t);
8654 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8655 		if (ret)
8656 			return ret;
8657 
8658 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8659 	}
8660 }
8661 
8662 /* non-recursive depth-first-search to detect loops in BPF program
8663  * loop == back-edge in directed graph
8664  */
8665 static int check_cfg(struct bpf_verifier_env *env)
8666 {
8667 	int insn_cnt = env->prog->len;
8668 	int *insn_stack, *insn_state;
8669 	int ret = 0;
8670 	int i;
8671 
8672 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8673 	if (!insn_state)
8674 		return -ENOMEM;
8675 
8676 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8677 	if (!insn_stack) {
8678 		kvfree(insn_state);
8679 		return -ENOMEM;
8680 	}
8681 
8682 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8683 	insn_stack[0] = 0; /* 0 is the first instruction */
8684 	env->cfg.cur_stack = 1;
8685 
8686 	while (env->cfg.cur_stack > 0) {
8687 		int t = insn_stack[env->cfg.cur_stack - 1];
8688 
8689 		ret = visit_insn(t, insn_cnt, env);
8690 		switch (ret) {
8691 		case DONE_EXPLORING:
8692 			insn_state[t] = EXPLORED;
8693 			env->cfg.cur_stack--;
8694 			break;
8695 		case KEEP_EXPLORING:
8696 			break;
8697 		default:
8698 			if (ret > 0) {
8699 				verbose(env, "visit_insn internal bug\n");
8700 				ret = -EFAULT;
8701 			}
8702 			goto err_free;
8703 		}
8704 	}
8705 
8706 	if (env->cfg.cur_stack < 0) {
8707 		verbose(env, "pop stack internal bug\n");
8708 		ret = -EFAULT;
8709 		goto err_free;
8710 	}
8711 
8712 	for (i = 0; i < insn_cnt; i++) {
8713 		if (insn_state[i] != EXPLORED) {
8714 			verbose(env, "unreachable insn %d\n", i);
8715 			ret = -EINVAL;
8716 			goto err_free;
8717 		}
8718 	}
8719 	ret = 0; /* cfg looks good */
8720 
8721 err_free:
8722 	kvfree(insn_state);
8723 	kvfree(insn_stack);
8724 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8725 	return ret;
8726 }
8727 
8728 static int check_abnormal_return(struct bpf_verifier_env *env)
8729 {
8730 	int i;
8731 
8732 	for (i = 1; i < env->subprog_cnt; i++) {
8733 		if (env->subprog_info[i].has_ld_abs) {
8734 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8735 			return -EINVAL;
8736 		}
8737 		if (env->subprog_info[i].has_tail_call) {
8738 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8739 			return -EINVAL;
8740 		}
8741 	}
8742 	return 0;
8743 }
8744 
8745 /* The minimum supported BTF func info size */
8746 #define MIN_BPF_FUNCINFO_SIZE	8
8747 #define MAX_FUNCINFO_REC_SIZE	252
8748 
8749 static int check_btf_func(struct bpf_verifier_env *env,
8750 			  const union bpf_attr *attr,
8751 			  union bpf_attr __user *uattr)
8752 {
8753 	const struct btf_type *type, *func_proto, *ret_type;
8754 	u32 i, nfuncs, urec_size, min_size;
8755 	u32 krec_size = sizeof(struct bpf_func_info);
8756 	struct bpf_func_info *krecord;
8757 	struct bpf_func_info_aux *info_aux = NULL;
8758 	struct bpf_prog *prog;
8759 	const struct btf *btf;
8760 	void __user *urecord;
8761 	u32 prev_offset = 0;
8762 	bool scalar_return;
8763 	int ret = -ENOMEM;
8764 
8765 	nfuncs = attr->func_info_cnt;
8766 	if (!nfuncs) {
8767 		if (check_abnormal_return(env))
8768 			return -EINVAL;
8769 		return 0;
8770 	}
8771 
8772 	if (nfuncs != env->subprog_cnt) {
8773 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8774 		return -EINVAL;
8775 	}
8776 
8777 	urec_size = attr->func_info_rec_size;
8778 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8779 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8780 	    urec_size % sizeof(u32)) {
8781 		verbose(env, "invalid func info rec size %u\n", urec_size);
8782 		return -EINVAL;
8783 	}
8784 
8785 	prog = env->prog;
8786 	btf = prog->aux->btf;
8787 
8788 	urecord = u64_to_user_ptr(attr->func_info);
8789 	min_size = min_t(u32, krec_size, urec_size);
8790 
8791 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8792 	if (!krecord)
8793 		return -ENOMEM;
8794 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8795 	if (!info_aux)
8796 		goto err_free;
8797 
8798 	for (i = 0; i < nfuncs; i++) {
8799 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8800 		if (ret) {
8801 			if (ret == -E2BIG) {
8802 				verbose(env, "nonzero tailing record in func info");
8803 				/* set the size kernel expects so loader can zero
8804 				 * out the rest of the record.
8805 				 */
8806 				if (put_user(min_size, &uattr->func_info_rec_size))
8807 					ret = -EFAULT;
8808 			}
8809 			goto err_free;
8810 		}
8811 
8812 		if (copy_from_user(&krecord[i], urecord, min_size)) {
8813 			ret = -EFAULT;
8814 			goto err_free;
8815 		}
8816 
8817 		/* check insn_off */
8818 		ret = -EINVAL;
8819 		if (i == 0) {
8820 			if (krecord[i].insn_off) {
8821 				verbose(env,
8822 					"nonzero insn_off %u for the first func info record",
8823 					krecord[i].insn_off);
8824 				goto err_free;
8825 			}
8826 		} else if (krecord[i].insn_off <= prev_offset) {
8827 			verbose(env,
8828 				"same or smaller insn offset (%u) than previous func info record (%u)",
8829 				krecord[i].insn_off, prev_offset);
8830 			goto err_free;
8831 		}
8832 
8833 		if (env->subprog_info[i].start != krecord[i].insn_off) {
8834 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8835 			goto err_free;
8836 		}
8837 
8838 		/* check type_id */
8839 		type = btf_type_by_id(btf, krecord[i].type_id);
8840 		if (!type || !btf_type_is_func(type)) {
8841 			verbose(env, "invalid type id %d in func info",
8842 				krecord[i].type_id);
8843 			goto err_free;
8844 		}
8845 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8846 
8847 		func_proto = btf_type_by_id(btf, type->type);
8848 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8849 			/* btf_func_check() already verified it during BTF load */
8850 			goto err_free;
8851 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8852 		scalar_return =
8853 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8854 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8855 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8856 			goto err_free;
8857 		}
8858 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8859 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8860 			goto err_free;
8861 		}
8862 
8863 		prev_offset = krecord[i].insn_off;
8864 		urecord += urec_size;
8865 	}
8866 
8867 	prog->aux->func_info = krecord;
8868 	prog->aux->func_info_cnt = nfuncs;
8869 	prog->aux->func_info_aux = info_aux;
8870 	return 0;
8871 
8872 err_free:
8873 	kvfree(krecord);
8874 	kfree(info_aux);
8875 	return ret;
8876 }
8877 
8878 static void adjust_btf_func(struct bpf_verifier_env *env)
8879 {
8880 	struct bpf_prog_aux *aux = env->prog->aux;
8881 	int i;
8882 
8883 	if (!aux->func_info)
8884 		return;
8885 
8886 	for (i = 0; i < env->subprog_cnt; i++)
8887 		aux->func_info[i].insn_off = env->subprog_info[i].start;
8888 }
8889 
8890 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
8891 		sizeof(((struct bpf_line_info *)(0))->line_col))
8892 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
8893 
8894 static int check_btf_line(struct bpf_verifier_env *env,
8895 			  const union bpf_attr *attr,
8896 			  union bpf_attr __user *uattr)
8897 {
8898 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8899 	struct bpf_subprog_info *sub;
8900 	struct bpf_line_info *linfo;
8901 	struct bpf_prog *prog;
8902 	const struct btf *btf;
8903 	void __user *ulinfo;
8904 	int err;
8905 
8906 	nr_linfo = attr->line_info_cnt;
8907 	if (!nr_linfo)
8908 		return 0;
8909 
8910 	rec_size = attr->line_info_rec_size;
8911 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8912 	    rec_size > MAX_LINEINFO_REC_SIZE ||
8913 	    rec_size & (sizeof(u32) - 1))
8914 		return -EINVAL;
8915 
8916 	/* Need to zero it in case the userspace may
8917 	 * pass in a smaller bpf_line_info object.
8918 	 */
8919 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8920 			 GFP_KERNEL | __GFP_NOWARN);
8921 	if (!linfo)
8922 		return -ENOMEM;
8923 
8924 	prog = env->prog;
8925 	btf = prog->aux->btf;
8926 
8927 	s = 0;
8928 	sub = env->subprog_info;
8929 	ulinfo = u64_to_user_ptr(attr->line_info);
8930 	expected_size = sizeof(struct bpf_line_info);
8931 	ncopy = min_t(u32, expected_size, rec_size);
8932 	for (i = 0; i < nr_linfo; i++) {
8933 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8934 		if (err) {
8935 			if (err == -E2BIG) {
8936 				verbose(env, "nonzero tailing record in line_info");
8937 				if (put_user(expected_size,
8938 					     &uattr->line_info_rec_size))
8939 					err = -EFAULT;
8940 			}
8941 			goto err_free;
8942 		}
8943 
8944 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8945 			err = -EFAULT;
8946 			goto err_free;
8947 		}
8948 
8949 		/*
8950 		 * Check insn_off to ensure
8951 		 * 1) strictly increasing AND
8952 		 * 2) bounded by prog->len
8953 		 *
8954 		 * The linfo[0].insn_off == 0 check logically falls into
8955 		 * the later "missing bpf_line_info for func..." case
8956 		 * because the first linfo[0].insn_off must be the
8957 		 * first sub also and the first sub must have
8958 		 * subprog_info[0].start == 0.
8959 		 */
8960 		if ((i && linfo[i].insn_off <= prev_offset) ||
8961 		    linfo[i].insn_off >= prog->len) {
8962 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8963 				i, linfo[i].insn_off, prev_offset,
8964 				prog->len);
8965 			err = -EINVAL;
8966 			goto err_free;
8967 		}
8968 
8969 		if (!prog->insnsi[linfo[i].insn_off].code) {
8970 			verbose(env,
8971 				"Invalid insn code at line_info[%u].insn_off\n",
8972 				i);
8973 			err = -EINVAL;
8974 			goto err_free;
8975 		}
8976 
8977 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8978 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8979 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8980 			err = -EINVAL;
8981 			goto err_free;
8982 		}
8983 
8984 		if (s != env->subprog_cnt) {
8985 			if (linfo[i].insn_off == sub[s].start) {
8986 				sub[s].linfo_idx = i;
8987 				s++;
8988 			} else if (sub[s].start < linfo[i].insn_off) {
8989 				verbose(env, "missing bpf_line_info for func#%u\n", s);
8990 				err = -EINVAL;
8991 				goto err_free;
8992 			}
8993 		}
8994 
8995 		prev_offset = linfo[i].insn_off;
8996 		ulinfo += rec_size;
8997 	}
8998 
8999 	if (s != env->subprog_cnt) {
9000 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9001 			env->subprog_cnt - s, s);
9002 		err = -EINVAL;
9003 		goto err_free;
9004 	}
9005 
9006 	prog->aux->linfo = linfo;
9007 	prog->aux->nr_linfo = nr_linfo;
9008 
9009 	return 0;
9010 
9011 err_free:
9012 	kvfree(linfo);
9013 	return err;
9014 }
9015 
9016 static int check_btf_info(struct bpf_verifier_env *env,
9017 			  const union bpf_attr *attr,
9018 			  union bpf_attr __user *uattr)
9019 {
9020 	struct btf *btf;
9021 	int err;
9022 
9023 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9024 		if (check_abnormal_return(env))
9025 			return -EINVAL;
9026 		return 0;
9027 	}
9028 
9029 	btf = btf_get_by_fd(attr->prog_btf_fd);
9030 	if (IS_ERR(btf))
9031 		return PTR_ERR(btf);
9032 	env->prog->aux->btf = btf;
9033 
9034 	err = check_btf_func(env, attr, uattr);
9035 	if (err)
9036 		return err;
9037 
9038 	err = check_btf_line(env, attr, uattr);
9039 	if (err)
9040 		return err;
9041 
9042 	return 0;
9043 }
9044 
9045 /* check %cur's range satisfies %old's */
9046 static bool range_within(struct bpf_reg_state *old,
9047 			 struct bpf_reg_state *cur)
9048 {
9049 	return old->umin_value <= cur->umin_value &&
9050 	       old->umax_value >= cur->umax_value &&
9051 	       old->smin_value <= cur->smin_value &&
9052 	       old->smax_value >= cur->smax_value &&
9053 	       old->u32_min_value <= cur->u32_min_value &&
9054 	       old->u32_max_value >= cur->u32_max_value &&
9055 	       old->s32_min_value <= cur->s32_min_value &&
9056 	       old->s32_max_value >= cur->s32_max_value;
9057 }
9058 
9059 /* Maximum number of register states that can exist at once */
9060 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9061 struct idpair {
9062 	u32 old;
9063 	u32 cur;
9064 };
9065 
9066 /* If in the old state two registers had the same id, then they need to have
9067  * the same id in the new state as well.  But that id could be different from
9068  * the old state, so we need to track the mapping from old to new ids.
9069  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9070  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9071  * regs with a different old id could still have new id 9, we don't care about
9072  * that.
9073  * So we look through our idmap to see if this old id has been seen before.  If
9074  * so, we require the new id to match; otherwise, we add the id pair to the map.
9075  */
9076 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9077 {
9078 	unsigned int i;
9079 
9080 	for (i = 0; i < ID_MAP_SIZE; i++) {
9081 		if (!idmap[i].old) {
9082 			/* Reached an empty slot; haven't seen this id before */
9083 			idmap[i].old = old_id;
9084 			idmap[i].cur = cur_id;
9085 			return true;
9086 		}
9087 		if (idmap[i].old == old_id)
9088 			return idmap[i].cur == cur_id;
9089 	}
9090 	/* We ran out of idmap slots, which should be impossible */
9091 	WARN_ON_ONCE(1);
9092 	return false;
9093 }
9094 
9095 static void clean_func_state(struct bpf_verifier_env *env,
9096 			     struct bpf_func_state *st)
9097 {
9098 	enum bpf_reg_liveness live;
9099 	int i, j;
9100 
9101 	for (i = 0; i < BPF_REG_FP; i++) {
9102 		live = st->regs[i].live;
9103 		/* liveness must not touch this register anymore */
9104 		st->regs[i].live |= REG_LIVE_DONE;
9105 		if (!(live & REG_LIVE_READ))
9106 			/* since the register is unused, clear its state
9107 			 * to make further comparison simpler
9108 			 */
9109 			__mark_reg_not_init(env, &st->regs[i]);
9110 	}
9111 
9112 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9113 		live = st->stack[i].spilled_ptr.live;
9114 		/* liveness must not touch this stack slot anymore */
9115 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9116 		if (!(live & REG_LIVE_READ)) {
9117 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9118 			for (j = 0; j < BPF_REG_SIZE; j++)
9119 				st->stack[i].slot_type[j] = STACK_INVALID;
9120 		}
9121 	}
9122 }
9123 
9124 static void clean_verifier_state(struct bpf_verifier_env *env,
9125 				 struct bpf_verifier_state *st)
9126 {
9127 	int i;
9128 
9129 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9130 		/* all regs in this state in all frames were already marked */
9131 		return;
9132 
9133 	for (i = 0; i <= st->curframe; i++)
9134 		clean_func_state(env, st->frame[i]);
9135 }
9136 
9137 /* the parentage chains form a tree.
9138  * the verifier states are added to state lists at given insn and
9139  * pushed into state stack for future exploration.
9140  * when the verifier reaches bpf_exit insn some of the verifer states
9141  * stored in the state lists have their final liveness state already,
9142  * but a lot of states will get revised from liveness point of view when
9143  * the verifier explores other branches.
9144  * Example:
9145  * 1: r0 = 1
9146  * 2: if r1 == 100 goto pc+1
9147  * 3: r0 = 2
9148  * 4: exit
9149  * when the verifier reaches exit insn the register r0 in the state list of
9150  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9151  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9152  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9153  *
9154  * Since the verifier pushes the branch states as it sees them while exploring
9155  * the program the condition of walking the branch instruction for the second
9156  * time means that all states below this branch were already explored and
9157  * their final liveness markes are already propagated.
9158  * Hence when the verifier completes the search of state list in is_state_visited()
9159  * we can call this clean_live_states() function to mark all liveness states
9160  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9161  * will not be used.
9162  * This function also clears the registers and stack for states that !READ
9163  * to simplify state merging.
9164  *
9165  * Important note here that walking the same branch instruction in the callee
9166  * doesn't meant that the states are DONE. The verifier has to compare
9167  * the callsites
9168  */
9169 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9170 			      struct bpf_verifier_state *cur)
9171 {
9172 	struct bpf_verifier_state_list *sl;
9173 	int i;
9174 
9175 	sl = *explored_state(env, insn);
9176 	while (sl) {
9177 		if (sl->state.branches)
9178 			goto next;
9179 		if (sl->state.insn_idx != insn ||
9180 		    sl->state.curframe != cur->curframe)
9181 			goto next;
9182 		for (i = 0; i <= cur->curframe; i++)
9183 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9184 				goto next;
9185 		clean_verifier_state(env, &sl->state);
9186 next:
9187 		sl = sl->next;
9188 	}
9189 }
9190 
9191 /* Returns true if (rold safe implies rcur safe) */
9192 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9193 		    struct idpair *idmap)
9194 {
9195 	bool equal;
9196 
9197 	if (!(rold->live & REG_LIVE_READ))
9198 		/* explored state didn't use this */
9199 		return true;
9200 
9201 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9202 
9203 	if (rold->type == PTR_TO_STACK)
9204 		/* two stack pointers are equal only if they're pointing to
9205 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9206 		 */
9207 		return equal && rold->frameno == rcur->frameno;
9208 
9209 	if (equal)
9210 		return true;
9211 
9212 	if (rold->type == NOT_INIT)
9213 		/* explored state can't have used this */
9214 		return true;
9215 	if (rcur->type == NOT_INIT)
9216 		return false;
9217 	switch (rold->type) {
9218 	case SCALAR_VALUE:
9219 		if (rcur->type == SCALAR_VALUE) {
9220 			if (!rold->precise && !rcur->precise)
9221 				return true;
9222 			/* new val must satisfy old val knowledge */
9223 			return range_within(rold, rcur) &&
9224 			       tnum_in(rold->var_off, rcur->var_off);
9225 		} else {
9226 			/* We're trying to use a pointer in place of a scalar.
9227 			 * Even if the scalar was unbounded, this could lead to
9228 			 * pointer leaks because scalars are allowed to leak
9229 			 * while pointers are not. We could make this safe in
9230 			 * special cases if root is calling us, but it's
9231 			 * probably not worth the hassle.
9232 			 */
9233 			return false;
9234 		}
9235 	case PTR_TO_MAP_VALUE:
9236 		/* If the new min/max/var_off satisfy the old ones and
9237 		 * everything else matches, we are OK.
9238 		 * 'id' is not compared, since it's only used for maps with
9239 		 * bpf_spin_lock inside map element and in such cases if
9240 		 * the rest of the prog is valid for one map element then
9241 		 * it's valid for all map elements regardless of the key
9242 		 * used in bpf_map_lookup()
9243 		 */
9244 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9245 		       range_within(rold, rcur) &&
9246 		       tnum_in(rold->var_off, rcur->var_off);
9247 	case PTR_TO_MAP_VALUE_OR_NULL:
9248 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9249 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9250 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9251 		 * checked, doing so could have affected others with the same
9252 		 * id, and we can't check for that because we lost the id when
9253 		 * we converted to a PTR_TO_MAP_VALUE.
9254 		 */
9255 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9256 			return false;
9257 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9258 			return false;
9259 		/* Check our ids match any regs they're supposed to */
9260 		return check_ids(rold->id, rcur->id, idmap);
9261 	case PTR_TO_PACKET_META:
9262 	case PTR_TO_PACKET:
9263 		if (rcur->type != rold->type)
9264 			return false;
9265 		/* We must have at least as much range as the old ptr
9266 		 * did, so that any accesses which were safe before are
9267 		 * still safe.  This is true even if old range < old off,
9268 		 * since someone could have accessed through (ptr - k), or
9269 		 * even done ptr -= k in a register, to get a safe access.
9270 		 */
9271 		if (rold->range > rcur->range)
9272 			return false;
9273 		/* If the offsets don't match, we can't trust our alignment;
9274 		 * nor can we be sure that we won't fall out of range.
9275 		 */
9276 		if (rold->off != rcur->off)
9277 			return false;
9278 		/* id relations must be preserved */
9279 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9280 			return false;
9281 		/* new val must satisfy old val knowledge */
9282 		return range_within(rold, rcur) &&
9283 		       tnum_in(rold->var_off, rcur->var_off);
9284 	case PTR_TO_CTX:
9285 	case CONST_PTR_TO_MAP:
9286 	case PTR_TO_PACKET_END:
9287 	case PTR_TO_FLOW_KEYS:
9288 	case PTR_TO_SOCKET:
9289 	case PTR_TO_SOCKET_OR_NULL:
9290 	case PTR_TO_SOCK_COMMON:
9291 	case PTR_TO_SOCK_COMMON_OR_NULL:
9292 	case PTR_TO_TCP_SOCK:
9293 	case PTR_TO_TCP_SOCK_OR_NULL:
9294 	case PTR_TO_XDP_SOCK:
9295 		/* Only valid matches are exact, which memcmp() above
9296 		 * would have accepted
9297 		 */
9298 	default:
9299 		/* Don't know what's going on, just say it's not safe */
9300 		return false;
9301 	}
9302 
9303 	/* Shouldn't get here; if we do, say it's not safe */
9304 	WARN_ON_ONCE(1);
9305 	return false;
9306 }
9307 
9308 static bool stacksafe(struct bpf_func_state *old,
9309 		      struct bpf_func_state *cur,
9310 		      struct idpair *idmap)
9311 {
9312 	int i, spi;
9313 
9314 	/* walk slots of the explored stack and ignore any additional
9315 	 * slots in the current stack, since explored(safe) state
9316 	 * didn't use them
9317 	 */
9318 	for (i = 0; i < old->allocated_stack; i++) {
9319 		spi = i / BPF_REG_SIZE;
9320 
9321 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9322 			i += BPF_REG_SIZE - 1;
9323 			/* explored state didn't use this */
9324 			continue;
9325 		}
9326 
9327 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9328 			continue;
9329 
9330 		/* explored stack has more populated slots than current stack
9331 		 * and these slots were used
9332 		 */
9333 		if (i >= cur->allocated_stack)
9334 			return false;
9335 
9336 		/* if old state was safe with misc data in the stack
9337 		 * it will be safe with zero-initialized stack.
9338 		 * The opposite is not true
9339 		 */
9340 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9341 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9342 			continue;
9343 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9344 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9345 			/* Ex: old explored (safe) state has STACK_SPILL in
9346 			 * this stack slot, but current has STACK_MISC ->
9347 			 * this verifier states are not equivalent,
9348 			 * return false to continue verification of this path
9349 			 */
9350 			return false;
9351 		if (i % BPF_REG_SIZE)
9352 			continue;
9353 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
9354 			continue;
9355 		if (!regsafe(&old->stack[spi].spilled_ptr,
9356 			     &cur->stack[spi].spilled_ptr,
9357 			     idmap))
9358 			/* when explored and current stack slot are both storing
9359 			 * spilled registers, check that stored pointers types
9360 			 * are the same as well.
9361 			 * Ex: explored safe path could have stored
9362 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9363 			 * but current path has stored:
9364 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9365 			 * such verifier states are not equivalent.
9366 			 * return false to continue verification of this path
9367 			 */
9368 			return false;
9369 	}
9370 	return true;
9371 }
9372 
9373 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9374 {
9375 	if (old->acquired_refs != cur->acquired_refs)
9376 		return false;
9377 	return !memcmp(old->refs, cur->refs,
9378 		       sizeof(*old->refs) * old->acquired_refs);
9379 }
9380 
9381 /* compare two verifier states
9382  *
9383  * all states stored in state_list are known to be valid, since
9384  * verifier reached 'bpf_exit' instruction through them
9385  *
9386  * this function is called when verifier exploring different branches of
9387  * execution popped from the state stack. If it sees an old state that has
9388  * more strict register state and more strict stack state then this execution
9389  * branch doesn't need to be explored further, since verifier already
9390  * concluded that more strict state leads to valid finish.
9391  *
9392  * Therefore two states are equivalent if register state is more conservative
9393  * and explored stack state is more conservative than the current one.
9394  * Example:
9395  *       explored                   current
9396  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9397  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9398  *
9399  * In other words if current stack state (one being explored) has more
9400  * valid slots than old one that already passed validation, it means
9401  * the verifier can stop exploring and conclude that current state is valid too
9402  *
9403  * Similarly with registers. If explored state has register type as invalid
9404  * whereas register type in current state is meaningful, it means that
9405  * the current state will reach 'bpf_exit' instruction safely
9406  */
9407 static bool func_states_equal(struct bpf_func_state *old,
9408 			      struct bpf_func_state *cur)
9409 {
9410 	struct idpair *idmap;
9411 	bool ret = false;
9412 	int i;
9413 
9414 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9415 	/* If we failed to allocate the idmap, just say it's not safe */
9416 	if (!idmap)
9417 		return false;
9418 
9419 	for (i = 0; i < MAX_BPF_REG; i++) {
9420 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9421 			goto out_free;
9422 	}
9423 
9424 	if (!stacksafe(old, cur, idmap))
9425 		goto out_free;
9426 
9427 	if (!refsafe(old, cur))
9428 		goto out_free;
9429 	ret = true;
9430 out_free:
9431 	kfree(idmap);
9432 	return ret;
9433 }
9434 
9435 static bool states_equal(struct bpf_verifier_env *env,
9436 			 struct bpf_verifier_state *old,
9437 			 struct bpf_verifier_state *cur)
9438 {
9439 	int i;
9440 
9441 	if (old->curframe != cur->curframe)
9442 		return false;
9443 
9444 	/* Verification state from speculative execution simulation
9445 	 * must never prune a non-speculative execution one.
9446 	 */
9447 	if (old->speculative && !cur->speculative)
9448 		return false;
9449 
9450 	if (old->active_spin_lock != cur->active_spin_lock)
9451 		return false;
9452 
9453 	/* for states to be equal callsites have to be the same
9454 	 * and all frame states need to be equivalent
9455 	 */
9456 	for (i = 0; i <= old->curframe; i++) {
9457 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9458 			return false;
9459 		if (!func_states_equal(old->frame[i], cur->frame[i]))
9460 			return false;
9461 	}
9462 	return true;
9463 }
9464 
9465 /* Return 0 if no propagation happened. Return negative error code if error
9466  * happened. Otherwise, return the propagated bit.
9467  */
9468 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9469 				  struct bpf_reg_state *reg,
9470 				  struct bpf_reg_state *parent_reg)
9471 {
9472 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9473 	u8 flag = reg->live & REG_LIVE_READ;
9474 	int err;
9475 
9476 	/* When comes here, read flags of PARENT_REG or REG could be any of
9477 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9478 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9479 	 */
9480 	if (parent_flag == REG_LIVE_READ64 ||
9481 	    /* Or if there is no read flag from REG. */
9482 	    !flag ||
9483 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9484 	    parent_flag == flag)
9485 		return 0;
9486 
9487 	err = mark_reg_read(env, reg, parent_reg, flag);
9488 	if (err)
9489 		return err;
9490 
9491 	return flag;
9492 }
9493 
9494 /* A write screens off any subsequent reads; but write marks come from the
9495  * straight-line code between a state and its parent.  When we arrive at an
9496  * equivalent state (jump target or such) we didn't arrive by the straight-line
9497  * code, so read marks in the state must propagate to the parent regardless
9498  * of the state's write marks. That's what 'parent == state->parent' comparison
9499  * in mark_reg_read() is for.
9500  */
9501 static int propagate_liveness(struct bpf_verifier_env *env,
9502 			      const struct bpf_verifier_state *vstate,
9503 			      struct bpf_verifier_state *vparent)
9504 {
9505 	struct bpf_reg_state *state_reg, *parent_reg;
9506 	struct bpf_func_state *state, *parent;
9507 	int i, frame, err = 0;
9508 
9509 	if (vparent->curframe != vstate->curframe) {
9510 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9511 		     vparent->curframe, vstate->curframe);
9512 		return -EFAULT;
9513 	}
9514 	/* Propagate read liveness of registers... */
9515 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9516 	for (frame = 0; frame <= vstate->curframe; frame++) {
9517 		parent = vparent->frame[frame];
9518 		state = vstate->frame[frame];
9519 		parent_reg = parent->regs;
9520 		state_reg = state->regs;
9521 		/* We don't need to worry about FP liveness, it's read-only */
9522 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9523 			err = propagate_liveness_reg(env, &state_reg[i],
9524 						     &parent_reg[i]);
9525 			if (err < 0)
9526 				return err;
9527 			if (err == REG_LIVE_READ64)
9528 				mark_insn_zext(env, &parent_reg[i]);
9529 		}
9530 
9531 		/* Propagate stack slots. */
9532 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9533 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9534 			parent_reg = &parent->stack[i].spilled_ptr;
9535 			state_reg = &state->stack[i].spilled_ptr;
9536 			err = propagate_liveness_reg(env, state_reg,
9537 						     parent_reg);
9538 			if (err < 0)
9539 				return err;
9540 		}
9541 	}
9542 	return 0;
9543 }
9544 
9545 /* find precise scalars in the previous equivalent state and
9546  * propagate them into the current state
9547  */
9548 static int propagate_precision(struct bpf_verifier_env *env,
9549 			       const struct bpf_verifier_state *old)
9550 {
9551 	struct bpf_reg_state *state_reg;
9552 	struct bpf_func_state *state;
9553 	int i, err = 0;
9554 
9555 	state = old->frame[old->curframe];
9556 	state_reg = state->regs;
9557 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9558 		if (state_reg->type != SCALAR_VALUE ||
9559 		    !state_reg->precise)
9560 			continue;
9561 		if (env->log.level & BPF_LOG_LEVEL2)
9562 			verbose(env, "propagating r%d\n", i);
9563 		err = mark_chain_precision(env, i);
9564 		if (err < 0)
9565 			return err;
9566 	}
9567 
9568 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9569 		if (state->stack[i].slot_type[0] != STACK_SPILL)
9570 			continue;
9571 		state_reg = &state->stack[i].spilled_ptr;
9572 		if (state_reg->type != SCALAR_VALUE ||
9573 		    !state_reg->precise)
9574 			continue;
9575 		if (env->log.level & BPF_LOG_LEVEL2)
9576 			verbose(env, "propagating fp%d\n",
9577 				(-i - 1) * BPF_REG_SIZE);
9578 		err = mark_chain_precision_stack(env, i);
9579 		if (err < 0)
9580 			return err;
9581 	}
9582 	return 0;
9583 }
9584 
9585 static bool states_maybe_looping(struct bpf_verifier_state *old,
9586 				 struct bpf_verifier_state *cur)
9587 {
9588 	struct bpf_func_state *fold, *fcur;
9589 	int i, fr = cur->curframe;
9590 
9591 	if (old->curframe != fr)
9592 		return false;
9593 
9594 	fold = old->frame[fr];
9595 	fcur = cur->frame[fr];
9596 	for (i = 0; i < MAX_BPF_REG; i++)
9597 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9598 			   offsetof(struct bpf_reg_state, parent)))
9599 			return false;
9600 	return true;
9601 }
9602 
9603 
9604 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9605 {
9606 	struct bpf_verifier_state_list *new_sl;
9607 	struct bpf_verifier_state_list *sl, **pprev;
9608 	struct bpf_verifier_state *cur = env->cur_state, *new;
9609 	int i, j, err, states_cnt = 0;
9610 	bool add_new_state = env->test_state_freq ? true : false;
9611 
9612 	cur->last_insn_idx = env->prev_insn_idx;
9613 	if (!env->insn_aux_data[insn_idx].prune_point)
9614 		/* this 'insn_idx' instruction wasn't marked, so we will not
9615 		 * be doing state search here
9616 		 */
9617 		return 0;
9618 
9619 	/* bpf progs typically have pruning point every 4 instructions
9620 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9621 	 * Do not add new state for future pruning if the verifier hasn't seen
9622 	 * at least 2 jumps and at least 8 instructions.
9623 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9624 	 * In tests that amounts to up to 50% reduction into total verifier
9625 	 * memory consumption and 20% verifier time speedup.
9626 	 */
9627 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9628 	    env->insn_processed - env->prev_insn_processed >= 8)
9629 		add_new_state = true;
9630 
9631 	pprev = explored_state(env, insn_idx);
9632 	sl = *pprev;
9633 
9634 	clean_live_states(env, insn_idx, cur);
9635 
9636 	while (sl) {
9637 		states_cnt++;
9638 		if (sl->state.insn_idx != insn_idx)
9639 			goto next;
9640 		if (sl->state.branches) {
9641 			if (states_maybe_looping(&sl->state, cur) &&
9642 			    states_equal(env, &sl->state, cur)) {
9643 				verbose_linfo(env, insn_idx, "; ");
9644 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9645 				return -EINVAL;
9646 			}
9647 			/* if the verifier is processing a loop, avoid adding new state
9648 			 * too often, since different loop iterations have distinct
9649 			 * states and may not help future pruning.
9650 			 * This threshold shouldn't be too low to make sure that
9651 			 * a loop with large bound will be rejected quickly.
9652 			 * The most abusive loop will be:
9653 			 * r1 += 1
9654 			 * if r1 < 1000000 goto pc-2
9655 			 * 1M insn_procssed limit / 100 == 10k peak states.
9656 			 * This threshold shouldn't be too high either, since states
9657 			 * at the end of the loop are likely to be useful in pruning.
9658 			 */
9659 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9660 			    env->insn_processed - env->prev_insn_processed < 100)
9661 				add_new_state = false;
9662 			goto miss;
9663 		}
9664 		if (states_equal(env, &sl->state, cur)) {
9665 			sl->hit_cnt++;
9666 			/* reached equivalent register/stack state,
9667 			 * prune the search.
9668 			 * Registers read by the continuation are read by us.
9669 			 * If we have any write marks in env->cur_state, they
9670 			 * will prevent corresponding reads in the continuation
9671 			 * from reaching our parent (an explored_state).  Our
9672 			 * own state will get the read marks recorded, but
9673 			 * they'll be immediately forgotten as we're pruning
9674 			 * this state and will pop a new one.
9675 			 */
9676 			err = propagate_liveness(env, &sl->state, cur);
9677 
9678 			/* if previous state reached the exit with precision and
9679 			 * current state is equivalent to it (except precsion marks)
9680 			 * the precision needs to be propagated back in
9681 			 * the current state.
9682 			 */
9683 			err = err ? : push_jmp_history(env, cur);
9684 			err = err ? : propagate_precision(env, &sl->state);
9685 			if (err)
9686 				return err;
9687 			return 1;
9688 		}
9689 miss:
9690 		/* when new state is not going to be added do not increase miss count.
9691 		 * Otherwise several loop iterations will remove the state
9692 		 * recorded earlier. The goal of these heuristics is to have
9693 		 * states from some iterations of the loop (some in the beginning
9694 		 * and some at the end) to help pruning.
9695 		 */
9696 		if (add_new_state)
9697 			sl->miss_cnt++;
9698 		/* heuristic to determine whether this state is beneficial
9699 		 * to keep checking from state equivalence point of view.
9700 		 * Higher numbers increase max_states_per_insn and verification time,
9701 		 * but do not meaningfully decrease insn_processed.
9702 		 */
9703 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9704 			/* the state is unlikely to be useful. Remove it to
9705 			 * speed up verification
9706 			 */
9707 			*pprev = sl->next;
9708 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9709 				u32 br = sl->state.branches;
9710 
9711 				WARN_ONCE(br,
9712 					  "BUG live_done but branches_to_explore %d\n",
9713 					  br);
9714 				free_verifier_state(&sl->state, false);
9715 				kfree(sl);
9716 				env->peak_states--;
9717 			} else {
9718 				/* cannot free this state, since parentage chain may
9719 				 * walk it later. Add it for free_list instead to
9720 				 * be freed at the end of verification
9721 				 */
9722 				sl->next = env->free_list;
9723 				env->free_list = sl;
9724 			}
9725 			sl = *pprev;
9726 			continue;
9727 		}
9728 next:
9729 		pprev = &sl->next;
9730 		sl = *pprev;
9731 	}
9732 
9733 	if (env->max_states_per_insn < states_cnt)
9734 		env->max_states_per_insn = states_cnt;
9735 
9736 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9737 		return push_jmp_history(env, cur);
9738 
9739 	if (!add_new_state)
9740 		return push_jmp_history(env, cur);
9741 
9742 	/* There were no equivalent states, remember the current one.
9743 	 * Technically the current state is not proven to be safe yet,
9744 	 * but it will either reach outer most bpf_exit (which means it's safe)
9745 	 * or it will be rejected. When there are no loops the verifier won't be
9746 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9747 	 * again on the way to bpf_exit.
9748 	 * When looping the sl->state.branches will be > 0 and this state
9749 	 * will not be considered for equivalence until branches == 0.
9750 	 */
9751 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9752 	if (!new_sl)
9753 		return -ENOMEM;
9754 	env->total_states++;
9755 	env->peak_states++;
9756 	env->prev_jmps_processed = env->jmps_processed;
9757 	env->prev_insn_processed = env->insn_processed;
9758 
9759 	/* add new state to the head of linked list */
9760 	new = &new_sl->state;
9761 	err = copy_verifier_state(new, cur);
9762 	if (err) {
9763 		free_verifier_state(new, false);
9764 		kfree(new_sl);
9765 		return err;
9766 	}
9767 	new->insn_idx = insn_idx;
9768 	WARN_ONCE(new->branches != 1,
9769 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9770 
9771 	cur->parent = new;
9772 	cur->first_insn_idx = insn_idx;
9773 	clear_jmp_history(cur);
9774 	new_sl->next = *explored_state(env, insn_idx);
9775 	*explored_state(env, insn_idx) = new_sl;
9776 	/* connect new state to parentage chain. Current frame needs all
9777 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9778 	 * to the stack implicitly by JITs) so in callers' frames connect just
9779 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9780 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9781 	 * from callee with its full parentage chain, anyway.
9782 	 */
9783 	/* clear write marks in current state: the writes we did are not writes
9784 	 * our child did, so they don't screen off its reads from us.
9785 	 * (There are no read marks in current state, because reads always mark
9786 	 * their parent and current state never has children yet.  Only
9787 	 * explored_states can get read marks.)
9788 	 */
9789 	for (j = 0; j <= cur->curframe; j++) {
9790 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9791 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9792 		for (i = 0; i < BPF_REG_FP; i++)
9793 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9794 	}
9795 
9796 	/* all stack frames are accessible from callee, clear them all */
9797 	for (j = 0; j <= cur->curframe; j++) {
9798 		struct bpf_func_state *frame = cur->frame[j];
9799 		struct bpf_func_state *newframe = new->frame[j];
9800 
9801 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9802 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9803 			frame->stack[i].spilled_ptr.parent =
9804 						&newframe->stack[i].spilled_ptr;
9805 		}
9806 	}
9807 	return 0;
9808 }
9809 
9810 /* Return true if it's OK to have the same insn return a different type. */
9811 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9812 {
9813 	switch (type) {
9814 	case PTR_TO_CTX:
9815 	case PTR_TO_SOCKET:
9816 	case PTR_TO_SOCKET_OR_NULL:
9817 	case PTR_TO_SOCK_COMMON:
9818 	case PTR_TO_SOCK_COMMON_OR_NULL:
9819 	case PTR_TO_TCP_SOCK:
9820 	case PTR_TO_TCP_SOCK_OR_NULL:
9821 	case PTR_TO_XDP_SOCK:
9822 	case PTR_TO_BTF_ID:
9823 	case PTR_TO_BTF_ID_OR_NULL:
9824 		return false;
9825 	default:
9826 		return true;
9827 	}
9828 }
9829 
9830 /* If an instruction was previously used with particular pointer types, then we
9831  * need to be careful to avoid cases such as the below, where it may be ok
9832  * for one branch accessing the pointer, but not ok for the other branch:
9833  *
9834  * R1 = sock_ptr
9835  * goto X;
9836  * ...
9837  * R1 = some_other_valid_ptr;
9838  * goto X;
9839  * ...
9840  * R2 = *(u32 *)(R1 + 0);
9841  */
9842 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9843 {
9844 	return src != prev && (!reg_type_mismatch_ok(src) ||
9845 			       !reg_type_mismatch_ok(prev));
9846 }
9847 
9848 static int do_check(struct bpf_verifier_env *env)
9849 {
9850 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9851 	struct bpf_verifier_state *state = env->cur_state;
9852 	struct bpf_insn *insns = env->prog->insnsi;
9853 	struct bpf_reg_state *regs;
9854 	int insn_cnt = env->prog->len;
9855 	bool do_print_state = false;
9856 	int prev_insn_idx = -1;
9857 
9858 	for (;;) {
9859 		struct bpf_insn *insn;
9860 		u8 class;
9861 		int err;
9862 
9863 		env->prev_insn_idx = prev_insn_idx;
9864 		if (env->insn_idx >= insn_cnt) {
9865 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
9866 				env->insn_idx, insn_cnt);
9867 			return -EFAULT;
9868 		}
9869 
9870 		insn = &insns[env->insn_idx];
9871 		class = BPF_CLASS(insn->code);
9872 
9873 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9874 			verbose(env,
9875 				"BPF program is too large. Processed %d insn\n",
9876 				env->insn_processed);
9877 			return -E2BIG;
9878 		}
9879 
9880 		err = is_state_visited(env, env->insn_idx);
9881 		if (err < 0)
9882 			return err;
9883 		if (err == 1) {
9884 			/* found equivalent state, can prune the search */
9885 			if (env->log.level & BPF_LOG_LEVEL) {
9886 				if (do_print_state)
9887 					verbose(env, "\nfrom %d to %d%s: safe\n",
9888 						env->prev_insn_idx, env->insn_idx,
9889 						env->cur_state->speculative ?
9890 						" (speculative execution)" : "");
9891 				else
9892 					verbose(env, "%d: safe\n", env->insn_idx);
9893 			}
9894 			goto process_bpf_exit;
9895 		}
9896 
9897 		if (signal_pending(current))
9898 			return -EAGAIN;
9899 
9900 		if (need_resched())
9901 			cond_resched();
9902 
9903 		if (env->log.level & BPF_LOG_LEVEL2 ||
9904 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9905 			if (env->log.level & BPF_LOG_LEVEL2)
9906 				verbose(env, "%d:", env->insn_idx);
9907 			else
9908 				verbose(env, "\nfrom %d to %d%s:",
9909 					env->prev_insn_idx, env->insn_idx,
9910 					env->cur_state->speculative ?
9911 					" (speculative execution)" : "");
9912 			print_verifier_state(env, state->frame[state->curframe]);
9913 			do_print_state = false;
9914 		}
9915 
9916 		if (env->log.level & BPF_LOG_LEVEL) {
9917 			const struct bpf_insn_cbs cbs = {
9918 				.cb_print	= verbose,
9919 				.private_data	= env,
9920 			};
9921 
9922 			verbose_linfo(env, env->insn_idx, "; ");
9923 			verbose(env, "%d: ", env->insn_idx);
9924 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9925 		}
9926 
9927 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
9928 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9929 							   env->prev_insn_idx);
9930 			if (err)
9931 				return err;
9932 		}
9933 
9934 		regs = cur_regs(env);
9935 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9936 		prev_insn_idx = env->insn_idx;
9937 
9938 		if (class == BPF_ALU || class == BPF_ALU64) {
9939 			err = check_alu_op(env, insn);
9940 			if (err)
9941 				return err;
9942 
9943 		} else if (class == BPF_LDX) {
9944 			enum bpf_reg_type *prev_src_type, src_reg_type;
9945 
9946 			/* check for reserved fields is already done */
9947 
9948 			/* check src operand */
9949 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9950 			if (err)
9951 				return err;
9952 
9953 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9954 			if (err)
9955 				return err;
9956 
9957 			src_reg_type = regs[insn->src_reg].type;
9958 
9959 			/* check that memory (src_reg + off) is readable,
9960 			 * the state of dst_reg will be updated by this func
9961 			 */
9962 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
9963 					       insn->off, BPF_SIZE(insn->code),
9964 					       BPF_READ, insn->dst_reg, false);
9965 			if (err)
9966 				return err;
9967 
9968 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9969 
9970 			if (*prev_src_type == NOT_INIT) {
9971 				/* saw a valid insn
9972 				 * dst_reg = *(u32 *)(src_reg + off)
9973 				 * save type to validate intersecting paths
9974 				 */
9975 				*prev_src_type = src_reg_type;
9976 
9977 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9978 				/* ABuser program is trying to use the same insn
9979 				 * dst_reg = *(u32*) (src_reg + off)
9980 				 * with different pointer types:
9981 				 * src_reg == ctx in one branch and
9982 				 * src_reg == stack|map in some other branch.
9983 				 * Reject it.
9984 				 */
9985 				verbose(env, "same insn cannot be used with different pointers\n");
9986 				return -EINVAL;
9987 			}
9988 
9989 		} else if (class == BPF_STX) {
9990 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
9991 
9992 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
9993 				err = check_atomic(env, env->insn_idx, insn);
9994 				if (err)
9995 					return err;
9996 				env->insn_idx++;
9997 				continue;
9998 			}
9999 
10000 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10001 				verbose(env, "BPF_STX uses reserved fields\n");
10002 				return -EINVAL;
10003 			}
10004 
10005 			/* check src1 operand */
10006 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10007 			if (err)
10008 				return err;
10009 			/* check src2 operand */
10010 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10011 			if (err)
10012 				return err;
10013 
10014 			dst_reg_type = regs[insn->dst_reg].type;
10015 
10016 			/* check that memory (dst_reg + off) is writeable */
10017 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10018 					       insn->off, BPF_SIZE(insn->code),
10019 					       BPF_WRITE, insn->src_reg, false);
10020 			if (err)
10021 				return err;
10022 
10023 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10024 
10025 			if (*prev_dst_type == NOT_INIT) {
10026 				*prev_dst_type = dst_reg_type;
10027 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10028 				verbose(env, "same insn cannot be used with different pointers\n");
10029 				return -EINVAL;
10030 			}
10031 
10032 		} else if (class == BPF_ST) {
10033 			if (BPF_MODE(insn->code) != BPF_MEM ||
10034 			    insn->src_reg != BPF_REG_0) {
10035 				verbose(env, "BPF_ST uses reserved fields\n");
10036 				return -EINVAL;
10037 			}
10038 			/* check src operand */
10039 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10040 			if (err)
10041 				return err;
10042 
10043 			if (is_ctx_reg(env, insn->dst_reg)) {
10044 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10045 					insn->dst_reg,
10046 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
10047 				return -EACCES;
10048 			}
10049 
10050 			/* check that memory (dst_reg + off) is writeable */
10051 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10052 					       insn->off, BPF_SIZE(insn->code),
10053 					       BPF_WRITE, -1, false);
10054 			if (err)
10055 				return err;
10056 
10057 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10058 			u8 opcode = BPF_OP(insn->code);
10059 
10060 			env->jmps_processed++;
10061 			if (opcode == BPF_CALL) {
10062 				if (BPF_SRC(insn->code) != BPF_K ||
10063 				    insn->off != 0 ||
10064 				    (insn->src_reg != BPF_REG_0 &&
10065 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10066 				    insn->dst_reg != BPF_REG_0 ||
10067 				    class == BPF_JMP32) {
10068 					verbose(env, "BPF_CALL uses reserved fields\n");
10069 					return -EINVAL;
10070 				}
10071 
10072 				if (env->cur_state->active_spin_lock &&
10073 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10074 				     insn->imm != BPF_FUNC_spin_unlock)) {
10075 					verbose(env, "function calls are not allowed while holding a lock\n");
10076 					return -EINVAL;
10077 				}
10078 				if (insn->src_reg == BPF_PSEUDO_CALL)
10079 					err = check_func_call(env, insn, &env->insn_idx);
10080 				else
10081 					err = check_helper_call(env, insn->imm, env->insn_idx);
10082 				if (err)
10083 					return err;
10084 
10085 			} else if (opcode == BPF_JA) {
10086 				if (BPF_SRC(insn->code) != BPF_K ||
10087 				    insn->imm != 0 ||
10088 				    insn->src_reg != BPF_REG_0 ||
10089 				    insn->dst_reg != BPF_REG_0 ||
10090 				    class == BPF_JMP32) {
10091 					verbose(env, "BPF_JA uses reserved fields\n");
10092 					return -EINVAL;
10093 				}
10094 
10095 				env->insn_idx += insn->off + 1;
10096 				continue;
10097 
10098 			} else if (opcode == BPF_EXIT) {
10099 				if (BPF_SRC(insn->code) != BPF_K ||
10100 				    insn->imm != 0 ||
10101 				    insn->src_reg != BPF_REG_0 ||
10102 				    insn->dst_reg != BPF_REG_0 ||
10103 				    class == BPF_JMP32) {
10104 					verbose(env, "BPF_EXIT uses reserved fields\n");
10105 					return -EINVAL;
10106 				}
10107 
10108 				if (env->cur_state->active_spin_lock) {
10109 					verbose(env, "bpf_spin_unlock is missing\n");
10110 					return -EINVAL;
10111 				}
10112 
10113 				if (state->curframe) {
10114 					/* exit from nested function */
10115 					err = prepare_func_exit(env, &env->insn_idx);
10116 					if (err)
10117 						return err;
10118 					do_print_state = true;
10119 					continue;
10120 				}
10121 
10122 				err = check_reference_leak(env);
10123 				if (err)
10124 					return err;
10125 
10126 				err = check_return_code(env);
10127 				if (err)
10128 					return err;
10129 process_bpf_exit:
10130 				update_branch_counts(env, env->cur_state);
10131 				err = pop_stack(env, &prev_insn_idx,
10132 						&env->insn_idx, pop_log);
10133 				if (err < 0) {
10134 					if (err != -ENOENT)
10135 						return err;
10136 					break;
10137 				} else {
10138 					do_print_state = true;
10139 					continue;
10140 				}
10141 			} else {
10142 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10143 				if (err)
10144 					return err;
10145 			}
10146 		} else if (class == BPF_LD) {
10147 			u8 mode = BPF_MODE(insn->code);
10148 
10149 			if (mode == BPF_ABS || mode == BPF_IND) {
10150 				err = check_ld_abs(env, insn);
10151 				if (err)
10152 					return err;
10153 
10154 			} else if (mode == BPF_IMM) {
10155 				err = check_ld_imm(env, insn);
10156 				if (err)
10157 					return err;
10158 
10159 				env->insn_idx++;
10160 				env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10161 			} else {
10162 				verbose(env, "invalid BPF_LD mode\n");
10163 				return -EINVAL;
10164 			}
10165 		} else {
10166 			verbose(env, "unknown insn class %d\n", class);
10167 			return -EINVAL;
10168 		}
10169 
10170 		env->insn_idx++;
10171 	}
10172 
10173 	return 0;
10174 }
10175 
10176 static int find_btf_percpu_datasec(struct btf *btf)
10177 {
10178 	const struct btf_type *t;
10179 	const char *tname;
10180 	int i, n;
10181 
10182 	/*
10183 	 * Both vmlinux and module each have their own ".data..percpu"
10184 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10185 	 * types to look at only module's own BTF types.
10186 	 */
10187 	n = btf_nr_types(btf);
10188 	if (btf_is_module(btf))
10189 		i = btf_nr_types(btf_vmlinux);
10190 	else
10191 		i = 1;
10192 
10193 	for(; i < n; i++) {
10194 		t = btf_type_by_id(btf, i);
10195 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10196 			continue;
10197 
10198 		tname = btf_name_by_offset(btf, t->name_off);
10199 		if (!strcmp(tname, ".data..percpu"))
10200 			return i;
10201 	}
10202 
10203 	return -ENOENT;
10204 }
10205 
10206 /* replace pseudo btf_id with kernel symbol address */
10207 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10208 			       struct bpf_insn *insn,
10209 			       struct bpf_insn_aux_data *aux)
10210 {
10211 	const struct btf_var_secinfo *vsi;
10212 	const struct btf_type *datasec;
10213 	struct btf_mod_pair *btf_mod;
10214 	const struct btf_type *t;
10215 	const char *sym_name;
10216 	bool percpu = false;
10217 	u32 type, id = insn->imm;
10218 	struct btf *btf;
10219 	s32 datasec_id;
10220 	u64 addr;
10221 	int i, btf_fd, err;
10222 
10223 	btf_fd = insn[1].imm;
10224 	if (btf_fd) {
10225 		btf = btf_get_by_fd(btf_fd);
10226 		if (IS_ERR(btf)) {
10227 			verbose(env, "invalid module BTF object FD specified.\n");
10228 			return -EINVAL;
10229 		}
10230 	} else {
10231 		if (!btf_vmlinux) {
10232 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10233 			return -EINVAL;
10234 		}
10235 		btf = btf_vmlinux;
10236 		btf_get(btf);
10237 	}
10238 
10239 	t = btf_type_by_id(btf, id);
10240 	if (!t) {
10241 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10242 		err = -ENOENT;
10243 		goto err_put;
10244 	}
10245 
10246 	if (!btf_type_is_var(t)) {
10247 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10248 		err = -EINVAL;
10249 		goto err_put;
10250 	}
10251 
10252 	sym_name = btf_name_by_offset(btf, t->name_off);
10253 	addr = kallsyms_lookup_name(sym_name);
10254 	if (!addr) {
10255 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10256 			sym_name);
10257 		err = -ENOENT;
10258 		goto err_put;
10259 	}
10260 
10261 	datasec_id = find_btf_percpu_datasec(btf);
10262 	if (datasec_id > 0) {
10263 		datasec = btf_type_by_id(btf, datasec_id);
10264 		for_each_vsi(i, datasec, vsi) {
10265 			if (vsi->type == id) {
10266 				percpu = true;
10267 				break;
10268 			}
10269 		}
10270 	}
10271 
10272 	insn[0].imm = (u32)addr;
10273 	insn[1].imm = addr >> 32;
10274 
10275 	type = t->type;
10276 	t = btf_type_skip_modifiers(btf, type, NULL);
10277 	if (percpu) {
10278 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10279 		aux->btf_var.btf = btf;
10280 		aux->btf_var.btf_id = type;
10281 	} else if (!btf_type_is_struct(t)) {
10282 		const struct btf_type *ret;
10283 		const char *tname;
10284 		u32 tsize;
10285 
10286 		/* resolve the type size of ksym. */
10287 		ret = btf_resolve_size(btf, t, &tsize);
10288 		if (IS_ERR(ret)) {
10289 			tname = btf_name_by_offset(btf, t->name_off);
10290 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10291 				tname, PTR_ERR(ret));
10292 			err = -EINVAL;
10293 			goto err_put;
10294 		}
10295 		aux->btf_var.reg_type = PTR_TO_MEM;
10296 		aux->btf_var.mem_size = tsize;
10297 	} else {
10298 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10299 		aux->btf_var.btf = btf;
10300 		aux->btf_var.btf_id = type;
10301 	}
10302 
10303 	/* check whether we recorded this BTF (and maybe module) already */
10304 	for (i = 0; i < env->used_btf_cnt; i++) {
10305 		if (env->used_btfs[i].btf == btf) {
10306 			btf_put(btf);
10307 			return 0;
10308 		}
10309 	}
10310 
10311 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
10312 		err = -E2BIG;
10313 		goto err_put;
10314 	}
10315 
10316 	btf_mod = &env->used_btfs[env->used_btf_cnt];
10317 	btf_mod->btf = btf;
10318 	btf_mod->module = NULL;
10319 
10320 	/* if we reference variables from kernel module, bump its refcount */
10321 	if (btf_is_module(btf)) {
10322 		btf_mod->module = btf_try_get_module(btf);
10323 		if (!btf_mod->module) {
10324 			err = -ENXIO;
10325 			goto err_put;
10326 		}
10327 	}
10328 
10329 	env->used_btf_cnt++;
10330 
10331 	return 0;
10332 err_put:
10333 	btf_put(btf);
10334 	return err;
10335 }
10336 
10337 static int check_map_prealloc(struct bpf_map *map)
10338 {
10339 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10340 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10341 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10342 		!(map->map_flags & BPF_F_NO_PREALLOC);
10343 }
10344 
10345 static bool is_tracing_prog_type(enum bpf_prog_type type)
10346 {
10347 	switch (type) {
10348 	case BPF_PROG_TYPE_KPROBE:
10349 	case BPF_PROG_TYPE_TRACEPOINT:
10350 	case BPF_PROG_TYPE_PERF_EVENT:
10351 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10352 		return true;
10353 	default:
10354 		return false;
10355 	}
10356 }
10357 
10358 static bool is_preallocated_map(struct bpf_map *map)
10359 {
10360 	if (!check_map_prealloc(map))
10361 		return false;
10362 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10363 		return false;
10364 	return true;
10365 }
10366 
10367 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10368 					struct bpf_map *map,
10369 					struct bpf_prog *prog)
10370 
10371 {
10372 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10373 	/*
10374 	 * Validate that trace type programs use preallocated hash maps.
10375 	 *
10376 	 * For programs attached to PERF events this is mandatory as the
10377 	 * perf NMI can hit any arbitrary code sequence.
10378 	 *
10379 	 * All other trace types using preallocated hash maps are unsafe as
10380 	 * well because tracepoint or kprobes can be inside locked regions
10381 	 * of the memory allocator or at a place where a recursion into the
10382 	 * memory allocator would see inconsistent state.
10383 	 *
10384 	 * On RT enabled kernels run-time allocation of all trace type
10385 	 * programs is strictly prohibited due to lock type constraints. On
10386 	 * !RT kernels it is allowed for backwards compatibility reasons for
10387 	 * now, but warnings are emitted so developers are made aware of
10388 	 * the unsafety and can fix their programs before this is enforced.
10389 	 */
10390 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10391 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10392 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10393 			return -EINVAL;
10394 		}
10395 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10396 			verbose(env, "trace type programs can only use preallocated hash map\n");
10397 			return -EINVAL;
10398 		}
10399 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10400 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10401 	}
10402 
10403 	if (map_value_has_spin_lock(map)) {
10404 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10405 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10406 			return -EINVAL;
10407 		}
10408 
10409 		if (is_tracing_prog_type(prog_type)) {
10410 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10411 			return -EINVAL;
10412 		}
10413 
10414 		if (prog->aux->sleepable) {
10415 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10416 			return -EINVAL;
10417 		}
10418 	}
10419 
10420 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10421 	    !bpf_offload_prog_map_match(prog, map)) {
10422 		verbose(env, "offload device mismatch between prog and map\n");
10423 		return -EINVAL;
10424 	}
10425 
10426 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10427 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10428 		return -EINVAL;
10429 	}
10430 
10431 	if (prog->aux->sleepable)
10432 		switch (map->map_type) {
10433 		case BPF_MAP_TYPE_HASH:
10434 		case BPF_MAP_TYPE_LRU_HASH:
10435 		case BPF_MAP_TYPE_ARRAY:
10436 		case BPF_MAP_TYPE_PERCPU_HASH:
10437 		case BPF_MAP_TYPE_PERCPU_ARRAY:
10438 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10439 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10440 		case BPF_MAP_TYPE_HASH_OF_MAPS:
10441 			if (!is_preallocated_map(map)) {
10442 				verbose(env,
10443 					"Sleepable programs can only use preallocated maps\n");
10444 				return -EINVAL;
10445 			}
10446 			break;
10447 		case BPF_MAP_TYPE_RINGBUF:
10448 			break;
10449 		default:
10450 			verbose(env,
10451 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
10452 			return -EINVAL;
10453 		}
10454 
10455 	return 0;
10456 }
10457 
10458 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10459 {
10460 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10461 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10462 }
10463 
10464 /* find and rewrite pseudo imm in ld_imm64 instructions:
10465  *
10466  * 1. if it accesses map FD, replace it with actual map pointer.
10467  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10468  *
10469  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10470  */
10471 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10472 {
10473 	struct bpf_insn *insn = env->prog->insnsi;
10474 	int insn_cnt = env->prog->len;
10475 	int i, j, err;
10476 
10477 	err = bpf_prog_calc_tag(env->prog);
10478 	if (err)
10479 		return err;
10480 
10481 	for (i = 0; i < insn_cnt; i++, insn++) {
10482 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10483 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10484 			verbose(env, "BPF_LDX uses reserved fields\n");
10485 			return -EINVAL;
10486 		}
10487 
10488 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10489 			struct bpf_insn_aux_data *aux;
10490 			struct bpf_map *map;
10491 			struct fd f;
10492 			u64 addr;
10493 
10494 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10495 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10496 			    insn[1].off != 0) {
10497 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10498 				return -EINVAL;
10499 			}
10500 
10501 			if (insn[0].src_reg == 0)
10502 				/* valid generic load 64-bit imm */
10503 				goto next_insn;
10504 
10505 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10506 				aux = &env->insn_aux_data[i];
10507 				err = check_pseudo_btf_id(env, insn, aux);
10508 				if (err)
10509 					return err;
10510 				goto next_insn;
10511 			}
10512 
10513 			/* In final convert_pseudo_ld_imm64() step, this is
10514 			 * converted into regular 64-bit imm load insn.
10515 			 */
10516 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10517 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10518 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10519 			     insn[1].imm != 0)) {
10520 				verbose(env,
10521 					"unrecognized bpf_ld_imm64 insn\n");
10522 				return -EINVAL;
10523 			}
10524 
10525 			f = fdget(insn[0].imm);
10526 			map = __bpf_map_get(f);
10527 			if (IS_ERR(map)) {
10528 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10529 					insn[0].imm);
10530 				return PTR_ERR(map);
10531 			}
10532 
10533 			err = check_map_prog_compatibility(env, map, env->prog);
10534 			if (err) {
10535 				fdput(f);
10536 				return err;
10537 			}
10538 
10539 			aux = &env->insn_aux_data[i];
10540 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10541 				addr = (unsigned long)map;
10542 			} else {
10543 				u32 off = insn[1].imm;
10544 
10545 				if (off >= BPF_MAX_VAR_OFF) {
10546 					verbose(env, "direct value offset of %u is not allowed\n", off);
10547 					fdput(f);
10548 					return -EINVAL;
10549 				}
10550 
10551 				if (!map->ops->map_direct_value_addr) {
10552 					verbose(env, "no direct value access support for this map type\n");
10553 					fdput(f);
10554 					return -EINVAL;
10555 				}
10556 
10557 				err = map->ops->map_direct_value_addr(map, &addr, off);
10558 				if (err) {
10559 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10560 						map->value_size, off);
10561 					fdput(f);
10562 					return err;
10563 				}
10564 
10565 				aux->map_off = off;
10566 				addr += off;
10567 			}
10568 
10569 			insn[0].imm = (u32)addr;
10570 			insn[1].imm = addr >> 32;
10571 
10572 			/* check whether we recorded this map already */
10573 			for (j = 0; j < env->used_map_cnt; j++) {
10574 				if (env->used_maps[j] == map) {
10575 					aux->map_index = j;
10576 					fdput(f);
10577 					goto next_insn;
10578 				}
10579 			}
10580 
10581 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10582 				fdput(f);
10583 				return -E2BIG;
10584 			}
10585 
10586 			/* hold the map. If the program is rejected by verifier,
10587 			 * the map will be released by release_maps() or it
10588 			 * will be used by the valid program until it's unloaded
10589 			 * and all maps are released in free_used_maps()
10590 			 */
10591 			bpf_map_inc(map);
10592 
10593 			aux->map_index = env->used_map_cnt;
10594 			env->used_maps[env->used_map_cnt++] = map;
10595 
10596 			if (bpf_map_is_cgroup_storage(map) &&
10597 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10598 				verbose(env, "only one cgroup storage of each type is allowed\n");
10599 				fdput(f);
10600 				return -EBUSY;
10601 			}
10602 
10603 			fdput(f);
10604 next_insn:
10605 			insn++;
10606 			i++;
10607 			continue;
10608 		}
10609 
10610 		/* Basic sanity check before we invest more work here. */
10611 		if (!bpf_opcode_in_insntable(insn->code)) {
10612 			verbose(env, "unknown opcode %02x\n", insn->code);
10613 			return -EINVAL;
10614 		}
10615 	}
10616 
10617 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10618 	 * 'struct bpf_map *' into a register instead of user map_fd.
10619 	 * These pointers will be used later by verifier to validate map access.
10620 	 */
10621 	return 0;
10622 }
10623 
10624 /* drop refcnt of maps used by the rejected program */
10625 static void release_maps(struct bpf_verifier_env *env)
10626 {
10627 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10628 			     env->used_map_cnt);
10629 }
10630 
10631 /* drop refcnt of maps used by the rejected program */
10632 static void release_btfs(struct bpf_verifier_env *env)
10633 {
10634 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10635 			     env->used_btf_cnt);
10636 }
10637 
10638 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10639 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10640 {
10641 	struct bpf_insn *insn = env->prog->insnsi;
10642 	int insn_cnt = env->prog->len;
10643 	int i;
10644 
10645 	for (i = 0; i < insn_cnt; i++, insn++)
10646 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10647 			insn->src_reg = 0;
10648 }
10649 
10650 /* single env->prog->insni[off] instruction was replaced with the range
10651  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10652  * [0, off) and [off, end) to new locations, so the patched range stays zero
10653  */
10654 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10655 				struct bpf_prog *new_prog, u32 off, u32 cnt)
10656 {
10657 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10658 	struct bpf_insn *insn = new_prog->insnsi;
10659 	u32 prog_len;
10660 	int i;
10661 
10662 	/* aux info at OFF always needs adjustment, no matter fast path
10663 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10664 	 * original insn at old prog.
10665 	 */
10666 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10667 
10668 	if (cnt == 1)
10669 		return 0;
10670 	prog_len = new_prog->len;
10671 	new_data = vzalloc(array_size(prog_len,
10672 				      sizeof(struct bpf_insn_aux_data)));
10673 	if (!new_data)
10674 		return -ENOMEM;
10675 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10676 	memcpy(new_data + off + cnt - 1, old_data + off,
10677 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10678 	for (i = off; i < off + cnt - 1; i++) {
10679 		new_data[i].seen = env->pass_cnt;
10680 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10681 	}
10682 	env->insn_aux_data = new_data;
10683 	vfree(old_data);
10684 	return 0;
10685 }
10686 
10687 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10688 {
10689 	int i;
10690 
10691 	if (len == 1)
10692 		return;
10693 	/* NOTE: fake 'exit' subprog should be updated as well. */
10694 	for (i = 0; i <= env->subprog_cnt; i++) {
10695 		if (env->subprog_info[i].start <= off)
10696 			continue;
10697 		env->subprog_info[i].start += len - 1;
10698 	}
10699 }
10700 
10701 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10702 {
10703 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10704 	int i, sz = prog->aux->size_poke_tab;
10705 	struct bpf_jit_poke_descriptor *desc;
10706 
10707 	for (i = 0; i < sz; i++) {
10708 		desc = &tab[i];
10709 		desc->insn_idx += len - 1;
10710 	}
10711 }
10712 
10713 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10714 					    const struct bpf_insn *patch, u32 len)
10715 {
10716 	struct bpf_prog *new_prog;
10717 
10718 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10719 	if (IS_ERR(new_prog)) {
10720 		if (PTR_ERR(new_prog) == -ERANGE)
10721 			verbose(env,
10722 				"insn %d cannot be patched due to 16-bit range\n",
10723 				env->insn_aux_data[off].orig_idx);
10724 		return NULL;
10725 	}
10726 	if (adjust_insn_aux_data(env, new_prog, off, len))
10727 		return NULL;
10728 	adjust_subprog_starts(env, off, len);
10729 	adjust_poke_descs(new_prog, len);
10730 	return new_prog;
10731 }
10732 
10733 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10734 					      u32 off, u32 cnt)
10735 {
10736 	int i, j;
10737 
10738 	/* find first prog starting at or after off (first to remove) */
10739 	for (i = 0; i < env->subprog_cnt; i++)
10740 		if (env->subprog_info[i].start >= off)
10741 			break;
10742 	/* find first prog starting at or after off + cnt (first to stay) */
10743 	for (j = i; j < env->subprog_cnt; j++)
10744 		if (env->subprog_info[j].start >= off + cnt)
10745 			break;
10746 	/* if j doesn't start exactly at off + cnt, we are just removing
10747 	 * the front of previous prog
10748 	 */
10749 	if (env->subprog_info[j].start != off + cnt)
10750 		j--;
10751 
10752 	if (j > i) {
10753 		struct bpf_prog_aux *aux = env->prog->aux;
10754 		int move;
10755 
10756 		/* move fake 'exit' subprog as well */
10757 		move = env->subprog_cnt + 1 - j;
10758 
10759 		memmove(env->subprog_info + i,
10760 			env->subprog_info + j,
10761 			sizeof(*env->subprog_info) * move);
10762 		env->subprog_cnt -= j - i;
10763 
10764 		/* remove func_info */
10765 		if (aux->func_info) {
10766 			move = aux->func_info_cnt - j;
10767 
10768 			memmove(aux->func_info + i,
10769 				aux->func_info + j,
10770 				sizeof(*aux->func_info) * move);
10771 			aux->func_info_cnt -= j - i;
10772 			/* func_info->insn_off is set after all code rewrites,
10773 			 * in adjust_btf_func() - no need to adjust
10774 			 */
10775 		}
10776 	} else {
10777 		/* convert i from "first prog to remove" to "first to adjust" */
10778 		if (env->subprog_info[i].start == off)
10779 			i++;
10780 	}
10781 
10782 	/* update fake 'exit' subprog as well */
10783 	for (; i <= env->subprog_cnt; i++)
10784 		env->subprog_info[i].start -= cnt;
10785 
10786 	return 0;
10787 }
10788 
10789 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10790 				      u32 cnt)
10791 {
10792 	struct bpf_prog *prog = env->prog;
10793 	u32 i, l_off, l_cnt, nr_linfo;
10794 	struct bpf_line_info *linfo;
10795 
10796 	nr_linfo = prog->aux->nr_linfo;
10797 	if (!nr_linfo)
10798 		return 0;
10799 
10800 	linfo = prog->aux->linfo;
10801 
10802 	/* find first line info to remove, count lines to be removed */
10803 	for (i = 0; i < nr_linfo; i++)
10804 		if (linfo[i].insn_off >= off)
10805 			break;
10806 
10807 	l_off = i;
10808 	l_cnt = 0;
10809 	for (; i < nr_linfo; i++)
10810 		if (linfo[i].insn_off < off + cnt)
10811 			l_cnt++;
10812 		else
10813 			break;
10814 
10815 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10816 	 * last removed linfo.  prog is already modified, so prog->len == off
10817 	 * means no live instructions after (tail of the program was removed).
10818 	 */
10819 	if (prog->len != off && l_cnt &&
10820 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10821 		l_cnt--;
10822 		linfo[--i].insn_off = off + cnt;
10823 	}
10824 
10825 	/* remove the line info which refer to the removed instructions */
10826 	if (l_cnt) {
10827 		memmove(linfo + l_off, linfo + i,
10828 			sizeof(*linfo) * (nr_linfo - i));
10829 
10830 		prog->aux->nr_linfo -= l_cnt;
10831 		nr_linfo = prog->aux->nr_linfo;
10832 	}
10833 
10834 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10835 	for (i = l_off; i < nr_linfo; i++)
10836 		linfo[i].insn_off -= cnt;
10837 
10838 	/* fix up all subprogs (incl. 'exit') which start >= off */
10839 	for (i = 0; i <= env->subprog_cnt; i++)
10840 		if (env->subprog_info[i].linfo_idx > l_off) {
10841 			/* program may have started in the removed region but
10842 			 * may not be fully removed
10843 			 */
10844 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10845 				env->subprog_info[i].linfo_idx -= l_cnt;
10846 			else
10847 				env->subprog_info[i].linfo_idx = l_off;
10848 		}
10849 
10850 	return 0;
10851 }
10852 
10853 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10854 {
10855 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10856 	unsigned int orig_prog_len = env->prog->len;
10857 	int err;
10858 
10859 	if (bpf_prog_is_dev_bound(env->prog->aux))
10860 		bpf_prog_offload_remove_insns(env, off, cnt);
10861 
10862 	err = bpf_remove_insns(env->prog, off, cnt);
10863 	if (err)
10864 		return err;
10865 
10866 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10867 	if (err)
10868 		return err;
10869 
10870 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10871 	if (err)
10872 		return err;
10873 
10874 	memmove(aux_data + off,	aux_data + off + cnt,
10875 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10876 
10877 	return 0;
10878 }
10879 
10880 /* The verifier does more data flow analysis than llvm and will not
10881  * explore branches that are dead at run time. Malicious programs can
10882  * have dead code too. Therefore replace all dead at-run-time code
10883  * with 'ja -1'.
10884  *
10885  * Just nops are not optimal, e.g. if they would sit at the end of the
10886  * program and through another bug we would manage to jump there, then
10887  * we'd execute beyond program memory otherwise. Returning exception
10888  * code also wouldn't work since we can have subprogs where the dead
10889  * code could be located.
10890  */
10891 static void sanitize_dead_code(struct bpf_verifier_env *env)
10892 {
10893 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10894 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10895 	struct bpf_insn *insn = env->prog->insnsi;
10896 	const int insn_cnt = env->prog->len;
10897 	int i;
10898 
10899 	for (i = 0; i < insn_cnt; i++) {
10900 		if (aux_data[i].seen)
10901 			continue;
10902 		memcpy(insn + i, &trap, sizeof(trap));
10903 	}
10904 }
10905 
10906 static bool insn_is_cond_jump(u8 code)
10907 {
10908 	u8 op;
10909 
10910 	if (BPF_CLASS(code) == BPF_JMP32)
10911 		return true;
10912 
10913 	if (BPF_CLASS(code) != BPF_JMP)
10914 		return false;
10915 
10916 	op = BPF_OP(code);
10917 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10918 }
10919 
10920 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10921 {
10922 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10923 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10924 	struct bpf_insn *insn = env->prog->insnsi;
10925 	const int insn_cnt = env->prog->len;
10926 	int i;
10927 
10928 	for (i = 0; i < insn_cnt; i++, insn++) {
10929 		if (!insn_is_cond_jump(insn->code))
10930 			continue;
10931 
10932 		if (!aux_data[i + 1].seen)
10933 			ja.off = insn->off;
10934 		else if (!aux_data[i + 1 + insn->off].seen)
10935 			ja.off = 0;
10936 		else
10937 			continue;
10938 
10939 		if (bpf_prog_is_dev_bound(env->prog->aux))
10940 			bpf_prog_offload_replace_insn(env, i, &ja);
10941 
10942 		memcpy(insn, &ja, sizeof(ja));
10943 	}
10944 }
10945 
10946 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10947 {
10948 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10949 	int insn_cnt = env->prog->len;
10950 	int i, err;
10951 
10952 	for (i = 0; i < insn_cnt; i++) {
10953 		int j;
10954 
10955 		j = 0;
10956 		while (i + j < insn_cnt && !aux_data[i + j].seen)
10957 			j++;
10958 		if (!j)
10959 			continue;
10960 
10961 		err = verifier_remove_insns(env, i, j);
10962 		if (err)
10963 			return err;
10964 		insn_cnt = env->prog->len;
10965 	}
10966 
10967 	return 0;
10968 }
10969 
10970 static int opt_remove_nops(struct bpf_verifier_env *env)
10971 {
10972 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10973 	struct bpf_insn *insn = env->prog->insnsi;
10974 	int insn_cnt = env->prog->len;
10975 	int i, err;
10976 
10977 	for (i = 0; i < insn_cnt; i++) {
10978 		if (memcmp(&insn[i], &ja, sizeof(ja)))
10979 			continue;
10980 
10981 		err = verifier_remove_insns(env, i, 1);
10982 		if (err)
10983 			return err;
10984 		insn_cnt--;
10985 		i--;
10986 	}
10987 
10988 	return 0;
10989 }
10990 
10991 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10992 					 const union bpf_attr *attr)
10993 {
10994 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10995 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
10996 	int i, patch_len, delta = 0, len = env->prog->len;
10997 	struct bpf_insn *insns = env->prog->insnsi;
10998 	struct bpf_prog *new_prog;
10999 	bool rnd_hi32;
11000 
11001 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11002 	zext_patch[1] = BPF_ZEXT_REG(0);
11003 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11004 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11005 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11006 	for (i = 0; i < len; i++) {
11007 		int adj_idx = i + delta;
11008 		struct bpf_insn insn;
11009 		u8 load_reg;
11010 
11011 		insn = insns[adj_idx];
11012 		if (!aux[adj_idx].zext_dst) {
11013 			u8 code, class;
11014 			u32 imm_rnd;
11015 
11016 			if (!rnd_hi32)
11017 				continue;
11018 
11019 			code = insn.code;
11020 			class = BPF_CLASS(code);
11021 			if (insn_no_def(&insn))
11022 				continue;
11023 
11024 			/* NOTE: arg "reg" (the fourth one) is only used for
11025 			 *       BPF_STX which has been ruled out in above
11026 			 *       check, it is safe to pass NULL here.
11027 			 */
11028 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11029 				if (class == BPF_LD &&
11030 				    BPF_MODE(code) == BPF_IMM)
11031 					i++;
11032 				continue;
11033 			}
11034 
11035 			/* ctx load could be transformed into wider load. */
11036 			if (class == BPF_LDX &&
11037 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
11038 				continue;
11039 
11040 			imm_rnd = get_random_int();
11041 			rnd_hi32_patch[0] = insn;
11042 			rnd_hi32_patch[1].imm = imm_rnd;
11043 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11044 			patch = rnd_hi32_patch;
11045 			patch_len = 4;
11046 			goto apply_patch_buffer;
11047 		}
11048 
11049 		if (!bpf_jit_needs_zext())
11050 			continue;
11051 
11052 		/* zext_dst means that we want to zero-extend whatever register
11053 		 * the insn defines, which is dst_reg most of the time, with
11054 		 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11055 		 */
11056 		if (BPF_CLASS(insn.code) == BPF_STX &&
11057 		    BPF_MODE(insn.code) == BPF_ATOMIC) {
11058 			/* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11059 			 * define any registers, therefore zext_dst cannot be
11060 			 * set.
11061 			 */
11062 			if (WARN_ON(!(insn.imm & BPF_FETCH)))
11063 				return -EINVAL;
11064 			load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11065 							   : insn.src_reg;
11066 		} else {
11067 			load_reg = insn.dst_reg;
11068 		}
11069 
11070 		zext_patch[0] = insn;
11071 		zext_patch[1].dst_reg = load_reg;
11072 		zext_patch[1].src_reg = load_reg;
11073 		patch = zext_patch;
11074 		patch_len = 2;
11075 apply_patch_buffer:
11076 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11077 		if (!new_prog)
11078 			return -ENOMEM;
11079 		env->prog = new_prog;
11080 		insns = new_prog->insnsi;
11081 		aux = env->insn_aux_data;
11082 		delta += patch_len - 1;
11083 	}
11084 
11085 	return 0;
11086 }
11087 
11088 /* convert load instructions that access fields of a context type into a
11089  * sequence of instructions that access fields of the underlying structure:
11090  *     struct __sk_buff    -> struct sk_buff
11091  *     struct bpf_sock_ops -> struct sock
11092  */
11093 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11094 {
11095 	const struct bpf_verifier_ops *ops = env->ops;
11096 	int i, cnt, size, ctx_field_size, delta = 0;
11097 	const int insn_cnt = env->prog->len;
11098 	struct bpf_insn insn_buf[16], *insn;
11099 	u32 target_size, size_default, off;
11100 	struct bpf_prog *new_prog;
11101 	enum bpf_access_type type;
11102 	bool is_narrower_load;
11103 
11104 	if (ops->gen_prologue || env->seen_direct_write) {
11105 		if (!ops->gen_prologue) {
11106 			verbose(env, "bpf verifier is misconfigured\n");
11107 			return -EINVAL;
11108 		}
11109 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11110 					env->prog);
11111 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11112 			verbose(env, "bpf verifier is misconfigured\n");
11113 			return -EINVAL;
11114 		} else if (cnt) {
11115 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11116 			if (!new_prog)
11117 				return -ENOMEM;
11118 
11119 			env->prog = new_prog;
11120 			delta += cnt - 1;
11121 		}
11122 	}
11123 
11124 	if (bpf_prog_is_dev_bound(env->prog->aux))
11125 		return 0;
11126 
11127 	insn = env->prog->insnsi + delta;
11128 
11129 	for (i = 0; i < insn_cnt; i++, insn++) {
11130 		bpf_convert_ctx_access_t convert_ctx_access;
11131 
11132 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11133 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11134 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11135 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11136 			type = BPF_READ;
11137 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11138 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11139 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11140 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11141 			type = BPF_WRITE;
11142 		else
11143 			continue;
11144 
11145 		if (type == BPF_WRITE &&
11146 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
11147 			struct bpf_insn patch[] = {
11148 				/* Sanitize suspicious stack slot with zero.
11149 				 * There are no memory dependencies for this store,
11150 				 * since it's only using frame pointer and immediate
11151 				 * constant of zero
11152 				 */
11153 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11154 					   env->insn_aux_data[i + delta].sanitize_stack_off,
11155 					   0),
11156 				/* the original STX instruction will immediately
11157 				 * overwrite the same stack slot with appropriate value
11158 				 */
11159 				*insn,
11160 			};
11161 
11162 			cnt = ARRAY_SIZE(patch);
11163 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11164 			if (!new_prog)
11165 				return -ENOMEM;
11166 
11167 			delta    += cnt - 1;
11168 			env->prog = new_prog;
11169 			insn      = new_prog->insnsi + i + delta;
11170 			continue;
11171 		}
11172 
11173 		switch (env->insn_aux_data[i + delta].ptr_type) {
11174 		case PTR_TO_CTX:
11175 			if (!ops->convert_ctx_access)
11176 				continue;
11177 			convert_ctx_access = ops->convert_ctx_access;
11178 			break;
11179 		case PTR_TO_SOCKET:
11180 		case PTR_TO_SOCK_COMMON:
11181 			convert_ctx_access = bpf_sock_convert_ctx_access;
11182 			break;
11183 		case PTR_TO_TCP_SOCK:
11184 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11185 			break;
11186 		case PTR_TO_XDP_SOCK:
11187 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11188 			break;
11189 		case PTR_TO_BTF_ID:
11190 			if (type == BPF_READ) {
11191 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11192 					BPF_SIZE((insn)->code);
11193 				env->prog->aux->num_exentries++;
11194 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11195 				verbose(env, "Writes through BTF pointers are not allowed\n");
11196 				return -EINVAL;
11197 			}
11198 			continue;
11199 		default:
11200 			continue;
11201 		}
11202 
11203 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11204 		size = BPF_LDST_BYTES(insn);
11205 
11206 		/* If the read access is a narrower load of the field,
11207 		 * convert to a 4/8-byte load, to minimum program type specific
11208 		 * convert_ctx_access changes. If conversion is successful,
11209 		 * we will apply proper mask to the result.
11210 		 */
11211 		is_narrower_load = size < ctx_field_size;
11212 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11213 		off = insn->off;
11214 		if (is_narrower_load) {
11215 			u8 size_code;
11216 
11217 			if (type == BPF_WRITE) {
11218 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11219 				return -EINVAL;
11220 			}
11221 
11222 			size_code = BPF_H;
11223 			if (ctx_field_size == 4)
11224 				size_code = BPF_W;
11225 			else if (ctx_field_size == 8)
11226 				size_code = BPF_DW;
11227 
11228 			insn->off = off & ~(size_default - 1);
11229 			insn->code = BPF_LDX | BPF_MEM | size_code;
11230 		}
11231 
11232 		target_size = 0;
11233 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11234 					 &target_size);
11235 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11236 		    (ctx_field_size && !target_size)) {
11237 			verbose(env, "bpf verifier is misconfigured\n");
11238 			return -EINVAL;
11239 		}
11240 
11241 		if (is_narrower_load && size < target_size) {
11242 			u8 shift = bpf_ctx_narrow_access_offset(
11243 				off, size, size_default) * 8;
11244 			if (ctx_field_size <= 4) {
11245 				if (shift)
11246 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11247 									insn->dst_reg,
11248 									shift);
11249 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11250 								(1 << size * 8) - 1);
11251 			} else {
11252 				if (shift)
11253 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11254 									insn->dst_reg,
11255 									shift);
11256 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11257 								(1ULL << size * 8) - 1);
11258 			}
11259 		}
11260 
11261 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11262 		if (!new_prog)
11263 			return -ENOMEM;
11264 
11265 		delta += cnt - 1;
11266 
11267 		/* keep walking new program and skip insns we just inserted */
11268 		env->prog = new_prog;
11269 		insn      = new_prog->insnsi + i + delta;
11270 	}
11271 
11272 	return 0;
11273 }
11274 
11275 static int jit_subprogs(struct bpf_verifier_env *env)
11276 {
11277 	struct bpf_prog *prog = env->prog, **func, *tmp;
11278 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11279 	struct bpf_map *map_ptr;
11280 	struct bpf_insn *insn;
11281 	void *old_bpf_func;
11282 	int err, num_exentries;
11283 
11284 	if (env->subprog_cnt <= 1)
11285 		return 0;
11286 
11287 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11288 		if (!bpf_pseudo_call(insn))
11289 			continue;
11290 		/* Upon error here we cannot fall back to interpreter but
11291 		 * need a hard reject of the program. Thus -EFAULT is
11292 		 * propagated in any case.
11293 		 */
11294 		subprog = find_subprog(env, i + insn->imm + 1);
11295 		if (subprog < 0) {
11296 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11297 				  i + insn->imm + 1);
11298 			return -EFAULT;
11299 		}
11300 		/* temporarily remember subprog id inside insn instead of
11301 		 * aux_data, since next loop will split up all insns into funcs
11302 		 */
11303 		insn->off = subprog;
11304 		/* remember original imm in case JIT fails and fallback
11305 		 * to interpreter will be needed
11306 		 */
11307 		env->insn_aux_data[i].call_imm = insn->imm;
11308 		/* point imm to __bpf_call_base+1 from JITs point of view */
11309 		insn->imm = 1;
11310 	}
11311 
11312 	err = bpf_prog_alloc_jited_linfo(prog);
11313 	if (err)
11314 		goto out_undo_insn;
11315 
11316 	err = -ENOMEM;
11317 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11318 	if (!func)
11319 		goto out_undo_insn;
11320 
11321 	for (i = 0; i < env->subprog_cnt; i++) {
11322 		subprog_start = subprog_end;
11323 		subprog_end = env->subprog_info[i + 1].start;
11324 
11325 		len = subprog_end - subprog_start;
11326 		/* BPF_PROG_RUN doesn't call subprogs directly,
11327 		 * hence main prog stats include the runtime of subprogs.
11328 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11329 		 * func[i]->stats will never be accessed and stays NULL
11330 		 */
11331 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11332 		if (!func[i])
11333 			goto out_free;
11334 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11335 		       len * sizeof(struct bpf_insn));
11336 		func[i]->type = prog->type;
11337 		func[i]->len = len;
11338 		if (bpf_prog_calc_tag(func[i]))
11339 			goto out_free;
11340 		func[i]->is_func = 1;
11341 		func[i]->aux->func_idx = i;
11342 		/* the btf and func_info will be freed only at prog->aux */
11343 		func[i]->aux->btf = prog->aux->btf;
11344 		func[i]->aux->func_info = prog->aux->func_info;
11345 
11346 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11347 			u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11348 			int ret;
11349 
11350 			if (!(insn_idx >= subprog_start &&
11351 			      insn_idx <= subprog_end))
11352 				continue;
11353 
11354 			ret = bpf_jit_add_poke_descriptor(func[i],
11355 							  &prog->aux->poke_tab[j]);
11356 			if (ret < 0) {
11357 				verbose(env, "adding tail call poke descriptor failed\n");
11358 				goto out_free;
11359 			}
11360 
11361 			func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11362 
11363 			map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11364 			ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11365 			if (ret < 0) {
11366 				verbose(env, "tracking tail call prog failed\n");
11367 				goto out_free;
11368 			}
11369 		}
11370 
11371 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
11372 		 * Long term would need debug info to populate names
11373 		 */
11374 		func[i]->aux->name[0] = 'F';
11375 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11376 		func[i]->jit_requested = 1;
11377 		func[i]->aux->linfo = prog->aux->linfo;
11378 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11379 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11380 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11381 		num_exentries = 0;
11382 		insn = func[i]->insnsi;
11383 		for (j = 0; j < func[i]->len; j++, insn++) {
11384 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11385 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11386 				num_exentries++;
11387 		}
11388 		func[i]->aux->num_exentries = num_exentries;
11389 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11390 		func[i] = bpf_int_jit_compile(func[i]);
11391 		if (!func[i]->jited) {
11392 			err = -ENOTSUPP;
11393 			goto out_free;
11394 		}
11395 		cond_resched();
11396 	}
11397 
11398 	/* Untrack main program's aux structs so that during map_poke_run()
11399 	 * we will not stumble upon the unfilled poke descriptors; each
11400 	 * of the main program's poke descs got distributed across subprogs
11401 	 * and got tracked onto map, so we are sure that none of them will
11402 	 * be missed after the operation below
11403 	 */
11404 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11405 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11406 
11407 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11408 	}
11409 
11410 	/* at this point all bpf functions were successfully JITed
11411 	 * now populate all bpf_calls with correct addresses and
11412 	 * run last pass of JIT
11413 	 */
11414 	for (i = 0; i < env->subprog_cnt; i++) {
11415 		insn = func[i]->insnsi;
11416 		for (j = 0; j < func[i]->len; j++, insn++) {
11417 			if (!bpf_pseudo_call(insn))
11418 				continue;
11419 			subprog = insn->off;
11420 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11421 				    __bpf_call_base;
11422 		}
11423 
11424 		/* we use the aux data to keep a list of the start addresses
11425 		 * of the JITed images for each function in the program
11426 		 *
11427 		 * for some architectures, such as powerpc64, the imm field
11428 		 * might not be large enough to hold the offset of the start
11429 		 * address of the callee's JITed image from __bpf_call_base
11430 		 *
11431 		 * in such cases, we can lookup the start address of a callee
11432 		 * by using its subprog id, available from the off field of
11433 		 * the call instruction, as an index for this list
11434 		 */
11435 		func[i]->aux->func = func;
11436 		func[i]->aux->func_cnt = env->subprog_cnt;
11437 	}
11438 	for (i = 0; i < env->subprog_cnt; i++) {
11439 		old_bpf_func = func[i]->bpf_func;
11440 		tmp = bpf_int_jit_compile(func[i]);
11441 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11442 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11443 			err = -ENOTSUPP;
11444 			goto out_free;
11445 		}
11446 		cond_resched();
11447 	}
11448 
11449 	/* finally lock prog and jit images for all functions and
11450 	 * populate kallsysm
11451 	 */
11452 	for (i = 0; i < env->subprog_cnt; i++) {
11453 		bpf_prog_lock_ro(func[i]);
11454 		bpf_prog_kallsyms_add(func[i]);
11455 	}
11456 
11457 	/* Last step: make now unused interpreter insns from main
11458 	 * prog consistent for later dump requests, so they can
11459 	 * later look the same as if they were interpreted only.
11460 	 */
11461 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11462 		if (!bpf_pseudo_call(insn))
11463 			continue;
11464 		insn->off = env->insn_aux_data[i].call_imm;
11465 		subprog = find_subprog(env, i + insn->off + 1);
11466 		insn->imm = subprog;
11467 	}
11468 
11469 	prog->jited = 1;
11470 	prog->bpf_func = func[0]->bpf_func;
11471 	prog->aux->func = func;
11472 	prog->aux->func_cnt = env->subprog_cnt;
11473 	bpf_prog_free_unused_jited_linfo(prog);
11474 	return 0;
11475 out_free:
11476 	for (i = 0; i < env->subprog_cnt; i++) {
11477 		if (!func[i])
11478 			continue;
11479 
11480 		for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11481 			map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11482 			map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11483 		}
11484 		bpf_jit_free(func[i]);
11485 	}
11486 	kfree(func);
11487 out_undo_insn:
11488 	/* cleanup main prog to be interpreted */
11489 	prog->jit_requested = 0;
11490 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11491 		if (!bpf_pseudo_call(insn))
11492 			continue;
11493 		insn->off = 0;
11494 		insn->imm = env->insn_aux_data[i].call_imm;
11495 	}
11496 	bpf_prog_free_jited_linfo(prog);
11497 	return err;
11498 }
11499 
11500 static int fixup_call_args(struct bpf_verifier_env *env)
11501 {
11502 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11503 	struct bpf_prog *prog = env->prog;
11504 	struct bpf_insn *insn = prog->insnsi;
11505 	int i, depth;
11506 #endif
11507 	int err = 0;
11508 
11509 	if (env->prog->jit_requested &&
11510 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11511 		err = jit_subprogs(env);
11512 		if (err == 0)
11513 			return 0;
11514 		if (err == -EFAULT)
11515 			return err;
11516 	}
11517 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11518 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11519 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11520 		 * have to be rejected, since interpreter doesn't support them yet.
11521 		 */
11522 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11523 		return -EINVAL;
11524 	}
11525 	for (i = 0; i < prog->len; i++, insn++) {
11526 		if (!bpf_pseudo_call(insn))
11527 			continue;
11528 		depth = get_callee_stack_depth(env, insn, i);
11529 		if (depth < 0)
11530 			return depth;
11531 		bpf_patch_call_args(insn, depth);
11532 	}
11533 	err = 0;
11534 #endif
11535 	return err;
11536 }
11537 
11538 /* fixup insn->imm field of bpf_call instructions
11539  * and inline eligible helpers as explicit sequence of BPF instructions
11540  *
11541  * this function is called after eBPF program passed verification
11542  */
11543 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11544 {
11545 	struct bpf_prog *prog = env->prog;
11546 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11547 	struct bpf_insn *insn = prog->insnsi;
11548 	const struct bpf_func_proto *fn;
11549 	const int insn_cnt = prog->len;
11550 	const struct bpf_map_ops *ops;
11551 	struct bpf_insn_aux_data *aux;
11552 	struct bpf_insn insn_buf[16];
11553 	struct bpf_prog *new_prog;
11554 	struct bpf_map *map_ptr;
11555 	int i, ret, cnt, delta = 0;
11556 
11557 	for (i = 0; i < insn_cnt; i++, insn++) {
11558 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11559 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11560 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11561 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11562 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11563 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11564 			struct bpf_insn *patchlet;
11565 			struct bpf_insn chk_and_div[] = {
11566 				/* [R,W]x div 0 -> 0 */
11567 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11568 					     BPF_JNE | BPF_K, insn->src_reg,
11569 					     0, 2, 0),
11570 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11571 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11572 				*insn,
11573 			};
11574 			struct bpf_insn chk_and_mod[] = {
11575 				/* [R,W]x mod 0 -> [R,W]x */
11576 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11577 					     BPF_JEQ | BPF_K, insn->src_reg,
11578 					     0, 1 + (is64 ? 0 : 1), 0),
11579 				*insn,
11580 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11581 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11582 			};
11583 
11584 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11585 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11586 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11587 
11588 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11589 			if (!new_prog)
11590 				return -ENOMEM;
11591 
11592 			delta    += cnt - 1;
11593 			env->prog = prog = new_prog;
11594 			insn      = new_prog->insnsi + i + delta;
11595 			continue;
11596 		}
11597 
11598 		if (BPF_CLASS(insn->code) == BPF_LD &&
11599 		    (BPF_MODE(insn->code) == BPF_ABS ||
11600 		     BPF_MODE(insn->code) == BPF_IND)) {
11601 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11602 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11603 				verbose(env, "bpf verifier is misconfigured\n");
11604 				return -EINVAL;
11605 			}
11606 
11607 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11608 			if (!new_prog)
11609 				return -ENOMEM;
11610 
11611 			delta    += cnt - 1;
11612 			env->prog = prog = new_prog;
11613 			insn      = new_prog->insnsi + i + delta;
11614 			continue;
11615 		}
11616 
11617 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11618 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11619 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11620 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11621 			struct bpf_insn insn_buf[16];
11622 			struct bpf_insn *patch = &insn_buf[0];
11623 			bool issrc, isneg;
11624 			u32 off_reg;
11625 
11626 			aux = &env->insn_aux_data[i + delta];
11627 			if (!aux->alu_state ||
11628 			    aux->alu_state == BPF_ALU_NON_POINTER)
11629 				continue;
11630 
11631 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11632 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11633 				BPF_ALU_SANITIZE_SRC;
11634 
11635 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11636 			if (isneg)
11637 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11638 			*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11639 			*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11640 			*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11641 			*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11642 			*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11643 			if (issrc) {
11644 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11645 							 off_reg);
11646 				insn->src_reg = BPF_REG_AX;
11647 			} else {
11648 				*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11649 							 BPF_REG_AX);
11650 			}
11651 			if (isneg)
11652 				insn->code = insn->code == code_add ?
11653 					     code_sub : code_add;
11654 			*patch++ = *insn;
11655 			if (issrc && isneg)
11656 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11657 			cnt = patch - insn_buf;
11658 
11659 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11660 			if (!new_prog)
11661 				return -ENOMEM;
11662 
11663 			delta    += cnt - 1;
11664 			env->prog = prog = new_prog;
11665 			insn      = new_prog->insnsi + i + delta;
11666 			continue;
11667 		}
11668 
11669 		if (insn->code != (BPF_JMP | BPF_CALL))
11670 			continue;
11671 		if (insn->src_reg == BPF_PSEUDO_CALL)
11672 			continue;
11673 
11674 		if (insn->imm == BPF_FUNC_get_route_realm)
11675 			prog->dst_needed = 1;
11676 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11677 			bpf_user_rnd_init_once();
11678 		if (insn->imm == BPF_FUNC_override_return)
11679 			prog->kprobe_override = 1;
11680 		if (insn->imm == BPF_FUNC_tail_call) {
11681 			/* If we tail call into other programs, we
11682 			 * cannot make any assumptions since they can
11683 			 * be replaced dynamically during runtime in
11684 			 * the program array.
11685 			 */
11686 			prog->cb_access = 1;
11687 			if (!allow_tail_call_in_subprogs(env))
11688 				prog->aux->stack_depth = MAX_BPF_STACK;
11689 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11690 
11691 			/* mark bpf_tail_call as different opcode to avoid
11692 			 * conditional branch in the interpeter for every normal
11693 			 * call and to prevent accidental JITing by JIT compiler
11694 			 * that doesn't support bpf_tail_call yet
11695 			 */
11696 			insn->imm = 0;
11697 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11698 
11699 			aux = &env->insn_aux_data[i + delta];
11700 			if (env->bpf_capable && !expect_blinding &&
11701 			    prog->jit_requested &&
11702 			    !bpf_map_key_poisoned(aux) &&
11703 			    !bpf_map_ptr_poisoned(aux) &&
11704 			    !bpf_map_ptr_unpriv(aux)) {
11705 				struct bpf_jit_poke_descriptor desc = {
11706 					.reason = BPF_POKE_REASON_TAIL_CALL,
11707 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11708 					.tail_call.key = bpf_map_key_immediate(aux),
11709 					.insn_idx = i + delta,
11710 				};
11711 
11712 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11713 				if (ret < 0) {
11714 					verbose(env, "adding tail call poke descriptor failed\n");
11715 					return ret;
11716 				}
11717 
11718 				insn->imm = ret + 1;
11719 				continue;
11720 			}
11721 
11722 			if (!bpf_map_ptr_unpriv(aux))
11723 				continue;
11724 
11725 			/* instead of changing every JIT dealing with tail_call
11726 			 * emit two extra insns:
11727 			 * if (index >= max_entries) goto out;
11728 			 * index &= array->index_mask;
11729 			 * to avoid out-of-bounds cpu speculation
11730 			 */
11731 			if (bpf_map_ptr_poisoned(aux)) {
11732 				verbose(env, "tail_call abusing map_ptr\n");
11733 				return -EINVAL;
11734 			}
11735 
11736 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11737 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11738 						  map_ptr->max_entries, 2);
11739 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11740 						    container_of(map_ptr,
11741 								 struct bpf_array,
11742 								 map)->index_mask);
11743 			insn_buf[2] = *insn;
11744 			cnt = 3;
11745 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11746 			if (!new_prog)
11747 				return -ENOMEM;
11748 
11749 			delta    += cnt - 1;
11750 			env->prog = prog = new_prog;
11751 			insn      = new_prog->insnsi + i + delta;
11752 			continue;
11753 		}
11754 
11755 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11756 		 * and other inlining handlers are currently limited to 64 bit
11757 		 * only.
11758 		 */
11759 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11760 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11761 		     insn->imm == BPF_FUNC_map_update_elem ||
11762 		     insn->imm == BPF_FUNC_map_delete_elem ||
11763 		     insn->imm == BPF_FUNC_map_push_elem   ||
11764 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11765 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11766 			aux = &env->insn_aux_data[i + delta];
11767 			if (bpf_map_ptr_poisoned(aux))
11768 				goto patch_call_imm;
11769 
11770 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11771 			ops = map_ptr->ops;
11772 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11773 			    ops->map_gen_lookup) {
11774 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11775 				if (cnt == -EOPNOTSUPP)
11776 					goto patch_map_ops_generic;
11777 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11778 					verbose(env, "bpf verifier is misconfigured\n");
11779 					return -EINVAL;
11780 				}
11781 
11782 				new_prog = bpf_patch_insn_data(env, i + delta,
11783 							       insn_buf, cnt);
11784 				if (!new_prog)
11785 					return -ENOMEM;
11786 
11787 				delta    += cnt - 1;
11788 				env->prog = prog = new_prog;
11789 				insn      = new_prog->insnsi + i + delta;
11790 				continue;
11791 			}
11792 
11793 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11794 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11795 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11796 				     (int (*)(struct bpf_map *map, void *key))NULL));
11797 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11798 				     (int (*)(struct bpf_map *map, void *key, void *value,
11799 					      u64 flags))NULL));
11800 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11801 				     (int (*)(struct bpf_map *map, void *value,
11802 					      u64 flags))NULL));
11803 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11804 				     (int (*)(struct bpf_map *map, void *value))NULL));
11805 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11806 				     (int (*)(struct bpf_map *map, void *value))NULL));
11807 patch_map_ops_generic:
11808 			switch (insn->imm) {
11809 			case BPF_FUNC_map_lookup_elem:
11810 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11811 					    __bpf_call_base;
11812 				continue;
11813 			case BPF_FUNC_map_update_elem:
11814 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11815 					    __bpf_call_base;
11816 				continue;
11817 			case BPF_FUNC_map_delete_elem:
11818 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11819 					    __bpf_call_base;
11820 				continue;
11821 			case BPF_FUNC_map_push_elem:
11822 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11823 					    __bpf_call_base;
11824 				continue;
11825 			case BPF_FUNC_map_pop_elem:
11826 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11827 					    __bpf_call_base;
11828 				continue;
11829 			case BPF_FUNC_map_peek_elem:
11830 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11831 					    __bpf_call_base;
11832 				continue;
11833 			}
11834 
11835 			goto patch_call_imm;
11836 		}
11837 
11838 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11839 		    insn->imm == BPF_FUNC_jiffies64) {
11840 			struct bpf_insn ld_jiffies_addr[2] = {
11841 				BPF_LD_IMM64(BPF_REG_0,
11842 					     (unsigned long)&jiffies),
11843 			};
11844 
11845 			insn_buf[0] = ld_jiffies_addr[0];
11846 			insn_buf[1] = ld_jiffies_addr[1];
11847 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11848 						  BPF_REG_0, 0);
11849 			cnt = 3;
11850 
11851 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11852 						       cnt);
11853 			if (!new_prog)
11854 				return -ENOMEM;
11855 
11856 			delta    += cnt - 1;
11857 			env->prog = prog = new_prog;
11858 			insn      = new_prog->insnsi + i + delta;
11859 			continue;
11860 		}
11861 
11862 patch_call_imm:
11863 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11864 		/* all functions that have prototype and verifier allowed
11865 		 * programs to call them, must be real in-kernel functions
11866 		 */
11867 		if (!fn->func) {
11868 			verbose(env,
11869 				"kernel subsystem misconfigured func %s#%d\n",
11870 				func_id_name(insn->imm), insn->imm);
11871 			return -EFAULT;
11872 		}
11873 		insn->imm = fn->func - __bpf_call_base;
11874 	}
11875 
11876 	/* Since poke tab is now finalized, publish aux to tracker. */
11877 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11878 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11879 		if (!map_ptr->ops->map_poke_track ||
11880 		    !map_ptr->ops->map_poke_untrack ||
11881 		    !map_ptr->ops->map_poke_run) {
11882 			verbose(env, "bpf verifier is misconfigured\n");
11883 			return -EINVAL;
11884 		}
11885 
11886 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11887 		if (ret < 0) {
11888 			verbose(env, "tracking tail call prog failed\n");
11889 			return ret;
11890 		}
11891 	}
11892 
11893 	return 0;
11894 }
11895 
11896 static void free_states(struct bpf_verifier_env *env)
11897 {
11898 	struct bpf_verifier_state_list *sl, *sln;
11899 	int i;
11900 
11901 	sl = env->free_list;
11902 	while (sl) {
11903 		sln = sl->next;
11904 		free_verifier_state(&sl->state, false);
11905 		kfree(sl);
11906 		sl = sln;
11907 	}
11908 	env->free_list = NULL;
11909 
11910 	if (!env->explored_states)
11911 		return;
11912 
11913 	for (i = 0; i < state_htab_size(env); i++) {
11914 		sl = env->explored_states[i];
11915 
11916 		while (sl) {
11917 			sln = sl->next;
11918 			free_verifier_state(&sl->state, false);
11919 			kfree(sl);
11920 			sl = sln;
11921 		}
11922 		env->explored_states[i] = NULL;
11923 	}
11924 }
11925 
11926 /* The verifier is using insn_aux_data[] to store temporary data during
11927  * verification and to store information for passes that run after the
11928  * verification like dead code sanitization. do_check_common() for subprogram N
11929  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11930  * temporary data after do_check_common() finds that subprogram N cannot be
11931  * verified independently. pass_cnt counts the number of times
11932  * do_check_common() was run and insn->aux->seen tells the pass number
11933  * insn_aux_data was touched. These variables are compared to clear temporary
11934  * data from failed pass. For testing and experiments do_check_common() can be
11935  * run multiple times even when prior attempt to verify is unsuccessful.
11936  */
11937 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11938 {
11939 	struct bpf_insn *insn = env->prog->insnsi;
11940 	struct bpf_insn_aux_data *aux;
11941 	int i, class;
11942 
11943 	for (i = 0; i < env->prog->len; i++) {
11944 		class = BPF_CLASS(insn[i].code);
11945 		if (class != BPF_LDX && class != BPF_STX)
11946 			continue;
11947 		aux = &env->insn_aux_data[i];
11948 		if (aux->seen != env->pass_cnt)
11949 			continue;
11950 		memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11951 	}
11952 }
11953 
11954 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11955 {
11956 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11957 	struct bpf_verifier_state *state;
11958 	struct bpf_reg_state *regs;
11959 	int ret, i;
11960 
11961 	env->prev_linfo = NULL;
11962 	env->pass_cnt++;
11963 
11964 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11965 	if (!state)
11966 		return -ENOMEM;
11967 	state->curframe = 0;
11968 	state->speculative = false;
11969 	state->branches = 1;
11970 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11971 	if (!state->frame[0]) {
11972 		kfree(state);
11973 		return -ENOMEM;
11974 	}
11975 	env->cur_state = state;
11976 	init_func_state(env, state->frame[0],
11977 			BPF_MAIN_FUNC /* callsite */,
11978 			0 /* frameno */,
11979 			subprog);
11980 
11981 	regs = state->frame[state->curframe]->regs;
11982 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11983 		ret = btf_prepare_func_args(env, subprog, regs);
11984 		if (ret)
11985 			goto out;
11986 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11987 			if (regs[i].type == PTR_TO_CTX)
11988 				mark_reg_known_zero(env, regs, i);
11989 			else if (regs[i].type == SCALAR_VALUE)
11990 				mark_reg_unknown(env, regs, i);
11991 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
11992 				const u32 mem_size = regs[i].mem_size;
11993 
11994 				mark_reg_known_zero(env, regs, i);
11995 				regs[i].mem_size = mem_size;
11996 				regs[i].id = ++env->id_gen;
11997 			}
11998 		}
11999 	} else {
12000 		/* 1st arg to a function */
12001 		regs[BPF_REG_1].type = PTR_TO_CTX;
12002 		mark_reg_known_zero(env, regs, BPF_REG_1);
12003 		ret = btf_check_func_arg_match(env, subprog, regs);
12004 		if (ret == -EFAULT)
12005 			/* unlikely verifier bug. abort.
12006 			 * ret == 0 and ret < 0 are sadly acceptable for
12007 			 * main() function due to backward compatibility.
12008 			 * Like socket filter program may be written as:
12009 			 * int bpf_prog(struct pt_regs *ctx)
12010 			 * and never dereference that ctx in the program.
12011 			 * 'struct pt_regs' is a type mismatch for socket
12012 			 * filter that should be using 'struct __sk_buff'.
12013 			 */
12014 			goto out;
12015 	}
12016 
12017 	ret = do_check(env);
12018 out:
12019 	/* check for NULL is necessary, since cur_state can be freed inside
12020 	 * do_check() under memory pressure.
12021 	 */
12022 	if (env->cur_state) {
12023 		free_verifier_state(env->cur_state, true);
12024 		env->cur_state = NULL;
12025 	}
12026 	while (!pop_stack(env, NULL, NULL, false));
12027 	if (!ret && pop_log)
12028 		bpf_vlog_reset(&env->log, 0);
12029 	free_states(env);
12030 	if (ret)
12031 		/* clean aux data in case subprog was rejected */
12032 		sanitize_insn_aux_data(env);
12033 	return ret;
12034 }
12035 
12036 /* Verify all global functions in a BPF program one by one based on their BTF.
12037  * All global functions must pass verification. Otherwise the whole program is rejected.
12038  * Consider:
12039  * int bar(int);
12040  * int foo(int f)
12041  * {
12042  *    return bar(f);
12043  * }
12044  * int bar(int b)
12045  * {
12046  *    ...
12047  * }
12048  * foo() will be verified first for R1=any_scalar_value. During verification it
12049  * will be assumed that bar() already verified successfully and call to bar()
12050  * from foo() will be checked for type match only. Later bar() will be verified
12051  * independently to check that it's safe for R1=any_scalar_value.
12052  */
12053 static int do_check_subprogs(struct bpf_verifier_env *env)
12054 {
12055 	struct bpf_prog_aux *aux = env->prog->aux;
12056 	int i, ret;
12057 
12058 	if (!aux->func_info)
12059 		return 0;
12060 
12061 	for (i = 1; i < env->subprog_cnt; i++) {
12062 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12063 			continue;
12064 		env->insn_idx = env->subprog_info[i].start;
12065 		WARN_ON_ONCE(env->insn_idx == 0);
12066 		ret = do_check_common(env, i);
12067 		if (ret) {
12068 			return ret;
12069 		} else if (env->log.level & BPF_LOG_LEVEL) {
12070 			verbose(env,
12071 				"Func#%d is safe for any args that match its prototype\n",
12072 				i);
12073 		}
12074 	}
12075 	return 0;
12076 }
12077 
12078 static int do_check_main(struct bpf_verifier_env *env)
12079 {
12080 	int ret;
12081 
12082 	env->insn_idx = 0;
12083 	ret = do_check_common(env, 0);
12084 	if (!ret)
12085 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12086 	return ret;
12087 }
12088 
12089 
12090 static void print_verification_stats(struct bpf_verifier_env *env)
12091 {
12092 	int i;
12093 
12094 	if (env->log.level & BPF_LOG_STATS) {
12095 		verbose(env, "verification time %lld usec\n",
12096 			div_u64(env->verification_time, 1000));
12097 		verbose(env, "stack depth ");
12098 		for (i = 0; i < env->subprog_cnt; i++) {
12099 			u32 depth = env->subprog_info[i].stack_depth;
12100 
12101 			verbose(env, "%d", depth);
12102 			if (i + 1 < env->subprog_cnt)
12103 				verbose(env, "+");
12104 		}
12105 		verbose(env, "\n");
12106 	}
12107 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12108 		"total_states %d peak_states %d mark_read %d\n",
12109 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12110 		env->max_states_per_insn, env->total_states,
12111 		env->peak_states, env->longest_mark_read_walk);
12112 }
12113 
12114 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12115 {
12116 	const struct btf_type *t, *func_proto;
12117 	const struct bpf_struct_ops *st_ops;
12118 	const struct btf_member *member;
12119 	struct bpf_prog *prog = env->prog;
12120 	u32 btf_id, member_idx;
12121 	const char *mname;
12122 
12123 	btf_id = prog->aux->attach_btf_id;
12124 	st_ops = bpf_struct_ops_find(btf_id);
12125 	if (!st_ops) {
12126 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12127 			btf_id);
12128 		return -ENOTSUPP;
12129 	}
12130 
12131 	t = st_ops->type;
12132 	member_idx = prog->expected_attach_type;
12133 	if (member_idx >= btf_type_vlen(t)) {
12134 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12135 			member_idx, st_ops->name);
12136 		return -EINVAL;
12137 	}
12138 
12139 	member = &btf_type_member(t)[member_idx];
12140 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12141 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12142 					       NULL);
12143 	if (!func_proto) {
12144 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12145 			mname, member_idx, st_ops->name);
12146 		return -EINVAL;
12147 	}
12148 
12149 	if (st_ops->check_member) {
12150 		int err = st_ops->check_member(t, member);
12151 
12152 		if (err) {
12153 			verbose(env, "attach to unsupported member %s of struct %s\n",
12154 				mname, st_ops->name);
12155 			return err;
12156 		}
12157 	}
12158 
12159 	prog->aux->attach_func_proto = func_proto;
12160 	prog->aux->attach_func_name = mname;
12161 	env->ops = st_ops->verifier_ops;
12162 
12163 	return 0;
12164 }
12165 #define SECURITY_PREFIX "security_"
12166 
12167 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12168 {
12169 	if (within_error_injection_list(addr) ||
12170 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12171 		return 0;
12172 
12173 	return -EINVAL;
12174 }
12175 
12176 /* list of non-sleepable functions that are otherwise on
12177  * ALLOW_ERROR_INJECTION list
12178  */
12179 BTF_SET_START(btf_non_sleepable_error_inject)
12180 /* Three functions below can be called from sleepable and non-sleepable context.
12181  * Assume non-sleepable from bpf safety point of view.
12182  */
12183 BTF_ID(func, __add_to_page_cache_locked)
12184 BTF_ID(func, should_fail_alloc_page)
12185 BTF_ID(func, should_failslab)
12186 BTF_SET_END(btf_non_sleepable_error_inject)
12187 
12188 static int check_non_sleepable_error_inject(u32 btf_id)
12189 {
12190 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12191 }
12192 
12193 int bpf_check_attach_target(struct bpf_verifier_log *log,
12194 			    const struct bpf_prog *prog,
12195 			    const struct bpf_prog *tgt_prog,
12196 			    u32 btf_id,
12197 			    struct bpf_attach_target_info *tgt_info)
12198 {
12199 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12200 	const char prefix[] = "btf_trace_";
12201 	int ret = 0, subprog = -1, i;
12202 	const struct btf_type *t;
12203 	bool conservative = true;
12204 	const char *tname;
12205 	struct btf *btf;
12206 	long addr = 0;
12207 
12208 	if (!btf_id) {
12209 		bpf_log(log, "Tracing programs must provide btf_id\n");
12210 		return -EINVAL;
12211 	}
12212 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12213 	if (!btf) {
12214 		bpf_log(log,
12215 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12216 		return -EINVAL;
12217 	}
12218 	t = btf_type_by_id(btf, btf_id);
12219 	if (!t) {
12220 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12221 		return -EINVAL;
12222 	}
12223 	tname = btf_name_by_offset(btf, t->name_off);
12224 	if (!tname) {
12225 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12226 		return -EINVAL;
12227 	}
12228 	if (tgt_prog) {
12229 		struct bpf_prog_aux *aux = tgt_prog->aux;
12230 
12231 		for (i = 0; i < aux->func_info_cnt; i++)
12232 			if (aux->func_info[i].type_id == btf_id) {
12233 				subprog = i;
12234 				break;
12235 			}
12236 		if (subprog == -1) {
12237 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12238 			return -EINVAL;
12239 		}
12240 		conservative = aux->func_info_aux[subprog].unreliable;
12241 		if (prog_extension) {
12242 			if (conservative) {
12243 				bpf_log(log,
12244 					"Cannot replace static functions\n");
12245 				return -EINVAL;
12246 			}
12247 			if (!prog->jit_requested) {
12248 				bpf_log(log,
12249 					"Extension programs should be JITed\n");
12250 				return -EINVAL;
12251 			}
12252 		}
12253 		if (!tgt_prog->jited) {
12254 			bpf_log(log, "Can attach to only JITed progs\n");
12255 			return -EINVAL;
12256 		}
12257 		if (tgt_prog->type == prog->type) {
12258 			/* Cannot fentry/fexit another fentry/fexit program.
12259 			 * Cannot attach program extension to another extension.
12260 			 * It's ok to attach fentry/fexit to extension program.
12261 			 */
12262 			bpf_log(log, "Cannot recursively attach\n");
12263 			return -EINVAL;
12264 		}
12265 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12266 		    prog_extension &&
12267 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12268 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12269 			/* Program extensions can extend all program types
12270 			 * except fentry/fexit. The reason is the following.
12271 			 * The fentry/fexit programs are used for performance
12272 			 * analysis, stats and can be attached to any program
12273 			 * type except themselves. When extension program is
12274 			 * replacing XDP function it is necessary to allow
12275 			 * performance analysis of all functions. Both original
12276 			 * XDP program and its program extension. Hence
12277 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12278 			 * allowed. If extending of fentry/fexit was allowed it
12279 			 * would be possible to create long call chain
12280 			 * fentry->extension->fentry->extension beyond
12281 			 * reasonable stack size. Hence extending fentry is not
12282 			 * allowed.
12283 			 */
12284 			bpf_log(log, "Cannot extend fentry/fexit\n");
12285 			return -EINVAL;
12286 		}
12287 	} else {
12288 		if (prog_extension) {
12289 			bpf_log(log, "Cannot replace kernel functions\n");
12290 			return -EINVAL;
12291 		}
12292 	}
12293 
12294 	switch (prog->expected_attach_type) {
12295 	case BPF_TRACE_RAW_TP:
12296 		if (tgt_prog) {
12297 			bpf_log(log,
12298 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12299 			return -EINVAL;
12300 		}
12301 		if (!btf_type_is_typedef(t)) {
12302 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12303 				btf_id);
12304 			return -EINVAL;
12305 		}
12306 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12307 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12308 				btf_id, tname);
12309 			return -EINVAL;
12310 		}
12311 		tname += sizeof(prefix) - 1;
12312 		t = btf_type_by_id(btf, t->type);
12313 		if (!btf_type_is_ptr(t))
12314 			/* should never happen in valid vmlinux build */
12315 			return -EINVAL;
12316 		t = btf_type_by_id(btf, t->type);
12317 		if (!btf_type_is_func_proto(t))
12318 			/* should never happen in valid vmlinux build */
12319 			return -EINVAL;
12320 
12321 		break;
12322 	case BPF_TRACE_ITER:
12323 		if (!btf_type_is_func(t)) {
12324 			bpf_log(log, "attach_btf_id %u is not a function\n",
12325 				btf_id);
12326 			return -EINVAL;
12327 		}
12328 		t = btf_type_by_id(btf, t->type);
12329 		if (!btf_type_is_func_proto(t))
12330 			return -EINVAL;
12331 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12332 		if (ret)
12333 			return ret;
12334 		break;
12335 	default:
12336 		if (!prog_extension)
12337 			return -EINVAL;
12338 		fallthrough;
12339 	case BPF_MODIFY_RETURN:
12340 	case BPF_LSM_MAC:
12341 	case BPF_TRACE_FENTRY:
12342 	case BPF_TRACE_FEXIT:
12343 		if (!btf_type_is_func(t)) {
12344 			bpf_log(log, "attach_btf_id %u is not a function\n",
12345 				btf_id);
12346 			return -EINVAL;
12347 		}
12348 		if (prog_extension &&
12349 		    btf_check_type_match(log, prog, btf, t))
12350 			return -EINVAL;
12351 		t = btf_type_by_id(btf, t->type);
12352 		if (!btf_type_is_func_proto(t))
12353 			return -EINVAL;
12354 
12355 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12356 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12357 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12358 			return -EINVAL;
12359 
12360 		if (tgt_prog && conservative)
12361 			t = NULL;
12362 
12363 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12364 		if (ret < 0)
12365 			return ret;
12366 
12367 		if (tgt_prog) {
12368 			if (subprog == 0)
12369 				addr = (long) tgt_prog->bpf_func;
12370 			else
12371 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12372 		} else {
12373 			addr = kallsyms_lookup_name(tname);
12374 			if (!addr) {
12375 				bpf_log(log,
12376 					"The address of function %s cannot be found\n",
12377 					tname);
12378 				return -ENOENT;
12379 			}
12380 		}
12381 
12382 		if (prog->aux->sleepable) {
12383 			ret = -EINVAL;
12384 			switch (prog->type) {
12385 			case BPF_PROG_TYPE_TRACING:
12386 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12387 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12388 				 */
12389 				if (!check_non_sleepable_error_inject(btf_id) &&
12390 				    within_error_injection_list(addr))
12391 					ret = 0;
12392 				break;
12393 			case BPF_PROG_TYPE_LSM:
12394 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12395 				 * Only some of them are sleepable.
12396 				 */
12397 				if (bpf_lsm_is_sleepable_hook(btf_id))
12398 					ret = 0;
12399 				break;
12400 			default:
12401 				break;
12402 			}
12403 			if (ret) {
12404 				bpf_log(log, "%s is not sleepable\n", tname);
12405 				return ret;
12406 			}
12407 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12408 			if (tgt_prog) {
12409 				bpf_log(log, "can't modify return codes of BPF programs\n");
12410 				return -EINVAL;
12411 			}
12412 			ret = check_attach_modify_return(addr, tname);
12413 			if (ret) {
12414 				bpf_log(log, "%s() is not modifiable\n", tname);
12415 				return ret;
12416 			}
12417 		}
12418 
12419 		break;
12420 	}
12421 	tgt_info->tgt_addr = addr;
12422 	tgt_info->tgt_name = tname;
12423 	tgt_info->tgt_type = t;
12424 	return 0;
12425 }
12426 
12427 static int check_attach_btf_id(struct bpf_verifier_env *env)
12428 {
12429 	struct bpf_prog *prog = env->prog;
12430 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12431 	struct bpf_attach_target_info tgt_info = {};
12432 	u32 btf_id = prog->aux->attach_btf_id;
12433 	struct bpf_trampoline *tr;
12434 	int ret;
12435 	u64 key;
12436 
12437 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12438 	    prog->type != BPF_PROG_TYPE_LSM) {
12439 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12440 		return -EINVAL;
12441 	}
12442 
12443 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12444 		return check_struct_ops_btf_id(env);
12445 
12446 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12447 	    prog->type != BPF_PROG_TYPE_LSM &&
12448 	    prog->type != BPF_PROG_TYPE_EXT)
12449 		return 0;
12450 
12451 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12452 	if (ret)
12453 		return ret;
12454 
12455 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12456 		/* to make freplace equivalent to their targets, they need to
12457 		 * inherit env->ops and expected_attach_type for the rest of the
12458 		 * verification
12459 		 */
12460 		env->ops = bpf_verifier_ops[tgt_prog->type];
12461 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12462 	}
12463 
12464 	/* store info about the attachment target that will be used later */
12465 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12466 	prog->aux->attach_func_name = tgt_info.tgt_name;
12467 
12468 	if (tgt_prog) {
12469 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12470 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12471 	}
12472 
12473 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12474 		prog->aux->attach_btf_trace = true;
12475 		return 0;
12476 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12477 		if (!bpf_iter_prog_supported(prog))
12478 			return -EINVAL;
12479 		return 0;
12480 	}
12481 
12482 	if (prog->type == BPF_PROG_TYPE_LSM) {
12483 		ret = bpf_lsm_verify_prog(&env->log, prog);
12484 		if (ret < 0)
12485 			return ret;
12486 	}
12487 
12488 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12489 	tr = bpf_trampoline_get(key, &tgt_info);
12490 	if (!tr)
12491 		return -ENOMEM;
12492 
12493 	prog->aux->dst_trampoline = tr;
12494 	return 0;
12495 }
12496 
12497 struct btf *bpf_get_btf_vmlinux(void)
12498 {
12499 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12500 		mutex_lock(&bpf_verifier_lock);
12501 		if (!btf_vmlinux)
12502 			btf_vmlinux = btf_parse_vmlinux();
12503 		mutex_unlock(&bpf_verifier_lock);
12504 	}
12505 	return btf_vmlinux;
12506 }
12507 
12508 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12509 	      union bpf_attr __user *uattr)
12510 {
12511 	u64 start_time = ktime_get_ns();
12512 	struct bpf_verifier_env *env;
12513 	struct bpf_verifier_log *log;
12514 	int i, len, ret = -EINVAL;
12515 	bool is_priv;
12516 
12517 	/* no program is valid */
12518 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12519 		return -EINVAL;
12520 
12521 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12522 	 * allocate/free it every time bpf_check() is called
12523 	 */
12524 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12525 	if (!env)
12526 		return -ENOMEM;
12527 	log = &env->log;
12528 
12529 	len = (*prog)->len;
12530 	env->insn_aux_data =
12531 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12532 	ret = -ENOMEM;
12533 	if (!env->insn_aux_data)
12534 		goto err_free_env;
12535 	for (i = 0; i < len; i++)
12536 		env->insn_aux_data[i].orig_idx = i;
12537 	env->prog = *prog;
12538 	env->ops = bpf_verifier_ops[env->prog->type];
12539 	is_priv = bpf_capable();
12540 
12541 	bpf_get_btf_vmlinux();
12542 
12543 	/* grab the mutex to protect few globals used by verifier */
12544 	if (!is_priv)
12545 		mutex_lock(&bpf_verifier_lock);
12546 
12547 	if (attr->log_level || attr->log_buf || attr->log_size) {
12548 		/* user requested verbose verifier output
12549 		 * and supplied buffer to store the verification trace
12550 		 */
12551 		log->level = attr->log_level;
12552 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12553 		log->len_total = attr->log_size;
12554 
12555 		ret = -EINVAL;
12556 		/* log attributes have to be sane */
12557 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12558 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12559 			goto err_unlock;
12560 	}
12561 
12562 	if (IS_ERR(btf_vmlinux)) {
12563 		/* Either gcc or pahole or kernel are broken. */
12564 		verbose(env, "in-kernel BTF is malformed\n");
12565 		ret = PTR_ERR(btf_vmlinux);
12566 		goto skip_full_check;
12567 	}
12568 
12569 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12570 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12571 		env->strict_alignment = true;
12572 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12573 		env->strict_alignment = false;
12574 
12575 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12576 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12577 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12578 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12579 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12580 	env->bpf_capable = bpf_capable();
12581 
12582 	if (is_priv)
12583 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12584 
12585 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12586 		ret = bpf_prog_offload_verifier_prep(env->prog);
12587 		if (ret)
12588 			goto skip_full_check;
12589 	}
12590 
12591 	env->explored_states = kvcalloc(state_htab_size(env),
12592 				       sizeof(struct bpf_verifier_state_list *),
12593 				       GFP_USER);
12594 	ret = -ENOMEM;
12595 	if (!env->explored_states)
12596 		goto skip_full_check;
12597 
12598 	ret = check_subprogs(env);
12599 	if (ret < 0)
12600 		goto skip_full_check;
12601 
12602 	ret = check_btf_info(env, attr, uattr);
12603 	if (ret < 0)
12604 		goto skip_full_check;
12605 
12606 	ret = check_attach_btf_id(env);
12607 	if (ret)
12608 		goto skip_full_check;
12609 
12610 	ret = resolve_pseudo_ldimm64(env);
12611 	if (ret < 0)
12612 		goto skip_full_check;
12613 
12614 	ret = check_cfg(env);
12615 	if (ret < 0)
12616 		goto skip_full_check;
12617 
12618 	ret = do_check_subprogs(env);
12619 	ret = ret ?: do_check_main(env);
12620 
12621 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12622 		ret = bpf_prog_offload_finalize(env);
12623 
12624 skip_full_check:
12625 	kvfree(env->explored_states);
12626 
12627 	if (ret == 0)
12628 		ret = check_max_stack_depth(env);
12629 
12630 	/* instruction rewrites happen after this point */
12631 	if (is_priv) {
12632 		if (ret == 0)
12633 			opt_hard_wire_dead_code_branches(env);
12634 		if (ret == 0)
12635 			ret = opt_remove_dead_code(env);
12636 		if (ret == 0)
12637 			ret = opt_remove_nops(env);
12638 	} else {
12639 		if (ret == 0)
12640 			sanitize_dead_code(env);
12641 	}
12642 
12643 	if (ret == 0)
12644 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12645 		ret = convert_ctx_accesses(env);
12646 
12647 	if (ret == 0)
12648 		ret = fixup_bpf_calls(env);
12649 
12650 	/* do 32-bit optimization after insn patching has done so those patched
12651 	 * insns could be handled correctly.
12652 	 */
12653 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12654 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12655 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12656 								     : false;
12657 	}
12658 
12659 	if (ret == 0)
12660 		ret = fixup_call_args(env);
12661 
12662 	env->verification_time = ktime_get_ns() - start_time;
12663 	print_verification_stats(env);
12664 
12665 	if (log->level && bpf_verifier_log_full(log))
12666 		ret = -ENOSPC;
12667 	if (log->level && !log->ubuf) {
12668 		ret = -EFAULT;
12669 		goto err_release_maps;
12670 	}
12671 
12672 	if (ret)
12673 		goto err_release_maps;
12674 
12675 	if (env->used_map_cnt) {
12676 		/* if program passed verifier, update used_maps in bpf_prog_info */
12677 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12678 							  sizeof(env->used_maps[0]),
12679 							  GFP_KERNEL);
12680 
12681 		if (!env->prog->aux->used_maps) {
12682 			ret = -ENOMEM;
12683 			goto err_release_maps;
12684 		}
12685 
12686 		memcpy(env->prog->aux->used_maps, env->used_maps,
12687 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12688 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12689 	}
12690 	if (env->used_btf_cnt) {
12691 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
12692 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12693 							  sizeof(env->used_btfs[0]),
12694 							  GFP_KERNEL);
12695 		if (!env->prog->aux->used_btfs) {
12696 			ret = -ENOMEM;
12697 			goto err_release_maps;
12698 		}
12699 
12700 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
12701 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12702 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12703 	}
12704 	if (env->used_map_cnt || env->used_btf_cnt) {
12705 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12706 		 * bpf_ld_imm64 instructions
12707 		 */
12708 		convert_pseudo_ld_imm64(env);
12709 	}
12710 
12711 	adjust_btf_func(env);
12712 
12713 err_release_maps:
12714 	if (!env->prog->aux->used_maps)
12715 		/* if we didn't copy map pointers into bpf_prog_info, release
12716 		 * them now. Otherwise free_used_maps() will release them.
12717 		 */
12718 		release_maps(env);
12719 	if (!env->prog->aux->used_btfs)
12720 		release_btfs(env);
12721 
12722 	/* extension progs temporarily inherit the attach_type of their targets
12723 	   for verification purposes, so set it back to zero before returning
12724 	 */
12725 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12726 		env->prog->expected_attach_type = 0;
12727 
12728 	*prog = env->prog;
12729 err_unlock:
12730 	if (!is_priv)
12731 		mutex_unlock(&bpf_verifier_lock);
12732 	vfree(env->insn_aux_data);
12733 err_free_env:
12734 	kfree(env);
12735 	return ret;
12736 }
12737