xref: /linux/kernel/bpf/verifier.c (revision ed30aef3c864f99111e16d4ea5cf29488d99a278)
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 struct bpf_call_arg_meta {
232 	struct bpf_map *map_ptr;
233 	bool raw_mode;
234 	bool pkt_access;
235 	int regno;
236 	int access_size;
237 	int mem_size;
238 	u64 msize_max_value;
239 	int ref_obj_id;
240 	int func_id;
241 	u32 btf_id;
242 	u32 ret_btf_id;
243 };
244 
245 struct btf *btf_vmlinux;
246 
247 static DEFINE_MUTEX(bpf_verifier_lock);
248 
249 static const struct bpf_line_info *
250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
251 {
252 	const struct bpf_line_info *linfo;
253 	const struct bpf_prog *prog;
254 	u32 i, nr_linfo;
255 
256 	prog = env->prog;
257 	nr_linfo = prog->aux->nr_linfo;
258 
259 	if (!nr_linfo || insn_off >= prog->len)
260 		return NULL;
261 
262 	linfo = prog->aux->linfo;
263 	for (i = 1; i < nr_linfo; i++)
264 		if (insn_off < linfo[i].insn_off)
265 			break;
266 
267 	return &linfo[i - 1];
268 }
269 
270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
271 		       va_list args)
272 {
273 	unsigned int n;
274 
275 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
276 
277 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 		  "verifier log line truncated - local buffer too short\n");
279 
280 	n = min(log->len_total - log->len_used - 1, n);
281 	log->kbuf[n] = '\0';
282 
283 	if (log->level == BPF_LOG_KERNEL) {
284 		pr_err("BPF:%s\n", log->kbuf);
285 		return;
286 	}
287 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
288 		log->len_used += n;
289 	else
290 		log->ubuf = NULL;
291 }
292 
293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
294 {
295 	char zero = 0;
296 
297 	if (!bpf_verifier_log_needed(log))
298 		return;
299 
300 	log->len_used = new_pos;
301 	if (put_user(zero, log->ubuf + new_pos))
302 		log->ubuf = NULL;
303 }
304 
305 /* log_level controls verbosity level of eBPF verifier.
306  * bpf_verifier_log_write() is used to dump the verification trace to the log,
307  * so the user can figure out what's wrong with the program
308  */
309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 					   const char *fmt, ...)
311 {
312 	va_list args;
313 
314 	if (!bpf_verifier_log_needed(&env->log))
315 		return;
316 
317 	va_start(args, fmt);
318 	bpf_verifier_vlog(&env->log, fmt, args);
319 	va_end(args);
320 }
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
322 
323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324 {
325 	struct bpf_verifier_env *env = private_data;
326 	va_list args;
327 
328 	if (!bpf_verifier_log_needed(&env->log))
329 		return;
330 
331 	va_start(args, fmt);
332 	bpf_verifier_vlog(&env->log, fmt, args);
333 	va_end(args);
334 }
335 
336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 			    const char *fmt, ...)
338 {
339 	va_list args;
340 
341 	if (!bpf_verifier_log_needed(log))
342 		return;
343 
344 	va_start(args, fmt);
345 	bpf_verifier_vlog(log, fmt, args);
346 	va_end(args);
347 }
348 
349 static const char *ltrim(const char *s)
350 {
351 	while (isspace(*s))
352 		s++;
353 
354 	return s;
355 }
356 
357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
358 					 u32 insn_off,
359 					 const char *prefix_fmt, ...)
360 {
361 	const struct bpf_line_info *linfo;
362 
363 	if (!bpf_verifier_log_needed(&env->log))
364 		return;
365 
366 	linfo = find_linfo(env, insn_off);
367 	if (!linfo || linfo == env->prev_linfo)
368 		return;
369 
370 	if (prefix_fmt) {
371 		va_list args;
372 
373 		va_start(args, prefix_fmt);
374 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
375 		va_end(args);
376 	}
377 
378 	verbose(env, "%s\n",
379 		ltrim(btf_name_by_offset(env->prog->aux->btf,
380 					 linfo->line_off)));
381 
382 	env->prev_linfo = linfo;
383 }
384 
385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
386 {
387 	return type == PTR_TO_PACKET ||
388 	       type == PTR_TO_PACKET_META;
389 }
390 
391 static bool type_is_sk_pointer(enum bpf_reg_type type)
392 {
393 	return type == PTR_TO_SOCKET ||
394 		type == PTR_TO_SOCK_COMMON ||
395 		type == PTR_TO_TCP_SOCK ||
396 		type == PTR_TO_XDP_SOCK;
397 }
398 
399 static bool reg_type_not_null(enum bpf_reg_type type)
400 {
401 	return type == PTR_TO_SOCKET ||
402 		type == PTR_TO_TCP_SOCK ||
403 		type == PTR_TO_MAP_VALUE ||
404 		type == PTR_TO_SOCK_COMMON;
405 }
406 
407 static bool reg_type_may_be_null(enum bpf_reg_type type)
408 {
409 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
410 	       type == PTR_TO_SOCKET_OR_NULL ||
411 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
412 	       type == PTR_TO_TCP_SOCK_OR_NULL ||
413 	       type == PTR_TO_BTF_ID_OR_NULL ||
414 	       type == PTR_TO_MEM_OR_NULL ||
415 	       type == PTR_TO_RDONLY_BUF_OR_NULL ||
416 	       type == PTR_TO_RDWR_BUF_OR_NULL;
417 }
418 
419 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
420 {
421 	return reg->type == PTR_TO_MAP_VALUE &&
422 		map_value_has_spin_lock(reg->map_ptr);
423 }
424 
425 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
426 {
427 	return type == PTR_TO_SOCKET ||
428 		type == PTR_TO_SOCKET_OR_NULL ||
429 		type == PTR_TO_TCP_SOCK ||
430 		type == PTR_TO_TCP_SOCK_OR_NULL ||
431 		type == PTR_TO_MEM ||
432 		type == PTR_TO_MEM_OR_NULL;
433 }
434 
435 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
436 {
437 	return type == ARG_PTR_TO_SOCK_COMMON;
438 }
439 
440 static bool arg_type_may_be_null(enum bpf_arg_type type)
441 {
442 	return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
443 	       type == ARG_PTR_TO_MEM_OR_NULL ||
444 	       type == ARG_PTR_TO_CTX_OR_NULL ||
445 	       type == ARG_PTR_TO_SOCKET_OR_NULL ||
446 	       type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
447 }
448 
449 /* Determine whether the function releases some resources allocated by another
450  * function call. The first reference type argument will be assumed to be
451  * released by release_reference().
452  */
453 static bool is_release_function(enum bpf_func_id func_id)
454 {
455 	return func_id == BPF_FUNC_sk_release ||
456 	       func_id == BPF_FUNC_ringbuf_submit ||
457 	       func_id == BPF_FUNC_ringbuf_discard;
458 }
459 
460 static bool may_be_acquire_function(enum bpf_func_id func_id)
461 {
462 	return func_id == BPF_FUNC_sk_lookup_tcp ||
463 		func_id == BPF_FUNC_sk_lookup_udp ||
464 		func_id == BPF_FUNC_skc_lookup_tcp ||
465 		func_id == BPF_FUNC_map_lookup_elem ||
466 	        func_id == BPF_FUNC_ringbuf_reserve;
467 }
468 
469 static bool is_acquire_function(enum bpf_func_id func_id,
470 				const struct bpf_map *map)
471 {
472 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
473 
474 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
475 	    func_id == BPF_FUNC_sk_lookup_udp ||
476 	    func_id == BPF_FUNC_skc_lookup_tcp ||
477 	    func_id == BPF_FUNC_ringbuf_reserve)
478 		return true;
479 
480 	if (func_id == BPF_FUNC_map_lookup_elem &&
481 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
482 	     map_type == BPF_MAP_TYPE_SOCKHASH))
483 		return true;
484 
485 	return false;
486 }
487 
488 static bool is_ptr_cast_function(enum bpf_func_id func_id)
489 {
490 	return func_id == BPF_FUNC_tcp_sock ||
491 		func_id == BPF_FUNC_sk_fullsock ||
492 		func_id == BPF_FUNC_skc_to_tcp_sock ||
493 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
494 		func_id == BPF_FUNC_skc_to_udp6_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
497 }
498 
499 /* string representation of 'enum bpf_reg_type' */
500 static const char * const reg_type_str[] = {
501 	[NOT_INIT]		= "?",
502 	[SCALAR_VALUE]		= "inv",
503 	[PTR_TO_CTX]		= "ctx",
504 	[CONST_PTR_TO_MAP]	= "map_ptr",
505 	[PTR_TO_MAP_VALUE]	= "map_value",
506 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
507 	[PTR_TO_STACK]		= "fp",
508 	[PTR_TO_PACKET]		= "pkt",
509 	[PTR_TO_PACKET_META]	= "pkt_meta",
510 	[PTR_TO_PACKET_END]	= "pkt_end",
511 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
512 	[PTR_TO_SOCKET]		= "sock",
513 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
514 	[PTR_TO_SOCK_COMMON]	= "sock_common",
515 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
516 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
517 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
518 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
519 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
520 	[PTR_TO_BTF_ID]		= "ptr_",
521 	[PTR_TO_BTF_ID_OR_NULL]	= "ptr_or_null_",
522 	[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
523 	[PTR_TO_MEM]		= "mem",
524 	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",
525 	[PTR_TO_RDONLY_BUF]	= "rdonly_buf",
526 	[PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
527 	[PTR_TO_RDWR_BUF]	= "rdwr_buf",
528 	[PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
529 };
530 
531 static char slot_type_char[] = {
532 	[STACK_INVALID]	= '?',
533 	[STACK_SPILL]	= 'r',
534 	[STACK_MISC]	= 'm',
535 	[STACK_ZERO]	= '0',
536 };
537 
538 static void print_liveness(struct bpf_verifier_env *env,
539 			   enum bpf_reg_liveness live)
540 {
541 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
542 	    verbose(env, "_");
543 	if (live & REG_LIVE_READ)
544 		verbose(env, "r");
545 	if (live & REG_LIVE_WRITTEN)
546 		verbose(env, "w");
547 	if (live & REG_LIVE_DONE)
548 		verbose(env, "D");
549 }
550 
551 static struct bpf_func_state *func(struct bpf_verifier_env *env,
552 				   const struct bpf_reg_state *reg)
553 {
554 	struct bpf_verifier_state *cur = env->cur_state;
555 
556 	return cur->frame[reg->frameno];
557 }
558 
559 const char *kernel_type_name(u32 id)
560 {
561 	return btf_name_by_offset(btf_vmlinux,
562 				  btf_type_by_id(btf_vmlinux, id)->name_off);
563 }
564 
565 static void print_verifier_state(struct bpf_verifier_env *env,
566 				 const struct bpf_func_state *state)
567 {
568 	const struct bpf_reg_state *reg;
569 	enum bpf_reg_type t;
570 	int i;
571 
572 	if (state->frameno)
573 		verbose(env, " frame%d:", state->frameno);
574 	for (i = 0; i < MAX_BPF_REG; i++) {
575 		reg = &state->regs[i];
576 		t = reg->type;
577 		if (t == NOT_INIT)
578 			continue;
579 		verbose(env, " R%d", i);
580 		print_liveness(env, reg->live);
581 		verbose(env, "=%s", reg_type_str[t]);
582 		if (t == SCALAR_VALUE && reg->precise)
583 			verbose(env, "P");
584 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
585 		    tnum_is_const(reg->var_off)) {
586 			/* reg->off should be 0 for SCALAR_VALUE */
587 			verbose(env, "%lld", reg->var_off.value + reg->off);
588 		} else {
589 			if (t == PTR_TO_BTF_ID ||
590 			    t == PTR_TO_BTF_ID_OR_NULL ||
591 			    t == PTR_TO_PERCPU_BTF_ID)
592 				verbose(env, "%s", kernel_type_name(reg->btf_id));
593 			verbose(env, "(id=%d", reg->id);
594 			if (reg_type_may_be_refcounted_or_null(t))
595 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
596 			if (t != SCALAR_VALUE)
597 				verbose(env, ",off=%d", reg->off);
598 			if (type_is_pkt_pointer(t))
599 				verbose(env, ",r=%d", reg->range);
600 			else if (t == CONST_PTR_TO_MAP ||
601 				 t == PTR_TO_MAP_VALUE ||
602 				 t == PTR_TO_MAP_VALUE_OR_NULL)
603 				verbose(env, ",ks=%d,vs=%d",
604 					reg->map_ptr->key_size,
605 					reg->map_ptr->value_size);
606 			if (tnum_is_const(reg->var_off)) {
607 				/* Typically an immediate SCALAR_VALUE, but
608 				 * could be a pointer whose offset is too big
609 				 * for reg->off
610 				 */
611 				verbose(env, ",imm=%llx", reg->var_off.value);
612 			} else {
613 				if (reg->smin_value != reg->umin_value &&
614 				    reg->smin_value != S64_MIN)
615 					verbose(env, ",smin_value=%lld",
616 						(long long)reg->smin_value);
617 				if (reg->smax_value != reg->umax_value &&
618 				    reg->smax_value != S64_MAX)
619 					verbose(env, ",smax_value=%lld",
620 						(long long)reg->smax_value);
621 				if (reg->umin_value != 0)
622 					verbose(env, ",umin_value=%llu",
623 						(unsigned long long)reg->umin_value);
624 				if (reg->umax_value != U64_MAX)
625 					verbose(env, ",umax_value=%llu",
626 						(unsigned long long)reg->umax_value);
627 				if (!tnum_is_unknown(reg->var_off)) {
628 					char tn_buf[48];
629 
630 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
631 					verbose(env, ",var_off=%s", tn_buf);
632 				}
633 				if (reg->s32_min_value != reg->smin_value &&
634 				    reg->s32_min_value != S32_MIN)
635 					verbose(env, ",s32_min_value=%d",
636 						(int)(reg->s32_min_value));
637 				if (reg->s32_max_value != reg->smax_value &&
638 				    reg->s32_max_value != S32_MAX)
639 					verbose(env, ",s32_max_value=%d",
640 						(int)(reg->s32_max_value));
641 				if (reg->u32_min_value != reg->umin_value &&
642 				    reg->u32_min_value != U32_MIN)
643 					verbose(env, ",u32_min_value=%d",
644 						(int)(reg->u32_min_value));
645 				if (reg->u32_max_value != reg->umax_value &&
646 				    reg->u32_max_value != U32_MAX)
647 					verbose(env, ",u32_max_value=%d",
648 						(int)(reg->u32_max_value));
649 			}
650 			verbose(env, ")");
651 		}
652 	}
653 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
654 		char types_buf[BPF_REG_SIZE + 1];
655 		bool valid = false;
656 		int j;
657 
658 		for (j = 0; j < BPF_REG_SIZE; j++) {
659 			if (state->stack[i].slot_type[j] != STACK_INVALID)
660 				valid = true;
661 			types_buf[j] = slot_type_char[
662 					state->stack[i].slot_type[j]];
663 		}
664 		types_buf[BPF_REG_SIZE] = 0;
665 		if (!valid)
666 			continue;
667 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
668 		print_liveness(env, state->stack[i].spilled_ptr.live);
669 		if (state->stack[i].slot_type[0] == STACK_SPILL) {
670 			reg = &state->stack[i].spilled_ptr;
671 			t = reg->type;
672 			verbose(env, "=%s", reg_type_str[t]);
673 			if (t == SCALAR_VALUE && reg->precise)
674 				verbose(env, "P");
675 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
676 				verbose(env, "%lld", reg->var_off.value + reg->off);
677 		} else {
678 			verbose(env, "=%s", types_buf);
679 		}
680 	}
681 	if (state->acquired_refs && state->refs[0].id) {
682 		verbose(env, " refs=%d", state->refs[0].id);
683 		for (i = 1; i < state->acquired_refs; i++)
684 			if (state->refs[i].id)
685 				verbose(env, ",%d", state->refs[i].id);
686 	}
687 	verbose(env, "\n");
688 }
689 
690 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
691 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
692 			       const struct bpf_func_state *src)	\
693 {									\
694 	if (!src->FIELD)						\
695 		return 0;						\
696 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
697 		/* internal bug, make state invalid to reject the program */ \
698 		memset(dst, 0, sizeof(*dst));				\
699 		return -EFAULT;						\
700 	}								\
701 	memcpy(dst->FIELD, src->FIELD,					\
702 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
703 	return 0;							\
704 }
705 /* copy_reference_state() */
706 COPY_STATE_FN(reference, acquired_refs, refs, 1)
707 /* copy_stack_state() */
708 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
709 #undef COPY_STATE_FN
710 
711 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
712 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
713 				  bool copy_old)			\
714 {									\
715 	u32 old_size = state->COUNT;					\
716 	struct bpf_##NAME##_state *new_##FIELD;				\
717 	int slot = size / SIZE;						\
718 									\
719 	if (size <= old_size || !size) {				\
720 		if (copy_old)						\
721 			return 0;					\
722 		state->COUNT = slot * SIZE;				\
723 		if (!size && old_size) {				\
724 			kfree(state->FIELD);				\
725 			state->FIELD = NULL;				\
726 		}							\
727 		return 0;						\
728 	}								\
729 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
730 				    GFP_KERNEL);			\
731 	if (!new_##FIELD)						\
732 		return -ENOMEM;						\
733 	if (copy_old) {							\
734 		if (state->FIELD)					\
735 			memcpy(new_##FIELD, state->FIELD,		\
736 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
737 		memset(new_##FIELD + old_size / SIZE, 0,		\
738 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
739 	}								\
740 	state->COUNT = slot * SIZE;					\
741 	kfree(state->FIELD);						\
742 	state->FIELD = new_##FIELD;					\
743 	return 0;							\
744 }
745 /* realloc_reference_state() */
746 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
747 /* realloc_stack_state() */
748 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
749 #undef REALLOC_STATE_FN
750 
751 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
752  * make it consume minimal amount of memory. check_stack_write() access from
753  * the program calls into realloc_func_state() to grow the stack size.
754  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
755  * which realloc_stack_state() copies over. It points to previous
756  * bpf_verifier_state which is never reallocated.
757  */
758 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
759 			      int refs_size, bool copy_old)
760 {
761 	int err = realloc_reference_state(state, refs_size, copy_old);
762 	if (err)
763 		return err;
764 	return realloc_stack_state(state, stack_size, copy_old);
765 }
766 
767 /* Acquire a pointer id from the env and update the state->refs to include
768  * this new pointer reference.
769  * On success, returns a valid pointer id to associate with the register
770  * On failure, returns a negative errno.
771  */
772 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
773 {
774 	struct bpf_func_state *state = cur_func(env);
775 	int new_ofs = state->acquired_refs;
776 	int id, err;
777 
778 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
779 	if (err)
780 		return err;
781 	id = ++env->id_gen;
782 	state->refs[new_ofs].id = id;
783 	state->refs[new_ofs].insn_idx = insn_idx;
784 
785 	return id;
786 }
787 
788 /* release function corresponding to acquire_reference_state(). Idempotent. */
789 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
790 {
791 	int i, last_idx;
792 
793 	last_idx = state->acquired_refs - 1;
794 	for (i = 0; i < state->acquired_refs; i++) {
795 		if (state->refs[i].id == ptr_id) {
796 			if (last_idx && i != last_idx)
797 				memcpy(&state->refs[i], &state->refs[last_idx],
798 				       sizeof(*state->refs));
799 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
800 			state->acquired_refs--;
801 			return 0;
802 		}
803 	}
804 	return -EINVAL;
805 }
806 
807 static int transfer_reference_state(struct bpf_func_state *dst,
808 				    struct bpf_func_state *src)
809 {
810 	int err = realloc_reference_state(dst, src->acquired_refs, false);
811 	if (err)
812 		return err;
813 	err = copy_reference_state(dst, src);
814 	if (err)
815 		return err;
816 	return 0;
817 }
818 
819 static void free_func_state(struct bpf_func_state *state)
820 {
821 	if (!state)
822 		return;
823 	kfree(state->refs);
824 	kfree(state->stack);
825 	kfree(state);
826 }
827 
828 static void clear_jmp_history(struct bpf_verifier_state *state)
829 {
830 	kfree(state->jmp_history);
831 	state->jmp_history = NULL;
832 	state->jmp_history_cnt = 0;
833 }
834 
835 static void free_verifier_state(struct bpf_verifier_state *state,
836 				bool free_self)
837 {
838 	int i;
839 
840 	for (i = 0; i <= state->curframe; i++) {
841 		free_func_state(state->frame[i]);
842 		state->frame[i] = NULL;
843 	}
844 	clear_jmp_history(state);
845 	if (free_self)
846 		kfree(state);
847 }
848 
849 /* copy verifier state from src to dst growing dst stack space
850  * when necessary to accommodate larger src stack
851  */
852 static int copy_func_state(struct bpf_func_state *dst,
853 			   const struct bpf_func_state *src)
854 {
855 	int err;
856 
857 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
858 				 false);
859 	if (err)
860 		return err;
861 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
862 	err = copy_reference_state(dst, src);
863 	if (err)
864 		return err;
865 	return copy_stack_state(dst, src);
866 }
867 
868 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
869 			       const struct bpf_verifier_state *src)
870 {
871 	struct bpf_func_state *dst;
872 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
873 	int i, err;
874 
875 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
876 		kfree(dst_state->jmp_history);
877 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
878 		if (!dst_state->jmp_history)
879 			return -ENOMEM;
880 	}
881 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
882 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
883 
884 	/* if dst has more stack frames then src frame, free them */
885 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
886 		free_func_state(dst_state->frame[i]);
887 		dst_state->frame[i] = NULL;
888 	}
889 	dst_state->speculative = src->speculative;
890 	dst_state->curframe = src->curframe;
891 	dst_state->active_spin_lock = src->active_spin_lock;
892 	dst_state->branches = src->branches;
893 	dst_state->parent = src->parent;
894 	dst_state->first_insn_idx = src->first_insn_idx;
895 	dst_state->last_insn_idx = src->last_insn_idx;
896 	for (i = 0; i <= src->curframe; i++) {
897 		dst = dst_state->frame[i];
898 		if (!dst) {
899 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
900 			if (!dst)
901 				return -ENOMEM;
902 			dst_state->frame[i] = dst;
903 		}
904 		err = copy_func_state(dst, src->frame[i]);
905 		if (err)
906 			return err;
907 	}
908 	return 0;
909 }
910 
911 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
912 {
913 	while (st) {
914 		u32 br = --st->branches;
915 
916 		/* WARN_ON(br > 1) technically makes sense here,
917 		 * but see comment in push_stack(), hence:
918 		 */
919 		WARN_ONCE((int)br < 0,
920 			  "BUG update_branch_counts:branches_to_explore=%d\n",
921 			  br);
922 		if (br)
923 			break;
924 		st = st->parent;
925 	}
926 }
927 
928 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
929 		     int *insn_idx, bool pop_log)
930 {
931 	struct bpf_verifier_state *cur = env->cur_state;
932 	struct bpf_verifier_stack_elem *elem, *head = env->head;
933 	int err;
934 
935 	if (env->head == NULL)
936 		return -ENOENT;
937 
938 	if (cur) {
939 		err = copy_verifier_state(cur, &head->st);
940 		if (err)
941 			return err;
942 	}
943 	if (pop_log)
944 		bpf_vlog_reset(&env->log, head->log_pos);
945 	if (insn_idx)
946 		*insn_idx = head->insn_idx;
947 	if (prev_insn_idx)
948 		*prev_insn_idx = head->prev_insn_idx;
949 	elem = head->next;
950 	free_verifier_state(&head->st, false);
951 	kfree(head);
952 	env->head = elem;
953 	env->stack_size--;
954 	return 0;
955 }
956 
957 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
958 					     int insn_idx, int prev_insn_idx,
959 					     bool speculative)
960 {
961 	struct bpf_verifier_state *cur = env->cur_state;
962 	struct bpf_verifier_stack_elem *elem;
963 	int err;
964 
965 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
966 	if (!elem)
967 		goto err;
968 
969 	elem->insn_idx = insn_idx;
970 	elem->prev_insn_idx = prev_insn_idx;
971 	elem->next = env->head;
972 	elem->log_pos = env->log.len_used;
973 	env->head = elem;
974 	env->stack_size++;
975 	err = copy_verifier_state(&elem->st, cur);
976 	if (err)
977 		goto err;
978 	elem->st.speculative |= speculative;
979 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
980 		verbose(env, "The sequence of %d jumps is too complex.\n",
981 			env->stack_size);
982 		goto err;
983 	}
984 	if (elem->st.parent) {
985 		++elem->st.parent->branches;
986 		/* WARN_ON(branches > 2) technically makes sense here,
987 		 * but
988 		 * 1. speculative states will bump 'branches' for non-branch
989 		 * instructions
990 		 * 2. is_state_visited() heuristics may decide not to create
991 		 * a new state for a sequence of branches and all such current
992 		 * and cloned states will be pointing to a single parent state
993 		 * which might have large 'branches' count.
994 		 */
995 	}
996 	return &elem->st;
997 err:
998 	free_verifier_state(env->cur_state, true);
999 	env->cur_state = NULL;
1000 	/* pop all elements and return */
1001 	while (!pop_stack(env, NULL, NULL, false));
1002 	return NULL;
1003 }
1004 
1005 #define CALLER_SAVED_REGS 6
1006 static const int caller_saved[CALLER_SAVED_REGS] = {
1007 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1008 };
1009 
1010 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1011 				struct bpf_reg_state *reg);
1012 
1013 /* This helper doesn't clear reg->id */
1014 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1015 {
1016 	reg->var_off = tnum_const(imm);
1017 	reg->smin_value = (s64)imm;
1018 	reg->smax_value = (s64)imm;
1019 	reg->umin_value = imm;
1020 	reg->umax_value = imm;
1021 
1022 	reg->s32_min_value = (s32)imm;
1023 	reg->s32_max_value = (s32)imm;
1024 	reg->u32_min_value = (u32)imm;
1025 	reg->u32_max_value = (u32)imm;
1026 }
1027 
1028 /* Mark the unknown part of a register (variable offset or scalar value) as
1029  * known to have the value @imm.
1030  */
1031 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1032 {
1033 	/* Clear id, off, and union(map_ptr, range) */
1034 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1035 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1036 	___mark_reg_known(reg, imm);
1037 }
1038 
1039 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1040 {
1041 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1042 	reg->s32_min_value = (s32)imm;
1043 	reg->s32_max_value = (s32)imm;
1044 	reg->u32_min_value = (u32)imm;
1045 	reg->u32_max_value = (u32)imm;
1046 }
1047 
1048 /* Mark the 'variable offset' part of a register as zero.  This should be
1049  * used only on registers holding a pointer type.
1050  */
1051 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1052 {
1053 	__mark_reg_known(reg, 0);
1054 }
1055 
1056 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1057 {
1058 	__mark_reg_known(reg, 0);
1059 	reg->type = SCALAR_VALUE;
1060 }
1061 
1062 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1063 				struct bpf_reg_state *regs, u32 regno)
1064 {
1065 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1066 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1067 		/* Something bad happened, let's kill all regs */
1068 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1069 			__mark_reg_not_init(env, regs + regno);
1070 		return;
1071 	}
1072 	__mark_reg_known_zero(regs + regno);
1073 }
1074 
1075 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1076 {
1077 	return type_is_pkt_pointer(reg->type);
1078 }
1079 
1080 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1081 {
1082 	return reg_is_pkt_pointer(reg) ||
1083 	       reg->type == PTR_TO_PACKET_END;
1084 }
1085 
1086 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1087 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1088 				    enum bpf_reg_type which)
1089 {
1090 	/* The register can already have a range from prior markings.
1091 	 * This is fine as long as it hasn't been advanced from its
1092 	 * origin.
1093 	 */
1094 	return reg->type == which &&
1095 	       reg->id == 0 &&
1096 	       reg->off == 0 &&
1097 	       tnum_equals_const(reg->var_off, 0);
1098 }
1099 
1100 /* Reset the min/max bounds of a register */
1101 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1102 {
1103 	reg->smin_value = S64_MIN;
1104 	reg->smax_value = S64_MAX;
1105 	reg->umin_value = 0;
1106 	reg->umax_value = U64_MAX;
1107 
1108 	reg->s32_min_value = S32_MIN;
1109 	reg->s32_max_value = S32_MAX;
1110 	reg->u32_min_value = 0;
1111 	reg->u32_max_value = U32_MAX;
1112 }
1113 
1114 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1115 {
1116 	reg->smin_value = S64_MIN;
1117 	reg->smax_value = S64_MAX;
1118 	reg->umin_value = 0;
1119 	reg->umax_value = U64_MAX;
1120 }
1121 
1122 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1123 {
1124 	reg->s32_min_value = S32_MIN;
1125 	reg->s32_max_value = S32_MAX;
1126 	reg->u32_min_value = 0;
1127 	reg->u32_max_value = U32_MAX;
1128 }
1129 
1130 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1131 {
1132 	struct tnum var32_off = tnum_subreg(reg->var_off);
1133 
1134 	/* min signed is max(sign bit) | min(other bits) */
1135 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1136 			var32_off.value | (var32_off.mask & S32_MIN));
1137 	/* max signed is min(sign bit) | max(other bits) */
1138 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1139 			var32_off.value | (var32_off.mask & S32_MAX));
1140 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1141 	reg->u32_max_value = min(reg->u32_max_value,
1142 				 (u32)(var32_off.value | var32_off.mask));
1143 }
1144 
1145 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1146 {
1147 	/* min signed is max(sign bit) | min(other bits) */
1148 	reg->smin_value = max_t(s64, reg->smin_value,
1149 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1150 	/* max signed is min(sign bit) | max(other bits) */
1151 	reg->smax_value = min_t(s64, reg->smax_value,
1152 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1153 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1154 	reg->umax_value = min(reg->umax_value,
1155 			      reg->var_off.value | reg->var_off.mask);
1156 }
1157 
1158 static void __update_reg_bounds(struct bpf_reg_state *reg)
1159 {
1160 	__update_reg32_bounds(reg);
1161 	__update_reg64_bounds(reg);
1162 }
1163 
1164 /* Uses signed min/max values to inform unsigned, and vice-versa */
1165 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1166 {
1167 	/* Learn sign from signed bounds.
1168 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1169 	 * are the same, so combine.  This works even in the negative case, e.g.
1170 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1171 	 */
1172 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1173 		reg->s32_min_value = reg->u32_min_value =
1174 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1175 		reg->s32_max_value = reg->u32_max_value =
1176 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1177 		return;
1178 	}
1179 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1180 	 * boundary, so we must be careful.
1181 	 */
1182 	if ((s32)reg->u32_max_value >= 0) {
1183 		/* Positive.  We can't learn anything from the smin, but smax
1184 		 * is positive, hence safe.
1185 		 */
1186 		reg->s32_min_value = reg->u32_min_value;
1187 		reg->s32_max_value = reg->u32_max_value =
1188 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1189 	} else if ((s32)reg->u32_min_value < 0) {
1190 		/* Negative.  We can't learn anything from the smax, but smin
1191 		 * is negative, hence safe.
1192 		 */
1193 		reg->s32_min_value = reg->u32_min_value =
1194 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1195 		reg->s32_max_value = reg->u32_max_value;
1196 	}
1197 }
1198 
1199 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1200 {
1201 	/* Learn sign from signed bounds.
1202 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1203 	 * are the same, so combine.  This works even in the negative case, e.g.
1204 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1205 	 */
1206 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1207 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1208 							  reg->umin_value);
1209 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1210 							  reg->umax_value);
1211 		return;
1212 	}
1213 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1214 	 * boundary, so we must be careful.
1215 	 */
1216 	if ((s64)reg->umax_value >= 0) {
1217 		/* Positive.  We can't learn anything from the smin, but smax
1218 		 * is positive, hence safe.
1219 		 */
1220 		reg->smin_value = reg->umin_value;
1221 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1222 							  reg->umax_value);
1223 	} else if ((s64)reg->umin_value < 0) {
1224 		/* Negative.  We can't learn anything from the smax, but smin
1225 		 * is negative, hence safe.
1226 		 */
1227 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1228 							  reg->umin_value);
1229 		reg->smax_value = reg->umax_value;
1230 	}
1231 }
1232 
1233 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1234 {
1235 	__reg32_deduce_bounds(reg);
1236 	__reg64_deduce_bounds(reg);
1237 }
1238 
1239 /* Attempts to improve var_off based on unsigned min/max information */
1240 static void __reg_bound_offset(struct bpf_reg_state *reg)
1241 {
1242 	struct tnum var64_off = tnum_intersect(reg->var_off,
1243 					       tnum_range(reg->umin_value,
1244 							  reg->umax_value));
1245 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1246 						tnum_range(reg->u32_min_value,
1247 							   reg->u32_max_value));
1248 
1249 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1250 }
1251 
1252 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1253 {
1254 	reg->umin_value = reg->u32_min_value;
1255 	reg->umax_value = reg->u32_max_value;
1256 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1257 	 * but must be positive otherwise set to worse case bounds
1258 	 * and refine later from tnum.
1259 	 */
1260 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1261 		reg->smax_value = reg->s32_max_value;
1262 	else
1263 		reg->smax_value = U32_MAX;
1264 	if (reg->s32_min_value >= 0)
1265 		reg->smin_value = reg->s32_min_value;
1266 	else
1267 		reg->smin_value = 0;
1268 }
1269 
1270 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1271 {
1272 	/* special case when 64-bit register has upper 32-bit register
1273 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1274 	 * allowing us to use 32-bit bounds directly,
1275 	 */
1276 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1277 		__reg_assign_32_into_64(reg);
1278 	} else {
1279 		/* Otherwise the best we can do is push lower 32bit known and
1280 		 * unknown bits into register (var_off set from jmp logic)
1281 		 * then learn as much as possible from the 64-bit tnum
1282 		 * known and unknown bits. The previous smin/smax bounds are
1283 		 * invalid here because of jmp32 compare so mark them unknown
1284 		 * so they do not impact tnum bounds calculation.
1285 		 */
1286 		__mark_reg64_unbounded(reg);
1287 		__update_reg_bounds(reg);
1288 	}
1289 
1290 	/* Intersecting with the old var_off might have improved our bounds
1291 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1292 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1293 	 */
1294 	__reg_deduce_bounds(reg);
1295 	__reg_bound_offset(reg);
1296 	__update_reg_bounds(reg);
1297 }
1298 
1299 static bool __reg64_bound_s32(s64 a)
1300 {
1301 	if (a > S32_MIN && a < S32_MAX)
1302 		return true;
1303 	return false;
1304 }
1305 
1306 static bool __reg64_bound_u32(u64 a)
1307 {
1308 	if (a > U32_MIN && a < U32_MAX)
1309 		return true;
1310 	return false;
1311 }
1312 
1313 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1314 {
1315 	__mark_reg32_unbounded(reg);
1316 
1317 	if (__reg64_bound_s32(reg->smin_value))
1318 		reg->s32_min_value = (s32)reg->smin_value;
1319 	if (__reg64_bound_s32(reg->smax_value))
1320 		reg->s32_max_value = (s32)reg->smax_value;
1321 	if (__reg64_bound_u32(reg->umin_value))
1322 		reg->u32_min_value = (u32)reg->umin_value;
1323 	if (__reg64_bound_u32(reg->umax_value))
1324 		reg->u32_max_value = (u32)reg->umax_value;
1325 
1326 	/* Intersecting with the old var_off might have improved our bounds
1327 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1328 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1329 	 */
1330 	__reg_deduce_bounds(reg);
1331 	__reg_bound_offset(reg);
1332 	__update_reg_bounds(reg);
1333 }
1334 
1335 /* Mark a register as having a completely unknown (scalar) value. */
1336 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1337 			       struct bpf_reg_state *reg)
1338 {
1339 	/*
1340 	 * Clear type, id, off, and union(map_ptr, range) and
1341 	 * padding between 'type' and union
1342 	 */
1343 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1344 	reg->type = SCALAR_VALUE;
1345 	reg->var_off = tnum_unknown;
1346 	reg->frameno = 0;
1347 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1348 	__mark_reg_unbounded(reg);
1349 }
1350 
1351 static void mark_reg_unknown(struct bpf_verifier_env *env,
1352 			     struct bpf_reg_state *regs, u32 regno)
1353 {
1354 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1355 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1356 		/* Something bad happened, let's kill all regs except FP */
1357 		for (regno = 0; regno < BPF_REG_FP; regno++)
1358 			__mark_reg_not_init(env, regs + regno);
1359 		return;
1360 	}
1361 	__mark_reg_unknown(env, regs + regno);
1362 }
1363 
1364 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1365 				struct bpf_reg_state *reg)
1366 {
1367 	__mark_reg_unknown(env, reg);
1368 	reg->type = NOT_INIT;
1369 }
1370 
1371 static void mark_reg_not_init(struct bpf_verifier_env *env,
1372 			      struct bpf_reg_state *regs, u32 regno)
1373 {
1374 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1375 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1376 		/* Something bad happened, let's kill all regs except FP */
1377 		for (regno = 0; regno < BPF_REG_FP; regno++)
1378 			__mark_reg_not_init(env, regs + regno);
1379 		return;
1380 	}
1381 	__mark_reg_not_init(env, regs + regno);
1382 }
1383 
1384 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1385 			    struct bpf_reg_state *regs, u32 regno,
1386 			    enum bpf_reg_type reg_type, u32 btf_id)
1387 {
1388 	if (reg_type == SCALAR_VALUE) {
1389 		mark_reg_unknown(env, regs, regno);
1390 		return;
1391 	}
1392 	mark_reg_known_zero(env, regs, regno);
1393 	regs[regno].type = PTR_TO_BTF_ID;
1394 	regs[regno].btf_id = btf_id;
1395 }
1396 
1397 #define DEF_NOT_SUBREG	(0)
1398 static void init_reg_state(struct bpf_verifier_env *env,
1399 			   struct bpf_func_state *state)
1400 {
1401 	struct bpf_reg_state *regs = state->regs;
1402 	int i;
1403 
1404 	for (i = 0; i < MAX_BPF_REG; i++) {
1405 		mark_reg_not_init(env, regs, i);
1406 		regs[i].live = REG_LIVE_NONE;
1407 		regs[i].parent = NULL;
1408 		regs[i].subreg_def = DEF_NOT_SUBREG;
1409 	}
1410 
1411 	/* frame pointer */
1412 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1413 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1414 	regs[BPF_REG_FP].frameno = state->frameno;
1415 }
1416 
1417 #define BPF_MAIN_FUNC (-1)
1418 static void init_func_state(struct bpf_verifier_env *env,
1419 			    struct bpf_func_state *state,
1420 			    int callsite, int frameno, int subprogno)
1421 {
1422 	state->callsite = callsite;
1423 	state->frameno = frameno;
1424 	state->subprogno = subprogno;
1425 	init_reg_state(env, state);
1426 }
1427 
1428 enum reg_arg_type {
1429 	SRC_OP,		/* register is used as source operand */
1430 	DST_OP,		/* register is used as destination operand */
1431 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1432 };
1433 
1434 static int cmp_subprogs(const void *a, const void *b)
1435 {
1436 	return ((struct bpf_subprog_info *)a)->start -
1437 	       ((struct bpf_subprog_info *)b)->start;
1438 }
1439 
1440 static int find_subprog(struct bpf_verifier_env *env, int off)
1441 {
1442 	struct bpf_subprog_info *p;
1443 
1444 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1445 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1446 	if (!p)
1447 		return -ENOENT;
1448 	return p - env->subprog_info;
1449 
1450 }
1451 
1452 static int add_subprog(struct bpf_verifier_env *env, int off)
1453 {
1454 	int insn_cnt = env->prog->len;
1455 	int ret;
1456 
1457 	if (off >= insn_cnt || off < 0) {
1458 		verbose(env, "call to invalid destination\n");
1459 		return -EINVAL;
1460 	}
1461 	ret = find_subprog(env, off);
1462 	if (ret >= 0)
1463 		return 0;
1464 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1465 		verbose(env, "too many subprograms\n");
1466 		return -E2BIG;
1467 	}
1468 	env->subprog_info[env->subprog_cnt++].start = off;
1469 	sort(env->subprog_info, env->subprog_cnt,
1470 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1471 	return 0;
1472 }
1473 
1474 static int check_subprogs(struct bpf_verifier_env *env)
1475 {
1476 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1477 	struct bpf_subprog_info *subprog = env->subprog_info;
1478 	struct bpf_insn *insn = env->prog->insnsi;
1479 	int insn_cnt = env->prog->len;
1480 
1481 	/* Add entry function. */
1482 	ret = add_subprog(env, 0);
1483 	if (ret < 0)
1484 		return ret;
1485 
1486 	/* determine subprog starts. The end is one before the next starts */
1487 	for (i = 0; i < insn_cnt; i++) {
1488 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1489 			continue;
1490 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1491 			continue;
1492 		if (!env->bpf_capable) {
1493 			verbose(env,
1494 				"function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1495 			return -EPERM;
1496 		}
1497 		ret = add_subprog(env, i + insn[i].imm + 1);
1498 		if (ret < 0)
1499 			return ret;
1500 	}
1501 
1502 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1503 	 * logic. 'subprog_cnt' should not be increased.
1504 	 */
1505 	subprog[env->subprog_cnt].start = insn_cnt;
1506 
1507 	if (env->log.level & BPF_LOG_LEVEL2)
1508 		for (i = 0; i < env->subprog_cnt; i++)
1509 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1510 
1511 	/* now check that all jumps are within the same subprog */
1512 	subprog_start = subprog[cur_subprog].start;
1513 	subprog_end = subprog[cur_subprog + 1].start;
1514 	for (i = 0; i < insn_cnt; i++) {
1515 		u8 code = insn[i].code;
1516 
1517 		if (code == (BPF_JMP | BPF_CALL) &&
1518 		    insn[i].imm == BPF_FUNC_tail_call &&
1519 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1520 			subprog[cur_subprog].has_tail_call = true;
1521 		if (BPF_CLASS(code) == BPF_LD &&
1522 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1523 			subprog[cur_subprog].has_ld_abs = true;
1524 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1525 			goto next;
1526 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1527 			goto next;
1528 		off = i + insn[i].off + 1;
1529 		if (off < subprog_start || off >= subprog_end) {
1530 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1531 			return -EINVAL;
1532 		}
1533 next:
1534 		if (i == subprog_end - 1) {
1535 			/* to avoid fall-through from one subprog into another
1536 			 * the last insn of the subprog should be either exit
1537 			 * or unconditional jump back
1538 			 */
1539 			if (code != (BPF_JMP | BPF_EXIT) &&
1540 			    code != (BPF_JMP | BPF_JA)) {
1541 				verbose(env, "last insn is not an exit or jmp\n");
1542 				return -EINVAL;
1543 			}
1544 			subprog_start = subprog_end;
1545 			cur_subprog++;
1546 			if (cur_subprog < env->subprog_cnt)
1547 				subprog_end = subprog[cur_subprog + 1].start;
1548 		}
1549 	}
1550 	return 0;
1551 }
1552 
1553 /* Parentage chain of this register (or stack slot) should take care of all
1554  * issues like callee-saved registers, stack slot allocation time, etc.
1555  */
1556 static int mark_reg_read(struct bpf_verifier_env *env,
1557 			 const struct bpf_reg_state *state,
1558 			 struct bpf_reg_state *parent, u8 flag)
1559 {
1560 	bool writes = parent == state->parent; /* Observe write marks */
1561 	int cnt = 0;
1562 
1563 	while (parent) {
1564 		/* if read wasn't screened by an earlier write ... */
1565 		if (writes && state->live & REG_LIVE_WRITTEN)
1566 			break;
1567 		if (parent->live & REG_LIVE_DONE) {
1568 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1569 				reg_type_str[parent->type],
1570 				parent->var_off.value, parent->off);
1571 			return -EFAULT;
1572 		}
1573 		/* The first condition is more likely to be true than the
1574 		 * second, checked it first.
1575 		 */
1576 		if ((parent->live & REG_LIVE_READ) == flag ||
1577 		    parent->live & REG_LIVE_READ64)
1578 			/* The parentage chain never changes and
1579 			 * this parent was already marked as LIVE_READ.
1580 			 * There is no need to keep walking the chain again and
1581 			 * keep re-marking all parents as LIVE_READ.
1582 			 * This case happens when the same register is read
1583 			 * multiple times without writes into it in-between.
1584 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1585 			 * then no need to set the weak REG_LIVE_READ32.
1586 			 */
1587 			break;
1588 		/* ... then we depend on parent's value */
1589 		parent->live |= flag;
1590 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1591 		if (flag == REG_LIVE_READ64)
1592 			parent->live &= ~REG_LIVE_READ32;
1593 		state = parent;
1594 		parent = state->parent;
1595 		writes = true;
1596 		cnt++;
1597 	}
1598 
1599 	if (env->longest_mark_read_walk < cnt)
1600 		env->longest_mark_read_walk = cnt;
1601 	return 0;
1602 }
1603 
1604 /* This function is supposed to be used by the following 32-bit optimization
1605  * code only. It returns TRUE if the source or destination register operates
1606  * on 64-bit, otherwise return FALSE.
1607  */
1608 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1609 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1610 {
1611 	u8 code, class, op;
1612 
1613 	code = insn->code;
1614 	class = BPF_CLASS(code);
1615 	op = BPF_OP(code);
1616 	if (class == BPF_JMP) {
1617 		/* BPF_EXIT for "main" will reach here. Return TRUE
1618 		 * conservatively.
1619 		 */
1620 		if (op == BPF_EXIT)
1621 			return true;
1622 		if (op == BPF_CALL) {
1623 			/* BPF to BPF call will reach here because of marking
1624 			 * caller saved clobber with DST_OP_NO_MARK for which we
1625 			 * don't care the register def because they are anyway
1626 			 * marked as NOT_INIT already.
1627 			 */
1628 			if (insn->src_reg == BPF_PSEUDO_CALL)
1629 				return false;
1630 			/* Helper call will reach here because of arg type
1631 			 * check, conservatively return TRUE.
1632 			 */
1633 			if (t == SRC_OP)
1634 				return true;
1635 
1636 			return false;
1637 		}
1638 	}
1639 
1640 	if (class == BPF_ALU64 || class == BPF_JMP ||
1641 	    /* BPF_END always use BPF_ALU class. */
1642 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1643 		return true;
1644 
1645 	if (class == BPF_ALU || class == BPF_JMP32)
1646 		return false;
1647 
1648 	if (class == BPF_LDX) {
1649 		if (t != SRC_OP)
1650 			return BPF_SIZE(code) == BPF_DW;
1651 		/* LDX source must be ptr. */
1652 		return true;
1653 	}
1654 
1655 	if (class == BPF_STX) {
1656 		if (reg->type != SCALAR_VALUE)
1657 			return true;
1658 		return BPF_SIZE(code) == BPF_DW;
1659 	}
1660 
1661 	if (class == BPF_LD) {
1662 		u8 mode = BPF_MODE(code);
1663 
1664 		/* LD_IMM64 */
1665 		if (mode == BPF_IMM)
1666 			return true;
1667 
1668 		/* Both LD_IND and LD_ABS return 32-bit data. */
1669 		if (t != SRC_OP)
1670 			return  false;
1671 
1672 		/* Implicit ctx ptr. */
1673 		if (regno == BPF_REG_6)
1674 			return true;
1675 
1676 		/* Explicit source could be any width. */
1677 		return true;
1678 	}
1679 
1680 	if (class == BPF_ST)
1681 		/* The only source register for BPF_ST is a ptr. */
1682 		return true;
1683 
1684 	/* Conservatively return true at default. */
1685 	return true;
1686 }
1687 
1688 /* Return TRUE if INSN doesn't have explicit value define. */
1689 static bool insn_no_def(struct bpf_insn *insn)
1690 {
1691 	u8 class = BPF_CLASS(insn->code);
1692 
1693 	return (class == BPF_JMP || class == BPF_JMP32 ||
1694 		class == BPF_STX || class == BPF_ST);
1695 }
1696 
1697 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1698 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1699 {
1700 	if (insn_no_def(insn))
1701 		return false;
1702 
1703 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1704 }
1705 
1706 static void mark_insn_zext(struct bpf_verifier_env *env,
1707 			   struct bpf_reg_state *reg)
1708 {
1709 	s32 def_idx = reg->subreg_def;
1710 
1711 	if (def_idx == DEF_NOT_SUBREG)
1712 		return;
1713 
1714 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1715 	/* The dst will be zero extended, so won't be sub-register anymore. */
1716 	reg->subreg_def = DEF_NOT_SUBREG;
1717 }
1718 
1719 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1720 			 enum reg_arg_type t)
1721 {
1722 	struct bpf_verifier_state *vstate = env->cur_state;
1723 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1724 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1725 	struct bpf_reg_state *reg, *regs = state->regs;
1726 	bool rw64;
1727 
1728 	if (regno >= MAX_BPF_REG) {
1729 		verbose(env, "R%d is invalid\n", regno);
1730 		return -EINVAL;
1731 	}
1732 
1733 	reg = &regs[regno];
1734 	rw64 = is_reg64(env, insn, regno, reg, t);
1735 	if (t == SRC_OP) {
1736 		/* check whether register used as source operand can be read */
1737 		if (reg->type == NOT_INIT) {
1738 			verbose(env, "R%d !read_ok\n", regno);
1739 			return -EACCES;
1740 		}
1741 		/* We don't need to worry about FP liveness because it's read-only */
1742 		if (regno == BPF_REG_FP)
1743 			return 0;
1744 
1745 		if (rw64)
1746 			mark_insn_zext(env, reg);
1747 
1748 		return mark_reg_read(env, reg, reg->parent,
1749 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1750 	} else {
1751 		/* check whether register used as dest operand can be written to */
1752 		if (regno == BPF_REG_FP) {
1753 			verbose(env, "frame pointer is read only\n");
1754 			return -EACCES;
1755 		}
1756 		reg->live |= REG_LIVE_WRITTEN;
1757 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1758 		if (t == DST_OP)
1759 			mark_reg_unknown(env, regs, regno);
1760 	}
1761 	return 0;
1762 }
1763 
1764 /* for any branch, call, exit record the history of jmps in the given state */
1765 static int push_jmp_history(struct bpf_verifier_env *env,
1766 			    struct bpf_verifier_state *cur)
1767 {
1768 	u32 cnt = cur->jmp_history_cnt;
1769 	struct bpf_idx_pair *p;
1770 
1771 	cnt++;
1772 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1773 	if (!p)
1774 		return -ENOMEM;
1775 	p[cnt - 1].idx = env->insn_idx;
1776 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1777 	cur->jmp_history = p;
1778 	cur->jmp_history_cnt = cnt;
1779 	return 0;
1780 }
1781 
1782 /* Backtrack one insn at a time. If idx is not at the top of recorded
1783  * history then previous instruction came from straight line execution.
1784  */
1785 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1786 			     u32 *history)
1787 {
1788 	u32 cnt = *history;
1789 
1790 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1791 		i = st->jmp_history[cnt - 1].prev_idx;
1792 		(*history)--;
1793 	} else {
1794 		i--;
1795 	}
1796 	return i;
1797 }
1798 
1799 /* For given verifier state backtrack_insn() is called from the last insn to
1800  * the first insn. Its purpose is to compute a bitmask of registers and
1801  * stack slots that needs precision in the parent verifier state.
1802  */
1803 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1804 			  u32 *reg_mask, u64 *stack_mask)
1805 {
1806 	const struct bpf_insn_cbs cbs = {
1807 		.cb_print	= verbose,
1808 		.private_data	= env,
1809 	};
1810 	struct bpf_insn *insn = env->prog->insnsi + idx;
1811 	u8 class = BPF_CLASS(insn->code);
1812 	u8 opcode = BPF_OP(insn->code);
1813 	u8 mode = BPF_MODE(insn->code);
1814 	u32 dreg = 1u << insn->dst_reg;
1815 	u32 sreg = 1u << insn->src_reg;
1816 	u32 spi;
1817 
1818 	if (insn->code == 0)
1819 		return 0;
1820 	if (env->log.level & BPF_LOG_LEVEL) {
1821 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1822 		verbose(env, "%d: ", idx);
1823 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1824 	}
1825 
1826 	if (class == BPF_ALU || class == BPF_ALU64) {
1827 		if (!(*reg_mask & dreg))
1828 			return 0;
1829 		if (opcode == BPF_MOV) {
1830 			if (BPF_SRC(insn->code) == BPF_X) {
1831 				/* dreg = sreg
1832 				 * dreg needs precision after this insn
1833 				 * sreg needs precision before this insn
1834 				 */
1835 				*reg_mask &= ~dreg;
1836 				*reg_mask |= sreg;
1837 			} else {
1838 				/* dreg = K
1839 				 * dreg needs precision after this insn.
1840 				 * Corresponding register is already marked
1841 				 * as precise=true in this verifier state.
1842 				 * No further markings in parent are necessary
1843 				 */
1844 				*reg_mask &= ~dreg;
1845 			}
1846 		} else {
1847 			if (BPF_SRC(insn->code) == BPF_X) {
1848 				/* dreg += sreg
1849 				 * both dreg and sreg need precision
1850 				 * before this insn
1851 				 */
1852 				*reg_mask |= sreg;
1853 			} /* else dreg += K
1854 			   * dreg still needs precision before this insn
1855 			   */
1856 		}
1857 	} else if (class == BPF_LDX) {
1858 		if (!(*reg_mask & dreg))
1859 			return 0;
1860 		*reg_mask &= ~dreg;
1861 
1862 		/* scalars can only be spilled into stack w/o losing precision.
1863 		 * Load from any other memory can be zero extended.
1864 		 * The desire to keep that precision is already indicated
1865 		 * by 'precise' mark in corresponding register of this state.
1866 		 * No further tracking necessary.
1867 		 */
1868 		if (insn->src_reg != BPF_REG_FP)
1869 			return 0;
1870 		if (BPF_SIZE(insn->code) != BPF_DW)
1871 			return 0;
1872 
1873 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1874 		 * that [fp - off] slot contains scalar that needs to be
1875 		 * tracked with precision
1876 		 */
1877 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1878 		if (spi >= 64) {
1879 			verbose(env, "BUG spi %d\n", spi);
1880 			WARN_ONCE(1, "verifier backtracking bug");
1881 			return -EFAULT;
1882 		}
1883 		*stack_mask |= 1ull << spi;
1884 	} else if (class == BPF_STX || class == BPF_ST) {
1885 		if (*reg_mask & dreg)
1886 			/* stx & st shouldn't be using _scalar_ dst_reg
1887 			 * to access memory. It means backtracking
1888 			 * encountered a case of pointer subtraction.
1889 			 */
1890 			return -ENOTSUPP;
1891 		/* scalars can only be spilled into stack */
1892 		if (insn->dst_reg != BPF_REG_FP)
1893 			return 0;
1894 		if (BPF_SIZE(insn->code) != BPF_DW)
1895 			return 0;
1896 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1897 		if (spi >= 64) {
1898 			verbose(env, "BUG spi %d\n", spi);
1899 			WARN_ONCE(1, "verifier backtracking bug");
1900 			return -EFAULT;
1901 		}
1902 		if (!(*stack_mask & (1ull << spi)))
1903 			return 0;
1904 		*stack_mask &= ~(1ull << spi);
1905 		if (class == BPF_STX)
1906 			*reg_mask |= sreg;
1907 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1908 		if (opcode == BPF_CALL) {
1909 			if (insn->src_reg == BPF_PSEUDO_CALL)
1910 				return -ENOTSUPP;
1911 			/* regular helper call sets R0 */
1912 			*reg_mask &= ~1;
1913 			if (*reg_mask & 0x3f) {
1914 				/* if backtracing was looking for registers R1-R5
1915 				 * they should have been found already.
1916 				 */
1917 				verbose(env, "BUG regs %x\n", *reg_mask);
1918 				WARN_ONCE(1, "verifier backtracking bug");
1919 				return -EFAULT;
1920 			}
1921 		} else if (opcode == BPF_EXIT) {
1922 			return -ENOTSUPP;
1923 		}
1924 	} else if (class == BPF_LD) {
1925 		if (!(*reg_mask & dreg))
1926 			return 0;
1927 		*reg_mask &= ~dreg;
1928 		/* It's ld_imm64 or ld_abs or ld_ind.
1929 		 * For ld_imm64 no further tracking of precision
1930 		 * into parent is necessary
1931 		 */
1932 		if (mode == BPF_IND || mode == BPF_ABS)
1933 			/* to be analyzed */
1934 			return -ENOTSUPP;
1935 	}
1936 	return 0;
1937 }
1938 
1939 /* the scalar precision tracking algorithm:
1940  * . at the start all registers have precise=false.
1941  * . scalar ranges are tracked as normal through alu and jmp insns.
1942  * . once precise value of the scalar register is used in:
1943  *   .  ptr + scalar alu
1944  *   . if (scalar cond K|scalar)
1945  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1946  *   backtrack through the verifier states and mark all registers and
1947  *   stack slots with spilled constants that these scalar regisers
1948  *   should be precise.
1949  * . during state pruning two registers (or spilled stack slots)
1950  *   are equivalent if both are not precise.
1951  *
1952  * Note the verifier cannot simply walk register parentage chain,
1953  * since many different registers and stack slots could have been
1954  * used to compute single precise scalar.
1955  *
1956  * The approach of starting with precise=true for all registers and then
1957  * backtrack to mark a register as not precise when the verifier detects
1958  * that program doesn't care about specific value (e.g., when helper
1959  * takes register as ARG_ANYTHING parameter) is not safe.
1960  *
1961  * It's ok to walk single parentage chain of the verifier states.
1962  * It's possible that this backtracking will go all the way till 1st insn.
1963  * All other branches will be explored for needing precision later.
1964  *
1965  * The backtracking needs to deal with cases like:
1966  *   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)
1967  * r9 -= r8
1968  * r5 = r9
1969  * if r5 > 0x79f goto pc+7
1970  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1971  * r5 += 1
1972  * ...
1973  * call bpf_perf_event_output#25
1974  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1975  *
1976  * and this case:
1977  * r6 = 1
1978  * call foo // uses callee's r6 inside to compute r0
1979  * r0 += r6
1980  * if r0 == 0 goto
1981  *
1982  * to track above reg_mask/stack_mask needs to be independent for each frame.
1983  *
1984  * Also if parent's curframe > frame where backtracking started,
1985  * the verifier need to mark registers in both frames, otherwise callees
1986  * may incorrectly prune callers. This is similar to
1987  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1988  *
1989  * For now backtracking falls back into conservative marking.
1990  */
1991 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1992 				     struct bpf_verifier_state *st)
1993 {
1994 	struct bpf_func_state *func;
1995 	struct bpf_reg_state *reg;
1996 	int i, j;
1997 
1998 	/* big hammer: mark all scalars precise in this path.
1999 	 * pop_stack may still get !precise scalars.
2000 	 */
2001 	for (; st; st = st->parent)
2002 		for (i = 0; i <= st->curframe; i++) {
2003 			func = st->frame[i];
2004 			for (j = 0; j < BPF_REG_FP; j++) {
2005 				reg = &func->regs[j];
2006 				if (reg->type != SCALAR_VALUE)
2007 					continue;
2008 				reg->precise = true;
2009 			}
2010 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2011 				if (func->stack[j].slot_type[0] != STACK_SPILL)
2012 					continue;
2013 				reg = &func->stack[j].spilled_ptr;
2014 				if (reg->type != SCALAR_VALUE)
2015 					continue;
2016 				reg->precise = true;
2017 			}
2018 		}
2019 }
2020 
2021 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2022 				  int spi)
2023 {
2024 	struct bpf_verifier_state *st = env->cur_state;
2025 	int first_idx = st->first_insn_idx;
2026 	int last_idx = env->insn_idx;
2027 	struct bpf_func_state *func;
2028 	struct bpf_reg_state *reg;
2029 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2030 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2031 	bool skip_first = true;
2032 	bool new_marks = false;
2033 	int i, err;
2034 
2035 	if (!env->bpf_capable)
2036 		return 0;
2037 
2038 	func = st->frame[st->curframe];
2039 	if (regno >= 0) {
2040 		reg = &func->regs[regno];
2041 		if (reg->type != SCALAR_VALUE) {
2042 			WARN_ONCE(1, "backtracing misuse");
2043 			return -EFAULT;
2044 		}
2045 		if (!reg->precise)
2046 			new_marks = true;
2047 		else
2048 			reg_mask = 0;
2049 		reg->precise = true;
2050 	}
2051 
2052 	while (spi >= 0) {
2053 		if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2054 			stack_mask = 0;
2055 			break;
2056 		}
2057 		reg = &func->stack[spi].spilled_ptr;
2058 		if (reg->type != SCALAR_VALUE) {
2059 			stack_mask = 0;
2060 			break;
2061 		}
2062 		if (!reg->precise)
2063 			new_marks = true;
2064 		else
2065 			stack_mask = 0;
2066 		reg->precise = true;
2067 		break;
2068 	}
2069 
2070 	if (!new_marks)
2071 		return 0;
2072 	if (!reg_mask && !stack_mask)
2073 		return 0;
2074 	for (;;) {
2075 		DECLARE_BITMAP(mask, 64);
2076 		u32 history = st->jmp_history_cnt;
2077 
2078 		if (env->log.level & BPF_LOG_LEVEL)
2079 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2080 		for (i = last_idx;;) {
2081 			if (skip_first) {
2082 				err = 0;
2083 				skip_first = false;
2084 			} else {
2085 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2086 			}
2087 			if (err == -ENOTSUPP) {
2088 				mark_all_scalars_precise(env, st);
2089 				return 0;
2090 			} else if (err) {
2091 				return err;
2092 			}
2093 			if (!reg_mask && !stack_mask)
2094 				/* Found assignment(s) into tracked register in this state.
2095 				 * Since this state is already marked, just return.
2096 				 * Nothing to be tracked further in the parent state.
2097 				 */
2098 				return 0;
2099 			if (i == first_idx)
2100 				break;
2101 			i = get_prev_insn_idx(st, i, &history);
2102 			if (i >= env->prog->len) {
2103 				/* This can happen if backtracking reached insn 0
2104 				 * and there are still reg_mask or stack_mask
2105 				 * to backtrack.
2106 				 * It means the backtracking missed the spot where
2107 				 * particular register was initialized with a constant.
2108 				 */
2109 				verbose(env, "BUG backtracking idx %d\n", i);
2110 				WARN_ONCE(1, "verifier backtracking bug");
2111 				return -EFAULT;
2112 			}
2113 		}
2114 		st = st->parent;
2115 		if (!st)
2116 			break;
2117 
2118 		new_marks = false;
2119 		func = st->frame[st->curframe];
2120 		bitmap_from_u64(mask, reg_mask);
2121 		for_each_set_bit(i, mask, 32) {
2122 			reg = &func->regs[i];
2123 			if (reg->type != SCALAR_VALUE) {
2124 				reg_mask &= ~(1u << i);
2125 				continue;
2126 			}
2127 			if (!reg->precise)
2128 				new_marks = true;
2129 			reg->precise = true;
2130 		}
2131 
2132 		bitmap_from_u64(mask, stack_mask);
2133 		for_each_set_bit(i, mask, 64) {
2134 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2135 				/* the sequence of instructions:
2136 				 * 2: (bf) r3 = r10
2137 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2138 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2139 				 * doesn't contain jmps. It's backtracked
2140 				 * as a single block.
2141 				 * During backtracking insn 3 is not recognized as
2142 				 * stack access, so at the end of backtracking
2143 				 * stack slot fp-8 is still marked in stack_mask.
2144 				 * However the parent state may not have accessed
2145 				 * fp-8 and it's "unallocated" stack space.
2146 				 * In such case fallback to conservative.
2147 				 */
2148 				mark_all_scalars_precise(env, st);
2149 				return 0;
2150 			}
2151 
2152 			if (func->stack[i].slot_type[0] != STACK_SPILL) {
2153 				stack_mask &= ~(1ull << i);
2154 				continue;
2155 			}
2156 			reg = &func->stack[i].spilled_ptr;
2157 			if (reg->type != SCALAR_VALUE) {
2158 				stack_mask &= ~(1ull << i);
2159 				continue;
2160 			}
2161 			if (!reg->precise)
2162 				new_marks = true;
2163 			reg->precise = true;
2164 		}
2165 		if (env->log.level & BPF_LOG_LEVEL) {
2166 			print_verifier_state(env, func);
2167 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2168 				new_marks ? "didn't have" : "already had",
2169 				reg_mask, stack_mask);
2170 		}
2171 
2172 		if (!reg_mask && !stack_mask)
2173 			break;
2174 		if (!new_marks)
2175 			break;
2176 
2177 		last_idx = st->last_insn_idx;
2178 		first_idx = st->first_insn_idx;
2179 	}
2180 	return 0;
2181 }
2182 
2183 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2184 {
2185 	return __mark_chain_precision(env, regno, -1);
2186 }
2187 
2188 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2189 {
2190 	return __mark_chain_precision(env, -1, spi);
2191 }
2192 
2193 static bool is_spillable_regtype(enum bpf_reg_type type)
2194 {
2195 	switch (type) {
2196 	case PTR_TO_MAP_VALUE:
2197 	case PTR_TO_MAP_VALUE_OR_NULL:
2198 	case PTR_TO_STACK:
2199 	case PTR_TO_CTX:
2200 	case PTR_TO_PACKET:
2201 	case PTR_TO_PACKET_META:
2202 	case PTR_TO_PACKET_END:
2203 	case PTR_TO_FLOW_KEYS:
2204 	case CONST_PTR_TO_MAP:
2205 	case PTR_TO_SOCKET:
2206 	case PTR_TO_SOCKET_OR_NULL:
2207 	case PTR_TO_SOCK_COMMON:
2208 	case PTR_TO_SOCK_COMMON_OR_NULL:
2209 	case PTR_TO_TCP_SOCK:
2210 	case PTR_TO_TCP_SOCK_OR_NULL:
2211 	case PTR_TO_XDP_SOCK:
2212 	case PTR_TO_BTF_ID:
2213 	case PTR_TO_BTF_ID_OR_NULL:
2214 	case PTR_TO_RDONLY_BUF:
2215 	case PTR_TO_RDONLY_BUF_OR_NULL:
2216 	case PTR_TO_RDWR_BUF:
2217 	case PTR_TO_RDWR_BUF_OR_NULL:
2218 	case PTR_TO_PERCPU_BTF_ID:
2219 		return true;
2220 	default:
2221 		return false;
2222 	}
2223 }
2224 
2225 /* Does this register contain a constant zero? */
2226 static bool register_is_null(struct bpf_reg_state *reg)
2227 {
2228 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2229 }
2230 
2231 static bool register_is_const(struct bpf_reg_state *reg)
2232 {
2233 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2234 }
2235 
2236 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2237 {
2238 	return tnum_is_unknown(reg->var_off) &&
2239 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2240 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2241 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2242 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2243 }
2244 
2245 static bool register_is_bounded(struct bpf_reg_state *reg)
2246 {
2247 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2248 }
2249 
2250 static bool __is_pointer_value(bool allow_ptr_leaks,
2251 			       const struct bpf_reg_state *reg)
2252 {
2253 	if (allow_ptr_leaks)
2254 		return false;
2255 
2256 	return reg->type != SCALAR_VALUE;
2257 }
2258 
2259 static void save_register_state(struct bpf_func_state *state,
2260 				int spi, struct bpf_reg_state *reg)
2261 {
2262 	int i;
2263 
2264 	state->stack[spi].spilled_ptr = *reg;
2265 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2266 
2267 	for (i = 0; i < BPF_REG_SIZE; i++)
2268 		state->stack[spi].slot_type[i] = STACK_SPILL;
2269 }
2270 
2271 /* check_stack_read/write functions track spill/fill of registers,
2272  * stack boundary and alignment are checked in check_mem_access()
2273  */
2274 static int check_stack_write(struct bpf_verifier_env *env,
2275 			     struct bpf_func_state *state, /* func where register points to */
2276 			     int off, int size, int value_regno, int insn_idx)
2277 {
2278 	struct bpf_func_state *cur; /* state of the current function */
2279 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2280 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2281 	struct bpf_reg_state *reg = NULL;
2282 
2283 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2284 				 state->acquired_refs, true);
2285 	if (err)
2286 		return err;
2287 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2288 	 * so it's aligned access and [off, off + size) are within stack limits
2289 	 */
2290 	if (!env->allow_ptr_leaks &&
2291 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2292 	    size != BPF_REG_SIZE) {
2293 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2294 		return -EACCES;
2295 	}
2296 
2297 	cur = env->cur_state->frame[env->cur_state->curframe];
2298 	if (value_regno >= 0)
2299 		reg = &cur->regs[value_regno];
2300 
2301 	if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2302 	    !register_is_null(reg) && env->bpf_capable) {
2303 		if (dst_reg != BPF_REG_FP) {
2304 			/* The backtracking logic can only recognize explicit
2305 			 * stack slot address like [fp - 8]. Other spill of
2306 			 * scalar via different register has to be conervative.
2307 			 * Backtrack from here and mark all registers as precise
2308 			 * that contributed into 'reg' being a constant.
2309 			 */
2310 			err = mark_chain_precision(env, value_regno);
2311 			if (err)
2312 				return err;
2313 		}
2314 		save_register_state(state, spi, reg);
2315 	} else if (reg && is_spillable_regtype(reg->type)) {
2316 		/* register containing pointer is being spilled into stack */
2317 		if (size != BPF_REG_SIZE) {
2318 			verbose_linfo(env, insn_idx, "; ");
2319 			verbose(env, "invalid size of register spill\n");
2320 			return -EACCES;
2321 		}
2322 
2323 		if (state != cur && reg->type == PTR_TO_STACK) {
2324 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2325 			return -EINVAL;
2326 		}
2327 
2328 		if (!env->bypass_spec_v4) {
2329 			bool sanitize = false;
2330 
2331 			if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2332 			    register_is_const(&state->stack[spi].spilled_ptr))
2333 				sanitize = true;
2334 			for (i = 0; i < BPF_REG_SIZE; i++)
2335 				if (state->stack[spi].slot_type[i] == STACK_MISC) {
2336 					sanitize = true;
2337 					break;
2338 				}
2339 			if (sanitize) {
2340 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2341 				int soff = (-spi - 1) * BPF_REG_SIZE;
2342 
2343 				/* detected reuse of integer stack slot with a pointer
2344 				 * which means either llvm is reusing stack slot or
2345 				 * an attacker is trying to exploit CVE-2018-3639
2346 				 * (speculative store bypass)
2347 				 * Have to sanitize that slot with preemptive
2348 				 * store of zero.
2349 				 */
2350 				if (*poff && *poff != soff) {
2351 					/* disallow programs where single insn stores
2352 					 * into two different stack slots, since verifier
2353 					 * cannot sanitize them
2354 					 */
2355 					verbose(env,
2356 						"insn %d cannot access two stack slots fp%d and fp%d",
2357 						insn_idx, *poff, soff);
2358 					return -EINVAL;
2359 				}
2360 				*poff = soff;
2361 			}
2362 		}
2363 		save_register_state(state, spi, reg);
2364 	} else {
2365 		u8 type = STACK_MISC;
2366 
2367 		/* regular write of data into stack destroys any spilled ptr */
2368 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2369 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2370 		if (state->stack[spi].slot_type[0] == STACK_SPILL)
2371 			for (i = 0; i < BPF_REG_SIZE; i++)
2372 				state->stack[spi].slot_type[i] = STACK_MISC;
2373 
2374 		/* only mark the slot as written if all 8 bytes were written
2375 		 * otherwise read propagation may incorrectly stop too soon
2376 		 * when stack slots are partially written.
2377 		 * This heuristic means that read propagation will be
2378 		 * conservative, since it will add reg_live_read marks
2379 		 * to stack slots all the way to first state when programs
2380 		 * writes+reads less than 8 bytes
2381 		 */
2382 		if (size == BPF_REG_SIZE)
2383 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2384 
2385 		/* when we zero initialize stack slots mark them as such */
2386 		if (reg && register_is_null(reg)) {
2387 			/* backtracking doesn't work for STACK_ZERO yet. */
2388 			err = mark_chain_precision(env, value_regno);
2389 			if (err)
2390 				return err;
2391 			type = STACK_ZERO;
2392 		}
2393 
2394 		/* Mark slots affected by this stack write. */
2395 		for (i = 0; i < size; i++)
2396 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2397 				type;
2398 	}
2399 	return 0;
2400 }
2401 
2402 static int check_stack_read(struct bpf_verifier_env *env,
2403 			    struct bpf_func_state *reg_state /* func where register points to */,
2404 			    int off, int size, int value_regno)
2405 {
2406 	struct bpf_verifier_state *vstate = env->cur_state;
2407 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2408 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2409 	struct bpf_reg_state *reg;
2410 	u8 *stype;
2411 
2412 	if (reg_state->allocated_stack <= slot) {
2413 		verbose(env, "invalid read from stack off %d+0 size %d\n",
2414 			off, size);
2415 		return -EACCES;
2416 	}
2417 	stype = reg_state->stack[spi].slot_type;
2418 	reg = &reg_state->stack[spi].spilled_ptr;
2419 
2420 	if (stype[0] == STACK_SPILL) {
2421 		if (size != BPF_REG_SIZE) {
2422 			if (reg->type != SCALAR_VALUE) {
2423 				verbose_linfo(env, env->insn_idx, "; ");
2424 				verbose(env, "invalid size of register fill\n");
2425 				return -EACCES;
2426 			}
2427 			if (value_regno >= 0) {
2428 				mark_reg_unknown(env, state->regs, value_regno);
2429 				state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2430 			}
2431 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2432 			return 0;
2433 		}
2434 		for (i = 1; i < BPF_REG_SIZE; i++) {
2435 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2436 				verbose(env, "corrupted spill memory\n");
2437 				return -EACCES;
2438 			}
2439 		}
2440 
2441 		if (value_regno >= 0) {
2442 			/* restore register state from stack */
2443 			state->regs[value_regno] = *reg;
2444 			/* mark reg as written since spilled pointer state likely
2445 			 * has its liveness marks cleared by is_state_visited()
2446 			 * which resets stack/reg liveness for state transitions
2447 			 */
2448 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2449 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2450 			/* If value_regno==-1, the caller is asking us whether
2451 			 * it is acceptable to use this value as a SCALAR_VALUE
2452 			 * (e.g. for XADD).
2453 			 * We must not allow unprivileged callers to do that
2454 			 * with spilled pointers.
2455 			 */
2456 			verbose(env, "leaking pointer from stack off %d\n",
2457 				off);
2458 			return -EACCES;
2459 		}
2460 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2461 	} else {
2462 		int zeros = 0;
2463 
2464 		for (i = 0; i < size; i++) {
2465 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2466 				continue;
2467 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2468 				zeros++;
2469 				continue;
2470 			}
2471 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2472 				off, i, size);
2473 			return -EACCES;
2474 		}
2475 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2476 		if (value_regno >= 0) {
2477 			if (zeros == size) {
2478 				/* any size read into register is zero extended,
2479 				 * so the whole register == const_zero
2480 				 */
2481 				__mark_reg_const_zero(&state->regs[value_regno]);
2482 				/* backtracking doesn't support STACK_ZERO yet,
2483 				 * so mark it precise here, so that later
2484 				 * backtracking can stop here.
2485 				 * Backtracking may not need this if this register
2486 				 * doesn't participate in pointer adjustment.
2487 				 * Forward propagation of precise flag is not
2488 				 * necessary either. This mark is only to stop
2489 				 * backtracking. Any register that contributed
2490 				 * to const 0 was marked precise before spill.
2491 				 */
2492 				state->regs[value_regno].precise = true;
2493 			} else {
2494 				/* have read misc data from the stack */
2495 				mark_reg_unknown(env, state->regs, value_regno);
2496 			}
2497 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2498 		}
2499 	}
2500 	return 0;
2501 }
2502 
2503 static int check_stack_access(struct bpf_verifier_env *env,
2504 			      const struct bpf_reg_state *reg,
2505 			      int off, int size)
2506 {
2507 	/* Stack accesses must be at a fixed offset, so that we
2508 	 * can determine what type of data were returned. See
2509 	 * check_stack_read().
2510 	 */
2511 	if (!tnum_is_const(reg->var_off)) {
2512 		char tn_buf[48];
2513 
2514 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2515 		verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2516 			tn_buf, off, size);
2517 		return -EACCES;
2518 	}
2519 
2520 	if (off >= 0 || off < -MAX_BPF_STACK) {
2521 		verbose(env, "invalid stack off=%d size=%d\n", off, size);
2522 		return -EACCES;
2523 	}
2524 
2525 	return 0;
2526 }
2527 
2528 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2529 				 int off, int size, enum bpf_access_type type)
2530 {
2531 	struct bpf_reg_state *regs = cur_regs(env);
2532 	struct bpf_map *map = regs[regno].map_ptr;
2533 	u32 cap = bpf_map_flags_to_cap(map);
2534 
2535 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2536 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2537 			map->value_size, off, size);
2538 		return -EACCES;
2539 	}
2540 
2541 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2542 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2543 			map->value_size, off, size);
2544 		return -EACCES;
2545 	}
2546 
2547 	return 0;
2548 }
2549 
2550 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2551 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2552 			      int off, int size, u32 mem_size,
2553 			      bool zero_size_allowed)
2554 {
2555 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2556 	struct bpf_reg_state *reg;
2557 
2558 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2559 		return 0;
2560 
2561 	reg = &cur_regs(env)[regno];
2562 	switch (reg->type) {
2563 	case PTR_TO_MAP_VALUE:
2564 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2565 			mem_size, off, size);
2566 		break;
2567 	case PTR_TO_PACKET:
2568 	case PTR_TO_PACKET_META:
2569 	case PTR_TO_PACKET_END:
2570 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2571 			off, size, regno, reg->id, off, mem_size);
2572 		break;
2573 	case PTR_TO_MEM:
2574 	default:
2575 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2576 			mem_size, off, size);
2577 	}
2578 
2579 	return -EACCES;
2580 }
2581 
2582 /* check read/write into a memory region with possible variable offset */
2583 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2584 				   int off, int size, u32 mem_size,
2585 				   bool zero_size_allowed)
2586 {
2587 	struct bpf_verifier_state *vstate = env->cur_state;
2588 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2589 	struct bpf_reg_state *reg = &state->regs[regno];
2590 	int err;
2591 
2592 	/* We may have adjusted the register pointing to memory region, so we
2593 	 * need to try adding each of min_value and max_value to off
2594 	 * to make sure our theoretical access will be safe.
2595 	 */
2596 	if (env->log.level & BPF_LOG_LEVEL)
2597 		print_verifier_state(env, state);
2598 
2599 	/* The minimum value is only important with signed
2600 	 * comparisons where we can't assume the floor of a
2601 	 * value is 0.  If we are using signed variables for our
2602 	 * index'es we need to make sure that whatever we use
2603 	 * will have a set floor within our range.
2604 	 */
2605 	if (reg->smin_value < 0 &&
2606 	    (reg->smin_value == S64_MIN ||
2607 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2608 	      reg->smin_value + off < 0)) {
2609 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2610 			regno);
2611 		return -EACCES;
2612 	}
2613 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
2614 				 mem_size, zero_size_allowed);
2615 	if (err) {
2616 		verbose(env, "R%d min value is outside of the allowed memory range\n",
2617 			regno);
2618 		return err;
2619 	}
2620 
2621 	/* If we haven't set a max value then we need to bail since we can't be
2622 	 * sure we won't do bad things.
2623 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
2624 	 */
2625 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2626 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2627 			regno);
2628 		return -EACCES;
2629 	}
2630 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
2631 				 mem_size, zero_size_allowed);
2632 	if (err) {
2633 		verbose(env, "R%d max value is outside of the allowed memory range\n",
2634 			regno);
2635 		return err;
2636 	}
2637 
2638 	return 0;
2639 }
2640 
2641 /* check read/write into a map element with possible variable offset */
2642 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2643 			    int off, int size, bool zero_size_allowed)
2644 {
2645 	struct bpf_verifier_state *vstate = env->cur_state;
2646 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2647 	struct bpf_reg_state *reg = &state->regs[regno];
2648 	struct bpf_map *map = reg->map_ptr;
2649 	int err;
2650 
2651 	err = check_mem_region_access(env, regno, off, size, map->value_size,
2652 				      zero_size_allowed);
2653 	if (err)
2654 		return err;
2655 
2656 	if (map_value_has_spin_lock(map)) {
2657 		u32 lock = map->spin_lock_off;
2658 
2659 		/* if any part of struct bpf_spin_lock can be touched by
2660 		 * load/store reject this program.
2661 		 * To check that [x1, x2) overlaps with [y1, y2)
2662 		 * it is sufficient to check x1 < y2 && y1 < x2.
2663 		 */
2664 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2665 		     lock < reg->umax_value + off + size) {
2666 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2667 			return -EACCES;
2668 		}
2669 	}
2670 	return err;
2671 }
2672 
2673 #define MAX_PACKET_OFF 0xffff
2674 
2675 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2676 {
2677 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2678 }
2679 
2680 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2681 				       const struct bpf_call_arg_meta *meta,
2682 				       enum bpf_access_type t)
2683 {
2684 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2685 
2686 	switch (prog_type) {
2687 	/* Program types only with direct read access go here! */
2688 	case BPF_PROG_TYPE_LWT_IN:
2689 	case BPF_PROG_TYPE_LWT_OUT:
2690 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2691 	case BPF_PROG_TYPE_SK_REUSEPORT:
2692 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2693 	case BPF_PROG_TYPE_CGROUP_SKB:
2694 		if (t == BPF_WRITE)
2695 			return false;
2696 		fallthrough;
2697 
2698 	/* Program types with direct read + write access go here! */
2699 	case BPF_PROG_TYPE_SCHED_CLS:
2700 	case BPF_PROG_TYPE_SCHED_ACT:
2701 	case BPF_PROG_TYPE_XDP:
2702 	case BPF_PROG_TYPE_LWT_XMIT:
2703 	case BPF_PROG_TYPE_SK_SKB:
2704 	case BPF_PROG_TYPE_SK_MSG:
2705 		if (meta)
2706 			return meta->pkt_access;
2707 
2708 		env->seen_direct_write = true;
2709 		return true;
2710 
2711 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2712 		if (t == BPF_WRITE)
2713 			env->seen_direct_write = true;
2714 
2715 		return true;
2716 
2717 	default:
2718 		return false;
2719 	}
2720 }
2721 
2722 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2723 			       int size, bool zero_size_allowed)
2724 {
2725 	struct bpf_reg_state *regs = cur_regs(env);
2726 	struct bpf_reg_state *reg = &regs[regno];
2727 	int err;
2728 
2729 	/* We may have added a variable offset to the packet pointer; but any
2730 	 * reg->range we have comes after that.  We are only checking the fixed
2731 	 * offset.
2732 	 */
2733 
2734 	/* We don't allow negative numbers, because we aren't tracking enough
2735 	 * detail to prove they're safe.
2736 	 */
2737 	if (reg->smin_value < 0) {
2738 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2739 			regno);
2740 		return -EACCES;
2741 	}
2742 
2743 	err = reg->range < 0 ? -EINVAL :
2744 	      __check_mem_access(env, regno, off, size, reg->range,
2745 				 zero_size_allowed);
2746 	if (err) {
2747 		verbose(env, "R%d offset is outside of the packet\n", regno);
2748 		return err;
2749 	}
2750 
2751 	/* __check_mem_access has made sure "off + size - 1" is within u16.
2752 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2753 	 * otherwise find_good_pkt_pointers would have refused to set range info
2754 	 * that __check_mem_access would have rejected this pkt access.
2755 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2756 	 */
2757 	env->prog->aux->max_pkt_offset =
2758 		max_t(u32, env->prog->aux->max_pkt_offset,
2759 		      off + reg->umax_value + size - 1);
2760 
2761 	return err;
2762 }
2763 
2764 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
2765 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2766 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
2767 			    u32 *btf_id)
2768 {
2769 	struct bpf_insn_access_aux info = {
2770 		.reg_type = *reg_type,
2771 		.log = &env->log,
2772 	};
2773 
2774 	if (env->ops->is_valid_access &&
2775 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2776 		/* A non zero info.ctx_field_size indicates that this field is a
2777 		 * candidate for later verifier transformation to load the whole
2778 		 * field and then apply a mask when accessed with a narrower
2779 		 * access than actual ctx access size. A zero info.ctx_field_size
2780 		 * will only allow for whole field access and rejects any other
2781 		 * type of narrower access.
2782 		 */
2783 		*reg_type = info.reg_type;
2784 
2785 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
2786 			*btf_id = info.btf_id;
2787 		else
2788 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2789 		/* remember the offset of last byte accessed in ctx */
2790 		if (env->prog->aux->max_ctx_offset < off + size)
2791 			env->prog->aux->max_ctx_offset = off + size;
2792 		return 0;
2793 	}
2794 
2795 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2796 	return -EACCES;
2797 }
2798 
2799 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2800 				  int size)
2801 {
2802 	if (size < 0 || off < 0 ||
2803 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
2804 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
2805 			off, size);
2806 		return -EACCES;
2807 	}
2808 	return 0;
2809 }
2810 
2811 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2812 			     u32 regno, int off, int size,
2813 			     enum bpf_access_type t)
2814 {
2815 	struct bpf_reg_state *regs = cur_regs(env);
2816 	struct bpf_reg_state *reg = &regs[regno];
2817 	struct bpf_insn_access_aux info = {};
2818 	bool valid;
2819 
2820 	if (reg->smin_value < 0) {
2821 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2822 			regno);
2823 		return -EACCES;
2824 	}
2825 
2826 	switch (reg->type) {
2827 	case PTR_TO_SOCK_COMMON:
2828 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2829 		break;
2830 	case PTR_TO_SOCKET:
2831 		valid = bpf_sock_is_valid_access(off, size, t, &info);
2832 		break;
2833 	case PTR_TO_TCP_SOCK:
2834 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2835 		break;
2836 	case PTR_TO_XDP_SOCK:
2837 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2838 		break;
2839 	default:
2840 		valid = false;
2841 	}
2842 
2843 
2844 	if (valid) {
2845 		env->insn_aux_data[insn_idx].ctx_field_size =
2846 			info.ctx_field_size;
2847 		return 0;
2848 	}
2849 
2850 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
2851 		regno, reg_type_str[reg->type], off, size);
2852 
2853 	return -EACCES;
2854 }
2855 
2856 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2857 {
2858 	return cur_regs(env) + regno;
2859 }
2860 
2861 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2862 {
2863 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2864 }
2865 
2866 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2867 {
2868 	const struct bpf_reg_state *reg = reg_state(env, regno);
2869 
2870 	return reg->type == PTR_TO_CTX;
2871 }
2872 
2873 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2874 {
2875 	const struct bpf_reg_state *reg = reg_state(env, regno);
2876 
2877 	return type_is_sk_pointer(reg->type);
2878 }
2879 
2880 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2881 {
2882 	const struct bpf_reg_state *reg = reg_state(env, regno);
2883 
2884 	return type_is_pkt_pointer(reg->type);
2885 }
2886 
2887 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2888 {
2889 	const struct bpf_reg_state *reg = reg_state(env, regno);
2890 
2891 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2892 	return reg->type == PTR_TO_FLOW_KEYS;
2893 }
2894 
2895 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2896 				   const struct bpf_reg_state *reg,
2897 				   int off, int size, bool strict)
2898 {
2899 	struct tnum reg_off;
2900 	int ip_align;
2901 
2902 	/* Byte size accesses are always allowed. */
2903 	if (!strict || size == 1)
2904 		return 0;
2905 
2906 	/* For platforms that do not have a Kconfig enabling
2907 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2908 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
2909 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2910 	 * to this code only in strict mode where we want to emulate
2911 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
2912 	 * unconditional IP align value of '2'.
2913 	 */
2914 	ip_align = 2;
2915 
2916 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2917 	if (!tnum_is_aligned(reg_off, size)) {
2918 		char tn_buf[48];
2919 
2920 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2921 		verbose(env,
2922 			"misaligned packet access off %d+%s+%d+%d size %d\n",
2923 			ip_align, tn_buf, reg->off, off, size);
2924 		return -EACCES;
2925 	}
2926 
2927 	return 0;
2928 }
2929 
2930 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2931 				       const struct bpf_reg_state *reg,
2932 				       const char *pointer_desc,
2933 				       int off, int size, bool strict)
2934 {
2935 	struct tnum reg_off;
2936 
2937 	/* Byte size accesses are always allowed. */
2938 	if (!strict || size == 1)
2939 		return 0;
2940 
2941 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2942 	if (!tnum_is_aligned(reg_off, size)) {
2943 		char tn_buf[48];
2944 
2945 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2946 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2947 			pointer_desc, tn_buf, reg->off, off, size);
2948 		return -EACCES;
2949 	}
2950 
2951 	return 0;
2952 }
2953 
2954 static int check_ptr_alignment(struct bpf_verifier_env *env,
2955 			       const struct bpf_reg_state *reg, int off,
2956 			       int size, bool strict_alignment_once)
2957 {
2958 	bool strict = env->strict_alignment || strict_alignment_once;
2959 	const char *pointer_desc = "";
2960 
2961 	switch (reg->type) {
2962 	case PTR_TO_PACKET:
2963 	case PTR_TO_PACKET_META:
2964 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
2965 		 * right in front, treat it the very same way.
2966 		 */
2967 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
2968 	case PTR_TO_FLOW_KEYS:
2969 		pointer_desc = "flow keys ";
2970 		break;
2971 	case PTR_TO_MAP_VALUE:
2972 		pointer_desc = "value ";
2973 		break;
2974 	case PTR_TO_CTX:
2975 		pointer_desc = "context ";
2976 		break;
2977 	case PTR_TO_STACK:
2978 		pointer_desc = "stack ";
2979 		/* The stack spill tracking logic in check_stack_write()
2980 		 * and check_stack_read() relies on stack accesses being
2981 		 * aligned.
2982 		 */
2983 		strict = true;
2984 		break;
2985 	case PTR_TO_SOCKET:
2986 		pointer_desc = "sock ";
2987 		break;
2988 	case PTR_TO_SOCK_COMMON:
2989 		pointer_desc = "sock_common ";
2990 		break;
2991 	case PTR_TO_TCP_SOCK:
2992 		pointer_desc = "tcp_sock ";
2993 		break;
2994 	case PTR_TO_XDP_SOCK:
2995 		pointer_desc = "xdp_sock ";
2996 		break;
2997 	default:
2998 		break;
2999 	}
3000 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3001 					   strict);
3002 }
3003 
3004 static int update_stack_depth(struct bpf_verifier_env *env,
3005 			      const struct bpf_func_state *func,
3006 			      int off)
3007 {
3008 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3009 
3010 	if (stack >= -off)
3011 		return 0;
3012 
3013 	/* update known max for given subprogram */
3014 	env->subprog_info[func->subprogno].stack_depth = -off;
3015 	return 0;
3016 }
3017 
3018 /* starting from main bpf function walk all instructions of the function
3019  * and recursively walk all callees that given function can call.
3020  * Ignore jump and exit insns.
3021  * Since recursion is prevented by check_cfg() this algorithm
3022  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3023  */
3024 static int check_max_stack_depth(struct bpf_verifier_env *env)
3025 {
3026 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3027 	struct bpf_subprog_info *subprog = env->subprog_info;
3028 	struct bpf_insn *insn = env->prog->insnsi;
3029 	bool tail_call_reachable = false;
3030 	int ret_insn[MAX_CALL_FRAMES];
3031 	int ret_prog[MAX_CALL_FRAMES];
3032 	int j;
3033 
3034 process_func:
3035 	/* protect against potential stack overflow that might happen when
3036 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3037 	 * depth for such case down to 256 so that the worst case scenario
3038 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3039 	 * 8k).
3040 	 *
3041 	 * To get the idea what might happen, see an example:
3042 	 * func1 -> sub rsp, 128
3043 	 *  subfunc1 -> sub rsp, 256
3044 	 *  tailcall1 -> add rsp, 256
3045 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3046 	 *   subfunc2 -> sub rsp, 64
3047 	 *   subfunc22 -> sub rsp, 128
3048 	 *   tailcall2 -> add rsp, 128
3049 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3050 	 *
3051 	 * tailcall will unwind the current stack frame but it will not get rid
3052 	 * of caller's stack as shown on the example above.
3053 	 */
3054 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3055 		verbose(env,
3056 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3057 			depth);
3058 		return -EACCES;
3059 	}
3060 	/* round up to 32-bytes, since this is granularity
3061 	 * of interpreter stack size
3062 	 */
3063 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3064 	if (depth > MAX_BPF_STACK) {
3065 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3066 			frame + 1, depth);
3067 		return -EACCES;
3068 	}
3069 continue_func:
3070 	subprog_end = subprog[idx + 1].start;
3071 	for (; i < subprog_end; i++) {
3072 		if (insn[i].code != (BPF_JMP | BPF_CALL))
3073 			continue;
3074 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
3075 			continue;
3076 		/* remember insn and function to return to */
3077 		ret_insn[frame] = i + 1;
3078 		ret_prog[frame] = idx;
3079 
3080 		/* find the callee */
3081 		i = i + insn[i].imm + 1;
3082 		idx = find_subprog(env, i);
3083 		if (idx < 0) {
3084 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3085 				  i);
3086 			return -EFAULT;
3087 		}
3088 
3089 		if (subprog[idx].has_tail_call)
3090 			tail_call_reachable = true;
3091 
3092 		frame++;
3093 		if (frame >= MAX_CALL_FRAMES) {
3094 			verbose(env, "the call stack of %d frames is too deep !\n",
3095 				frame);
3096 			return -E2BIG;
3097 		}
3098 		goto process_func;
3099 	}
3100 	/* if tail call got detected across bpf2bpf calls then mark each of the
3101 	 * currently present subprog frames as tail call reachable subprogs;
3102 	 * this info will be utilized by JIT so that we will be preserving the
3103 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3104 	 */
3105 	if (tail_call_reachable)
3106 		for (j = 0; j < frame; j++)
3107 			subprog[ret_prog[j]].tail_call_reachable = true;
3108 
3109 	/* end of for() loop means the last insn of the 'subprog'
3110 	 * was reached. Doesn't matter whether it was JA or EXIT
3111 	 */
3112 	if (frame == 0)
3113 		return 0;
3114 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3115 	frame--;
3116 	i = ret_insn[frame];
3117 	idx = ret_prog[frame];
3118 	goto continue_func;
3119 }
3120 
3121 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3122 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3123 				  const struct bpf_insn *insn, int idx)
3124 {
3125 	int start = idx + insn->imm + 1, subprog;
3126 
3127 	subprog = find_subprog(env, start);
3128 	if (subprog < 0) {
3129 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3130 			  start);
3131 		return -EFAULT;
3132 	}
3133 	return env->subprog_info[subprog].stack_depth;
3134 }
3135 #endif
3136 
3137 int check_ctx_reg(struct bpf_verifier_env *env,
3138 		  const struct bpf_reg_state *reg, int regno)
3139 {
3140 	/* Access to ctx or passing it to a helper is only allowed in
3141 	 * its original, unmodified form.
3142 	 */
3143 
3144 	if (reg->off) {
3145 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3146 			regno, reg->off);
3147 		return -EACCES;
3148 	}
3149 
3150 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3151 		char tn_buf[48];
3152 
3153 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3154 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3155 		return -EACCES;
3156 	}
3157 
3158 	return 0;
3159 }
3160 
3161 static int __check_buffer_access(struct bpf_verifier_env *env,
3162 				 const char *buf_info,
3163 				 const struct bpf_reg_state *reg,
3164 				 int regno, int off, int size)
3165 {
3166 	if (off < 0) {
3167 		verbose(env,
3168 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3169 			regno, buf_info, off, size);
3170 		return -EACCES;
3171 	}
3172 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3173 		char tn_buf[48];
3174 
3175 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3176 		verbose(env,
3177 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3178 			regno, off, tn_buf);
3179 		return -EACCES;
3180 	}
3181 
3182 	return 0;
3183 }
3184 
3185 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3186 				  const struct bpf_reg_state *reg,
3187 				  int regno, int off, int size)
3188 {
3189 	int err;
3190 
3191 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3192 	if (err)
3193 		return err;
3194 
3195 	if (off + size > env->prog->aux->max_tp_access)
3196 		env->prog->aux->max_tp_access = off + size;
3197 
3198 	return 0;
3199 }
3200 
3201 static int check_buffer_access(struct bpf_verifier_env *env,
3202 			       const struct bpf_reg_state *reg,
3203 			       int regno, int off, int size,
3204 			       bool zero_size_allowed,
3205 			       const char *buf_info,
3206 			       u32 *max_access)
3207 {
3208 	int err;
3209 
3210 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3211 	if (err)
3212 		return err;
3213 
3214 	if (off + size > *max_access)
3215 		*max_access = off + size;
3216 
3217 	return 0;
3218 }
3219 
3220 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3221 static void zext_32_to_64(struct bpf_reg_state *reg)
3222 {
3223 	reg->var_off = tnum_subreg(reg->var_off);
3224 	__reg_assign_32_into_64(reg);
3225 }
3226 
3227 /* truncate register to smaller size (in bytes)
3228  * must be called with size < BPF_REG_SIZE
3229  */
3230 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3231 {
3232 	u64 mask;
3233 
3234 	/* clear high bits in bit representation */
3235 	reg->var_off = tnum_cast(reg->var_off, size);
3236 
3237 	/* fix arithmetic bounds */
3238 	mask = ((u64)1 << (size * 8)) - 1;
3239 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3240 		reg->umin_value &= mask;
3241 		reg->umax_value &= mask;
3242 	} else {
3243 		reg->umin_value = 0;
3244 		reg->umax_value = mask;
3245 	}
3246 	reg->smin_value = reg->umin_value;
3247 	reg->smax_value = reg->umax_value;
3248 
3249 	/* If size is smaller than 32bit register the 32bit register
3250 	 * values are also truncated so we push 64-bit bounds into
3251 	 * 32-bit bounds. Above were truncated < 32-bits already.
3252 	 */
3253 	if (size >= 4)
3254 		return;
3255 	__reg_combine_64_into_32(reg);
3256 }
3257 
3258 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3259 {
3260 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3261 }
3262 
3263 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3264 {
3265 	void *ptr;
3266 	u64 addr;
3267 	int err;
3268 
3269 	err = map->ops->map_direct_value_addr(map, &addr, off);
3270 	if (err)
3271 		return err;
3272 	ptr = (void *)(long)addr + off;
3273 
3274 	switch (size) {
3275 	case sizeof(u8):
3276 		*val = (u64)*(u8 *)ptr;
3277 		break;
3278 	case sizeof(u16):
3279 		*val = (u64)*(u16 *)ptr;
3280 		break;
3281 	case sizeof(u32):
3282 		*val = (u64)*(u32 *)ptr;
3283 		break;
3284 	case sizeof(u64):
3285 		*val = *(u64 *)ptr;
3286 		break;
3287 	default:
3288 		return -EINVAL;
3289 	}
3290 	return 0;
3291 }
3292 
3293 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3294 				   struct bpf_reg_state *regs,
3295 				   int regno, int off, int size,
3296 				   enum bpf_access_type atype,
3297 				   int value_regno)
3298 {
3299 	struct bpf_reg_state *reg = regs + regno;
3300 	const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3301 	const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3302 	u32 btf_id;
3303 	int ret;
3304 
3305 	if (off < 0) {
3306 		verbose(env,
3307 			"R%d is ptr_%s invalid negative access: off=%d\n",
3308 			regno, tname, off);
3309 		return -EACCES;
3310 	}
3311 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3312 		char tn_buf[48];
3313 
3314 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3315 		verbose(env,
3316 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3317 			regno, tname, off, tn_buf);
3318 		return -EACCES;
3319 	}
3320 
3321 	if (env->ops->btf_struct_access) {
3322 		ret = env->ops->btf_struct_access(&env->log, t, off, size,
3323 						  atype, &btf_id);
3324 	} else {
3325 		if (atype != BPF_READ) {
3326 			verbose(env, "only read is supported\n");
3327 			return -EACCES;
3328 		}
3329 
3330 		ret = btf_struct_access(&env->log, t, off, size, atype,
3331 					&btf_id);
3332 	}
3333 
3334 	if (ret < 0)
3335 		return ret;
3336 
3337 	if (atype == BPF_READ && value_regno >= 0)
3338 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3339 
3340 	return 0;
3341 }
3342 
3343 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3344 				   struct bpf_reg_state *regs,
3345 				   int regno, int off, int size,
3346 				   enum bpf_access_type atype,
3347 				   int value_regno)
3348 {
3349 	struct bpf_reg_state *reg = regs + regno;
3350 	struct bpf_map *map = reg->map_ptr;
3351 	const struct btf_type *t;
3352 	const char *tname;
3353 	u32 btf_id;
3354 	int ret;
3355 
3356 	if (!btf_vmlinux) {
3357 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3358 		return -ENOTSUPP;
3359 	}
3360 
3361 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3362 		verbose(env, "map_ptr access not supported for map type %d\n",
3363 			map->map_type);
3364 		return -ENOTSUPP;
3365 	}
3366 
3367 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3368 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3369 
3370 	if (!env->allow_ptr_to_map_access) {
3371 		verbose(env,
3372 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3373 			tname);
3374 		return -EPERM;
3375 	}
3376 
3377 	if (off < 0) {
3378 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3379 			regno, tname, off);
3380 		return -EACCES;
3381 	}
3382 
3383 	if (atype != BPF_READ) {
3384 		verbose(env, "only read from %s is supported\n", tname);
3385 		return -EACCES;
3386 	}
3387 
3388 	ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3389 	if (ret < 0)
3390 		return ret;
3391 
3392 	if (value_regno >= 0)
3393 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3394 
3395 	return 0;
3396 }
3397 
3398 
3399 /* check whether memory at (regno + off) is accessible for t = (read | write)
3400  * if t==write, value_regno is a register which value is stored into memory
3401  * if t==read, value_regno is a register which will receive the value from memory
3402  * if t==write && value_regno==-1, some unknown value is stored into memory
3403  * if t==read && value_regno==-1, don't care what we read from memory
3404  */
3405 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3406 			    int off, int bpf_size, enum bpf_access_type t,
3407 			    int value_regno, bool strict_alignment_once)
3408 {
3409 	struct bpf_reg_state *regs = cur_regs(env);
3410 	struct bpf_reg_state *reg = regs + regno;
3411 	struct bpf_func_state *state;
3412 	int size, err = 0;
3413 
3414 	size = bpf_size_to_bytes(bpf_size);
3415 	if (size < 0)
3416 		return size;
3417 
3418 	/* alignment checks will add in reg->off themselves */
3419 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3420 	if (err)
3421 		return err;
3422 
3423 	/* for access checks, reg->off is just part of off */
3424 	off += reg->off;
3425 
3426 	if (reg->type == PTR_TO_MAP_VALUE) {
3427 		if (t == BPF_WRITE && value_regno >= 0 &&
3428 		    is_pointer_value(env, value_regno)) {
3429 			verbose(env, "R%d leaks addr into map\n", value_regno);
3430 			return -EACCES;
3431 		}
3432 		err = check_map_access_type(env, regno, off, size, t);
3433 		if (err)
3434 			return err;
3435 		err = check_map_access(env, regno, off, size, false);
3436 		if (!err && t == BPF_READ && value_regno >= 0) {
3437 			struct bpf_map *map = reg->map_ptr;
3438 
3439 			/* if map is read-only, track its contents as scalars */
3440 			if (tnum_is_const(reg->var_off) &&
3441 			    bpf_map_is_rdonly(map) &&
3442 			    map->ops->map_direct_value_addr) {
3443 				int map_off = off + reg->var_off.value;
3444 				u64 val = 0;
3445 
3446 				err = bpf_map_direct_read(map, map_off, size,
3447 							  &val);
3448 				if (err)
3449 					return err;
3450 
3451 				regs[value_regno].type = SCALAR_VALUE;
3452 				__mark_reg_known(&regs[value_regno], val);
3453 			} else {
3454 				mark_reg_unknown(env, regs, value_regno);
3455 			}
3456 		}
3457 	} else if (reg->type == PTR_TO_MEM) {
3458 		if (t == BPF_WRITE && value_regno >= 0 &&
3459 		    is_pointer_value(env, value_regno)) {
3460 			verbose(env, "R%d leaks addr into mem\n", value_regno);
3461 			return -EACCES;
3462 		}
3463 		err = check_mem_region_access(env, regno, off, size,
3464 					      reg->mem_size, false);
3465 		if (!err && t == BPF_READ && value_regno >= 0)
3466 			mark_reg_unknown(env, regs, value_regno);
3467 	} else if (reg->type == PTR_TO_CTX) {
3468 		enum bpf_reg_type reg_type = SCALAR_VALUE;
3469 		u32 btf_id = 0;
3470 
3471 		if (t == BPF_WRITE && value_regno >= 0 &&
3472 		    is_pointer_value(env, value_regno)) {
3473 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
3474 			return -EACCES;
3475 		}
3476 
3477 		err = check_ctx_reg(env, reg, regno);
3478 		if (err < 0)
3479 			return err;
3480 
3481 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3482 		if (err)
3483 			verbose_linfo(env, insn_idx, "; ");
3484 		if (!err && t == BPF_READ && value_regno >= 0) {
3485 			/* ctx access returns either a scalar, or a
3486 			 * PTR_TO_PACKET[_META,_END]. In the latter
3487 			 * case, we know the offset is zero.
3488 			 */
3489 			if (reg_type == SCALAR_VALUE) {
3490 				mark_reg_unknown(env, regs, value_regno);
3491 			} else {
3492 				mark_reg_known_zero(env, regs,
3493 						    value_regno);
3494 				if (reg_type_may_be_null(reg_type))
3495 					regs[value_regno].id = ++env->id_gen;
3496 				/* A load of ctx field could have different
3497 				 * actual load size with the one encoded in the
3498 				 * insn. When the dst is PTR, it is for sure not
3499 				 * a sub-register.
3500 				 */
3501 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3502 				if (reg_type == PTR_TO_BTF_ID ||
3503 				    reg_type == PTR_TO_BTF_ID_OR_NULL)
3504 					regs[value_regno].btf_id = btf_id;
3505 			}
3506 			regs[value_regno].type = reg_type;
3507 		}
3508 
3509 	} else if (reg->type == PTR_TO_STACK) {
3510 		off += reg->var_off.value;
3511 		err = check_stack_access(env, reg, off, size);
3512 		if (err)
3513 			return err;
3514 
3515 		state = func(env, reg);
3516 		err = update_stack_depth(env, state, off);
3517 		if (err)
3518 			return err;
3519 
3520 		if (t == BPF_WRITE)
3521 			err = check_stack_write(env, state, off, size,
3522 						value_regno, insn_idx);
3523 		else
3524 			err = check_stack_read(env, state, off, size,
3525 					       value_regno);
3526 	} else if (reg_is_pkt_pointer(reg)) {
3527 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3528 			verbose(env, "cannot write into packet\n");
3529 			return -EACCES;
3530 		}
3531 		if (t == BPF_WRITE && value_regno >= 0 &&
3532 		    is_pointer_value(env, value_regno)) {
3533 			verbose(env, "R%d leaks addr into packet\n",
3534 				value_regno);
3535 			return -EACCES;
3536 		}
3537 		err = check_packet_access(env, regno, off, size, false);
3538 		if (!err && t == BPF_READ && value_regno >= 0)
3539 			mark_reg_unknown(env, regs, value_regno);
3540 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
3541 		if (t == BPF_WRITE && value_regno >= 0 &&
3542 		    is_pointer_value(env, value_regno)) {
3543 			verbose(env, "R%d leaks addr into flow keys\n",
3544 				value_regno);
3545 			return -EACCES;
3546 		}
3547 
3548 		err = check_flow_keys_access(env, off, size);
3549 		if (!err && t == BPF_READ && value_regno >= 0)
3550 			mark_reg_unknown(env, regs, value_regno);
3551 	} else if (type_is_sk_pointer(reg->type)) {
3552 		if (t == BPF_WRITE) {
3553 			verbose(env, "R%d cannot write into %s\n",
3554 				regno, reg_type_str[reg->type]);
3555 			return -EACCES;
3556 		}
3557 		err = check_sock_access(env, insn_idx, regno, off, size, t);
3558 		if (!err && value_regno >= 0)
3559 			mark_reg_unknown(env, regs, value_regno);
3560 	} else if (reg->type == PTR_TO_TP_BUFFER) {
3561 		err = check_tp_buffer_access(env, reg, regno, off, size);
3562 		if (!err && t == BPF_READ && value_regno >= 0)
3563 			mark_reg_unknown(env, regs, value_regno);
3564 	} else if (reg->type == PTR_TO_BTF_ID) {
3565 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3566 					      value_regno);
3567 	} else if (reg->type == CONST_PTR_TO_MAP) {
3568 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3569 					      value_regno);
3570 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
3571 		if (t == BPF_WRITE) {
3572 			verbose(env, "R%d cannot write into %s\n",
3573 				regno, reg_type_str[reg->type]);
3574 			return -EACCES;
3575 		}
3576 		err = check_buffer_access(env, reg, regno, off, size, false,
3577 					  "rdonly",
3578 					  &env->prog->aux->max_rdonly_access);
3579 		if (!err && value_regno >= 0)
3580 			mark_reg_unknown(env, regs, value_regno);
3581 	} else if (reg->type == PTR_TO_RDWR_BUF) {
3582 		err = check_buffer_access(env, reg, regno, off, size, false,
3583 					  "rdwr",
3584 					  &env->prog->aux->max_rdwr_access);
3585 		if (!err && t == BPF_READ && value_regno >= 0)
3586 			mark_reg_unknown(env, regs, value_regno);
3587 	} else {
3588 		verbose(env, "R%d invalid mem access '%s'\n", regno,
3589 			reg_type_str[reg->type]);
3590 		return -EACCES;
3591 	}
3592 
3593 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3594 	    regs[value_regno].type == SCALAR_VALUE) {
3595 		/* b/h/w load zero-extends, mark upper bits as known 0 */
3596 		coerce_reg_to_size(&regs[value_regno], size);
3597 	}
3598 	return err;
3599 }
3600 
3601 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3602 {
3603 	int err;
3604 
3605 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3606 	    insn->imm != 0) {
3607 		verbose(env, "BPF_XADD uses reserved fields\n");
3608 		return -EINVAL;
3609 	}
3610 
3611 	/* check src1 operand */
3612 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
3613 	if (err)
3614 		return err;
3615 
3616 	/* check src2 operand */
3617 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3618 	if (err)
3619 		return err;
3620 
3621 	if (is_pointer_value(env, insn->src_reg)) {
3622 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3623 		return -EACCES;
3624 	}
3625 
3626 	if (is_ctx_reg(env, insn->dst_reg) ||
3627 	    is_pkt_reg(env, insn->dst_reg) ||
3628 	    is_flow_key_reg(env, insn->dst_reg) ||
3629 	    is_sk_reg(env, insn->dst_reg)) {
3630 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3631 			insn->dst_reg,
3632 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
3633 		return -EACCES;
3634 	}
3635 
3636 	/* check whether atomic_add can read the memory */
3637 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3638 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
3639 	if (err)
3640 		return err;
3641 
3642 	/* check whether atomic_add can write into the same memory */
3643 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3644 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3645 }
3646 
3647 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3648 				  int off, int access_size,
3649 				  bool zero_size_allowed)
3650 {
3651 	struct bpf_reg_state *reg = reg_state(env, regno);
3652 
3653 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3654 	    access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3655 		if (tnum_is_const(reg->var_off)) {
3656 			verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3657 				regno, off, access_size);
3658 		} else {
3659 			char tn_buf[48];
3660 
3661 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3662 			verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3663 				regno, tn_buf, access_size);
3664 		}
3665 		return -EACCES;
3666 	}
3667 	return 0;
3668 }
3669 
3670 /* when register 'regno' is passed into function that will read 'access_size'
3671  * bytes from that pointer, make sure that it's within stack boundary
3672  * and all elements of stack are initialized.
3673  * Unlike most pointer bounds-checking functions, this one doesn't take an
3674  * 'off' argument, so it has to add in reg->off itself.
3675  */
3676 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3677 				int access_size, bool zero_size_allowed,
3678 				struct bpf_call_arg_meta *meta)
3679 {
3680 	struct bpf_reg_state *reg = reg_state(env, regno);
3681 	struct bpf_func_state *state = func(env, reg);
3682 	int err, min_off, max_off, i, j, slot, spi;
3683 
3684 	if (tnum_is_const(reg->var_off)) {
3685 		min_off = max_off = reg->var_off.value + reg->off;
3686 		err = __check_stack_boundary(env, regno, min_off, access_size,
3687 					     zero_size_allowed);
3688 		if (err)
3689 			return err;
3690 	} else {
3691 		/* Variable offset is prohibited for unprivileged mode for
3692 		 * simplicity since it requires corresponding support in
3693 		 * Spectre masking for stack ALU.
3694 		 * See also retrieve_ptr_limit().
3695 		 */
3696 		if (!env->bypass_spec_v1) {
3697 			char tn_buf[48];
3698 
3699 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3700 			verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3701 				regno, tn_buf);
3702 			return -EACCES;
3703 		}
3704 		/* Only initialized buffer on stack is allowed to be accessed
3705 		 * with variable offset. With uninitialized buffer it's hard to
3706 		 * guarantee that whole memory is marked as initialized on
3707 		 * helper return since specific bounds are unknown what may
3708 		 * cause uninitialized stack leaking.
3709 		 */
3710 		if (meta && meta->raw_mode)
3711 			meta = NULL;
3712 
3713 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3714 		    reg->smax_value <= -BPF_MAX_VAR_OFF) {
3715 			verbose(env, "R%d unbounded indirect variable offset stack access\n",
3716 				regno);
3717 			return -EACCES;
3718 		}
3719 		min_off = reg->smin_value + reg->off;
3720 		max_off = reg->smax_value + reg->off;
3721 		err = __check_stack_boundary(env, regno, min_off, access_size,
3722 					     zero_size_allowed);
3723 		if (err) {
3724 			verbose(env, "R%d min value is outside of stack bound\n",
3725 				regno);
3726 			return err;
3727 		}
3728 		err = __check_stack_boundary(env, regno, max_off, access_size,
3729 					     zero_size_allowed);
3730 		if (err) {
3731 			verbose(env, "R%d max value is outside of stack bound\n",
3732 				regno);
3733 			return err;
3734 		}
3735 	}
3736 
3737 	if (meta && meta->raw_mode) {
3738 		meta->access_size = access_size;
3739 		meta->regno = regno;
3740 		return 0;
3741 	}
3742 
3743 	for (i = min_off; i < max_off + access_size; i++) {
3744 		u8 *stype;
3745 
3746 		slot = -i - 1;
3747 		spi = slot / BPF_REG_SIZE;
3748 		if (state->allocated_stack <= slot)
3749 			goto err;
3750 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3751 		if (*stype == STACK_MISC)
3752 			goto mark;
3753 		if (*stype == STACK_ZERO) {
3754 			/* helper can write anything into the stack */
3755 			*stype = STACK_MISC;
3756 			goto mark;
3757 		}
3758 
3759 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3760 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3761 			goto mark;
3762 
3763 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3764 		    state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3765 			__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
3766 			for (j = 0; j < BPF_REG_SIZE; j++)
3767 				state->stack[spi].slot_type[j] = STACK_MISC;
3768 			goto mark;
3769 		}
3770 
3771 err:
3772 		if (tnum_is_const(reg->var_off)) {
3773 			verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3774 				min_off, i - min_off, access_size);
3775 		} else {
3776 			char tn_buf[48];
3777 
3778 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3779 			verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3780 				tn_buf, i - min_off, access_size);
3781 		}
3782 		return -EACCES;
3783 mark:
3784 		/* reading any byte out of 8-byte 'spill_slot' will cause
3785 		 * the whole slot to be marked as 'read'
3786 		 */
3787 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
3788 			      state->stack[spi].spilled_ptr.parent,
3789 			      REG_LIVE_READ64);
3790 	}
3791 	return update_stack_depth(env, state, min_off);
3792 }
3793 
3794 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3795 				   int access_size, bool zero_size_allowed,
3796 				   struct bpf_call_arg_meta *meta)
3797 {
3798 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3799 
3800 	switch (reg->type) {
3801 	case PTR_TO_PACKET:
3802 	case PTR_TO_PACKET_META:
3803 		return check_packet_access(env, regno, reg->off, access_size,
3804 					   zero_size_allowed);
3805 	case PTR_TO_MAP_VALUE:
3806 		if (check_map_access_type(env, regno, reg->off, access_size,
3807 					  meta && meta->raw_mode ? BPF_WRITE :
3808 					  BPF_READ))
3809 			return -EACCES;
3810 		return check_map_access(env, regno, reg->off, access_size,
3811 					zero_size_allowed);
3812 	case PTR_TO_MEM:
3813 		return check_mem_region_access(env, regno, reg->off,
3814 					       access_size, reg->mem_size,
3815 					       zero_size_allowed);
3816 	case PTR_TO_RDONLY_BUF:
3817 		if (meta && meta->raw_mode)
3818 			return -EACCES;
3819 		return check_buffer_access(env, reg, regno, reg->off,
3820 					   access_size, zero_size_allowed,
3821 					   "rdonly",
3822 					   &env->prog->aux->max_rdonly_access);
3823 	case PTR_TO_RDWR_BUF:
3824 		return check_buffer_access(env, reg, regno, reg->off,
3825 					   access_size, zero_size_allowed,
3826 					   "rdwr",
3827 					   &env->prog->aux->max_rdwr_access);
3828 	case PTR_TO_STACK:
3829 		return check_stack_boundary(env, regno, access_size,
3830 					    zero_size_allowed, meta);
3831 	default: /* scalar_value or invalid ptr */
3832 		/* Allow zero-byte read from NULL, regardless of pointer type */
3833 		if (zero_size_allowed && access_size == 0 &&
3834 		    register_is_null(reg))
3835 			return 0;
3836 
3837 		verbose(env, "R%d type=%s expected=%s\n", regno,
3838 			reg_type_str[reg->type],
3839 			reg_type_str[PTR_TO_STACK]);
3840 		return -EACCES;
3841 	}
3842 }
3843 
3844 /* Implementation details:
3845  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3846  * Two bpf_map_lookups (even with the same key) will have different reg->id.
3847  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3848  * value_or_null->value transition, since the verifier only cares about
3849  * the range of access to valid map value pointer and doesn't care about actual
3850  * address of the map element.
3851  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3852  * reg->id > 0 after value_or_null->value transition. By doing so
3853  * two bpf_map_lookups will be considered two different pointers that
3854  * point to different bpf_spin_locks.
3855  * The verifier allows taking only one bpf_spin_lock at a time to avoid
3856  * dead-locks.
3857  * Since only one bpf_spin_lock is allowed the checks are simpler than
3858  * reg_is_refcounted() logic. The verifier needs to remember only
3859  * one spin_lock instead of array of acquired_refs.
3860  * cur_state->active_spin_lock remembers which map value element got locked
3861  * and clears it after bpf_spin_unlock.
3862  */
3863 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3864 			     bool is_lock)
3865 {
3866 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3867 	struct bpf_verifier_state *cur = env->cur_state;
3868 	bool is_const = tnum_is_const(reg->var_off);
3869 	struct bpf_map *map = reg->map_ptr;
3870 	u64 val = reg->var_off.value;
3871 
3872 	if (!is_const) {
3873 		verbose(env,
3874 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3875 			regno);
3876 		return -EINVAL;
3877 	}
3878 	if (!map->btf) {
3879 		verbose(env,
3880 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
3881 			map->name);
3882 		return -EINVAL;
3883 	}
3884 	if (!map_value_has_spin_lock(map)) {
3885 		if (map->spin_lock_off == -E2BIG)
3886 			verbose(env,
3887 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
3888 				map->name);
3889 		else if (map->spin_lock_off == -ENOENT)
3890 			verbose(env,
3891 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
3892 				map->name);
3893 		else
3894 			verbose(env,
3895 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3896 				map->name);
3897 		return -EINVAL;
3898 	}
3899 	if (map->spin_lock_off != val + reg->off) {
3900 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3901 			val + reg->off);
3902 		return -EINVAL;
3903 	}
3904 	if (is_lock) {
3905 		if (cur->active_spin_lock) {
3906 			verbose(env,
3907 				"Locking two bpf_spin_locks are not allowed\n");
3908 			return -EINVAL;
3909 		}
3910 		cur->active_spin_lock = reg->id;
3911 	} else {
3912 		if (!cur->active_spin_lock) {
3913 			verbose(env, "bpf_spin_unlock without taking a lock\n");
3914 			return -EINVAL;
3915 		}
3916 		if (cur->active_spin_lock != reg->id) {
3917 			verbose(env, "bpf_spin_unlock of different lock\n");
3918 			return -EINVAL;
3919 		}
3920 		cur->active_spin_lock = 0;
3921 	}
3922 	return 0;
3923 }
3924 
3925 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3926 {
3927 	return type == ARG_PTR_TO_MEM ||
3928 	       type == ARG_PTR_TO_MEM_OR_NULL ||
3929 	       type == ARG_PTR_TO_UNINIT_MEM;
3930 }
3931 
3932 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3933 {
3934 	return type == ARG_CONST_SIZE ||
3935 	       type == ARG_CONST_SIZE_OR_ZERO;
3936 }
3937 
3938 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3939 {
3940 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3941 }
3942 
3943 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3944 {
3945 	return type == ARG_PTR_TO_INT ||
3946 	       type == ARG_PTR_TO_LONG;
3947 }
3948 
3949 static int int_ptr_type_to_size(enum bpf_arg_type type)
3950 {
3951 	if (type == ARG_PTR_TO_INT)
3952 		return sizeof(u32);
3953 	else if (type == ARG_PTR_TO_LONG)
3954 		return sizeof(u64);
3955 
3956 	return -EINVAL;
3957 }
3958 
3959 static int resolve_map_arg_type(struct bpf_verifier_env *env,
3960 				 const struct bpf_call_arg_meta *meta,
3961 				 enum bpf_arg_type *arg_type)
3962 {
3963 	if (!meta->map_ptr) {
3964 		/* kernel subsystem misconfigured verifier */
3965 		verbose(env, "invalid map_ptr to access map->type\n");
3966 		return -EACCES;
3967 	}
3968 
3969 	switch (meta->map_ptr->map_type) {
3970 	case BPF_MAP_TYPE_SOCKMAP:
3971 	case BPF_MAP_TYPE_SOCKHASH:
3972 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
3973 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
3974 		} else {
3975 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
3976 			return -EINVAL;
3977 		}
3978 		break;
3979 
3980 	default:
3981 		break;
3982 	}
3983 	return 0;
3984 }
3985 
3986 struct bpf_reg_types {
3987 	const enum bpf_reg_type types[10];
3988 	u32 *btf_id;
3989 };
3990 
3991 static const struct bpf_reg_types map_key_value_types = {
3992 	.types = {
3993 		PTR_TO_STACK,
3994 		PTR_TO_PACKET,
3995 		PTR_TO_PACKET_META,
3996 		PTR_TO_MAP_VALUE,
3997 	},
3998 };
3999 
4000 static const struct bpf_reg_types sock_types = {
4001 	.types = {
4002 		PTR_TO_SOCK_COMMON,
4003 		PTR_TO_SOCKET,
4004 		PTR_TO_TCP_SOCK,
4005 		PTR_TO_XDP_SOCK,
4006 	},
4007 };
4008 
4009 #ifdef CONFIG_NET
4010 static const struct bpf_reg_types btf_id_sock_common_types = {
4011 	.types = {
4012 		PTR_TO_SOCK_COMMON,
4013 		PTR_TO_SOCKET,
4014 		PTR_TO_TCP_SOCK,
4015 		PTR_TO_XDP_SOCK,
4016 		PTR_TO_BTF_ID,
4017 	},
4018 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4019 };
4020 #endif
4021 
4022 static const struct bpf_reg_types mem_types = {
4023 	.types = {
4024 		PTR_TO_STACK,
4025 		PTR_TO_PACKET,
4026 		PTR_TO_PACKET_META,
4027 		PTR_TO_MAP_VALUE,
4028 		PTR_TO_MEM,
4029 		PTR_TO_RDONLY_BUF,
4030 		PTR_TO_RDWR_BUF,
4031 	},
4032 };
4033 
4034 static const struct bpf_reg_types int_ptr_types = {
4035 	.types = {
4036 		PTR_TO_STACK,
4037 		PTR_TO_PACKET,
4038 		PTR_TO_PACKET_META,
4039 		PTR_TO_MAP_VALUE,
4040 	},
4041 };
4042 
4043 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4044 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4045 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4046 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4047 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4048 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4049 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4050 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4051 
4052 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4053 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4054 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4055 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4056 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
4057 	[ARG_CONST_SIZE]		= &scalar_types,
4058 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4059 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4060 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4061 	[ARG_PTR_TO_CTX]		= &context_types,
4062 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
4063 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4064 #ifdef CONFIG_NET
4065 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4066 #endif
4067 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4068 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
4069 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4070 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4071 	[ARG_PTR_TO_MEM]		= &mem_types,
4072 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
4073 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4074 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4075 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
4076 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4077 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4078 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4079 };
4080 
4081 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4082 			  enum bpf_arg_type arg_type,
4083 			  const u32 *arg_btf_id)
4084 {
4085 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4086 	enum bpf_reg_type expected, type = reg->type;
4087 	const struct bpf_reg_types *compatible;
4088 	int i, j;
4089 
4090 	compatible = compatible_reg_types[arg_type];
4091 	if (!compatible) {
4092 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4093 		return -EFAULT;
4094 	}
4095 
4096 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4097 		expected = compatible->types[i];
4098 		if (expected == NOT_INIT)
4099 			break;
4100 
4101 		if (type == expected)
4102 			goto found;
4103 	}
4104 
4105 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4106 	for (j = 0; j + 1 < i; j++)
4107 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4108 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4109 	return -EACCES;
4110 
4111 found:
4112 	if (type == PTR_TO_BTF_ID) {
4113 		if (!arg_btf_id) {
4114 			if (!compatible->btf_id) {
4115 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4116 				return -EFAULT;
4117 			}
4118 			arg_btf_id = compatible->btf_id;
4119 		}
4120 
4121 		if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4122 					  *arg_btf_id)) {
4123 			verbose(env, "R%d is of type %s but %s is expected\n",
4124 				regno, kernel_type_name(reg->btf_id),
4125 				kernel_type_name(*arg_btf_id));
4126 			return -EACCES;
4127 		}
4128 
4129 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4130 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4131 				regno);
4132 			return -EACCES;
4133 		}
4134 	}
4135 
4136 	return 0;
4137 }
4138 
4139 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4140 			  struct bpf_call_arg_meta *meta,
4141 			  const struct bpf_func_proto *fn)
4142 {
4143 	u32 regno = BPF_REG_1 + arg;
4144 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4145 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4146 	enum bpf_reg_type type = reg->type;
4147 	int err = 0;
4148 
4149 	if (arg_type == ARG_DONTCARE)
4150 		return 0;
4151 
4152 	err = check_reg_arg(env, regno, SRC_OP);
4153 	if (err)
4154 		return err;
4155 
4156 	if (arg_type == ARG_ANYTHING) {
4157 		if (is_pointer_value(env, regno)) {
4158 			verbose(env, "R%d leaks addr into helper function\n",
4159 				regno);
4160 			return -EACCES;
4161 		}
4162 		return 0;
4163 	}
4164 
4165 	if (type_is_pkt_pointer(type) &&
4166 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4167 		verbose(env, "helper access to the packet is not allowed\n");
4168 		return -EACCES;
4169 	}
4170 
4171 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4172 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4173 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4174 		err = resolve_map_arg_type(env, meta, &arg_type);
4175 		if (err)
4176 			return err;
4177 	}
4178 
4179 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4180 		/* A NULL register has a SCALAR_VALUE type, so skip
4181 		 * type checking.
4182 		 */
4183 		goto skip_type_check;
4184 
4185 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4186 	if (err)
4187 		return err;
4188 
4189 	if (type == PTR_TO_CTX) {
4190 		err = check_ctx_reg(env, reg, regno);
4191 		if (err < 0)
4192 			return err;
4193 	}
4194 
4195 skip_type_check:
4196 	if (reg->ref_obj_id) {
4197 		if (meta->ref_obj_id) {
4198 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4199 				regno, reg->ref_obj_id,
4200 				meta->ref_obj_id);
4201 			return -EFAULT;
4202 		}
4203 		meta->ref_obj_id = reg->ref_obj_id;
4204 	}
4205 
4206 	if (arg_type == ARG_CONST_MAP_PTR) {
4207 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4208 		meta->map_ptr = reg->map_ptr;
4209 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4210 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4211 		 * check that [key, key + map->key_size) are within
4212 		 * stack limits and initialized
4213 		 */
4214 		if (!meta->map_ptr) {
4215 			/* in function declaration map_ptr must come before
4216 			 * map_key, so that it's verified and known before
4217 			 * we have to check map_key here. Otherwise it means
4218 			 * that kernel subsystem misconfigured verifier
4219 			 */
4220 			verbose(env, "invalid map_ptr to access map->key\n");
4221 			return -EACCES;
4222 		}
4223 		err = check_helper_mem_access(env, regno,
4224 					      meta->map_ptr->key_size, false,
4225 					      NULL);
4226 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4227 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4228 		    !register_is_null(reg)) ||
4229 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4230 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4231 		 * check [value, value + map->value_size) validity
4232 		 */
4233 		if (!meta->map_ptr) {
4234 			/* kernel subsystem misconfigured verifier */
4235 			verbose(env, "invalid map_ptr to access map->value\n");
4236 			return -EACCES;
4237 		}
4238 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4239 		err = check_helper_mem_access(env, regno,
4240 					      meta->map_ptr->value_size, false,
4241 					      meta);
4242 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4243 		if (!reg->btf_id) {
4244 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4245 			return -EACCES;
4246 		}
4247 		meta->ret_btf_id = reg->btf_id;
4248 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4249 		if (meta->func_id == BPF_FUNC_spin_lock) {
4250 			if (process_spin_lock(env, regno, true))
4251 				return -EACCES;
4252 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4253 			if (process_spin_lock(env, regno, false))
4254 				return -EACCES;
4255 		} else {
4256 			verbose(env, "verifier internal error\n");
4257 			return -EFAULT;
4258 		}
4259 	} else if (arg_type_is_mem_ptr(arg_type)) {
4260 		/* The access to this pointer is only checked when we hit the
4261 		 * next is_mem_size argument below.
4262 		 */
4263 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4264 	} else if (arg_type_is_mem_size(arg_type)) {
4265 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4266 
4267 		/* This is used to refine r0 return value bounds for helpers
4268 		 * that enforce this value as an upper bound on return values.
4269 		 * See do_refine_retval_range() for helpers that can refine
4270 		 * the return value. C type of helper is u32 so we pull register
4271 		 * bound from umax_value however, if negative verifier errors
4272 		 * out. Only upper bounds can be learned because retval is an
4273 		 * int type and negative retvals are allowed.
4274 		 */
4275 		meta->msize_max_value = reg->umax_value;
4276 
4277 		/* The register is SCALAR_VALUE; the access check
4278 		 * happens using its boundaries.
4279 		 */
4280 		if (!tnum_is_const(reg->var_off))
4281 			/* For unprivileged variable accesses, disable raw
4282 			 * mode so that the program is required to
4283 			 * initialize all the memory that the helper could
4284 			 * just partially fill up.
4285 			 */
4286 			meta = NULL;
4287 
4288 		if (reg->smin_value < 0) {
4289 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4290 				regno);
4291 			return -EACCES;
4292 		}
4293 
4294 		if (reg->umin_value == 0) {
4295 			err = check_helper_mem_access(env, regno - 1, 0,
4296 						      zero_size_allowed,
4297 						      meta);
4298 			if (err)
4299 				return err;
4300 		}
4301 
4302 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4303 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4304 				regno);
4305 			return -EACCES;
4306 		}
4307 		err = check_helper_mem_access(env, regno - 1,
4308 					      reg->umax_value,
4309 					      zero_size_allowed, meta);
4310 		if (!err)
4311 			err = mark_chain_precision(env, regno);
4312 	} else if (arg_type_is_alloc_size(arg_type)) {
4313 		if (!tnum_is_const(reg->var_off)) {
4314 			verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4315 				regno);
4316 			return -EACCES;
4317 		}
4318 		meta->mem_size = reg->var_off.value;
4319 	} else if (arg_type_is_int_ptr(arg_type)) {
4320 		int size = int_ptr_type_to_size(arg_type);
4321 
4322 		err = check_helper_mem_access(env, regno, size, false, meta);
4323 		if (err)
4324 			return err;
4325 		err = check_ptr_alignment(env, reg, 0, size, true);
4326 	}
4327 
4328 	return err;
4329 }
4330 
4331 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4332 {
4333 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4334 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4335 
4336 	if (func_id != BPF_FUNC_map_update_elem)
4337 		return false;
4338 
4339 	/* It's not possible to get access to a locked struct sock in these
4340 	 * contexts, so updating is safe.
4341 	 */
4342 	switch (type) {
4343 	case BPF_PROG_TYPE_TRACING:
4344 		if (eatype == BPF_TRACE_ITER)
4345 			return true;
4346 		break;
4347 	case BPF_PROG_TYPE_SOCKET_FILTER:
4348 	case BPF_PROG_TYPE_SCHED_CLS:
4349 	case BPF_PROG_TYPE_SCHED_ACT:
4350 	case BPF_PROG_TYPE_XDP:
4351 	case BPF_PROG_TYPE_SK_REUSEPORT:
4352 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4353 	case BPF_PROG_TYPE_SK_LOOKUP:
4354 		return true;
4355 	default:
4356 		break;
4357 	}
4358 
4359 	verbose(env, "cannot update sockmap in this context\n");
4360 	return false;
4361 }
4362 
4363 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4364 {
4365 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4366 }
4367 
4368 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4369 					struct bpf_map *map, int func_id)
4370 {
4371 	if (!map)
4372 		return 0;
4373 
4374 	/* We need a two way check, first is from map perspective ... */
4375 	switch (map->map_type) {
4376 	case BPF_MAP_TYPE_PROG_ARRAY:
4377 		if (func_id != BPF_FUNC_tail_call)
4378 			goto error;
4379 		break;
4380 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4381 		if (func_id != BPF_FUNC_perf_event_read &&
4382 		    func_id != BPF_FUNC_perf_event_output &&
4383 		    func_id != BPF_FUNC_skb_output &&
4384 		    func_id != BPF_FUNC_perf_event_read_value &&
4385 		    func_id != BPF_FUNC_xdp_output)
4386 			goto error;
4387 		break;
4388 	case BPF_MAP_TYPE_RINGBUF:
4389 		if (func_id != BPF_FUNC_ringbuf_output &&
4390 		    func_id != BPF_FUNC_ringbuf_reserve &&
4391 		    func_id != BPF_FUNC_ringbuf_submit &&
4392 		    func_id != BPF_FUNC_ringbuf_discard &&
4393 		    func_id != BPF_FUNC_ringbuf_query)
4394 			goto error;
4395 		break;
4396 	case BPF_MAP_TYPE_STACK_TRACE:
4397 		if (func_id != BPF_FUNC_get_stackid)
4398 			goto error;
4399 		break;
4400 	case BPF_MAP_TYPE_CGROUP_ARRAY:
4401 		if (func_id != BPF_FUNC_skb_under_cgroup &&
4402 		    func_id != BPF_FUNC_current_task_under_cgroup)
4403 			goto error;
4404 		break;
4405 	case BPF_MAP_TYPE_CGROUP_STORAGE:
4406 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4407 		if (func_id != BPF_FUNC_get_local_storage)
4408 			goto error;
4409 		break;
4410 	case BPF_MAP_TYPE_DEVMAP:
4411 	case BPF_MAP_TYPE_DEVMAP_HASH:
4412 		if (func_id != BPF_FUNC_redirect_map &&
4413 		    func_id != BPF_FUNC_map_lookup_elem)
4414 			goto error;
4415 		break;
4416 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
4417 	 * appear.
4418 	 */
4419 	case BPF_MAP_TYPE_CPUMAP:
4420 		if (func_id != BPF_FUNC_redirect_map)
4421 			goto error;
4422 		break;
4423 	case BPF_MAP_TYPE_XSKMAP:
4424 		if (func_id != BPF_FUNC_redirect_map &&
4425 		    func_id != BPF_FUNC_map_lookup_elem)
4426 			goto error;
4427 		break;
4428 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4429 	case BPF_MAP_TYPE_HASH_OF_MAPS:
4430 		if (func_id != BPF_FUNC_map_lookup_elem)
4431 			goto error;
4432 		break;
4433 	case BPF_MAP_TYPE_SOCKMAP:
4434 		if (func_id != BPF_FUNC_sk_redirect_map &&
4435 		    func_id != BPF_FUNC_sock_map_update &&
4436 		    func_id != BPF_FUNC_map_delete_elem &&
4437 		    func_id != BPF_FUNC_msg_redirect_map &&
4438 		    func_id != BPF_FUNC_sk_select_reuseport &&
4439 		    func_id != BPF_FUNC_map_lookup_elem &&
4440 		    !may_update_sockmap(env, func_id))
4441 			goto error;
4442 		break;
4443 	case BPF_MAP_TYPE_SOCKHASH:
4444 		if (func_id != BPF_FUNC_sk_redirect_hash &&
4445 		    func_id != BPF_FUNC_sock_hash_update &&
4446 		    func_id != BPF_FUNC_map_delete_elem &&
4447 		    func_id != BPF_FUNC_msg_redirect_hash &&
4448 		    func_id != BPF_FUNC_sk_select_reuseport &&
4449 		    func_id != BPF_FUNC_map_lookup_elem &&
4450 		    !may_update_sockmap(env, func_id))
4451 			goto error;
4452 		break;
4453 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4454 		if (func_id != BPF_FUNC_sk_select_reuseport)
4455 			goto error;
4456 		break;
4457 	case BPF_MAP_TYPE_QUEUE:
4458 	case BPF_MAP_TYPE_STACK:
4459 		if (func_id != BPF_FUNC_map_peek_elem &&
4460 		    func_id != BPF_FUNC_map_pop_elem &&
4461 		    func_id != BPF_FUNC_map_push_elem)
4462 			goto error;
4463 		break;
4464 	case BPF_MAP_TYPE_SK_STORAGE:
4465 		if (func_id != BPF_FUNC_sk_storage_get &&
4466 		    func_id != BPF_FUNC_sk_storage_delete)
4467 			goto error;
4468 		break;
4469 	case BPF_MAP_TYPE_INODE_STORAGE:
4470 		if (func_id != BPF_FUNC_inode_storage_get &&
4471 		    func_id != BPF_FUNC_inode_storage_delete)
4472 			goto error;
4473 		break;
4474 	case BPF_MAP_TYPE_TASK_STORAGE:
4475 		if (func_id != BPF_FUNC_task_storage_get &&
4476 		    func_id != BPF_FUNC_task_storage_delete)
4477 			goto error;
4478 		break;
4479 	default:
4480 		break;
4481 	}
4482 
4483 	/* ... and second from the function itself. */
4484 	switch (func_id) {
4485 	case BPF_FUNC_tail_call:
4486 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4487 			goto error;
4488 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4489 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4490 			return -EINVAL;
4491 		}
4492 		break;
4493 	case BPF_FUNC_perf_event_read:
4494 	case BPF_FUNC_perf_event_output:
4495 	case BPF_FUNC_perf_event_read_value:
4496 	case BPF_FUNC_skb_output:
4497 	case BPF_FUNC_xdp_output:
4498 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4499 			goto error;
4500 		break;
4501 	case BPF_FUNC_get_stackid:
4502 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4503 			goto error;
4504 		break;
4505 	case BPF_FUNC_current_task_under_cgroup:
4506 	case BPF_FUNC_skb_under_cgroup:
4507 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4508 			goto error;
4509 		break;
4510 	case BPF_FUNC_redirect_map:
4511 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4512 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4513 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
4514 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
4515 			goto error;
4516 		break;
4517 	case BPF_FUNC_sk_redirect_map:
4518 	case BPF_FUNC_msg_redirect_map:
4519 	case BPF_FUNC_sock_map_update:
4520 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4521 			goto error;
4522 		break;
4523 	case BPF_FUNC_sk_redirect_hash:
4524 	case BPF_FUNC_msg_redirect_hash:
4525 	case BPF_FUNC_sock_hash_update:
4526 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4527 			goto error;
4528 		break;
4529 	case BPF_FUNC_get_local_storage:
4530 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4531 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4532 			goto error;
4533 		break;
4534 	case BPF_FUNC_sk_select_reuseport:
4535 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4536 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4537 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
4538 			goto error;
4539 		break;
4540 	case BPF_FUNC_map_peek_elem:
4541 	case BPF_FUNC_map_pop_elem:
4542 	case BPF_FUNC_map_push_elem:
4543 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4544 		    map->map_type != BPF_MAP_TYPE_STACK)
4545 			goto error;
4546 		break;
4547 	case BPF_FUNC_sk_storage_get:
4548 	case BPF_FUNC_sk_storage_delete:
4549 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4550 			goto error;
4551 		break;
4552 	case BPF_FUNC_inode_storage_get:
4553 	case BPF_FUNC_inode_storage_delete:
4554 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4555 			goto error;
4556 		break;
4557 	case BPF_FUNC_task_storage_get:
4558 	case BPF_FUNC_task_storage_delete:
4559 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
4560 			goto error;
4561 		break;
4562 	default:
4563 		break;
4564 	}
4565 
4566 	return 0;
4567 error:
4568 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
4569 		map->map_type, func_id_name(func_id), func_id);
4570 	return -EINVAL;
4571 }
4572 
4573 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4574 {
4575 	int count = 0;
4576 
4577 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4578 		count++;
4579 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4580 		count++;
4581 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4582 		count++;
4583 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4584 		count++;
4585 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4586 		count++;
4587 
4588 	/* We only support one arg being in raw mode at the moment,
4589 	 * which is sufficient for the helper functions we have
4590 	 * right now.
4591 	 */
4592 	return count <= 1;
4593 }
4594 
4595 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4596 				    enum bpf_arg_type arg_next)
4597 {
4598 	return (arg_type_is_mem_ptr(arg_curr) &&
4599 	        !arg_type_is_mem_size(arg_next)) ||
4600 	       (!arg_type_is_mem_ptr(arg_curr) &&
4601 		arg_type_is_mem_size(arg_next));
4602 }
4603 
4604 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4605 {
4606 	/* bpf_xxx(..., buf, len) call will access 'len'
4607 	 * bytes from memory 'buf'. Both arg types need
4608 	 * to be paired, so make sure there's no buggy
4609 	 * helper function specification.
4610 	 */
4611 	if (arg_type_is_mem_size(fn->arg1_type) ||
4612 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
4613 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4614 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4615 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4616 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4617 		return false;
4618 
4619 	return true;
4620 }
4621 
4622 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4623 {
4624 	int count = 0;
4625 
4626 	if (arg_type_may_be_refcounted(fn->arg1_type))
4627 		count++;
4628 	if (arg_type_may_be_refcounted(fn->arg2_type))
4629 		count++;
4630 	if (arg_type_may_be_refcounted(fn->arg3_type))
4631 		count++;
4632 	if (arg_type_may_be_refcounted(fn->arg4_type))
4633 		count++;
4634 	if (arg_type_may_be_refcounted(fn->arg5_type))
4635 		count++;
4636 
4637 	/* A reference acquiring function cannot acquire
4638 	 * another refcounted ptr.
4639 	 */
4640 	if (may_be_acquire_function(func_id) && count)
4641 		return false;
4642 
4643 	/* We only support one arg being unreferenced at the moment,
4644 	 * which is sufficient for the helper functions we have right now.
4645 	 */
4646 	return count <= 1;
4647 }
4648 
4649 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4650 {
4651 	int i;
4652 
4653 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4654 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4655 			return false;
4656 
4657 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4658 			return false;
4659 	}
4660 
4661 	return true;
4662 }
4663 
4664 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
4665 {
4666 	return check_raw_mode_ok(fn) &&
4667 	       check_arg_pair_ok(fn) &&
4668 	       check_btf_id_ok(fn) &&
4669 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
4670 }
4671 
4672 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4673  * are now invalid, so turn them into unknown SCALAR_VALUE.
4674  */
4675 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4676 				     struct bpf_func_state *state)
4677 {
4678 	struct bpf_reg_state *regs = state->regs, *reg;
4679 	int i;
4680 
4681 	for (i = 0; i < MAX_BPF_REG; i++)
4682 		if (reg_is_pkt_pointer_any(&regs[i]))
4683 			mark_reg_unknown(env, regs, i);
4684 
4685 	bpf_for_each_spilled_reg(i, state, reg) {
4686 		if (!reg)
4687 			continue;
4688 		if (reg_is_pkt_pointer_any(reg))
4689 			__mark_reg_unknown(env, reg);
4690 	}
4691 }
4692 
4693 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4694 {
4695 	struct bpf_verifier_state *vstate = env->cur_state;
4696 	int i;
4697 
4698 	for (i = 0; i <= vstate->curframe; i++)
4699 		__clear_all_pkt_pointers(env, vstate->frame[i]);
4700 }
4701 
4702 enum {
4703 	AT_PKT_END = -1,
4704 	BEYOND_PKT_END = -2,
4705 };
4706 
4707 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
4708 {
4709 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4710 	struct bpf_reg_state *reg = &state->regs[regn];
4711 
4712 	if (reg->type != PTR_TO_PACKET)
4713 		/* PTR_TO_PACKET_META is not supported yet */
4714 		return;
4715 
4716 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
4717 	 * How far beyond pkt_end it goes is unknown.
4718 	 * if (!range_open) it's the case of pkt >= pkt_end
4719 	 * if (range_open) it's the case of pkt > pkt_end
4720 	 * hence this pointer is at least 1 byte bigger than pkt_end
4721 	 */
4722 	if (range_open)
4723 		reg->range = BEYOND_PKT_END;
4724 	else
4725 		reg->range = AT_PKT_END;
4726 }
4727 
4728 static void release_reg_references(struct bpf_verifier_env *env,
4729 				   struct bpf_func_state *state,
4730 				   int ref_obj_id)
4731 {
4732 	struct bpf_reg_state *regs = state->regs, *reg;
4733 	int i;
4734 
4735 	for (i = 0; i < MAX_BPF_REG; i++)
4736 		if (regs[i].ref_obj_id == ref_obj_id)
4737 			mark_reg_unknown(env, regs, i);
4738 
4739 	bpf_for_each_spilled_reg(i, state, reg) {
4740 		if (!reg)
4741 			continue;
4742 		if (reg->ref_obj_id == ref_obj_id)
4743 			__mark_reg_unknown(env, reg);
4744 	}
4745 }
4746 
4747 /* The pointer with the specified id has released its reference to kernel
4748  * resources. Identify all copies of the same pointer and clear the reference.
4749  */
4750 static int release_reference(struct bpf_verifier_env *env,
4751 			     int ref_obj_id)
4752 {
4753 	struct bpf_verifier_state *vstate = env->cur_state;
4754 	int err;
4755 	int i;
4756 
4757 	err = release_reference_state(cur_func(env), ref_obj_id);
4758 	if (err)
4759 		return err;
4760 
4761 	for (i = 0; i <= vstate->curframe; i++)
4762 		release_reg_references(env, vstate->frame[i], ref_obj_id);
4763 
4764 	return 0;
4765 }
4766 
4767 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4768 				    struct bpf_reg_state *regs)
4769 {
4770 	int i;
4771 
4772 	/* after the call registers r0 - r5 were scratched */
4773 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
4774 		mark_reg_not_init(env, regs, caller_saved[i]);
4775 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4776 	}
4777 }
4778 
4779 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4780 			   int *insn_idx)
4781 {
4782 	struct bpf_verifier_state *state = env->cur_state;
4783 	struct bpf_func_info_aux *func_info_aux;
4784 	struct bpf_func_state *caller, *callee;
4785 	int i, err, subprog, target_insn;
4786 	bool is_global = false;
4787 
4788 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
4789 		verbose(env, "the call stack of %d frames is too deep\n",
4790 			state->curframe + 2);
4791 		return -E2BIG;
4792 	}
4793 
4794 	target_insn = *insn_idx + insn->imm;
4795 	subprog = find_subprog(env, target_insn + 1);
4796 	if (subprog < 0) {
4797 		verbose(env, "verifier bug. No program starts at insn %d\n",
4798 			target_insn + 1);
4799 		return -EFAULT;
4800 	}
4801 
4802 	caller = state->frame[state->curframe];
4803 	if (state->frame[state->curframe + 1]) {
4804 		verbose(env, "verifier bug. Frame %d already allocated\n",
4805 			state->curframe + 1);
4806 		return -EFAULT;
4807 	}
4808 
4809 	func_info_aux = env->prog->aux->func_info_aux;
4810 	if (func_info_aux)
4811 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4812 	err = btf_check_func_arg_match(env, subprog, caller->regs);
4813 	if (err == -EFAULT)
4814 		return err;
4815 	if (is_global) {
4816 		if (err) {
4817 			verbose(env, "Caller passes invalid args into func#%d\n",
4818 				subprog);
4819 			return err;
4820 		} else {
4821 			if (env->log.level & BPF_LOG_LEVEL)
4822 				verbose(env,
4823 					"Func#%d is global and valid. Skipping.\n",
4824 					subprog);
4825 			clear_caller_saved_regs(env, caller->regs);
4826 
4827 			/* All global functions return SCALAR_VALUE */
4828 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
4829 
4830 			/* continue with next insn after call */
4831 			return 0;
4832 		}
4833 	}
4834 
4835 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4836 	if (!callee)
4837 		return -ENOMEM;
4838 	state->frame[state->curframe + 1] = callee;
4839 
4840 	/* callee cannot access r0, r6 - r9 for reading and has to write
4841 	 * into its own stack before reading from it.
4842 	 * callee can read/write into caller's stack
4843 	 */
4844 	init_func_state(env, callee,
4845 			/* remember the callsite, it will be used by bpf_exit */
4846 			*insn_idx /* callsite */,
4847 			state->curframe + 1 /* frameno within this callchain */,
4848 			subprog /* subprog number within this prog */);
4849 
4850 	/* Transfer references to the callee */
4851 	err = transfer_reference_state(callee, caller);
4852 	if (err)
4853 		return err;
4854 
4855 	/* copy r1 - r5 args that callee can access.  The copy includes parent
4856 	 * pointers, which connects us up to the liveness chain
4857 	 */
4858 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4859 		callee->regs[i] = caller->regs[i];
4860 
4861 	clear_caller_saved_regs(env, caller->regs);
4862 
4863 	/* only increment it after check_reg_arg() finished */
4864 	state->curframe++;
4865 
4866 	/* and go analyze first insn of the callee */
4867 	*insn_idx = target_insn;
4868 
4869 	if (env->log.level & BPF_LOG_LEVEL) {
4870 		verbose(env, "caller:\n");
4871 		print_verifier_state(env, caller);
4872 		verbose(env, "callee:\n");
4873 		print_verifier_state(env, callee);
4874 	}
4875 	return 0;
4876 }
4877 
4878 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4879 {
4880 	struct bpf_verifier_state *state = env->cur_state;
4881 	struct bpf_func_state *caller, *callee;
4882 	struct bpf_reg_state *r0;
4883 	int err;
4884 
4885 	callee = state->frame[state->curframe];
4886 	r0 = &callee->regs[BPF_REG_0];
4887 	if (r0->type == PTR_TO_STACK) {
4888 		/* technically it's ok to return caller's stack pointer
4889 		 * (or caller's caller's pointer) back to the caller,
4890 		 * since these pointers are valid. Only current stack
4891 		 * pointer will be invalid as soon as function exits,
4892 		 * but let's be conservative
4893 		 */
4894 		verbose(env, "cannot return stack pointer to the caller\n");
4895 		return -EINVAL;
4896 	}
4897 
4898 	state->curframe--;
4899 	caller = state->frame[state->curframe];
4900 	/* return to the caller whatever r0 had in the callee */
4901 	caller->regs[BPF_REG_0] = *r0;
4902 
4903 	/* Transfer references to the caller */
4904 	err = transfer_reference_state(caller, callee);
4905 	if (err)
4906 		return err;
4907 
4908 	*insn_idx = callee->callsite + 1;
4909 	if (env->log.level & BPF_LOG_LEVEL) {
4910 		verbose(env, "returning from callee:\n");
4911 		print_verifier_state(env, callee);
4912 		verbose(env, "to caller at %d:\n", *insn_idx);
4913 		print_verifier_state(env, caller);
4914 	}
4915 	/* clear everything in the callee */
4916 	free_func_state(callee);
4917 	state->frame[state->curframe + 1] = NULL;
4918 	return 0;
4919 }
4920 
4921 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4922 				   int func_id,
4923 				   struct bpf_call_arg_meta *meta)
4924 {
4925 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4926 
4927 	if (ret_type != RET_INTEGER ||
4928 	    (func_id != BPF_FUNC_get_stack &&
4929 	     func_id != BPF_FUNC_probe_read_str &&
4930 	     func_id != BPF_FUNC_probe_read_kernel_str &&
4931 	     func_id != BPF_FUNC_probe_read_user_str))
4932 		return;
4933 
4934 	ret_reg->smax_value = meta->msize_max_value;
4935 	ret_reg->s32_max_value = meta->msize_max_value;
4936 	__reg_deduce_bounds(ret_reg);
4937 	__reg_bound_offset(ret_reg);
4938 	__update_reg_bounds(ret_reg);
4939 }
4940 
4941 static int
4942 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4943 		int func_id, int insn_idx)
4944 {
4945 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4946 	struct bpf_map *map = meta->map_ptr;
4947 
4948 	if (func_id != BPF_FUNC_tail_call &&
4949 	    func_id != BPF_FUNC_map_lookup_elem &&
4950 	    func_id != BPF_FUNC_map_update_elem &&
4951 	    func_id != BPF_FUNC_map_delete_elem &&
4952 	    func_id != BPF_FUNC_map_push_elem &&
4953 	    func_id != BPF_FUNC_map_pop_elem &&
4954 	    func_id != BPF_FUNC_map_peek_elem)
4955 		return 0;
4956 
4957 	if (map == NULL) {
4958 		verbose(env, "kernel subsystem misconfigured verifier\n");
4959 		return -EINVAL;
4960 	}
4961 
4962 	/* In case of read-only, some additional restrictions
4963 	 * need to be applied in order to prevent altering the
4964 	 * state of the map from program side.
4965 	 */
4966 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4967 	    (func_id == BPF_FUNC_map_delete_elem ||
4968 	     func_id == BPF_FUNC_map_update_elem ||
4969 	     func_id == BPF_FUNC_map_push_elem ||
4970 	     func_id == BPF_FUNC_map_pop_elem)) {
4971 		verbose(env, "write into map forbidden\n");
4972 		return -EACCES;
4973 	}
4974 
4975 	if (!BPF_MAP_PTR(aux->map_ptr_state))
4976 		bpf_map_ptr_store(aux, meta->map_ptr,
4977 				  !meta->map_ptr->bypass_spec_v1);
4978 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
4979 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4980 				  !meta->map_ptr->bypass_spec_v1);
4981 	return 0;
4982 }
4983 
4984 static int
4985 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4986 		int func_id, int insn_idx)
4987 {
4988 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4989 	struct bpf_reg_state *regs = cur_regs(env), *reg;
4990 	struct bpf_map *map = meta->map_ptr;
4991 	struct tnum range;
4992 	u64 val;
4993 	int err;
4994 
4995 	if (func_id != BPF_FUNC_tail_call)
4996 		return 0;
4997 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4998 		verbose(env, "kernel subsystem misconfigured verifier\n");
4999 		return -EINVAL;
5000 	}
5001 
5002 	range = tnum_range(0, map->max_entries - 1);
5003 	reg = &regs[BPF_REG_3];
5004 
5005 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5006 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5007 		return 0;
5008 	}
5009 
5010 	err = mark_chain_precision(env, BPF_REG_3);
5011 	if (err)
5012 		return err;
5013 
5014 	val = reg->var_off.value;
5015 	if (bpf_map_key_unseen(aux))
5016 		bpf_map_key_store(aux, val);
5017 	else if (!bpf_map_key_poisoned(aux) &&
5018 		  bpf_map_key_immediate(aux) != val)
5019 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5020 	return 0;
5021 }
5022 
5023 static int check_reference_leak(struct bpf_verifier_env *env)
5024 {
5025 	struct bpf_func_state *state = cur_func(env);
5026 	int i;
5027 
5028 	for (i = 0; i < state->acquired_refs; i++) {
5029 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5030 			state->refs[i].id, state->refs[i].insn_idx);
5031 	}
5032 	return state->acquired_refs ? -EINVAL : 0;
5033 }
5034 
5035 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5036 {
5037 	const struct bpf_func_proto *fn = NULL;
5038 	struct bpf_reg_state *regs;
5039 	struct bpf_call_arg_meta meta;
5040 	bool changes_data;
5041 	int i, err;
5042 
5043 	/* find function prototype */
5044 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5045 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5046 			func_id);
5047 		return -EINVAL;
5048 	}
5049 
5050 	if (env->ops->get_func_proto)
5051 		fn = env->ops->get_func_proto(func_id, env->prog);
5052 	if (!fn) {
5053 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5054 			func_id);
5055 		return -EINVAL;
5056 	}
5057 
5058 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5059 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5060 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5061 		return -EINVAL;
5062 	}
5063 
5064 	if (fn->allowed && !fn->allowed(env->prog)) {
5065 		verbose(env, "helper call is not allowed in probe\n");
5066 		return -EINVAL;
5067 	}
5068 
5069 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5070 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5071 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5072 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5073 			func_id_name(func_id), func_id);
5074 		return -EINVAL;
5075 	}
5076 
5077 	memset(&meta, 0, sizeof(meta));
5078 	meta.pkt_access = fn->pkt_access;
5079 
5080 	err = check_func_proto(fn, func_id);
5081 	if (err) {
5082 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5083 			func_id_name(func_id), func_id);
5084 		return err;
5085 	}
5086 
5087 	meta.func_id = func_id;
5088 	/* check args */
5089 	for (i = 0; i < 5; i++) {
5090 		err = check_func_arg(env, i, &meta, fn);
5091 		if (err)
5092 			return err;
5093 	}
5094 
5095 	err = record_func_map(env, &meta, func_id, insn_idx);
5096 	if (err)
5097 		return err;
5098 
5099 	err = record_func_key(env, &meta, func_id, insn_idx);
5100 	if (err)
5101 		return err;
5102 
5103 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5104 	 * is inferred from register state.
5105 	 */
5106 	for (i = 0; i < meta.access_size; i++) {
5107 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5108 				       BPF_WRITE, -1, false);
5109 		if (err)
5110 			return err;
5111 	}
5112 
5113 	if (func_id == BPF_FUNC_tail_call) {
5114 		err = check_reference_leak(env);
5115 		if (err) {
5116 			verbose(env, "tail_call would lead to reference leak\n");
5117 			return err;
5118 		}
5119 	} else if (is_release_function(func_id)) {
5120 		err = release_reference(env, meta.ref_obj_id);
5121 		if (err) {
5122 			verbose(env, "func %s#%d reference has not been acquired before\n",
5123 				func_id_name(func_id), func_id);
5124 			return err;
5125 		}
5126 	}
5127 
5128 	regs = cur_regs(env);
5129 
5130 	/* check that flags argument in get_local_storage(map, flags) is 0,
5131 	 * this is required because get_local_storage() can't return an error.
5132 	 */
5133 	if (func_id == BPF_FUNC_get_local_storage &&
5134 	    !register_is_null(&regs[BPF_REG_2])) {
5135 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5136 		return -EINVAL;
5137 	}
5138 
5139 	/* reset caller saved regs */
5140 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5141 		mark_reg_not_init(env, regs, caller_saved[i]);
5142 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5143 	}
5144 
5145 	/* helper call returns 64-bit value. */
5146 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5147 
5148 	/* update return register (already marked as written above) */
5149 	if (fn->ret_type == RET_INTEGER) {
5150 		/* sets type to SCALAR_VALUE */
5151 		mark_reg_unknown(env, regs, BPF_REG_0);
5152 	} else if (fn->ret_type == RET_VOID) {
5153 		regs[BPF_REG_0].type = NOT_INIT;
5154 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5155 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5156 		/* There is no offset yet applied, variable or fixed */
5157 		mark_reg_known_zero(env, regs, BPF_REG_0);
5158 		/* remember map_ptr, so that check_map_access()
5159 		 * can check 'value_size' boundary of memory access
5160 		 * to map element returned from bpf_map_lookup_elem()
5161 		 */
5162 		if (meta.map_ptr == NULL) {
5163 			verbose(env,
5164 				"kernel subsystem misconfigured verifier\n");
5165 			return -EINVAL;
5166 		}
5167 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5168 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5169 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5170 			if (map_value_has_spin_lock(meta.map_ptr))
5171 				regs[BPF_REG_0].id = ++env->id_gen;
5172 		} else {
5173 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5174 		}
5175 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5176 		mark_reg_known_zero(env, regs, BPF_REG_0);
5177 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5178 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5179 		mark_reg_known_zero(env, regs, BPF_REG_0);
5180 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5181 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5182 		mark_reg_known_zero(env, regs, BPF_REG_0);
5183 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5184 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5185 		mark_reg_known_zero(env, regs, BPF_REG_0);
5186 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5187 		regs[BPF_REG_0].mem_size = meta.mem_size;
5188 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5189 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5190 		const struct btf_type *t;
5191 
5192 		mark_reg_known_zero(env, regs, BPF_REG_0);
5193 		t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5194 		if (!btf_type_is_struct(t)) {
5195 			u32 tsize;
5196 			const struct btf_type *ret;
5197 			const char *tname;
5198 
5199 			/* resolve the type size of ksym. */
5200 			ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5201 			if (IS_ERR(ret)) {
5202 				tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5203 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5204 					tname, PTR_ERR(ret));
5205 				return -EINVAL;
5206 			}
5207 			regs[BPF_REG_0].type =
5208 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5209 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5210 			regs[BPF_REG_0].mem_size = tsize;
5211 		} else {
5212 			regs[BPF_REG_0].type =
5213 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5214 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5215 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5216 		}
5217 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5218 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
5219 		int ret_btf_id;
5220 
5221 		mark_reg_known_zero(env, regs, BPF_REG_0);
5222 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5223 						     PTR_TO_BTF_ID :
5224 						     PTR_TO_BTF_ID_OR_NULL;
5225 		ret_btf_id = *fn->ret_btf_id;
5226 		if (ret_btf_id == 0) {
5227 			verbose(env, "invalid return type %d of func %s#%d\n",
5228 				fn->ret_type, func_id_name(func_id), func_id);
5229 			return -EINVAL;
5230 		}
5231 		regs[BPF_REG_0].btf_id = ret_btf_id;
5232 	} else {
5233 		verbose(env, "unknown return type %d of func %s#%d\n",
5234 			fn->ret_type, func_id_name(func_id), func_id);
5235 		return -EINVAL;
5236 	}
5237 
5238 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
5239 		regs[BPF_REG_0].id = ++env->id_gen;
5240 
5241 	if (is_ptr_cast_function(func_id)) {
5242 		/* For release_reference() */
5243 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5244 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5245 		int id = acquire_reference_state(env, insn_idx);
5246 
5247 		if (id < 0)
5248 			return id;
5249 		/* For mark_ptr_or_null_reg() */
5250 		regs[BPF_REG_0].id = id;
5251 		/* For release_reference() */
5252 		regs[BPF_REG_0].ref_obj_id = id;
5253 	}
5254 
5255 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5256 
5257 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5258 	if (err)
5259 		return err;
5260 
5261 	if ((func_id == BPF_FUNC_get_stack ||
5262 	     func_id == BPF_FUNC_get_task_stack) &&
5263 	    !env->prog->has_callchain_buf) {
5264 		const char *err_str;
5265 
5266 #ifdef CONFIG_PERF_EVENTS
5267 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5268 		err_str = "cannot get callchain buffer for func %s#%d\n";
5269 #else
5270 		err = -ENOTSUPP;
5271 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5272 #endif
5273 		if (err) {
5274 			verbose(env, err_str, func_id_name(func_id), func_id);
5275 			return err;
5276 		}
5277 
5278 		env->prog->has_callchain_buf = true;
5279 	}
5280 
5281 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5282 		env->prog->call_get_stack = true;
5283 
5284 	if (changes_data)
5285 		clear_all_pkt_pointers(env);
5286 	return 0;
5287 }
5288 
5289 static bool signed_add_overflows(s64 a, s64 b)
5290 {
5291 	/* Do the add in u64, where overflow is well-defined */
5292 	s64 res = (s64)((u64)a + (u64)b);
5293 
5294 	if (b < 0)
5295 		return res > a;
5296 	return res < a;
5297 }
5298 
5299 static bool signed_add32_overflows(s64 a, s64 b)
5300 {
5301 	/* Do the add in u32, where overflow is well-defined */
5302 	s32 res = (s32)((u32)a + (u32)b);
5303 
5304 	if (b < 0)
5305 		return res > a;
5306 	return res < a;
5307 }
5308 
5309 static bool signed_sub_overflows(s32 a, s32 b)
5310 {
5311 	/* Do the sub in u64, where overflow is well-defined */
5312 	s64 res = (s64)((u64)a - (u64)b);
5313 
5314 	if (b < 0)
5315 		return res < a;
5316 	return res > a;
5317 }
5318 
5319 static bool signed_sub32_overflows(s32 a, s32 b)
5320 {
5321 	/* Do the sub in u64, where overflow is well-defined */
5322 	s32 res = (s32)((u32)a - (u32)b);
5323 
5324 	if (b < 0)
5325 		return res < a;
5326 	return res > a;
5327 }
5328 
5329 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5330 				  const struct bpf_reg_state *reg,
5331 				  enum bpf_reg_type type)
5332 {
5333 	bool known = tnum_is_const(reg->var_off);
5334 	s64 val = reg->var_off.value;
5335 	s64 smin = reg->smin_value;
5336 
5337 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5338 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5339 			reg_type_str[type], val);
5340 		return false;
5341 	}
5342 
5343 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5344 		verbose(env, "%s pointer offset %d is not allowed\n",
5345 			reg_type_str[type], reg->off);
5346 		return false;
5347 	}
5348 
5349 	if (smin == S64_MIN) {
5350 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5351 			reg_type_str[type]);
5352 		return false;
5353 	}
5354 
5355 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5356 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5357 			smin, reg_type_str[type]);
5358 		return false;
5359 	}
5360 
5361 	return true;
5362 }
5363 
5364 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5365 {
5366 	return &env->insn_aux_data[env->insn_idx];
5367 }
5368 
5369 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5370 			      u32 *ptr_limit, u8 opcode, bool off_is_neg)
5371 {
5372 	bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
5373 			    (opcode == BPF_SUB && !off_is_neg);
5374 	u32 off;
5375 
5376 	switch (ptr_reg->type) {
5377 	case PTR_TO_STACK:
5378 		/* Indirect variable offset stack access is prohibited in
5379 		 * unprivileged mode so it's not handled here.
5380 		 */
5381 		off = ptr_reg->off + ptr_reg->var_off.value;
5382 		if (mask_to_left)
5383 			*ptr_limit = MAX_BPF_STACK + off;
5384 		else
5385 			*ptr_limit = -off;
5386 		return 0;
5387 	case PTR_TO_MAP_VALUE:
5388 		if (mask_to_left) {
5389 			*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5390 		} else {
5391 			off = ptr_reg->smin_value + ptr_reg->off;
5392 			*ptr_limit = ptr_reg->map_ptr->value_size - off;
5393 		}
5394 		return 0;
5395 	default:
5396 		return -EINVAL;
5397 	}
5398 }
5399 
5400 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5401 				    const struct bpf_insn *insn)
5402 {
5403 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5404 }
5405 
5406 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5407 				       u32 alu_state, u32 alu_limit)
5408 {
5409 	/* If we arrived here from different branches with different
5410 	 * state or limits to sanitize, then this won't work.
5411 	 */
5412 	if (aux->alu_state &&
5413 	    (aux->alu_state != alu_state ||
5414 	     aux->alu_limit != alu_limit))
5415 		return -EACCES;
5416 
5417 	/* Corresponding fixup done in fixup_bpf_calls(). */
5418 	aux->alu_state = alu_state;
5419 	aux->alu_limit = alu_limit;
5420 	return 0;
5421 }
5422 
5423 static int sanitize_val_alu(struct bpf_verifier_env *env,
5424 			    struct bpf_insn *insn)
5425 {
5426 	struct bpf_insn_aux_data *aux = cur_aux(env);
5427 
5428 	if (can_skip_alu_sanitation(env, insn))
5429 		return 0;
5430 
5431 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5432 }
5433 
5434 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5435 			    struct bpf_insn *insn,
5436 			    const struct bpf_reg_state *ptr_reg,
5437 			    struct bpf_reg_state *dst_reg,
5438 			    bool off_is_neg)
5439 {
5440 	struct bpf_verifier_state *vstate = env->cur_state;
5441 	struct bpf_insn_aux_data *aux = cur_aux(env);
5442 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
5443 	u8 opcode = BPF_OP(insn->code);
5444 	u32 alu_state, alu_limit;
5445 	struct bpf_reg_state tmp;
5446 	bool ret;
5447 
5448 	if (can_skip_alu_sanitation(env, insn))
5449 		return 0;
5450 
5451 	/* We already marked aux for masking from non-speculative
5452 	 * paths, thus we got here in the first place. We only care
5453 	 * to explore bad access from here.
5454 	 */
5455 	if (vstate->speculative)
5456 		goto do_sim;
5457 
5458 	alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5459 	alu_state |= ptr_is_dst_reg ?
5460 		     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5461 
5462 	if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5463 		return 0;
5464 	if (update_alu_sanitation_state(aux, alu_state, alu_limit))
5465 		return -EACCES;
5466 do_sim:
5467 	/* Simulate and find potential out-of-bounds access under
5468 	 * speculative execution from truncation as a result of
5469 	 * masking when off was not within expected range. If off
5470 	 * sits in dst, then we temporarily need to move ptr there
5471 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5472 	 * for cases where we use K-based arithmetic in one direction
5473 	 * and truncated reg-based in the other in order to explore
5474 	 * bad access.
5475 	 */
5476 	if (!ptr_is_dst_reg) {
5477 		tmp = *dst_reg;
5478 		*dst_reg = *ptr_reg;
5479 	}
5480 	ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
5481 	if (!ptr_is_dst_reg && ret)
5482 		*dst_reg = tmp;
5483 	return !ret ? -EFAULT : 0;
5484 }
5485 
5486 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5487  * Caller should also handle BPF_MOV case separately.
5488  * If we return -EACCES, caller may want to try again treating pointer as a
5489  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
5490  */
5491 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5492 				   struct bpf_insn *insn,
5493 				   const struct bpf_reg_state *ptr_reg,
5494 				   const struct bpf_reg_state *off_reg)
5495 {
5496 	struct bpf_verifier_state *vstate = env->cur_state;
5497 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5498 	struct bpf_reg_state *regs = state->regs, *dst_reg;
5499 	bool known = tnum_is_const(off_reg->var_off);
5500 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5501 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5502 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5503 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
5504 	u32 dst = insn->dst_reg, src = insn->src_reg;
5505 	u8 opcode = BPF_OP(insn->code);
5506 	int ret;
5507 
5508 	dst_reg = &regs[dst];
5509 
5510 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5511 	    smin_val > smax_val || umin_val > umax_val) {
5512 		/* Taint dst register if offset had invalid bounds derived from
5513 		 * e.g. dead branches.
5514 		 */
5515 		__mark_reg_unknown(env, dst_reg);
5516 		return 0;
5517 	}
5518 
5519 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
5520 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
5521 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5522 			__mark_reg_unknown(env, dst_reg);
5523 			return 0;
5524 		}
5525 
5526 		verbose(env,
5527 			"R%d 32-bit pointer arithmetic prohibited\n",
5528 			dst);
5529 		return -EACCES;
5530 	}
5531 
5532 	switch (ptr_reg->type) {
5533 	case PTR_TO_MAP_VALUE_OR_NULL:
5534 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5535 			dst, reg_type_str[ptr_reg->type]);
5536 		return -EACCES;
5537 	case CONST_PTR_TO_MAP:
5538 		/* smin_val represents the known value */
5539 		if (known && smin_val == 0 && opcode == BPF_ADD)
5540 			break;
5541 		fallthrough;
5542 	case PTR_TO_PACKET_END:
5543 	case PTR_TO_SOCKET:
5544 	case PTR_TO_SOCKET_OR_NULL:
5545 	case PTR_TO_SOCK_COMMON:
5546 	case PTR_TO_SOCK_COMMON_OR_NULL:
5547 	case PTR_TO_TCP_SOCK:
5548 	case PTR_TO_TCP_SOCK_OR_NULL:
5549 	case PTR_TO_XDP_SOCK:
5550 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5551 			dst, reg_type_str[ptr_reg->type]);
5552 		return -EACCES;
5553 	case PTR_TO_MAP_VALUE:
5554 		if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5555 			verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5556 				off_reg == dst_reg ? dst : src);
5557 			return -EACCES;
5558 		}
5559 		fallthrough;
5560 	default:
5561 		break;
5562 	}
5563 
5564 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5565 	 * The id may be overwritten later if we create a new variable offset.
5566 	 */
5567 	dst_reg->type = ptr_reg->type;
5568 	dst_reg->id = ptr_reg->id;
5569 
5570 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5571 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5572 		return -EINVAL;
5573 
5574 	/* pointer types do not carry 32-bit bounds at the moment. */
5575 	__mark_reg32_unbounded(dst_reg);
5576 
5577 	switch (opcode) {
5578 	case BPF_ADD:
5579 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5580 		if (ret < 0) {
5581 			verbose(env, "R%d tried to add from different maps or paths\n", dst);
5582 			return ret;
5583 		}
5584 		/* We can take a fixed offset as long as it doesn't overflow
5585 		 * the s32 'off' field
5586 		 */
5587 		if (known && (ptr_reg->off + smin_val ==
5588 			      (s64)(s32)(ptr_reg->off + smin_val))) {
5589 			/* pointer += K.  Accumulate it into fixed offset */
5590 			dst_reg->smin_value = smin_ptr;
5591 			dst_reg->smax_value = smax_ptr;
5592 			dst_reg->umin_value = umin_ptr;
5593 			dst_reg->umax_value = umax_ptr;
5594 			dst_reg->var_off = ptr_reg->var_off;
5595 			dst_reg->off = ptr_reg->off + smin_val;
5596 			dst_reg->raw = ptr_reg->raw;
5597 			break;
5598 		}
5599 		/* A new variable offset is created.  Note that off_reg->off
5600 		 * == 0, since it's a scalar.
5601 		 * dst_reg gets the pointer type and since some positive
5602 		 * integer value was added to the pointer, give it a new 'id'
5603 		 * if it's a PTR_TO_PACKET.
5604 		 * this creates a new 'base' pointer, off_reg (variable) gets
5605 		 * added into the variable offset, and we copy the fixed offset
5606 		 * from ptr_reg.
5607 		 */
5608 		if (signed_add_overflows(smin_ptr, smin_val) ||
5609 		    signed_add_overflows(smax_ptr, smax_val)) {
5610 			dst_reg->smin_value = S64_MIN;
5611 			dst_reg->smax_value = S64_MAX;
5612 		} else {
5613 			dst_reg->smin_value = smin_ptr + smin_val;
5614 			dst_reg->smax_value = smax_ptr + smax_val;
5615 		}
5616 		if (umin_ptr + umin_val < umin_ptr ||
5617 		    umax_ptr + umax_val < umax_ptr) {
5618 			dst_reg->umin_value = 0;
5619 			dst_reg->umax_value = U64_MAX;
5620 		} else {
5621 			dst_reg->umin_value = umin_ptr + umin_val;
5622 			dst_reg->umax_value = umax_ptr + umax_val;
5623 		}
5624 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5625 		dst_reg->off = ptr_reg->off;
5626 		dst_reg->raw = ptr_reg->raw;
5627 		if (reg_is_pkt_pointer(ptr_reg)) {
5628 			dst_reg->id = ++env->id_gen;
5629 			/* something was added to pkt_ptr, set range to zero */
5630 			dst_reg->raw = 0;
5631 		}
5632 		break;
5633 	case BPF_SUB:
5634 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5635 		if (ret < 0) {
5636 			verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5637 			return ret;
5638 		}
5639 		if (dst_reg == off_reg) {
5640 			/* scalar -= pointer.  Creates an unknown scalar */
5641 			verbose(env, "R%d tried to subtract pointer from scalar\n",
5642 				dst);
5643 			return -EACCES;
5644 		}
5645 		/* We don't allow subtraction from FP, because (according to
5646 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
5647 		 * be able to deal with it.
5648 		 */
5649 		if (ptr_reg->type == PTR_TO_STACK) {
5650 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
5651 				dst);
5652 			return -EACCES;
5653 		}
5654 		if (known && (ptr_reg->off - smin_val ==
5655 			      (s64)(s32)(ptr_reg->off - smin_val))) {
5656 			/* pointer -= K.  Subtract it from fixed offset */
5657 			dst_reg->smin_value = smin_ptr;
5658 			dst_reg->smax_value = smax_ptr;
5659 			dst_reg->umin_value = umin_ptr;
5660 			dst_reg->umax_value = umax_ptr;
5661 			dst_reg->var_off = ptr_reg->var_off;
5662 			dst_reg->id = ptr_reg->id;
5663 			dst_reg->off = ptr_reg->off - smin_val;
5664 			dst_reg->raw = ptr_reg->raw;
5665 			break;
5666 		}
5667 		/* A new variable offset is created.  If the subtrahend is known
5668 		 * nonnegative, then any reg->range we had before is still good.
5669 		 */
5670 		if (signed_sub_overflows(smin_ptr, smax_val) ||
5671 		    signed_sub_overflows(smax_ptr, smin_val)) {
5672 			/* Overflow possible, we know nothing */
5673 			dst_reg->smin_value = S64_MIN;
5674 			dst_reg->smax_value = S64_MAX;
5675 		} else {
5676 			dst_reg->smin_value = smin_ptr - smax_val;
5677 			dst_reg->smax_value = smax_ptr - smin_val;
5678 		}
5679 		if (umin_ptr < umax_val) {
5680 			/* Overflow possible, we know nothing */
5681 			dst_reg->umin_value = 0;
5682 			dst_reg->umax_value = U64_MAX;
5683 		} else {
5684 			/* Cannot overflow (as long as bounds are consistent) */
5685 			dst_reg->umin_value = umin_ptr - umax_val;
5686 			dst_reg->umax_value = umax_ptr - umin_val;
5687 		}
5688 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5689 		dst_reg->off = ptr_reg->off;
5690 		dst_reg->raw = ptr_reg->raw;
5691 		if (reg_is_pkt_pointer(ptr_reg)) {
5692 			dst_reg->id = ++env->id_gen;
5693 			/* something was added to pkt_ptr, set range to zero */
5694 			if (smin_val < 0)
5695 				dst_reg->raw = 0;
5696 		}
5697 		break;
5698 	case BPF_AND:
5699 	case BPF_OR:
5700 	case BPF_XOR:
5701 		/* bitwise ops on pointers are troublesome, prohibit. */
5702 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5703 			dst, bpf_alu_string[opcode >> 4]);
5704 		return -EACCES;
5705 	default:
5706 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
5707 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5708 			dst, bpf_alu_string[opcode >> 4]);
5709 		return -EACCES;
5710 	}
5711 
5712 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5713 		return -EINVAL;
5714 
5715 	__update_reg_bounds(dst_reg);
5716 	__reg_deduce_bounds(dst_reg);
5717 	__reg_bound_offset(dst_reg);
5718 
5719 	/* For unprivileged we require that resulting offset must be in bounds
5720 	 * in order to be able to sanitize access later on.
5721 	 */
5722 	if (!env->bypass_spec_v1) {
5723 		if (dst_reg->type == PTR_TO_MAP_VALUE &&
5724 		    check_map_access(env, dst, dst_reg->off, 1, false)) {
5725 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5726 				"prohibited for !root\n", dst);
5727 			return -EACCES;
5728 		} else if (dst_reg->type == PTR_TO_STACK &&
5729 			   check_stack_access(env, dst_reg, dst_reg->off +
5730 					      dst_reg->var_off.value, 1)) {
5731 			verbose(env, "R%d stack pointer arithmetic goes out of range, "
5732 				"prohibited for !root\n", dst);
5733 			return -EACCES;
5734 		}
5735 	}
5736 
5737 	return 0;
5738 }
5739 
5740 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5741 				 struct bpf_reg_state *src_reg)
5742 {
5743 	s32 smin_val = src_reg->s32_min_value;
5744 	s32 smax_val = src_reg->s32_max_value;
5745 	u32 umin_val = src_reg->u32_min_value;
5746 	u32 umax_val = src_reg->u32_max_value;
5747 
5748 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5749 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5750 		dst_reg->s32_min_value = S32_MIN;
5751 		dst_reg->s32_max_value = S32_MAX;
5752 	} else {
5753 		dst_reg->s32_min_value += smin_val;
5754 		dst_reg->s32_max_value += smax_val;
5755 	}
5756 	if (dst_reg->u32_min_value + umin_val < umin_val ||
5757 	    dst_reg->u32_max_value + umax_val < umax_val) {
5758 		dst_reg->u32_min_value = 0;
5759 		dst_reg->u32_max_value = U32_MAX;
5760 	} else {
5761 		dst_reg->u32_min_value += umin_val;
5762 		dst_reg->u32_max_value += umax_val;
5763 	}
5764 }
5765 
5766 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5767 			       struct bpf_reg_state *src_reg)
5768 {
5769 	s64 smin_val = src_reg->smin_value;
5770 	s64 smax_val = src_reg->smax_value;
5771 	u64 umin_val = src_reg->umin_value;
5772 	u64 umax_val = src_reg->umax_value;
5773 
5774 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5775 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
5776 		dst_reg->smin_value = S64_MIN;
5777 		dst_reg->smax_value = S64_MAX;
5778 	} else {
5779 		dst_reg->smin_value += smin_val;
5780 		dst_reg->smax_value += smax_val;
5781 	}
5782 	if (dst_reg->umin_value + umin_val < umin_val ||
5783 	    dst_reg->umax_value + umax_val < umax_val) {
5784 		dst_reg->umin_value = 0;
5785 		dst_reg->umax_value = U64_MAX;
5786 	} else {
5787 		dst_reg->umin_value += umin_val;
5788 		dst_reg->umax_value += umax_val;
5789 	}
5790 }
5791 
5792 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5793 				 struct bpf_reg_state *src_reg)
5794 {
5795 	s32 smin_val = src_reg->s32_min_value;
5796 	s32 smax_val = src_reg->s32_max_value;
5797 	u32 umin_val = src_reg->u32_min_value;
5798 	u32 umax_val = src_reg->u32_max_value;
5799 
5800 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5801 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5802 		/* Overflow possible, we know nothing */
5803 		dst_reg->s32_min_value = S32_MIN;
5804 		dst_reg->s32_max_value = S32_MAX;
5805 	} else {
5806 		dst_reg->s32_min_value -= smax_val;
5807 		dst_reg->s32_max_value -= smin_val;
5808 	}
5809 	if (dst_reg->u32_min_value < umax_val) {
5810 		/* Overflow possible, we know nothing */
5811 		dst_reg->u32_min_value = 0;
5812 		dst_reg->u32_max_value = U32_MAX;
5813 	} else {
5814 		/* Cannot overflow (as long as bounds are consistent) */
5815 		dst_reg->u32_min_value -= umax_val;
5816 		dst_reg->u32_max_value -= umin_val;
5817 	}
5818 }
5819 
5820 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5821 			       struct bpf_reg_state *src_reg)
5822 {
5823 	s64 smin_val = src_reg->smin_value;
5824 	s64 smax_val = src_reg->smax_value;
5825 	u64 umin_val = src_reg->umin_value;
5826 	u64 umax_val = src_reg->umax_value;
5827 
5828 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5829 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5830 		/* Overflow possible, we know nothing */
5831 		dst_reg->smin_value = S64_MIN;
5832 		dst_reg->smax_value = S64_MAX;
5833 	} else {
5834 		dst_reg->smin_value -= smax_val;
5835 		dst_reg->smax_value -= smin_val;
5836 	}
5837 	if (dst_reg->umin_value < umax_val) {
5838 		/* Overflow possible, we know nothing */
5839 		dst_reg->umin_value = 0;
5840 		dst_reg->umax_value = U64_MAX;
5841 	} else {
5842 		/* Cannot overflow (as long as bounds are consistent) */
5843 		dst_reg->umin_value -= umax_val;
5844 		dst_reg->umax_value -= umin_val;
5845 	}
5846 }
5847 
5848 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5849 				 struct bpf_reg_state *src_reg)
5850 {
5851 	s32 smin_val = src_reg->s32_min_value;
5852 	u32 umin_val = src_reg->u32_min_value;
5853 	u32 umax_val = src_reg->u32_max_value;
5854 
5855 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5856 		/* Ain't nobody got time to multiply that sign */
5857 		__mark_reg32_unbounded(dst_reg);
5858 		return;
5859 	}
5860 	/* Both values are positive, so we can work with unsigned and
5861 	 * copy the result to signed (unless it exceeds S32_MAX).
5862 	 */
5863 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5864 		/* Potential overflow, we know nothing */
5865 		__mark_reg32_unbounded(dst_reg);
5866 		return;
5867 	}
5868 	dst_reg->u32_min_value *= umin_val;
5869 	dst_reg->u32_max_value *= umax_val;
5870 	if (dst_reg->u32_max_value > S32_MAX) {
5871 		/* Overflow possible, we know nothing */
5872 		dst_reg->s32_min_value = S32_MIN;
5873 		dst_reg->s32_max_value = S32_MAX;
5874 	} else {
5875 		dst_reg->s32_min_value = dst_reg->u32_min_value;
5876 		dst_reg->s32_max_value = dst_reg->u32_max_value;
5877 	}
5878 }
5879 
5880 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5881 			       struct bpf_reg_state *src_reg)
5882 {
5883 	s64 smin_val = src_reg->smin_value;
5884 	u64 umin_val = src_reg->umin_value;
5885 	u64 umax_val = src_reg->umax_value;
5886 
5887 	if (smin_val < 0 || dst_reg->smin_value < 0) {
5888 		/* Ain't nobody got time to multiply that sign */
5889 		__mark_reg64_unbounded(dst_reg);
5890 		return;
5891 	}
5892 	/* Both values are positive, so we can work with unsigned and
5893 	 * copy the result to signed (unless it exceeds S64_MAX).
5894 	 */
5895 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5896 		/* Potential overflow, we know nothing */
5897 		__mark_reg64_unbounded(dst_reg);
5898 		return;
5899 	}
5900 	dst_reg->umin_value *= umin_val;
5901 	dst_reg->umax_value *= umax_val;
5902 	if (dst_reg->umax_value > S64_MAX) {
5903 		/* Overflow possible, we know nothing */
5904 		dst_reg->smin_value = S64_MIN;
5905 		dst_reg->smax_value = S64_MAX;
5906 	} else {
5907 		dst_reg->smin_value = dst_reg->umin_value;
5908 		dst_reg->smax_value = dst_reg->umax_value;
5909 	}
5910 }
5911 
5912 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5913 				 struct bpf_reg_state *src_reg)
5914 {
5915 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
5916 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5917 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5918 	s32 smin_val = src_reg->s32_min_value;
5919 	u32 umax_val = src_reg->u32_max_value;
5920 
5921 	/* Assuming scalar64_min_max_and will be called so its safe
5922 	 * to skip updating register for known 32-bit case.
5923 	 */
5924 	if (src_known && dst_known)
5925 		return;
5926 
5927 	/* We get our minimum from the var_off, since that's inherently
5928 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
5929 	 */
5930 	dst_reg->u32_min_value = var32_off.value;
5931 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5932 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5933 		/* Lose signed bounds when ANDing negative numbers,
5934 		 * ain't nobody got time for that.
5935 		 */
5936 		dst_reg->s32_min_value = S32_MIN;
5937 		dst_reg->s32_max_value = S32_MAX;
5938 	} else {
5939 		/* ANDing two positives gives a positive, so safe to
5940 		 * cast result into s64.
5941 		 */
5942 		dst_reg->s32_min_value = dst_reg->u32_min_value;
5943 		dst_reg->s32_max_value = dst_reg->u32_max_value;
5944 	}
5945 
5946 }
5947 
5948 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5949 			       struct bpf_reg_state *src_reg)
5950 {
5951 	bool src_known = tnum_is_const(src_reg->var_off);
5952 	bool dst_known = tnum_is_const(dst_reg->var_off);
5953 	s64 smin_val = src_reg->smin_value;
5954 	u64 umax_val = src_reg->umax_value;
5955 
5956 	if (src_known && dst_known) {
5957 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
5958 		return;
5959 	}
5960 
5961 	/* We get our minimum from the var_off, since that's inherently
5962 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
5963 	 */
5964 	dst_reg->umin_value = dst_reg->var_off.value;
5965 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5966 	if (dst_reg->smin_value < 0 || smin_val < 0) {
5967 		/* Lose signed bounds when ANDing negative numbers,
5968 		 * ain't nobody got time for that.
5969 		 */
5970 		dst_reg->smin_value = S64_MIN;
5971 		dst_reg->smax_value = S64_MAX;
5972 	} else {
5973 		/* ANDing two positives gives a positive, so safe to
5974 		 * cast result into s64.
5975 		 */
5976 		dst_reg->smin_value = dst_reg->umin_value;
5977 		dst_reg->smax_value = dst_reg->umax_value;
5978 	}
5979 	/* We may learn something more from the var_off */
5980 	__update_reg_bounds(dst_reg);
5981 }
5982 
5983 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5984 				struct bpf_reg_state *src_reg)
5985 {
5986 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
5987 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5988 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5989 	s32 smin_val = src_reg->s32_min_value;
5990 	u32 umin_val = src_reg->u32_min_value;
5991 
5992 	/* Assuming scalar64_min_max_or will be called so it is safe
5993 	 * to skip updating register for known case.
5994 	 */
5995 	if (src_known && dst_known)
5996 		return;
5997 
5998 	/* We get our maximum from the var_off, and our minimum is the
5999 	 * maximum of the operands' minima
6000 	 */
6001 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6002 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6003 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6004 		/* Lose signed bounds when ORing negative numbers,
6005 		 * ain't nobody got time for that.
6006 		 */
6007 		dst_reg->s32_min_value = S32_MIN;
6008 		dst_reg->s32_max_value = S32_MAX;
6009 	} else {
6010 		/* ORing two positives gives a positive, so safe to
6011 		 * cast result into s64.
6012 		 */
6013 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6014 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6015 	}
6016 }
6017 
6018 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6019 			      struct bpf_reg_state *src_reg)
6020 {
6021 	bool src_known = tnum_is_const(src_reg->var_off);
6022 	bool dst_known = tnum_is_const(dst_reg->var_off);
6023 	s64 smin_val = src_reg->smin_value;
6024 	u64 umin_val = src_reg->umin_value;
6025 
6026 	if (src_known && dst_known) {
6027 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6028 		return;
6029 	}
6030 
6031 	/* We get our maximum from the var_off, and our minimum is the
6032 	 * maximum of the operands' minima
6033 	 */
6034 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6035 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6036 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6037 		/* Lose signed bounds when ORing negative numbers,
6038 		 * ain't nobody got time for that.
6039 		 */
6040 		dst_reg->smin_value = S64_MIN;
6041 		dst_reg->smax_value = S64_MAX;
6042 	} else {
6043 		/* ORing two positives gives a positive, so safe to
6044 		 * cast result into s64.
6045 		 */
6046 		dst_reg->smin_value = dst_reg->umin_value;
6047 		dst_reg->smax_value = dst_reg->umax_value;
6048 	}
6049 	/* We may learn something more from the var_off */
6050 	__update_reg_bounds(dst_reg);
6051 }
6052 
6053 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6054 				 struct bpf_reg_state *src_reg)
6055 {
6056 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6057 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6058 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6059 	s32 smin_val = src_reg->s32_min_value;
6060 
6061 	/* Assuming scalar64_min_max_xor will be called so it is safe
6062 	 * to skip updating register for known case.
6063 	 */
6064 	if (src_known && dst_known)
6065 		return;
6066 
6067 	/* We get both minimum and maximum from the var32_off. */
6068 	dst_reg->u32_min_value = var32_off.value;
6069 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6070 
6071 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6072 		/* XORing two positive sign numbers gives a positive,
6073 		 * so safe to cast u32 result into s32.
6074 		 */
6075 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6076 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6077 	} else {
6078 		dst_reg->s32_min_value = S32_MIN;
6079 		dst_reg->s32_max_value = S32_MAX;
6080 	}
6081 }
6082 
6083 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6084 			       struct bpf_reg_state *src_reg)
6085 {
6086 	bool src_known = tnum_is_const(src_reg->var_off);
6087 	bool dst_known = tnum_is_const(dst_reg->var_off);
6088 	s64 smin_val = src_reg->smin_value;
6089 
6090 	if (src_known && dst_known) {
6091 		/* dst_reg->var_off.value has been updated earlier */
6092 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6093 		return;
6094 	}
6095 
6096 	/* We get both minimum and maximum from the var_off. */
6097 	dst_reg->umin_value = dst_reg->var_off.value;
6098 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6099 
6100 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6101 		/* XORing two positive sign numbers gives a positive,
6102 		 * so safe to cast u64 result into s64.
6103 		 */
6104 		dst_reg->smin_value = dst_reg->umin_value;
6105 		dst_reg->smax_value = dst_reg->umax_value;
6106 	} else {
6107 		dst_reg->smin_value = S64_MIN;
6108 		dst_reg->smax_value = S64_MAX;
6109 	}
6110 
6111 	__update_reg_bounds(dst_reg);
6112 }
6113 
6114 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6115 				   u64 umin_val, u64 umax_val)
6116 {
6117 	/* We lose all sign bit information (except what we can pick
6118 	 * up from var_off)
6119 	 */
6120 	dst_reg->s32_min_value = S32_MIN;
6121 	dst_reg->s32_max_value = S32_MAX;
6122 	/* If we might shift our top bit out, then we know nothing */
6123 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6124 		dst_reg->u32_min_value = 0;
6125 		dst_reg->u32_max_value = U32_MAX;
6126 	} else {
6127 		dst_reg->u32_min_value <<= umin_val;
6128 		dst_reg->u32_max_value <<= umax_val;
6129 	}
6130 }
6131 
6132 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6133 				 struct bpf_reg_state *src_reg)
6134 {
6135 	u32 umax_val = src_reg->u32_max_value;
6136 	u32 umin_val = src_reg->u32_min_value;
6137 	/* u32 alu operation will zext upper bits */
6138 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6139 
6140 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6141 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6142 	/* Not required but being careful mark reg64 bounds as unknown so
6143 	 * that we are forced to pick them up from tnum and zext later and
6144 	 * if some path skips this step we are still safe.
6145 	 */
6146 	__mark_reg64_unbounded(dst_reg);
6147 	__update_reg32_bounds(dst_reg);
6148 }
6149 
6150 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6151 				   u64 umin_val, u64 umax_val)
6152 {
6153 	/* Special case <<32 because it is a common compiler pattern to sign
6154 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6155 	 * positive we know this shift will also be positive so we can track
6156 	 * bounds correctly. Otherwise we lose all sign bit information except
6157 	 * what we can pick up from var_off. Perhaps we can generalize this
6158 	 * later to shifts of any length.
6159 	 */
6160 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6161 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6162 	else
6163 		dst_reg->smax_value = S64_MAX;
6164 
6165 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6166 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6167 	else
6168 		dst_reg->smin_value = S64_MIN;
6169 
6170 	/* If we might shift our top bit out, then we know nothing */
6171 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6172 		dst_reg->umin_value = 0;
6173 		dst_reg->umax_value = U64_MAX;
6174 	} else {
6175 		dst_reg->umin_value <<= umin_val;
6176 		dst_reg->umax_value <<= umax_val;
6177 	}
6178 }
6179 
6180 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6181 			       struct bpf_reg_state *src_reg)
6182 {
6183 	u64 umax_val = src_reg->umax_value;
6184 	u64 umin_val = src_reg->umin_value;
6185 
6186 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6187 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6188 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6189 
6190 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6191 	/* We may learn something more from the var_off */
6192 	__update_reg_bounds(dst_reg);
6193 }
6194 
6195 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6196 				 struct bpf_reg_state *src_reg)
6197 {
6198 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6199 	u32 umax_val = src_reg->u32_max_value;
6200 	u32 umin_val = src_reg->u32_min_value;
6201 
6202 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6203 	 * be negative, then either:
6204 	 * 1) src_reg might be zero, so the sign bit of the result is
6205 	 *    unknown, so we lose our signed bounds
6206 	 * 2) it's known negative, thus the unsigned bounds capture the
6207 	 *    signed bounds
6208 	 * 3) the signed bounds cross zero, so they tell us nothing
6209 	 *    about the result
6210 	 * If the value in dst_reg is known nonnegative, then again the
6211 	 * unsigned bounts capture the signed bounds.
6212 	 * Thus, in all cases it suffices to blow away our signed bounds
6213 	 * and rely on inferring new ones from the unsigned bounds and
6214 	 * var_off of the result.
6215 	 */
6216 	dst_reg->s32_min_value = S32_MIN;
6217 	dst_reg->s32_max_value = S32_MAX;
6218 
6219 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6220 	dst_reg->u32_min_value >>= umax_val;
6221 	dst_reg->u32_max_value >>= umin_val;
6222 
6223 	__mark_reg64_unbounded(dst_reg);
6224 	__update_reg32_bounds(dst_reg);
6225 }
6226 
6227 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6228 			       struct bpf_reg_state *src_reg)
6229 {
6230 	u64 umax_val = src_reg->umax_value;
6231 	u64 umin_val = src_reg->umin_value;
6232 
6233 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6234 	 * be negative, then either:
6235 	 * 1) src_reg might be zero, so the sign bit of the result is
6236 	 *    unknown, so we lose our signed bounds
6237 	 * 2) it's known negative, thus the unsigned bounds capture the
6238 	 *    signed bounds
6239 	 * 3) the signed bounds cross zero, so they tell us nothing
6240 	 *    about the result
6241 	 * If the value in dst_reg is known nonnegative, then again the
6242 	 * unsigned bounts capture the signed bounds.
6243 	 * Thus, in all cases it suffices to blow away our signed bounds
6244 	 * and rely on inferring new ones from the unsigned bounds and
6245 	 * var_off of the result.
6246 	 */
6247 	dst_reg->smin_value = S64_MIN;
6248 	dst_reg->smax_value = S64_MAX;
6249 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6250 	dst_reg->umin_value >>= umax_val;
6251 	dst_reg->umax_value >>= umin_val;
6252 
6253 	/* Its not easy to operate on alu32 bounds here because it depends
6254 	 * on bits being shifted in. Take easy way out and mark unbounded
6255 	 * so we can recalculate later from tnum.
6256 	 */
6257 	__mark_reg32_unbounded(dst_reg);
6258 	__update_reg_bounds(dst_reg);
6259 }
6260 
6261 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6262 				  struct bpf_reg_state *src_reg)
6263 {
6264 	u64 umin_val = src_reg->u32_min_value;
6265 
6266 	/* Upon reaching here, src_known is true and
6267 	 * umax_val is equal to umin_val.
6268 	 */
6269 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6270 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6271 
6272 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6273 
6274 	/* blow away the dst_reg umin_value/umax_value and rely on
6275 	 * dst_reg var_off to refine the result.
6276 	 */
6277 	dst_reg->u32_min_value = 0;
6278 	dst_reg->u32_max_value = U32_MAX;
6279 
6280 	__mark_reg64_unbounded(dst_reg);
6281 	__update_reg32_bounds(dst_reg);
6282 }
6283 
6284 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6285 				struct bpf_reg_state *src_reg)
6286 {
6287 	u64 umin_val = src_reg->umin_value;
6288 
6289 	/* Upon reaching here, src_known is true and umax_val is equal
6290 	 * to umin_val.
6291 	 */
6292 	dst_reg->smin_value >>= umin_val;
6293 	dst_reg->smax_value >>= umin_val;
6294 
6295 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6296 
6297 	/* blow away the dst_reg umin_value/umax_value and rely on
6298 	 * dst_reg var_off to refine the result.
6299 	 */
6300 	dst_reg->umin_value = 0;
6301 	dst_reg->umax_value = U64_MAX;
6302 
6303 	/* Its not easy to operate on alu32 bounds here because it depends
6304 	 * on bits being shifted in from upper 32-bits. Take easy way out
6305 	 * and mark unbounded so we can recalculate later from tnum.
6306 	 */
6307 	__mark_reg32_unbounded(dst_reg);
6308 	__update_reg_bounds(dst_reg);
6309 }
6310 
6311 /* WARNING: This function does calculations on 64-bit values, but the actual
6312  * execution may occur on 32-bit values. Therefore, things like bitshifts
6313  * need extra checks in the 32-bit case.
6314  */
6315 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6316 				      struct bpf_insn *insn,
6317 				      struct bpf_reg_state *dst_reg,
6318 				      struct bpf_reg_state src_reg)
6319 {
6320 	struct bpf_reg_state *regs = cur_regs(env);
6321 	u8 opcode = BPF_OP(insn->code);
6322 	bool src_known;
6323 	s64 smin_val, smax_val;
6324 	u64 umin_val, umax_val;
6325 	s32 s32_min_val, s32_max_val;
6326 	u32 u32_min_val, u32_max_val;
6327 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6328 	u32 dst = insn->dst_reg;
6329 	int ret;
6330 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6331 
6332 	smin_val = src_reg.smin_value;
6333 	smax_val = src_reg.smax_value;
6334 	umin_val = src_reg.umin_value;
6335 	umax_val = src_reg.umax_value;
6336 
6337 	s32_min_val = src_reg.s32_min_value;
6338 	s32_max_val = src_reg.s32_max_value;
6339 	u32_min_val = src_reg.u32_min_value;
6340 	u32_max_val = src_reg.u32_max_value;
6341 
6342 	if (alu32) {
6343 		src_known = tnum_subreg_is_const(src_reg.var_off);
6344 		if ((src_known &&
6345 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6346 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6347 			/* Taint dst register if offset had invalid bounds
6348 			 * derived from e.g. dead branches.
6349 			 */
6350 			__mark_reg_unknown(env, dst_reg);
6351 			return 0;
6352 		}
6353 	} else {
6354 		src_known = tnum_is_const(src_reg.var_off);
6355 		if ((src_known &&
6356 		     (smin_val != smax_val || umin_val != umax_val)) ||
6357 		    smin_val > smax_val || umin_val > umax_val) {
6358 			/* Taint dst register if offset had invalid bounds
6359 			 * derived from e.g. dead branches.
6360 			 */
6361 			__mark_reg_unknown(env, dst_reg);
6362 			return 0;
6363 		}
6364 	}
6365 
6366 	if (!src_known &&
6367 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6368 		__mark_reg_unknown(env, dst_reg);
6369 		return 0;
6370 	}
6371 
6372 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6373 	 * There are two classes of instructions: The first class we track both
6374 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
6375 	 * greatest amount of precision when alu operations are mixed with jmp32
6376 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6377 	 * and BPF_OR. This is possible because these ops have fairly easy to
6378 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6379 	 * See alu32 verifier tests for examples. The second class of
6380 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6381 	 * with regards to tracking sign/unsigned bounds because the bits may
6382 	 * cross subreg boundaries in the alu64 case. When this happens we mark
6383 	 * the reg unbounded in the subreg bound space and use the resulting
6384 	 * tnum to calculate an approximation of the sign/unsigned bounds.
6385 	 */
6386 	switch (opcode) {
6387 	case BPF_ADD:
6388 		ret = sanitize_val_alu(env, insn);
6389 		if (ret < 0) {
6390 			verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6391 			return ret;
6392 		}
6393 		scalar32_min_max_add(dst_reg, &src_reg);
6394 		scalar_min_max_add(dst_reg, &src_reg);
6395 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6396 		break;
6397 	case BPF_SUB:
6398 		ret = sanitize_val_alu(env, insn);
6399 		if (ret < 0) {
6400 			verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6401 			return ret;
6402 		}
6403 		scalar32_min_max_sub(dst_reg, &src_reg);
6404 		scalar_min_max_sub(dst_reg, &src_reg);
6405 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6406 		break;
6407 	case BPF_MUL:
6408 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6409 		scalar32_min_max_mul(dst_reg, &src_reg);
6410 		scalar_min_max_mul(dst_reg, &src_reg);
6411 		break;
6412 	case BPF_AND:
6413 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6414 		scalar32_min_max_and(dst_reg, &src_reg);
6415 		scalar_min_max_and(dst_reg, &src_reg);
6416 		break;
6417 	case BPF_OR:
6418 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6419 		scalar32_min_max_or(dst_reg, &src_reg);
6420 		scalar_min_max_or(dst_reg, &src_reg);
6421 		break;
6422 	case BPF_XOR:
6423 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6424 		scalar32_min_max_xor(dst_reg, &src_reg);
6425 		scalar_min_max_xor(dst_reg, &src_reg);
6426 		break;
6427 	case BPF_LSH:
6428 		if (umax_val >= insn_bitness) {
6429 			/* Shifts greater than 31 or 63 are undefined.
6430 			 * This includes shifts by a negative number.
6431 			 */
6432 			mark_reg_unknown(env, regs, insn->dst_reg);
6433 			break;
6434 		}
6435 		if (alu32)
6436 			scalar32_min_max_lsh(dst_reg, &src_reg);
6437 		else
6438 			scalar_min_max_lsh(dst_reg, &src_reg);
6439 		break;
6440 	case BPF_RSH:
6441 		if (umax_val >= insn_bitness) {
6442 			/* Shifts greater than 31 or 63 are undefined.
6443 			 * This includes shifts by a negative number.
6444 			 */
6445 			mark_reg_unknown(env, regs, insn->dst_reg);
6446 			break;
6447 		}
6448 		if (alu32)
6449 			scalar32_min_max_rsh(dst_reg, &src_reg);
6450 		else
6451 			scalar_min_max_rsh(dst_reg, &src_reg);
6452 		break;
6453 	case BPF_ARSH:
6454 		if (umax_val >= insn_bitness) {
6455 			/* Shifts greater than 31 or 63 are undefined.
6456 			 * This includes shifts by a negative number.
6457 			 */
6458 			mark_reg_unknown(env, regs, insn->dst_reg);
6459 			break;
6460 		}
6461 		if (alu32)
6462 			scalar32_min_max_arsh(dst_reg, &src_reg);
6463 		else
6464 			scalar_min_max_arsh(dst_reg, &src_reg);
6465 		break;
6466 	default:
6467 		mark_reg_unknown(env, regs, insn->dst_reg);
6468 		break;
6469 	}
6470 
6471 	/* ALU32 ops are zero extended into 64bit register */
6472 	if (alu32)
6473 		zext_32_to_64(dst_reg);
6474 
6475 	__update_reg_bounds(dst_reg);
6476 	__reg_deduce_bounds(dst_reg);
6477 	__reg_bound_offset(dst_reg);
6478 	return 0;
6479 }
6480 
6481 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6482  * and var_off.
6483  */
6484 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6485 				   struct bpf_insn *insn)
6486 {
6487 	struct bpf_verifier_state *vstate = env->cur_state;
6488 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6489 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
6490 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6491 	u8 opcode = BPF_OP(insn->code);
6492 	int err;
6493 
6494 	dst_reg = &regs[insn->dst_reg];
6495 	src_reg = NULL;
6496 	if (dst_reg->type != SCALAR_VALUE)
6497 		ptr_reg = dst_reg;
6498 	else
6499 		/* Make sure ID is cleared otherwise dst_reg min/max could be
6500 		 * incorrectly propagated into other registers by find_equal_scalars()
6501 		 */
6502 		dst_reg->id = 0;
6503 	if (BPF_SRC(insn->code) == BPF_X) {
6504 		src_reg = &regs[insn->src_reg];
6505 		if (src_reg->type != SCALAR_VALUE) {
6506 			if (dst_reg->type != SCALAR_VALUE) {
6507 				/* Combining two pointers by any ALU op yields
6508 				 * an arbitrary scalar. Disallow all math except
6509 				 * pointer subtraction
6510 				 */
6511 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6512 					mark_reg_unknown(env, regs, insn->dst_reg);
6513 					return 0;
6514 				}
6515 				verbose(env, "R%d pointer %s pointer prohibited\n",
6516 					insn->dst_reg,
6517 					bpf_alu_string[opcode >> 4]);
6518 				return -EACCES;
6519 			} else {
6520 				/* scalar += pointer
6521 				 * This is legal, but we have to reverse our
6522 				 * src/dest handling in computing the range
6523 				 */
6524 				err = mark_chain_precision(env, insn->dst_reg);
6525 				if (err)
6526 					return err;
6527 				return adjust_ptr_min_max_vals(env, insn,
6528 							       src_reg, dst_reg);
6529 			}
6530 		} else if (ptr_reg) {
6531 			/* pointer += scalar */
6532 			err = mark_chain_precision(env, insn->src_reg);
6533 			if (err)
6534 				return err;
6535 			return adjust_ptr_min_max_vals(env, insn,
6536 						       dst_reg, src_reg);
6537 		}
6538 	} else {
6539 		/* Pretend the src is a reg with a known value, since we only
6540 		 * need to be able to read from this state.
6541 		 */
6542 		off_reg.type = SCALAR_VALUE;
6543 		__mark_reg_known(&off_reg, insn->imm);
6544 		src_reg = &off_reg;
6545 		if (ptr_reg) /* pointer += K */
6546 			return adjust_ptr_min_max_vals(env, insn,
6547 						       ptr_reg, src_reg);
6548 	}
6549 
6550 	/* Got here implies adding two SCALAR_VALUEs */
6551 	if (WARN_ON_ONCE(ptr_reg)) {
6552 		print_verifier_state(env, state);
6553 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
6554 		return -EINVAL;
6555 	}
6556 	if (WARN_ON(!src_reg)) {
6557 		print_verifier_state(env, state);
6558 		verbose(env, "verifier internal error: no src_reg\n");
6559 		return -EINVAL;
6560 	}
6561 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
6562 }
6563 
6564 /* check validity of 32-bit and 64-bit arithmetic operations */
6565 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
6566 {
6567 	struct bpf_reg_state *regs = cur_regs(env);
6568 	u8 opcode = BPF_OP(insn->code);
6569 	int err;
6570 
6571 	if (opcode == BPF_END || opcode == BPF_NEG) {
6572 		if (opcode == BPF_NEG) {
6573 			if (BPF_SRC(insn->code) != 0 ||
6574 			    insn->src_reg != BPF_REG_0 ||
6575 			    insn->off != 0 || insn->imm != 0) {
6576 				verbose(env, "BPF_NEG uses reserved fields\n");
6577 				return -EINVAL;
6578 			}
6579 		} else {
6580 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
6581 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6582 			    BPF_CLASS(insn->code) == BPF_ALU64) {
6583 				verbose(env, "BPF_END uses reserved fields\n");
6584 				return -EINVAL;
6585 			}
6586 		}
6587 
6588 		/* check src operand */
6589 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6590 		if (err)
6591 			return err;
6592 
6593 		if (is_pointer_value(env, insn->dst_reg)) {
6594 			verbose(env, "R%d pointer arithmetic prohibited\n",
6595 				insn->dst_reg);
6596 			return -EACCES;
6597 		}
6598 
6599 		/* check dest operand */
6600 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
6601 		if (err)
6602 			return err;
6603 
6604 	} else if (opcode == BPF_MOV) {
6605 
6606 		if (BPF_SRC(insn->code) == BPF_X) {
6607 			if (insn->imm != 0 || insn->off != 0) {
6608 				verbose(env, "BPF_MOV uses reserved fields\n");
6609 				return -EINVAL;
6610 			}
6611 
6612 			/* check src operand */
6613 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
6614 			if (err)
6615 				return err;
6616 		} else {
6617 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6618 				verbose(env, "BPF_MOV uses reserved fields\n");
6619 				return -EINVAL;
6620 			}
6621 		}
6622 
6623 		/* check dest operand, mark as required later */
6624 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6625 		if (err)
6626 			return err;
6627 
6628 		if (BPF_SRC(insn->code) == BPF_X) {
6629 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
6630 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6631 
6632 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
6633 				/* case: R1 = R2
6634 				 * copy register state to dest reg
6635 				 */
6636 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
6637 					/* Assign src and dst registers the same ID
6638 					 * that will be used by find_equal_scalars()
6639 					 * to propagate min/max range.
6640 					 */
6641 					src_reg->id = ++env->id_gen;
6642 				*dst_reg = *src_reg;
6643 				dst_reg->live |= REG_LIVE_WRITTEN;
6644 				dst_reg->subreg_def = DEF_NOT_SUBREG;
6645 			} else {
6646 				/* R1 = (u32) R2 */
6647 				if (is_pointer_value(env, insn->src_reg)) {
6648 					verbose(env,
6649 						"R%d partial copy of pointer\n",
6650 						insn->src_reg);
6651 					return -EACCES;
6652 				} else if (src_reg->type == SCALAR_VALUE) {
6653 					*dst_reg = *src_reg;
6654 					/* Make sure ID is cleared otherwise
6655 					 * dst_reg min/max could be incorrectly
6656 					 * propagated into src_reg by find_equal_scalars()
6657 					 */
6658 					dst_reg->id = 0;
6659 					dst_reg->live |= REG_LIVE_WRITTEN;
6660 					dst_reg->subreg_def = env->insn_idx + 1;
6661 				} else {
6662 					mark_reg_unknown(env, regs,
6663 							 insn->dst_reg);
6664 				}
6665 				zext_32_to_64(dst_reg);
6666 			}
6667 		} else {
6668 			/* case: R = imm
6669 			 * remember the value we stored into this reg
6670 			 */
6671 			/* clear any state __mark_reg_known doesn't set */
6672 			mark_reg_unknown(env, regs, insn->dst_reg);
6673 			regs[insn->dst_reg].type = SCALAR_VALUE;
6674 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
6675 				__mark_reg_known(regs + insn->dst_reg,
6676 						 insn->imm);
6677 			} else {
6678 				__mark_reg_known(regs + insn->dst_reg,
6679 						 (u32)insn->imm);
6680 			}
6681 		}
6682 
6683 	} else if (opcode > BPF_END) {
6684 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
6685 		return -EINVAL;
6686 
6687 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
6688 
6689 		if (BPF_SRC(insn->code) == BPF_X) {
6690 			if (insn->imm != 0 || insn->off != 0) {
6691 				verbose(env, "BPF_ALU uses reserved fields\n");
6692 				return -EINVAL;
6693 			}
6694 			/* check src1 operand */
6695 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
6696 			if (err)
6697 				return err;
6698 		} else {
6699 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6700 				verbose(env, "BPF_ALU uses reserved fields\n");
6701 				return -EINVAL;
6702 			}
6703 		}
6704 
6705 		/* check src2 operand */
6706 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6707 		if (err)
6708 			return err;
6709 
6710 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6711 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
6712 			verbose(env, "div by zero\n");
6713 			return -EINVAL;
6714 		}
6715 
6716 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6717 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6718 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6719 
6720 			if (insn->imm < 0 || insn->imm >= size) {
6721 				verbose(env, "invalid shift %d\n", insn->imm);
6722 				return -EINVAL;
6723 			}
6724 		}
6725 
6726 		/* check dest operand */
6727 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6728 		if (err)
6729 			return err;
6730 
6731 		return adjust_reg_min_max_vals(env, insn);
6732 	}
6733 
6734 	return 0;
6735 }
6736 
6737 static void __find_good_pkt_pointers(struct bpf_func_state *state,
6738 				     struct bpf_reg_state *dst_reg,
6739 				     enum bpf_reg_type type, int new_range)
6740 {
6741 	struct bpf_reg_state *reg;
6742 	int i;
6743 
6744 	for (i = 0; i < MAX_BPF_REG; i++) {
6745 		reg = &state->regs[i];
6746 		if (reg->type == type && reg->id == dst_reg->id)
6747 			/* keep the maximum range already checked */
6748 			reg->range = max(reg->range, new_range);
6749 	}
6750 
6751 	bpf_for_each_spilled_reg(i, state, reg) {
6752 		if (!reg)
6753 			continue;
6754 		if (reg->type == type && reg->id == dst_reg->id)
6755 			reg->range = max(reg->range, new_range);
6756 	}
6757 }
6758 
6759 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
6760 				   struct bpf_reg_state *dst_reg,
6761 				   enum bpf_reg_type type,
6762 				   bool range_right_open)
6763 {
6764 	int new_range, i;
6765 
6766 	if (dst_reg->off < 0 ||
6767 	    (dst_reg->off == 0 && range_right_open))
6768 		/* This doesn't give us any range */
6769 		return;
6770 
6771 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
6772 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
6773 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
6774 		 * than pkt_end, but that's because it's also less than pkt.
6775 		 */
6776 		return;
6777 
6778 	new_range = dst_reg->off;
6779 	if (range_right_open)
6780 		new_range--;
6781 
6782 	/* Examples for register markings:
6783 	 *
6784 	 * pkt_data in dst register:
6785 	 *
6786 	 *   r2 = r3;
6787 	 *   r2 += 8;
6788 	 *   if (r2 > pkt_end) goto <handle exception>
6789 	 *   <access okay>
6790 	 *
6791 	 *   r2 = r3;
6792 	 *   r2 += 8;
6793 	 *   if (r2 < pkt_end) goto <access okay>
6794 	 *   <handle exception>
6795 	 *
6796 	 *   Where:
6797 	 *     r2 == dst_reg, pkt_end == src_reg
6798 	 *     r2=pkt(id=n,off=8,r=0)
6799 	 *     r3=pkt(id=n,off=0,r=0)
6800 	 *
6801 	 * pkt_data in src register:
6802 	 *
6803 	 *   r2 = r3;
6804 	 *   r2 += 8;
6805 	 *   if (pkt_end >= r2) goto <access okay>
6806 	 *   <handle exception>
6807 	 *
6808 	 *   r2 = r3;
6809 	 *   r2 += 8;
6810 	 *   if (pkt_end <= r2) goto <handle exception>
6811 	 *   <access okay>
6812 	 *
6813 	 *   Where:
6814 	 *     pkt_end == dst_reg, r2 == src_reg
6815 	 *     r2=pkt(id=n,off=8,r=0)
6816 	 *     r3=pkt(id=n,off=0,r=0)
6817 	 *
6818 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6819 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6820 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
6821 	 * the check.
6822 	 */
6823 
6824 	/* If our ids match, then we must have the same max_value.  And we
6825 	 * don't care about the other reg's fixed offset, since if it's too big
6826 	 * the range won't allow anything.
6827 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6828 	 */
6829 	for (i = 0; i <= vstate->curframe; i++)
6830 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6831 					 new_range);
6832 }
6833 
6834 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
6835 {
6836 	struct tnum subreg = tnum_subreg(reg->var_off);
6837 	s32 sval = (s32)val;
6838 
6839 	switch (opcode) {
6840 	case BPF_JEQ:
6841 		if (tnum_is_const(subreg))
6842 			return !!tnum_equals_const(subreg, val);
6843 		break;
6844 	case BPF_JNE:
6845 		if (tnum_is_const(subreg))
6846 			return !tnum_equals_const(subreg, val);
6847 		break;
6848 	case BPF_JSET:
6849 		if ((~subreg.mask & subreg.value) & val)
6850 			return 1;
6851 		if (!((subreg.mask | subreg.value) & val))
6852 			return 0;
6853 		break;
6854 	case BPF_JGT:
6855 		if (reg->u32_min_value > val)
6856 			return 1;
6857 		else if (reg->u32_max_value <= val)
6858 			return 0;
6859 		break;
6860 	case BPF_JSGT:
6861 		if (reg->s32_min_value > sval)
6862 			return 1;
6863 		else if (reg->s32_max_value < sval)
6864 			return 0;
6865 		break;
6866 	case BPF_JLT:
6867 		if (reg->u32_max_value < val)
6868 			return 1;
6869 		else if (reg->u32_min_value >= val)
6870 			return 0;
6871 		break;
6872 	case BPF_JSLT:
6873 		if (reg->s32_max_value < sval)
6874 			return 1;
6875 		else if (reg->s32_min_value >= sval)
6876 			return 0;
6877 		break;
6878 	case BPF_JGE:
6879 		if (reg->u32_min_value >= val)
6880 			return 1;
6881 		else if (reg->u32_max_value < val)
6882 			return 0;
6883 		break;
6884 	case BPF_JSGE:
6885 		if (reg->s32_min_value >= sval)
6886 			return 1;
6887 		else if (reg->s32_max_value < sval)
6888 			return 0;
6889 		break;
6890 	case BPF_JLE:
6891 		if (reg->u32_max_value <= val)
6892 			return 1;
6893 		else if (reg->u32_min_value > val)
6894 			return 0;
6895 		break;
6896 	case BPF_JSLE:
6897 		if (reg->s32_max_value <= sval)
6898 			return 1;
6899 		else if (reg->s32_min_value > sval)
6900 			return 0;
6901 		break;
6902 	}
6903 
6904 	return -1;
6905 }
6906 
6907 
6908 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6909 {
6910 	s64 sval = (s64)val;
6911 
6912 	switch (opcode) {
6913 	case BPF_JEQ:
6914 		if (tnum_is_const(reg->var_off))
6915 			return !!tnum_equals_const(reg->var_off, val);
6916 		break;
6917 	case BPF_JNE:
6918 		if (tnum_is_const(reg->var_off))
6919 			return !tnum_equals_const(reg->var_off, val);
6920 		break;
6921 	case BPF_JSET:
6922 		if ((~reg->var_off.mask & reg->var_off.value) & val)
6923 			return 1;
6924 		if (!((reg->var_off.mask | reg->var_off.value) & val))
6925 			return 0;
6926 		break;
6927 	case BPF_JGT:
6928 		if (reg->umin_value > val)
6929 			return 1;
6930 		else if (reg->umax_value <= val)
6931 			return 0;
6932 		break;
6933 	case BPF_JSGT:
6934 		if (reg->smin_value > sval)
6935 			return 1;
6936 		else if (reg->smax_value < sval)
6937 			return 0;
6938 		break;
6939 	case BPF_JLT:
6940 		if (reg->umax_value < val)
6941 			return 1;
6942 		else if (reg->umin_value >= val)
6943 			return 0;
6944 		break;
6945 	case BPF_JSLT:
6946 		if (reg->smax_value < sval)
6947 			return 1;
6948 		else if (reg->smin_value >= sval)
6949 			return 0;
6950 		break;
6951 	case BPF_JGE:
6952 		if (reg->umin_value >= val)
6953 			return 1;
6954 		else if (reg->umax_value < val)
6955 			return 0;
6956 		break;
6957 	case BPF_JSGE:
6958 		if (reg->smin_value >= sval)
6959 			return 1;
6960 		else if (reg->smax_value < sval)
6961 			return 0;
6962 		break;
6963 	case BPF_JLE:
6964 		if (reg->umax_value <= val)
6965 			return 1;
6966 		else if (reg->umin_value > val)
6967 			return 0;
6968 		break;
6969 	case BPF_JSLE:
6970 		if (reg->smax_value <= sval)
6971 			return 1;
6972 		else if (reg->smin_value > sval)
6973 			return 0;
6974 		break;
6975 	}
6976 
6977 	return -1;
6978 }
6979 
6980 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6981  * and return:
6982  *  1 - branch will be taken and "goto target" will be executed
6983  *  0 - branch will not be taken and fall-through to next insn
6984  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6985  *      range [0,10]
6986  */
6987 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6988 			   bool is_jmp32)
6989 {
6990 	if (__is_pointer_value(false, reg)) {
6991 		if (!reg_type_not_null(reg->type))
6992 			return -1;
6993 
6994 		/* If pointer is valid tests against zero will fail so we can
6995 		 * use this to direct branch taken.
6996 		 */
6997 		if (val != 0)
6998 			return -1;
6999 
7000 		switch (opcode) {
7001 		case BPF_JEQ:
7002 			return 0;
7003 		case BPF_JNE:
7004 			return 1;
7005 		default:
7006 			return -1;
7007 		}
7008 	}
7009 
7010 	if (is_jmp32)
7011 		return is_branch32_taken(reg, val, opcode);
7012 	return is_branch64_taken(reg, val, opcode);
7013 }
7014 
7015 static int flip_opcode(u32 opcode)
7016 {
7017 	/* How can we transform "a <op> b" into "b <op> a"? */
7018 	static const u8 opcode_flip[16] = {
7019 		/* these stay the same */
7020 		[BPF_JEQ  >> 4] = BPF_JEQ,
7021 		[BPF_JNE  >> 4] = BPF_JNE,
7022 		[BPF_JSET >> 4] = BPF_JSET,
7023 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7024 		[BPF_JGE  >> 4] = BPF_JLE,
7025 		[BPF_JGT  >> 4] = BPF_JLT,
7026 		[BPF_JLE  >> 4] = BPF_JGE,
7027 		[BPF_JLT  >> 4] = BPF_JGT,
7028 		[BPF_JSGE >> 4] = BPF_JSLE,
7029 		[BPF_JSGT >> 4] = BPF_JSLT,
7030 		[BPF_JSLE >> 4] = BPF_JSGE,
7031 		[BPF_JSLT >> 4] = BPF_JSGT
7032 	};
7033 	return opcode_flip[opcode >> 4];
7034 }
7035 
7036 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7037 				   struct bpf_reg_state *src_reg,
7038 				   u8 opcode)
7039 {
7040 	struct bpf_reg_state *pkt;
7041 
7042 	if (src_reg->type == PTR_TO_PACKET_END) {
7043 		pkt = dst_reg;
7044 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7045 		pkt = src_reg;
7046 		opcode = flip_opcode(opcode);
7047 	} else {
7048 		return -1;
7049 	}
7050 
7051 	if (pkt->range >= 0)
7052 		return -1;
7053 
7054 	switch (opcode) {
7055 	case BPF_JLE:
7056 		/* pkt <= pkt_end */
7057 		fallthrough;
7058 	case BPF_JGT:
7059 		/* pkt > pkt_end */
7060 		if (pkt->range == BEYOND_PKT_END)
7061 			/* pkt has at last one extra byte beyond pkt_end */
7062 			return opcode == BPF_JGT;
7063 		break;
7064 	case BPF_JLT:
7065 		/* pkt < pkt_end */
7066 		fallthrough;
7067 	case BPF_JGE:
7068 		/* pkt >= pkt_end */
7069 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7070 			return opcode == BPF_JGE;
7071 		break;
7072 	}
7073 	return -1;
7074 }
7075 
7076 /* Adjusts the register min/max values in the case that the dst_reg is the
7077  * variable register that we are working on, and src_reg is a constant or we're
7078  * simply doing a BPF_K check.
7079  * In JEQ/JNE cases we also adjust the var_off values.
7080  */
7081 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7082 			    struct bpf_reg_state *false_reg,
7083 			    u64 val, u32 val32,
7084 			    u8 opcode, bool is_jmp32)
7085 {
7086 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7087 	struct tnum false_64off = false_reg->var_off;
7088 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7089 	struct tnum true_64off = true_reg->var_off;
7090 	s64 sval = (s64)val;
7091 	s32 sval32 = (s32)val32;
7092 
7093 	/* If the dst_reg is a pointer, we can't learn anything about its
7094 	 * variable offset from the compare (unless src_reg were a pointer into
7095 	 * the same object, but we don't bother with that.
7096 	 * Since false_reg and true_reg have the same type by construction, we
7097 	 * only need to check one of them for pointerness.
7098 	 */
7099 	if (__is_pointer_value(false, false_reg))
7100 		return;
7101 
7102 	switch (opcode) {
7103 	case BPF_JEQ:
7104 	case BPF_JNE:
7105 	{
7106 		struct bpf_reg_state *reg =
7107 			opcode == BPF_JEQ ? true_reg : false_reg;
7108 
7109 		/* JEQ/JNE comparison doesn't change the register equivalence.
7110 		 * r1 = r2;
7111 		 * if (r1 == 42) goto label;
7112 		 * ...
7113 		 * label: // here both r1 and r2 are known to be 42.
7114 		 *
7115 		 * Hence when marking register as known preserve it's ID.
7116 		 */
7117 		if (is_jmp32)
7118 			__mark_reg32_known(reg, val32);
7119 		else
7120 			___mark_reg_known(reg, val);
7121 		break;
7122 	}
7123 	case BPF_JSET:
7124 		if (is_jmp32) {
7125 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7126 			if (is_power_of_2(val32))
7127 				true_32off = tnum_or(true_32off,
7128 						     tnum_const(val32));
7129 		} else {
7130 			false_64off = tnum_and(false_64off, tnum_const(~val));
7131 			if (is_power_of_2(val))
7132 				true_64off = tnum_or(true_64off,
7133 						     tnum_const(val));
7134 		}
7135 		break;
7136 	case BPF_JGE:
7137 	case BPF_JGT:
7138 	{
7139 		if (is_jmp32) {
7140 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7141 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7142 
7143 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7144 						       false_umax);
7145 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7146 						      true_umin);
7147 		} else {
7148 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7149 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7150 
7151 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7152 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7153 		}
7154 		break;
7155 	}
7156 	case BPF_JSGE:
7157 	case BPF_JSGT:
7158 	{
7159 		if (is_jmp32) {
7160 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7161 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7162 
7163 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7164 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7165 		} else {
7166 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7167 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7168 
7169 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7170 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7171 		}
7172 		break;
7173 	}
7174 	case BPF_JLE:
7175 	case BPF_JLT:
7176 	{
7177 		if (is_jmp32) {
7178 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7179 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7180 
7181 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7182 						       false_umin);
7183 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7184 						      true_umax);
7185 		} else {
7186 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7187 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7188 
7189 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7190 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7191 		}
7192 		break;
7193 	}
7194 	case BPF_JSLE:
7195 	case BPF_JSLT:
7196 	{
7197 		if (is_jmp32) {
7198 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7199 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7200 
7201 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7202 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7203 		} else {
7204 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7205 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7206 
7207 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7208 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7209 		}
7210 		break;
7211 	}
7212 	default:
7213 		return;
7214 	}
7215 
7216 	if (is_jmp32) {
7217 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7218 					     tnum_subreg(false_32off));
7219 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7220 					    tnum_subreg(true_32off));
7221 		__reg_combine_32_into_64(false_reg);
7222 		__reg_combine_32_into_64(true_reg);
7223 	} else {
7224 		false_reg->var_off = false_64off;
7225 		true_reg->var_off = true_64off;
7226 		__reg_combine_64_into_32(false_reg);
7227 		__reg_combine_64_into_32(true_reg);
7228 	}
7229 }
7230 
7231 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7232  * the variable reg.
7233  */
7234 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7235 				struct bpf_reg_state *false_reg,
7236 				u64 val, u32 val32,
7237 				u8 opcode, bool is_jmp32)
7238 {
7239 	opcode = flip_opcode(opcode);
7240 	/* This uses zero as "not present in table"; luckily the zero opcode,
7241 	 * BPF_JA, can't get here.
7242 	 */
7243 	if (opcode)
7244 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7245 }
7246 
7247 /* Regs are known to be equal, so intersect their min/max/var_off */
7248 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7249 				  struct bpf_reg_state *dst_reg)
7250 {
7251 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7252 							dst_reg->umin_value);
7253 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7254 							dst_reg->umax_value);
7255 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7256 							dst_reg->smin_value);
7257 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7258 							dst_reg->smax_value);
7259 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7260 							     dst_reg->var_off);
7261 	/* We might have learned new bounds from the var_off. */
7262 	__update_reg_bounds(src_reg);
7263 	__update_reg_bounds(dst_reg);
7264 	/* We might have learned something about the sign bit. */
7265 	__reg_deduce_bounds(src_reg);
7266 	__reg_deduce_bounds(dst_reg);
7267 	/* We might have learned some bits from the bounds. */
7268 	__reg_bound_offset(src_reg);
7269 	__reg_bound_offset(dst_reg);
7270 	/* Intersecting with the old var_off might have improved our bounds
7271 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7272 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
7273 	 */
7274 	__update_reg_bounds(src_reg);
7275 	__update_reg_bounds(dst_reg);
7276 }
7277 
7278 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7279 				struct bpf_reg_state *true_dst,
7280 				struct bpf_reg_state *false_src,
7281 				struct bpf_reg_state *false_dst,
7282 				u8 opcode)
7283 {
7284 	switch (opcode) {
7285 	case BPF_JEQ:
7286 		__reg_combine_min_max(true_src, true_dst);
7287 		break;
7288 	case BPF_JNE:
7289 		__reg_combine_min_max(false_src, false_dst);
7290 		break;
7291 	}
7292 }
7293 
7294 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7295 				 struct bpf_reg_state *reg, u32 id,
7296 				 bool is_null)
7297 {
7298 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
7299 	    !WARN_ON_ONCE(!reg->id)) {
7300 		/* Old offset (both fixed and variable parts) should
7301 		 * have been known-zero, because we don't allow pointer
7302 		 * arithmetic on pointers that might be NULL.
7303 		 */
7304 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7305 				 !tnum_equals_const(reg->var_off, 0) ||
7306 				 reg->off)) {
7307 			__mark_reg_known_zero(reg);
7308 			reg->off = 0;
7309 		}
7310 		if (is_null) {
7311 			reg->type = SCALAR_VALUE;
7312 		} else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7313 			const struct bpf_map *map = reg->map_ptr;
7314 
7315 			if (map->inner_map_meta) {
7316 				reg->type = CONST_PTR_TO_MAP;
7317 				reg->map_ptr = map->inner_map_meta;
7318 			} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7319 				reg->type = PTR_TO_XDP_SOCK;
7320 			} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7321 				   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7322 				reg->type = PTR_TO_SOCKET;
7323 			} else {
7324 				reg->type = PTR_TO_MAP_VALUE;
7325 			}
7326 		} else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7327 			reg->type = PTR_TO_SOCKET;
7328 		} else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7329 			reg->type = PTR_TO_SOCK_COMMON;
7330 		} else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7331 			reg->type = PTR_TO_TCP_SOCK;
7332 		} else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7333 			reg->type = PTR_TO_BTF_ID;
7334 		} else if (reg->type == PTR_TO_MEM_OR_NULL) {
7335 			reg->type = PTR_TO_MEM;
7336 		} else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7337 			reg->type = PTR_TO_RDONLY_BUF;
7338 		} else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7339 			reg->type = PTR_TO_RDWR_BUF;
7340 		}
7341 		if (is_null) {
7342 			/* We don't need id and ref_obj_id from this point
7343 			 * onwards anymore, thus we should better reset it,
7344 			 * so that state pruning has chances to take effect.
7345 			 */
7346 			reg->id = 0;
7347 			reg->ref_obj_id = 0;
7348 		} else if (!reg_may_point_to_spin_lock(reg)) {
7349 			/* For not-NULL ptr, reg->ref_obj_id will be reset
7350 			 * in release_reg_references().
7351 			 *
7352 			 * reg->id is still used by spin_lock ptr. Other
7353 			 * than spin_lock ptr type, reg->id can be reset.
7354 			 */
7355 			reg->id = 0;
7356 		}
7357 	}
7358 }
7359 
7360 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7361 				    bool is_null)
7362 {
7363 	struct bpf_reg_state *reg;
7364 	int i;
7365 
7366 	for (i = 0; i < MAX_BPF_REG; i++)
7367 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7368 
7369 	bpf_for_each_spilled_reg(i, state, reg) {
7370 		if (!reg)
7371 			continue;
7372 		mark_ptr_or_null_reg(state, reg, id, is_null);
7373 	}
7374 }
7375 
7376 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7377  * be folded together at some point.
7378  */
7379 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7380 				  bool is_null)
7381 {
7382 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7383 	struct bpf_reg_state *regs = state->regs;
7384 	u32 ref_obj_id = regs[regno].ref_obj_id;
7385 	u32 id = regs[regno].id;
7386 	int i;
7387 
7388 	if (ref_obj_id && ref_obj_id == id && is_null)
7389 		/* regs[regno] is in the " == NULL" branch.
7390 		 * No one could have freed the reference state before
7391 		 * doing the NULL check.
7392 		 */
7393 		WARN_ON_ONCE(release_reference_state(state, id));
7394 
7395 	for (i = 0; i <= vstate->curframe; i++)
7396 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7397 }
7398 
7399 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7400 				   struct bpf_reg_state *dst_reg,
7401 				   struct bpf_reg_state *src_reg,
7402 				   struct bpf_verifier_state *this_branch,
7403 				   struct bpf_verifier_state *other_branch)
7404 {
7405 	if (BPF_SRC(insn->code) != BPF_X)
7406 		return false;
7407 
7408 	/* Pointers are always 64-bit. */
7409 	if (BPF_CLASS(insn->code) == BPF_JMP32)
7410 		return false;
7411 
7412 	switch (BPF_OP(insn->code)) {
7413 	case BPF_JGT:
7414 		if ((dst_reg->type == PTR_TO_PACKET &&
7415 		     src_reg->type == PTR_TO_PACKET_END) ||
7416 		    (dst_reg->type == PTR_TO_PACKET_META &&
7417 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7418 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7419 			find_good_pkt_pointers(this_branch, dst_reg,
7420 					       dst_reg->type, false);
7421 			mark_pkt_end(other_branch, insn->dst_reg, true);
7422 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7423 			    src_reg->type == PTR_TO_PACKET) ||
7424 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7425 			    src_reg->type == PTR_TO_PACKET_META)) {
7426 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
7427 			find_good_pkt_pointers(other_branch, src_reg,
7428 					       src_reg->type, true);
7429 			mark_pkt_end(this_branch, insn->src_reg, false);
7430 		} else {
7431 			return false;
7432 		}
7433 		break;
7434 	case BPF_JLT:
7435 		if ((dst_reg->type == PTR_TO_PACKET &&
7436 		     src_reg->type == PTR_TO_PACKET_END) ||
7437 		    (dst_reg->type == PTR_TO_PACKET_META &&
7438 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7439 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7440 			find_good_pkt_pointers(other_branch, dst_reg,
7441 					       dst_reg->type, true);
7442 			mark_pkt_end(this_branch, insn->dst_reg, false);
7443 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7444 			    src_reg->type == PTR_TO_PACKET) ||
7445 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7446 			    src_reg->type == PTR_TO_PACKET_META)) {
7447 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
7448 			find_good_pkt_pointers(this_branch, src_reg,
7449 					       src_reg->type, false);
7450 			mark_pkt_end(other_branch, insn->src_reg, true);
7451 		} else {
7452 			return false;
7453 		}
7454 		break;
7455 	case BPF_JGE:
7456 		if ((dst_reg->type == PTR_TO_PACKET &&
7457 		     src_reg->type == PTR_TO_PACKET_END) ||
7458 		    (dst_reg->type == PTR_TO_PACKET_META &&
7459 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7460 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7461 			find_good_pkt_pointers(this_branch, dst_reg,
7462 					       dst_reg->type, true);
7463 			mark_pkt_end(other_branch, insn->dst_reg, false);
7464 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7465 			    src_reg->type == PTR_TO_PACKET) ||
7466 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7467 			    src_reg->type == PTR_TO_PACKET_META)) {
7468 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7469 			find_good_pkt_pointers(other_branch, src_reg,
7470 					       src_reg->type, false);
7471 			mark_pkt_end(this_branch, insn->src_reg, true);
7472 		} else {
7473 			return false;
7474 		}
7475 		break;
7476 	case BPF_JLE:
7477 		if ((dst_reg->type == PTR_TO_PACKET &&
7478 		     src_reg->type == PTR_TO_PACKET_END) ||
7479 		    (dst_reg->type == PTR_TO_PACKET_META &&
7480 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7481 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7482 			find_good_pkt_pointers(other_branch, dst_reg,
7483 					       dst_reg->type, false);
7484 			mark_pkt_end(this_branch, insn->dst_reg, true);
7485 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7486 			    src_reg->type == PTR_TO_PACKET) ||
7487 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7488 			    src_reg->type == PTR_TO_PACKET_META)) {
7489 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7490 			find_good_pkt_pointers(this_branch, src_reg,
7491 					       src_reg->type, true);
7492 			mark_pkt_end(other_branch, insn->src_reg, false);
7493 		} else {
7494 			return false;
7495 		}
7496 		break;
7497 	default:
7498 		return false;
7499 	}
7500 
7501 	return true;
7502 }
7503 
7504 static void find_equal_scalars(struct bpf_verifier_state *vstate,
7505 			       struct bpf_reg_state *known_reg)
7506 {
7507 	struct bpf_func_state *state;
7508 	struct bpf_reg_state *reg;
7509 	int i, j;
7510 
7511 	for (i = 0; i <= vstate->curframe; i++) {
7512 		state = vstate->frame[i];
7513 		for (j = 0; j < MAX_BPF_REG; j++) {
7514 			reg = &state->regs[j];
7515 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7516 				*reg = *known_reg;
7517 		}
7518 
7519 		bpf_for_each_spilled_reg(j, state, reg) {
7520 			if (!reg)
7521 				continue;
7522 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7523 				*reg = *known_reg;
7524 		}
7525 	}
7526 }
7527 
7528 static int check_cond_jmp_op(struct bpf_verifier_env *env,
7529 			     struct bpf_insn *insn, int *insn_idx)
7530 {
7531 	struct bpf_verifier_state *this_branch = env->cur_state;
7532 	struct bpf_verifier_state *other_branch;
7533 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
7534 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
7535 	u8 opcode = BPF_OP(insn->code);
7536 	bool is_jmp32;
7537 	int pred = -1;
7538 	int err;
7539 
7540 	/* Only conditional jumps are expected to reach here. */
7541 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
7542 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
7543 		return -EINVAL;
7544 	}
7545 
7546 	if (BPF_SRC(insn->code) == BPF_X) {
7547 		if (insn->imm != 0) {
7548 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
7549 			return -EINVAL;
7550 		}
7551 
7552 		/* check src1 operand */
7553 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
7554 		if (err)
7555 			return err;
7556 
7557 		if (is_pointer_value(env, insn->src_reg)) {
7558 			verbose(env, "R%d pointer comparison prohibited\n",
7559 				insn->src_reg);
7560 			return -EACCES;
7561 		}
7562 		src_reg = &regs[insn->src_reg];
7563 	} else {
7564 		if (insn->src_reg != BPF_REG_0) {
7565 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
7566 			return -EINVAL;
7567 		}
7568 	}
7569 
7570 	/* check src2 operand */
7571 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7572 	if (err)
7573 		return err;
7574 
7575 	dst_reg = &regs[insn->dst_reg];
7576 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
7577 
7578 	if (BPF_SRC(insn->code) == BPF_K) {
7579 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7580 	} else if (src_reg->type == SCALAR_VALUE &&
7581 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7582 		pred = is_branch_taken(dst_reg,
7583 				       tnum_subreg(src_reg->var_off).value,
7584 				       opcode,
7585 				       is_jmp32);
7586 	} else if (src_reg->type == SCALAR_VALUE &&
7587 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7588 		pred = is_branch_taken(dst_reg,
7589 				       src_reg->var_off.value,
7590 				       opcode,
7591 				       is_jmp32);
7592 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
7593 		   reg_is_pkt_pointer_any(src_reg) &&
7594 		   !is_jmp32) {
7595 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
7596 	}
7597 
7598 	if (pred >= 0) {
7599 		/* If we get here with a dst_reg pointer type it is because
7600 		 * above is_branch_taken() special cased the 0 comparison.
7601 		 */
7602 		if (!__is_pointer_value(false, dst_reg))
7603 			err = mark_chain_precision(env, insn->dst_reg);
7604 		if (BPF_SRC(insn->code) == BPF_X && !err &&
7605 		    !__is_pointer_value(false, src_reg))
7606 			err = mark_chain_precision(env, insn->src_reg);
7607 		if (err)
7608 			return err;
7609 	}
7610 	if (pred == 1) {
7611 		/* only follow the goto, ignore fall-through */
7612 		*insn_idx += insn->off;
7613 		return 0;
7614 	} else if (pred == 0) {
7615 		/* only follow fall-through branch, since
7616 		 * that's where the program will go
7617 		 */
7618 		return 0;
7619 	}
7620 
7621 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7622 				  false);
7623 	if (!other_branch)
7624 		return -EFAULT;
7625 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
7626 
7627 	/* detect if we are comparing against a constant value so we can adjust
7628 	 * our min/max values for our dst register.
7629 	 * this is only legit if both are scalars (or pointers to the same
7630 	 * object, I suppose, but we don't support that right now), because
7631 	 * otherwise the different base pointers mean the offsets aren't
7632 	 * comparable.
7633 	 */
7634 	if (BPF_SRC(insn->code) == BPF_X) {
7635 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
7636 
7637 		if (dst_reg->type == SCALAR_VALUE &&
7638 		    src_reg->type == SCALAR_VALUE) {
7639 			if (tnum_is_const(src_reg->var_off) ||
7640 			    (is_jmp32 &&
7641 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
7642 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
7643 						dst_reg,
7644 						src_reg->var_off.value,
7645 						tnum_subreg(src_reg->var_off).value,
7646 						opcode, is_jmp32);
7647 			else if (tnum_is_const(dst_reg->var_off) ||
7648 				 (is_jmp32 &&
7649 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
7650 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
7651 						    src_reg,
7652 						    dst_reg->var_off.value,
7653 						    tnum_subreg(dst_reg->var_off).value,
7654 						    opcode, is_jmp32);
7655 			else if (!is_jmp32 &&
7656 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
7657 				/* Comparing for equality, we can combine knowledge */
7658 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
7659 						    &other_branch_regs[insn->dst_reg],
7660 						    src_reg, dst_reg, opcode);
7661 			if (src_reg->id &&
7662 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
7663 				find_equal_scalars(this_branch, src_reg);
7664 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
7665 			}
7666 
7667 		}
7668 	} else if (dst_reg->type == SCALAR_VALUE) {
7669 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
7670 					dst_reg, insn->imm, (u32)insn->imm,
7671 					opcode, is_jmp32);
7672 	}
7673 
7674 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
7675 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
7676 		find_equal_scalars(this_branch, dst_reg);
7677 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
7678 	}
7679 
7680 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7681 	 * NOTE: these optimizations below are related with pointer comparison
7682 	 *       which will never be JMP32.
7683 	 */
7684 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
7685 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
7686 	    reg_type_may_be_null(dst_reg->type)) {
7687 		/* Mark all identical registers in each branch as either
7688 		 * safe or unknown depending R == 0 or R != 0 conditional.
7689 		 */
7690 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7691 				      opcode == BPF_JNE);
7692 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7693 				      opcode == BPF_JEQ);
7694 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7695 					   this_branch, other_branch) &&
7696 		   is_pointer_value(env, insn->dst_reg)) {
7697 		verbose(env, "R%d pointer comparison prohibited\n",
7698 			insn->dst_reg);
7699 		return -EACCES;
7700 	}
7701 	if (env->log.level & BPF_LOG_LEVEL)
7702 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
7703 	return 0;
7704 }
7705 
7706 /* verify BPF_LD_IMM64 instruction */
7707 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
7708 {
7709 	struct bpf_insn_aux_data *aux = cur_aux(env);
7710 	struct bpf_reg_state *regs = cur_regs(env);
7711 	struct bpf_reg_state *dst_reg;
7712 	struct bpf_map *map;
7713 	int err;
7714 
7715 	if (BPF_SIZE(insn->code) != BPF_DW) {
7716 		verbose(env, "invalid BPF_LD_IMM insn\n");
7717 		return -EINVAL;
7718 	}
7719 	if (insn->off != 0) {
7720 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
7721 		return -EINVAL;
7722 	}
7723 
7724 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
7725 	if (err)
7726 		return err;
7727 
7728 	dst_reg = &regs[insn->dst_reg];
7729 	if (insn->src_reg == 0) {
7730 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7731 
7732 		dst_reg->type = SCALAR_VALUE;
7733 		__mark_reg_known(&regs[insn->dst_reg], imm);
7734 		return 0;
7735 	}
7736 
7737 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
7738 		mark_reg_known_zero(env, regs, insn->dst_reg);
7739 
7740 		dst_reg->type = aux->btf_var.reg_type;
7741 		switch (dst_reg->type) {
7742 		case PTR_TO_MEM:
7743 			dst_reg->mem_size = aux->btf_var.mem_size;
7744 			break;
7745 		case PTR_TO_BTF_ID:
7746 		case PTR_TO_PERCPU_BTF_ID:
7747 			dst_reg->btf_id = aux->btf_var.btf_id;
7748 			break;
7749 		default:
7750 			verbose(env, "bpf verifier is misconfigured\n");
7751 			return -EFAULT;
7752 		}
7753 		return 0;
7754 	}
7755 
7756 	map = env->used_maps[aux->map_index];
7757 	mark_reg_known_zero(env, regs, insn->dst_reg);
7758 	dst_reg->map_ptr = map;
7759 
7760 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7761 		dst_reg->type = PTR_TO_MAP_VALUE;
7762 		dst_reg->off = aux->map_off;
7763 		if (map_value_has_spin_lock(map))
7764 			dst_reg->id = ++env->id_gen;
7765 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7766 		dst_reg->type = CONST_PTR_TO_MAP;
7767 	} else {
7768 		verbose(env, "bpf verifier is misconfigured\n");
7769 		return -EINVAL;
7770 	}
7771 
7772 	return 0;
7773 }
7774 
7775 static bool may_access_skb(enum bpf_prog_type type)
7776 {
7777 	switch (type) {
7778 	case BPF_PROG_TYPE_SOCKET_FILTER:
7779 	case BPF_PROG_TYPE_SCHED_CLS:
7780 	case BPF_PROG_TYPE_SCHED_ACT:
7781 		return true;
7782 	default:
7783 		return false;
7784 	}
7785 }
7786 
7787 /* verify safety of LD_ABS|LD_IND instructions:
7788  * - they can only appear in the programs where ctx == skb
7789  * - since they are wrappers of function calls, they scratch R1-R5 registers,
7790  *   preserve R6-R9, and store return value into R0
7791  *
7792  * Implicit input:
7793  *   ctx == skb == R6 == CTX
7794  *
7795  * Explicit input:
7796  *   SRC == any register
7797  *   IMM == 32-bit immediate
7798  *
7799  * Output:
7800  *   R0 - 8/16/32-bit skb data converted to cpu endianness
7801  */
7802 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
7803 {
7804 	struct bpf_reg_state *regs = cur_regs(env);
7805 	static const int ctx_reg = BPF_REG_6;
7806 	u8 mode = BPF_MODE(insn->code);
7807 	int i, err;
7808 
7809 	if (!may_access_skb(resolve_prog_type(env->prog))) {
7810 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
7811 		return -EINVAL;
7812 	}
7813 
7814 	if (!env->ops->gen_ld_abs) {
7815 		verbose(env, "bpf verifier is misconfigured\n");
7816 		return -EINVAL;
7817 	}
7818 
7819 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
7820 	    BPF_SIZE(insn->code) == BPF_DW ||
7821 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
7822 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
7823 		return -EINVAL;
7824 	}
7825 
7826 	/* check whether implicit source operand (register R6) is readable */
7827 	err = check_reg_arg(env, ctx_reg, SRC_OP);
7828 	if (err)
7829 		return err;
7830 
7831 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7832 	 * gen_ld_abs() may terminate the program at runtime, leading to
7833 	 * reference leak.
7834 	 */
7835 	err = check_reference_leak(env);
7836 	if (err) {
7837 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7838 		return err;
7839 	}
7840 
7841 	if (env->cur_state->active_spin_lock) {
7842 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7843 		return -EINVAL;
7844 	}
7845 
7846 	if (regs[ctx_reg].type != PTR_TO_CTX) {
7847 		verbose(env,
7848 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
7849 		return -EINVAL;
7850 	}
7851 
7852 	if (mode == BPF_IND) {
7853 		/* check explicit source operand */
7854 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
7855 		if (err)
7856 			return err;
7857 	}
7858 
7859 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7860 	if (err < 0)
7861 		return err;
7862 
7863 	/* reset caller saved regs to unreadable */
7864 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7865 		mark_reg_not_init(env, regs, caller_saved[i]);
7866 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7867 	}
7868 
7869 	/* mark destination R0 register as readable, since it contains
7870 	 * the value fetched from the packet.
7871 	 * Already marked as written above.
7872 	 */
7873 	mark_reg_unknown(env, regs, BPF_REG_0);
7874 	/* ld_abs load up to 32-bit skb data. */
7875 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
7876 	return 0;
7877 }
7878 
7879 static int check_return_code(struct bpf_verifier_env *env)
7880 {
7881 	struct tnum enforce_attach_type_range = tnum_unknown;
7882 	const struct bpf_prog *prog = env->prog;
7883 	struct bpf_reg_state *reg;
7884 	struct tnum range = tnum_range(0, 1);
7885 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7886 	int err;
7887 
7888 	/* LSM and struct_ops func-ptr's return type could be "void" */
7889 	if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7890 	     prog_type == BPF_PROG_TYPE_LSM) &&
7891 	    !prog->aux->attach_func_proto->type)
7892 		return 0;
7893 
7894 	/* eBPF calling convetion is such that R0 is used
7895 	 * to return the value from eBPF program.
7896 	 * Make sure that it's readable at this time
7897 	 * of bpf_exit, which means that program wrote
7898 	 * something into it earlier
7899 	 */
7900 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7901 	if (err)
7902 		return err;
7903 
7904 	if (is_pointer_value(env, BPF_REG_0)) {
7905 		verbose(env, "R0 leaks addr as return value\n");
7906 		return -EACCES;
7907 	}
7908 
7909 	switch (prog_type) {
7910 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7911 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
7912 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7913 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7914 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7915 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7916 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
7917 			range = tnum_range(1, 1);
7918 		break;
7919 	case BPF_PROG_TYPE_CGROUP_SKB:
7920 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7921 			range = tnum_range(0, 3);
7922 			enforce_attach_type_range = tnum_range(2, 3);
7923 		}
7924 		break;
7925 	case BPF_PROG_TYPE_CGROUP_SOCK:
7926 	case BPF_PROG_TYPE_SOCK_OPS:
7927 	case BPF_PROG_TYPE_CGROUP_DEVICE:
7928 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
7929 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
7930 		break;
7931 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7932 		if (!env->prog->aux->attach_btf_id)
7933 			return 0;
7934 		range = tnum_const(0);
7935 		break;
7936 	case BPF_PROG_TYPE_TRACING:
7937 		switch (env->prog->expected_attach_type) {
7938 		case BPF_TRACE_FENTRY:
7939 		case BPF_TRACE_FEXIT:
7940 			range = tnum_const(0);
7941 			break;
7942 		case BPF_TRACE_RAW_TP:
7943 		case BPF_MODIFY_RETURN:
7944 			return 0;
7945 		case BPF_TRACE_ITER:
7946 			break;
7947 		default:
7948 			return -ENOTSUPP;
7949 		}
7950 		break;
7951 	case BPF_PROG_TYPE_SK_LOOKUP:
7952 		range = tnum_range(SK_DROP, SK_PASS);
7953 		break;
7954 	case BPF_PROG_TYPE_EXT:
7955 		/* freplace program can return anything as its return value
7956 		 * depends on the to-be-replaced kernel func or bpf program.
7957 		 */
7958 	default:
7959 		return 0;
7960 	}
7961 
7962 	reg = cur_regs(env) + BPF_REG_0;
7963 	if (reg->type != SCALAR_VALUE) {
7964 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
7965 			reg_type_str[reg->type]);
7966 		return -EINVAL;
7967 	}
7968 
7969 	if (!tnum_in(range, reg->var_off)) {
7970 		char tn_buf[48];
7971 
7972 		verbose(env, "At program exit the register R0 ");
7973 		if (!tnum_is_unknown(reg->var_off)) {
7974 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7975 			verbose(env, "has value %s", tn_buf);
7976 		} else {
7977 			verbose(env, "has unknown scalar value");
7978 		}
7979 		tnum_strn(tn_buf, sizeof(tn_buf), range);
7980 		verbose(env, " should have been in %s\n", tn_buf);
7981 		return -EINVAL;
7982 	}
7983 
7984 	if (!tnum_is_unknown(enforce_attach_type_range) &&
7985 	    tnum_in(enforce_attach_type_range, reg->var_off))
7986 		env->prog->enforce_expected_attach_type = 1;
7987 	return 0;
7988 }
7989 
7990 /* non-recursive DFS pseudo code
7991  * 1  procedure DFS-iterative(G,v):
7992  * 2      label v as discovered
7993  * 3      let S be a stack
7994  * 4      S.push(v)
7995  * 5      while S is not empty
7996  * 6            t <- S.pop()
7997  * 7            if t is what we're looking for:
7998  * 8                return t
7999  * 9            for all edges e in G.adjacentEdges(t) do
8000  * 10               if edge e is already labelled
8001  * 11                   continue with the next edge
8002  * 12               w <- G.adjacentVertex(t,e)
8003  * 13               if vertex w is not discovered and not explored
8004  * 14                   label e as tree-edge
8005  * 15                   label w as discovered
8006  * 16                   S.push(w)
8007  * 17                   continue at 5
8008  * 18               else if vertex w is discovered
8009  * 19                   label e as back-edge
8010  * 20               else
8011  * 21                   // vertex w is explored
8012  * 22                   label e as forward- or cross-edge
8013  * 23           label t as explored
8014  * 24           S.pop()
8015  *
8016  * convention:
8017  * 0x10 - discovered
8018  * 0x11 - discovered and fall-through edge labelled
8019  * 0x12 - discovered and fall-through and branch edges labelled
8020  * 0x20 - explored
8021  */
8022 
8023 enum {
8024 	DISCOVERED = 0x10,
8025 	EXPLORED = 0x20,
8026 	FALLTHROUGH = 1,
8027 	BRANCH = 2,
8028 };
8029 
8030 static u32 state_htab_size(struct bpf_verifier_env *env)
8031 {
8032 	return env->prog->len;
8033 }
8034 
8035 static struct bpf_verifier_state_list **explored_state(
8036 					struct bpf_verifier_env *env,
8037 					int idx)
8038 {
8039 	struct bpf_verifier_state *cur = env->cur_state;
8040 	struct bpf_func_state *state = cur->frame[cur->curframe];
8041 
8042 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8043 }
8044 
8045 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8046 {
8047 	env->insn_aux_data[idx].prune_point = true;
8048 }
8049 
8050 /* t, w, e - match pseudo-code above:
8051  * t - index of current instruction
8052  * w - next instruction
8053  * e - edge
8054  */
8055 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8056 		     bool loop_ok)
8057 {
8058 	int *insn_stack = env->cfg.insn_stack;
8059 	int *insn_state = env->cfg.insn_state;
8060 
8061 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8062 		return 0;
8063 
8064 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8065 		return 0;
8066 
8067 	if (w < 0 || w >= env->prog->len) {
8068 		verbose_linfo(env, t, "%d: ", t);
8069 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8070 		return -EINVAL;
8071 	}
8072 
8073 	if (e == BRANCH)
8074 		/* mark branch target for state pruning */
8075 		init_explored_state(env, w);
8076 
8077 	if (insn_state[w] == 0) {
8078 		/* tree-edge */
8079 		insn_state[t] = DISCOVERED | e;
8080 		insn_state[w] = DISCOVERED;
8081 		if (env->cfg.cur_stack >= env->prog->len)
8082 			return -E2BIG;
8083 		insn_stack[env->cfg.cur_stack++] = w;
8084 		return 1;
8085 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8086 		if (loop_ok && env->bpf_capable)
8087 			return 0;
8088 		verbose_linfo(env, t, "%d: ", t);
8089 		verbose_linfo(env, w, "%d: ", w);
8090 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8091 		return -EINVAL;
8092 	} else if (insn_state[w] == EXPLORED) {
8093 		/* forward- or cross-edge */
8094 		insn_state[t] = DISCOVERED | e;
8095 	} else {
8096 		verbose(env, "insn state internal bug\n");
8097 		return -EFAULT;
8098 	}
8099 	return 0;
8100 }
8101 
8102 /* non-recursive depth-first-search to detect loops in BPF program
8103  * loop == back-edge in directed graph
8104  */
8105 static int check_cfg(struct bpf_verifier_env *env)
8106 {
8107 	struct bpf_insn *insns = env->prog->insnsi;
8108 	int insn_cnt = env->prog->len;
8109 	int *insn_stack, *insn_state;
8110 	int ret = 0;
8111 	int i, t;
8112 
8113 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8114 	if (!insn_state)
8115 		return -ENOMEM;
8116 
8117 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8118 	if (!insn_stack) {
8119 		kvfree(insn_state);
8120 		return -ENOMEM;
8121 	}
8122 
8123 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8124 	insn_stack[0] = 0; /* 0 is the first instruction */
8125 	env->cfg.cur_stack = 1;
8126 
8127 peek_stack:
8128 	if (env->cfg.cur_stack == 0)
8129 		goto check_state;
8130 	t = insn_stack[env->cfg.cur_stack - 1];
8131 
8132 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8133 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8134 		u8 opcode = BPF_OP(insns[t].code);
8135 
8136 		if (opcode == BPF_EXIT) {
8137 			goto mark_explored;
8138 		} else if (opcode == BPF_CALL) {
8139 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8140 			if (ret == 1)
8141 				goto peek_stack;
8142 			else if (ret < 0)
8143 				goto err_free;
8144 			if (t + 1 < insn_cnt)
8145 				init_explored_state(env, t + 1);
8146 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8147 				init_explored_state(env, t);
8148 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8149 						env, false);
8150 				if (ret == 1)
8151 					goto peek_stack;
8152 				else if (ret < 0)
8153 					goto err_free;
8154 			}
8155 		} else if (opcode == BPF_JA) {
8156 			if (BPF_SRC(insns[t].code) != BPF_K) {
8157 				ret = -EINVAL;
8158 				goto err_free;
8159 			}
8160 			/* unconditional jump with single edge */
8161 			ret = push_insn(t, t + insns[t].off + 1,
8162 					FALLTHROUGH, env, true);
8163 			if (ret == 1)
8164 				goto peek_stack;
8165 			else if (ret < 0)
8166 				goto err_free;
8167 			/* unconditional jmp is not a good pruning point,
8168 			 * but it's marked, since backtracking needs
8169 			 * to record jmp history in is_state_visited().
8170 			 */
8171 			init_explored_state(env, t + insns[t].off + 1);
8172 			/* tell verifier to check for equivalent states
8173 			 * after every call and jump
8174 			 */
8175 			if (t + 1 < insn_cnt)
8176 				init_explored_state(env, t + 1);
8177 		} else {
8178 			/* conditional jump with two edges */
8179 			init_explored_state(env, t);
8180 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8181 			if (ret == 1)
8182 				goto peek_stack;
8183 			else if (ret < 0)
8184 				goto err_free;
8185 
8186 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8187 			if (ret == 1)
8188 				goto peek_stack;
8189 			else if (ret < 0)
8190 				goto err_free;
8191 		}
8192 	} else {
8193 		/* all other non-branch instructions with single
8194 		 * fall-through edge
8195 		 */
8196 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8197 		if (ret == 1)
8198 			goto peek_stack;
8199 		else if (ret < 0)
8200 			goto err_free;
8201 	}
8202 
8203 mark_explored:
8204 	insn_state[t] = EXPLORED;
8205 	if (env->cfg.cur_stack-- <= 0) {
8206 		verbose(env, "pop stack internal bug\n");
8207 		ret = -EFAULT;
8208 		goto err_free;
8209 	}
8210 	goto peek_stack;
8211 
8212 check_state:
8213 	for (i = 0; i < insn_cnt; i++) {
8214 		if (insn_state[i] != EXPLORED) {
8215 			verbose(env, "unreachable insn %d\n", i);
8216 			ret = -EINVAL;
8217 			goto err_free;
8218 		}
8219 	}
8220 	ret = 0; /* cfg looks good */
8221 
8222 err_free:
8223 	kvfree(insn_state);
8224 	kvfree(insn_stack);
8225 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8226 	return ret;
8227 }
8228 
8229 static int check_abnormal_return(struct bpf_verifier_env *env)
8230 {
8231 	int i;
8232 
8233 	for (i = 1; i < env->subprog_cnt; i++) {
8234 		if (env->subprog_info[i].has_ld_abs) {
8235 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8236 			return -EINVAL;
8237 		}
8238 		if (env->subprog_info[i].has_tail_call) {
8239 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8240 			return -EINVAL;
8241 		}
8242 	}
8243 	return 0;
8244 }
8245 
8246 /* The minimum supported BTF func info size */
8247 #define MIN_BPF_FUNCINFO_SIZE	8
8248 #define MAX_FUNCINFO_REC_SIZE	252
8249 
8250 static int check_btf_func(struct bpf_verifier_env *env,
8251 			  const union bpf_attr *attr,
8252 			  union bpf_attr __user *uattr)
8253 {
8254 	const struct btf_type *type, *func_proto, *ret_type;
8255 	u32 i, nfuncs, urec_size, min_size;
8256 	u32 krec_size = sizeof(struct bpf_func_info);
8257 	struct bpf_func_info *krecord;
8258 	struct bpf_func_info_aux *info_aux = NULL;
8259 	struct bpf_prog *prog;
8260 	const struct btf *btf;
8261 	void __user *urecord;
8262 	u32 prev_offset = 0;
8263 	bool scalar_return;
8264 	int ret = -ENOMEM;
8265 
8266 	nfuncs = attr->func_info_cnt;
8267 	if (!nfuncs) {
8268 		if (check_abnormal_return(env))
8269 			return -EINVAL;
8270 		return 0;
8271 	}
8272 
8273 	if (nfuncs != env->subprog_cnt) {
8274 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8275 		return -EINVAL;
8276 	}
8277 
8278 	urec_size = attr->func_info_rec_size;
8279 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8280 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8281 	    urec_size % sizeof(u32)) {
8282 		verbose(env, "invalid func info rec size %u\n", urec_size);
8283 		return -EINVAL;
8284 	}
8285 
8286 	prog = env->prog;
8287 	btf = prog->aux->btf;
8288 
8289 	urecord = u64_to_user_ptr(attr->func_info);
8290 	min_size = min_t(u32, krec_size, urec_size);
8291 
8292 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8293 	if (!krecord)
8294 		return -ENOMEM;
8295 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8296 	if (!info_aux)
8297 		goto err_free;
8298 
8299 	for (i = 0; i < nfuncs; i++) {
8300 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8301 		if (ret) {
8302 			if (ret == -E2BIG) {
8303 				verbose(env, "nonzero tailing record in func info");
8304 				/* set the size kernel expects so loader can zero
8305 				 * out the rest of the record.
8306 				 */
8307 				if (put_user(min_size, &uattr->func_info_rec_size))
8308 					ret = -EFAULT;
8309 			}
8310 			goto err_free;
8311 		}
8312 
8313 		if (copy_from_user(&krecord[i], urecord, min_size)) {
8314 			ret = -EFAULT;
8315 			goto err_free;
8316 		}
8317 
8318 		/* check insn_off */
8319 		ret = -EINVAL;
8320 		if (i == 0) {
8321 			if (krecord[i].insn_off) {
8322 				verbose(env,
8323 					"nonzero insn_off %u for the first func info record",
8324 					krecord[i].insn_off);
8325 				goto err_free;
8326 			}
8327 		} else if (krecord[i].insn_off <= prev_offset) {
8328 			verbose(env,
8329 				"same or smaller insn offset (%u) than previous func info record (%u)",
8330 				krecord[i].insn_off, prev_offset);
8331 			goto err_free;
8332 		}
8333 
8334 		if (env->subprog_info[i].start != krecord[i].insn_off) {
8335 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8336 			goto err_free;
8337 		}
8338 
8339 		/* check type_id */
8340 		type = btf_type_by_id(btf, krecord[i].type_id);
8341 		if (!type || !btf_type_is_func(type)) {
8342 			verbose(env, "invalid type id %d in func info",
8343 				krecord[i].type_id);
8344 			goto err_free;
8345 		}
8346 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8347 
8348 		func_proto = btf_type_by_id(btf, type->type);
8349 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8350 			/* btf_func_check() already verified it during BTF load */
8351 			goto err_free;
8352 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8353 		scalar_return =
8354 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8355 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8356 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8357 			goto err_free;
8358 		}
8359 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8360 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8361 			goto err_free;
8362 		}
8363 
8364 		prev_offset = krecord[i].insn_off;
8365 		urecord += urec_size;
8366 	}
8367 
8368 	prog->aux->func_info = krecord;
8369 	prog->aux->func_info_cnt = nfuncs;
8370 	prog->aux->func_info_aux = info_aux;
8371 	return 0;
8372 
8373 err_free:
8374 	kvfree(krecord);
8375 	kfree(info_aux);
8376 	return ret;
8377 }
8378 
8379 static void adjust_btf_func(struct bpf_verifier_env *env)
8380 {
8381 	struct bpf_prog_aux *aux = env->prog->aux;
8382 	int i;
8383 
8384 	if (!aux->func_info)
8385 		return;
8386 
8387 	for (i = 0; i < env->subprog_cnt; i++)
8388 		aux->func_info[i].insn_off = env->subprog_info[i].start;
8389 }
8390 
8391 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
8392 		sizeof(((struct bpf_line_info *)(0))->line_col))
8393 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
8394 
8395 static int check_btf_line(struct bpf_verifier_env *env,
8396 			  const union bpf_attr *attr,
8397 			  union bpf_attr __user *uattr)
8398 {
8399 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8400 	struct bpf_subprog_info *sub;
8401 	struct bpf_line_info *linfo;
8402 	struct bpf_prog *prog;
8403 	const struct btf *btf;
8404 	void __user *ulinfo;
8405 	int err;
8406 
8407 	nr_linfo = attr->line_info_cnt;
8408 	if (!nr_linfo)
8409 		return 0;
8410 
8411 	rec_size = attr->line_info_rec_size;
8412 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8413 	    rec_size > MAX_LINEINFO_REC_SIZE ||
8414 	    rec_size & (sizeof(u32) - 1))
8415 		return -EINVAL;
8416 
8417 	/* Need to zero it in case the userspace may
8418 	 * pass in a smaller bpf_line_info object.
8419 	 */
8420 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8421 			 GFP_KERNEL | __GFP_NOWARN);
8422 	if (!linfo)
8423 		return -ENOMEM;
8424 
8425 	prog = env->prog;
8426 	btf = prog->aux->btf;
8427 
8428 	s = 0;
8429 	sub = env->subprog_info;
8430 	ulinfo = u64_to_user_ptr(attr->line_info);
8431 	expected_size = sizeof(struct bpf_line_info);
8432 	ncopy = min_t(u32, expected_size, rec_size);
8433 	for (i = 0; i < nr_linfo; i++) {
8434 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8435 		if (err) {
8436 			if (err == -E2BIG) {
8437 				verbose(env, "nonzero tailing record in line_info");
8438 				if (put_user(expected_size,
8439 					     &uattr->line_info_rec_size))
8440 					err = -EFAULT;
8441 			}
8442 			goto err_free;
8443 		}
8444 
8445 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8446 			err = -EFAULT;
8447 			goto err_free;
8448 		}
8449 
8450 		/*
8451 		 * Check insn_off to ensure
8452 		 * 1) strictly increasing AND
8453 		 * 2) bounded by prog->len
8454 		 *
8455 		 * The linfo[0].insn_off == 0 check logically falls into
8456 		 * the later "missing bpf_line_info for func..." case
8457 		 * because the first linfo[0].insn_off must be the
8458 		 * first sub also and the first sub must have
8459 		 * subprog_info[0].start == 0.
8460 		 */
8461 		if ((i && linfo[i].insn_off <= prev_offset) ||
8462 		    linfo[i].insn_off >= prog->len) {
8463 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8464 				i, linfo[i].insn_off, prev_offset,
8465 				prog->len);
8466 			err = -EINVAL;
8467 			goto err_free;
8468 		}
8469 
8470 		if (!prog->insnsi[linfo[i].insn_off].code) {
8471 			verbose(env,
8472 				"Invalid insn code at line_info[%u].insn_off\n",
8473 				i);
8474 			err = -EINVAL;
8475 			goto err_free;
8476 		}
8477 
8478 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8479 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8480 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8481 			err = -EINVAL;
8482 			goto err_free;
8483 		}
8484 
8485 		if (s != env->subprog_cnt) {
8486 			if (linfo[i].insn_off == sub[s].start) {
8487 				sub[s].linfo_idx = i;
8488 				s++;
8489 			} else if (sub[s].start < linfo[i].insn_off) {
8490 				verbose(env, "missing bpf_line_info for func#%u\n", s);
8491 				err = -EINVAL;
8492 				goto err_free;
8493 			}
8494 		}
8495 
8496 		prev_offset = linfo[i].insn_off;
8497 		ulinfo += rec_size;
8498 	}
8499 
8500 	if (s != env->subprog_cnt) {
8501 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8502 			env->subprog_cnt - s, s);
8503 		err = -EINVAL;
8504 		goto err_free;
8505 	}
8506 
8507 	prog->aux->linfo = linfo;
8508 	prog->aux->nr_linfo = nr_linfo;
8509 
8510 	return 0;
8511 
8512 err_free:
8513 	kvfree(linfo);
8514 	return err;
8515 }
8516 
8517 static int check_btf_info(struct bpf_verifier_env *env,
8518 			  const union bpf_attr *attr,
8519 			  union bpf_attr __user *uattr)
8520 {
8521 	struct btf *btf;
8522 	int err;
8523 
8524 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
8525 		if (check_abnormal_return(env))
8526 			return -EINVAL;
8527 		return 0;
8528 	}
8529 
8530 	btf = btf_get_by_fd(attr->prog_btf_fd);
8531 	if (IS_ERR(btf))
8532 		return PTR_ERR(btf);
8533 	env->prog->aux->btf = btf;
8534 
8535 	err = check_btf_func(env, attr, uattr);
8536 	if (err)
8537 		return err;
8538 
8539 	err = check_btf_line(env, attr, uattr);
8540 	if (err)
8541 		return err;
8542 
8543 	return 0;
8544 }
8545 
8546 /* check %cur's range satisfies %old's */
8547 static bool range_within(struct bpf_reg_state *old,
8548 			 struct bpf_reg_state *cur)
8549 {
8550 	return old->umin_value <= cur->umin_value &&
8551 	       old->umax_value >= cur->umax_value &&
8552 	       old->smin_value <= cur->smin_value &&
8553 	       old->smax_value >= cur->smax_value;
8554 }
8555 
8556 /* Maximum number of register states that can exist at once */
8557 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8558 struct idpair {
8559 	u32 old;
8560 	u32 cur;
8561 };
8562 
8563 /* If in the old state two registers had the same id, then they need to have
8564  * the same id in the new state as well.  But that id could be different from
8565  * the old state, so we need to track the mapping from old to new ids.
8566  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8567  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
8568  * regs with a different old id could still have new id 9, we don't care about
8569  * that.
8570  * So we look through our idmap to see if this old id has been seen before.  If
8571  * so, we require the new id to match; otherwise, we add the id pair to the map.
8572  */
8573 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
8574 {
8575 	unsigned int i;
8576 
8577 	for (i = 0; i < ID_MAP_SIZE; i++) {
8578 		if (!idmap[i].old) {
8579 			/* Reached an empty slot; haven't seen this id before */
8580 			idmap[i].old = old_id;
8581 			idmap[i].cur = cur_id;
8582 			return true;
8583 		}
8584 		if (idmap[i].old == old_id)
8585 			return idmap[i].cur == cur_id;
8586 	}
8587 	/* We ran out of idmap slots, which should be impossible */
8588 	WARN_ON_ONCE(1);
8589 	return false;
8590 }
8591 
8592 static void clean_func_state(struct bpf_verifier_env *env,
8593 			     struct bpf_func_state *st)
8594 {
8595 	enum bpf_reg_liveness live;
8596 	int i, j;
8597 
8598 	for (i = 0; i < BPF_REG_FP; i++) {
8599 		live = st->regs[i].live;
8600 		/* liveness must not touch this register anymore */
8601 		st->regs[i].live |= REG_LIVE_DONE;
8602 		if (!(live & REG_LIVE_READ))
8603 			/* since the register is unused, clear its state
8604 			 * to make further comparison simpler
8605 			 */
8606 			__mark_reg_not_init(env, &st->regs[i]);
8607 	}
8608 
8609 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8610 		live = st->stack[i].spilled_ptr.live;
8611 		/* liveness must not touch this stack slot anymore */
8612 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8613 		if (!(live & REG_LIVE_READ)) {
8614 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
8615 			for (j = 0; j < BPF_REG_SIZE; j++)
8616 				st->stack[i].slot_type[j] = STACK_INVALID;
8617 		}
8618 	}
8619 }
8620 
8621 static void clean_verifier_state(struct bpf_verifier_env *env,
8622 				 struct bpf_verifier_state *st)
8623 {
8624 	int i;
8625 
8626 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8627 		/* all regs in this state in all frames were already marked */
8628 		return;
8629 
8630 	for (i = 0; i <= st->curframe; i++)
8631 		clean_func_state(env, st->frame[i]);
8632 }
8633 
8634 /* the parentage chains form a tree.
8635  * the verifier states are added to state lists at given insn and
8636  * pushed into state stack for future exploration.
8637  * when the verifier reaches bpf_exit insn some of the verifer states
8638  * stored in the state lists have their final liveness state already,
8639  * but a lot of states will get revised from liveness point of view when
8640  * the verifier explores other branches.
8641  * Example:
8642  * 1: r0 = 1
8643  * 2: if r1 == 100 goto pc+1
8644  * 3: r0 = 2
8645  * 4: exit
8646  * when the verifier reaches exit insn the register r0 in the state list of
8647  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8648  * of insn 2 and goes exploring further. At the insn 4 it will walk the
8649  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8650  *
8651  * Since the verifier pushes the branch states as it sees them while exploring
8652  * the program the condition of walking the branch instruction for the second
8653  * time means that all states below this branch were already explored and
8654  * their final liveness markes are already propagated.
8655  * Hence when the verifier completes the search of state list in is_state_visited()
8656  * we can call this clean_live_states() function to mark all liveness states
8657  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8658  * will not be used.
8659  * This function also clears the registers and stack for states that !READ
8660  * to simplify state merging.
8661  *
8662  * Important note here that walking the same branch instruction in the callee
8663  * doesn't meant that the states are DONE. The verifier has to compare
8664  * the callsites
8665  */
8666 static void clean_live_states(struct bpf_verifier_env *env, int insn,
8667 			      struct bpf_verifier_state *cur)
8668 {
8669 	struct bpf_verifier_state_list *sl;
8670 	int i;
8671 
8672 	sl = *explored_state(env, insn);
8673 	while (sl) {
8674 		if (sl->state.branches)
8675 			goto next;
8676 		if (sl->state.insn_idx != insn ||
8677 		    sl->state.curframe != cur->curframe)
8678 			goto next;
8679 		for (i = 0; i <= cur->curframe; i++)
8680 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8681 				goto next;
8682 		clean_verifier_state(env, &sl->state);
8683 next:
8684 		sl = sl->next;
8685 	}
8686 }
8687 
8688 /* Returns true if (rold safe implies rcur safe) */
8689 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8690 		    struct idpair *idmap)
8691 {
8692 	bool equal;
8693 
8694 	if (!(rold->live & REG_LIVE_READ))
8695 		/* explored state didn't use this */
8696 		return true;
8697 
8698 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
8699 
8700 	if (rold->type == PTR_TO_STACK)
8701 		/* two stack pointers are equal only if they're pointing to
8702 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
8703 		 */
8704 		return equal && rold->frameno == rcur->frameno;
8705 
8706 	if (equal)
8707 		return true;
8708 
8709 	if (rold->type == NOT_INIT)
8710 		/* explored state can't have used this */
8711 		return true;
8712 	if (rcur->type == NOT_INIT)
8713 		return false;
8714 	switch (rold->type) {
8715 	case SCALAR_VALUE:
8716 		if (rcur->type == SCALAR_VALUE) {
8717 			if (!rold->precise && !rcur->precise)
8718 				return true;
8719 			/* new val must satisfy old val knowledge */
8720 			return range_within(rold, rcur) &&
8721 			       tnum_in(rold->var_off, rcur->var_off);
8722 		} else {
8723 			/* We're trying to use a pointer in place of a scalar.
8724 			 * Even if the scalar was unbounded, this could lead to
8725 			 * pointer leaks because scalars are allowed to leak
8726 			 * while pointers are not. We could make this safe in
8727 			 * special cases if root is calling us, but it's
8728 			 * probably not worth the hassle.
8729 			 */
8730 			return false;
8731 		}
8732 	case PTR_TO_MAP_VALUE:
8733 		/* If the new min/max/var_off satisfy the old ones and
8734 		 * everything else matches, we are OK.
8735 		 * 'id' is not compared, since it's only used for maps with
8736 		 * bpf_spin_lock inside map element and in such cases if
8737 		 * the rest of the prog is valid for one map element then
8738 		 * it's valid for all map elements regardless of the key
8739 		 * used in bpf_map_lookup()
8740 		 */
8741 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8742 		       range_within(rold, rcur) &&
8743 		       tnum_in(rold->var_off, rcur->var_off);
8744 	case PTR_TO_MAP_VALUE_OR_NULL:
8745 		/* a PTR_TO_MAP_VALUE could be safe to use as a
8746 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8747 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8748 		 * checked, doing so could have affected others with the same
8749 		 * id, and we can't check for that because we lost the id when
8750 		 * we converted to a PTR_TO_MAP_VALUE.
8751 		 */
8752 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8753 			return false;
8754 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8755 			return false;
8756 		/* Check our ids match any regs they're supposed to */
8757 		return check_ids(rold->id, rcur->id, idmap);
8758 	case PTR_TO_PACKET_META:
8759 	case PTR_TO_PACKET:
8760 		if (rcur->type != rold->type)
8761 			return false;
8762 		/* We must have at least as much range as the old ptr
8763 		 * did, so that any accesses which were safe before are
8764 		 * still safe.  This is true even if old range < old off,
8765 		 * since someone could have accessed through (ptr - k), or
8766 		 * even done ptr -= k in a register, to get a safe access.
8767 		 */
8768 		if (rold->range > rcur->range)
8769 			return false;
8770 		/* If the offsets don't match, we can't trust our alignment;
8771 		 * nor can we be sure that we won't fall out of range.
8772 		 */
8773 		if (rold->off != rcur->off)
8774 			return false;
8775 		/* id relations must be preserved */
8776 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8777 			return false;
8778 		/* new val must satisfy old val knowledge */
8779 		return range_within(rold, rcur) &&
8780 		       tnum_in(rold->var_off, rcur->var_off);
8781 	case PTR_TO_CTX:
8782 	case CONST_PTR_TO_MAP:
8783 	case PTR_TO_PACKET_END:
8784 	case PTR_TO_FLOW_KEYS:
8785 	case PTR_TO_SOCKET:
8786 	case PTR_TO_SOCKET_OR_NULL:
8787 	case PTR_TO_SOCK_COMMON:
8788 	case PTR_TO_SOCK_COMMON_OR_NULL:
8789 	case PTR_TO_TCP_SOCK:
8790 	case PTR_TO_TCP_SOCK_OR_NULL:
8791 	case PTR_TO_XDP_SOCK:
8792 		/* Only valid matches are exact, which memcmp() above
8793 		 * would have accepted
8794 		 */
8795 	default:
8796 		/* Don't know what's going on, just say it's not safe */
8797 		return false;
8798 	}
8799 
8800 	/* Shouldn't get here; if we do, say it's not safe */
8801 	WARN_ON_ONCE(1);
8802 	return false;
8803 }
8804 
8805 static bool stacksafe(struct bpf_func_state *old,
8806 		      struct bpf_func_state *cur,
8807 		      struct idpair *idmap)
8808 {
8809 	int i, spi;
8810 
8811 	/* walk slots of the explored stack and ignore any additional
8812 	 * slots in the current stack, since explored(safe) state
8813 	 * didn't use them
8814 	 */
8815 	for (i = 0; i < old->allocated_stack; i++) {
8816 		spi = i / BPF_REG_SIZE;
8817 
8818 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8819 			i += BPF_REG_SIZE - 1;
8820 			/* explored state didn't use this */
8821 			continue;
8822 		}
8823 
8824 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8825 			continue;
8826 
8827 		/* explored stack has more populated slots than current stack
8828 		 * and these slots were used
8829 		 */
8830 		if (i >= cur->allocated_stack)
8831 			return false;
8832 
8833 		/* if old state was safe with misc data in the stack
8834 		 * it will be safe with zero-initialized stack.
8835 		 * The opposite is not true
8836 		 */
8837 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8838 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8839 			continue;
8840 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8841 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8842 			/* Ex: old explored (safe) state has STACK_SPILL in
8843 			 * this stack slot, but current has STACK_MISC ->
8844 			 * this verifier states are not equivalent,
8845 			 * return false to continue verification of this path
8846 			 */
8847 			return false;
8848 		if (i % BPF_REG_SIZE)
8849 			continue;
8850 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
8851 			continue;
8852 		if (!regsafe(&old->stack[spi].spilled_ptr,
8853 			     &cur->stack[spi].spilled_ptr,
8854 			     idmap))
8855 			/* when explored and current stack slot are both storing
8856 			 * spilled registers, check that stored pointers types
8857 			 * are the same as well.
8858 			 * Ex: explored safe path could have stored
8859 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8860 			 * but current path has stored:
8861 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8862 			 * such verifier states are not equivalent.
8863 			 * return false to continue verification of this path
8864 			 */
8865 			return false;
8866 	}
8867 	return true;
8868 }
8869 
8870 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8871 {
8872 	if (old->acquired_refs != cur->acquired_refs)
8873 		return false;
8874 	return !memcmp(old->refs, cur->refs,
8875 		       sizeof(*old->refs) * old->acquired_refs);
8876 }
8877 
8878 /* compare two verifier states
8879  *
8880  * all states stored in state_list are known to be valid, since
8881  * verifier reached 'bpf_exit' instruction through them
8882  *
8883  * this function is called when verifier exploring different branches of
8884  * execution popped from the state stack. If it sees an old state that has
8885  * more strict register state and more strict stack state then this execution
8886  * branch doesn't need to be explored further, since verifier already
8887  * concluded that more strict state leads to valid finish.
8888  *
8889  * Therefore two states are equivalent if register state is more conservative
8890  * and explored stack state is more conservative than the current one.
8891  * Example:
8892  *       explored                   current
8893  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8894  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8895  *
8896  * In other words if current stack state (one being explored) has more
8897  * valid slots than old one that already passed validation, it means
8898  * the verifier can stop exploring and conclude that current state is valid too
8899  *
8900  * Similarly with registers. If explored state has register type as invalid
8901  * whereas register type in current state is meaningful, it means that
8902  * the current state will reach 'bpf_exit' instruction safely
8903  */
8904 static bool func_states_equal(struct bpf_func_state *old,
8905 			      struct bpf_func_state *cur)
8906 {
8907 	struct idpair *idmap;
8908 	bool ret = false;
8909 	int i;
8910 
8911 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8912 	/* If we failed to allocate the idmap, just say it's not safe */
8913 	if (!idmap)
8914 		return false;
8915 
8916 	for (i = 0; i < MAX_BPF_REG; i++) {
8917 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
8918 			goto out_free;
8919 	}
8920 
8921 	if (!stacksafe(old, cur, idmap))
8922 		goto out_free;
8923 
8924 	if (!refsafe(old, cur))
8925 		goto out_free;
8926 	ret = true;
8927 out_free:
8928 	kfree(idmap);
8929 	return ret;
8930 }
8931 
8932 static bool states_equal(struct bpf_verifier_env *env,
8933 			 struct bpf_verifier_state *old,
8934 			 struct bpf_verifier_state *cur)
8935 {
8936 	int i;
8937 
8938 	if (old->curframe != cur->curframe)
8939 		return false;
8940 
8941 	/* Verification state from speculative execution simulation
8942 	 * must never prune a non-speculative execution one.
8943 	 */
8944 	if (old->speculative && !cur->speculative)
8945 		return false;
8946 
8947 	if (old->active_spin_lock != cur->active_spin_lock)
8948 		return false;
8949 
8950 	/* for states to be equal callsites have to be the same
8951 	 * and all frame states need to be equivalent
8952 	 */
8953 	for (i = 0; i <= old->curframe; i++) {
8954 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
8955 			return false;
8956 		if (!func_states_equal(old->frame[i], cur->frame[i]))
8957 			return false;
8958 	}
8959 	return true;
8960 }
8961 
8962 /* Return 0 if no propagation happened. Return negative error code if error
8963  * happened. Otherwise, return the propagated bit.
8964  */
8965 static int propagate_liveness_reg(struct bpf_verifier_env *env,
8966 				  struct bpf_reg_state *reg,
8967 				  struct bpf_reg_state *parent_reg)
8968 {
8969 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8970 	u8 flag = reg->live & REG_LIVE_READ;
8971 	int err;
8972 
8973 	/* When comes here, read flags of PARENT_REG or REG could be any of
8974 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8975 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8976 	 */
8977 	if (parent_flag == REG_LIVE_READ64 ||
8978 	    /* Or if there is no read flag from REG. */
8979 	    !flag ||
8980 	    /* Or if the read flag from REG is the same as PARENT_REG. */
8981 	    parent_flag == flag)
8982 		return 0;
8983 
8984 	err = mark_reg_read(env, reg, parent_reg, flag);
8985 	if (err)
8986 		return err;
8987 
8988 	return flag;
8989 }
8990 
8991 /* A write screens off any subsequent reads; but write marks come from the
8992  * straight-line code between a state and its parent.  When we arrive at an
8993  * equivalent state (jump target or such) we didn't arrive by the straight-line
8994  * code, so read marks in the state must propagate to the parent regardless
8995  * of the state's write marks. That's what 'parent == state->parent' comparison
8996  * in mark_reg_read() is for.
8997  */
8998 static int propagate_liveness(struct bpf_verifier_env *env,
8999 			      const struct bpf_verifier_state *vstate,
9000 			      struct bpf_verifier_state *vparent)
9001 {
9002 	struct bpf_reg_state *state_reg, *parent_reg;
9003 	struct bpf_func_state *state, *parent;
9004 	int i, frame, err = 0;
9005 
9006 	if (vparent->curframe != vstate->curframe) {
9007 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9008 		     vparent->curframe, vstate->curframe);
9009 		return -EFAULT;
9010 	}
9011 	/* Propagate read liveness of registers... */
9012 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9013 	for (frame = 0; frame <= vstate->curframe; frame++) {
9014 		parent = vparent->frame[frame];
9015 		state = vstate->frame[frame];
9016 		parent_reg = parent->regs;
9017 		state_reg = state->regs;
9018 		/* We don't need to worry about FP liveness, it's read-only */
9019 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9020 			err = propagate_liveness_reg(env, &state_reg[i],
9021 						     &parent_reg[i]);
9022 			if (err < 0)
9023 				return err;
9024 			if (err == REG_LIVE_READ64)
9025 				mark_insn_zext(env, &parent_reg[i]);
9026 		}
9027 
9028 		/* Propagate stack slots. */
9029 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9030 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9031 			parent_reg = &parent->stack[i].spilled_ptr;
9032 			state_reg = &state->stack[i].spilled_ptr;
9033 			err = propagate_liveness_reg(env, state_reg,
9034 						     parent_reg);
9035 			if (err < 0)
9036 				return err;
9037 		}
9038 	}
9039 	return 0;
9040 }
9041 
9042 /* find precise scalars in the previous equivalent state and
9043  * propagate them into the current state
9044  */
9045 static int propagate_precision(struct bpf_verifier_env *env,
9046 			       const struct bpf_verifier_state *old)
9047 {
9048 	struct bpf_reg_state *state_reg;
9049 	struct bpf_func_state *state;
9050 	int i, err = 0;
9051 
9052 	state = old->frame[old->curframe];
9053 	state_reg = state->regs;
9054 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9055 		if (state_reg->type != SCALAR_VALUE ||
9056 		    !state_reg->precise)
9057 			continue;
9058 		if (env->log.level & BPF_LOG_LEVEL2)
9059 			verbose(env, "propagating r%d\n", i);
9060 		err = mark_chain_precision(env, i);
9061 		if (err < 0)
9062 			return err;
9063 	}
9064 
9065 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9066 		if (state->stack[i].slot_type[0] != STACK_SPILL)
9067 			continue;
9068 		state_reg = &state->stack[i].spilled_ptr;
9069 		if (state_reg->type != SCALAR_VALUE ||
9070 		    !state_reg->precise)
9071 			continue;
9072 		if (env->log.level & BPF_LOG_LEVEL2)
9073 			verbose(env, "propagating fp%d\n",
9074 				(-i - 1) * BPF_REG_SIZE);
9075 		err = mark_chain_precision_stack(env, i);
9076 		if (err < 0)
9077 			return err;
9078 	}
9079 	return 0;
9080 }
9081 
9082 static bool states_maybe_looping(struct bpf_verifier_state *old,
9083 				 struct bpf_verifier_state *cur)
9084 {
9085 	struct bpf_func_state *fold, *fcur;
9086 	int i, fr = cur->curframe;
9087 
9088 	if (old->curframe != fr)
9089 		return false;
9090 
9091 	fold = old->frame[fr];
9092 	fcur = cur->frame[fr];
9093 	for (i = 0; i < MAX_BPF_REG; i++)
9094 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9095 			   offsetof(struct bpf_reg_state, parent)))
9096 			return false;
9097 	return true;
9098 }
9099 
9100 
9101 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9102 {
9103 	struct bpf_verifier_state_list *new_sl;
9104 	struct bpf_verifier_state_list *sl, **pprev;
9105 	struct bpf_verifier_state *cur = env->cur_state, *new;
9106 	int i, j, err, states_cnt = 0;
9107 	bool add_new_state = env->test_state_freq ? true : false;
9108 
9109 	cur->last_insn_idx = env->prev_insn_idx;
9110 	if (!env->insn_aux_data[insn_idx].prune_point)
9111 		/* this 'insn_idx' instruction wasn't marked, so we will not
9112 		 * be doing state search here
9113 		 */
9114 		return 0;
9115 
9116 	/* bpf progs typically have pruning point every 4 instructions
9117 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9118 	 * Do not add new state for future pruning if the verifier hasn't seen
9119 	 * at least 2 jumps and at least 8 instructions.
9120 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9121 	 * In tests that amounts to up to 50% reduction into total verifier
9122 	 * memory consumption and 20% verifier time speedup.
9123 	 */
9124 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9125 	    env->insn_processed - env->prev_insn_processed >= 8)
9126 		add_new_state = true;
9127 
9128 	pprev = explored_state(env, insn_idx);
9129 	sl = *pprev;
9130 
9131 	clean_live_states(env, insn_idx, cur);
9132 
9133 	while (sl) {
9134 		states_cnt++;
9135 		if (sl->state.insn_idx != insn_idx)
9136 			goto next;
9137 		if (sl->state.branches) {
9138 			if (states_maybe_looping(&sl->state, cur) &&
9139 			    states_equal(env, &sl->state, cur)) {
9140 				verbose_linfo(env, insn_idx, "; ");
9141 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9142 				return -EINVAL;
9143 			}
9144 			/* if the verifier is processing a loop, avoid adding new state
9145 			 * too often, since different loop iterations have distinct
9146 			 * states and may not help future pruning.
9147 			 * This threshold shouldn't be too low to make sure that
9148 			 * a loop with large bound will be rejected quickly.
9149 			 * The most abusive loop will be:
9150 			 * r1 += 1
9151 			 * if r1 < 1000000 goto pc-2
9152 			 * 1M insn_procssed limit / 100 == 10k peak states.
9153 			 * This threshold shouldn't be too high either, since states
9154 			 * at the end of the loop are likely to be useful in pruning.
9155 			 */
9156 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9157 			    env->insn_processed - env->prev_insn_processed < 100)
9158 				add_new_state = false;
9159 			goto miss;
9160 		}
9161 		if (states_equal(env, &sl->state, cur)) {
9162 			sl->hit_cnt++;
9163 			/* reached equivalent register/stack state,
9164 			 * prune the search.
9165 			 * Registers read by the continuation are read by us.
9166 			 * If we have any write marks in env->cur_state, they
9167 			 * will prevent corresponding reads in the continuation
9168 			 * from reaching our parent (an explored_state).  Our
9169 			 * own state will get the read marks recorded, but
9170 			 * they'll be immediately forgotten as we're pruning
9171 			 * this state and will pop a new one.
9172 			 */
9173 			err = propagate_liveness(env, &sl->state, cur);
9174 
9175 			/* if previous state reached the exit with precision and
9176 			 * current state is equivalent to it (except precsion marks)
9177 			 * the precision needs to be propagated back in
9178 			 * the current state.
9179 			 */
9180 			err = err ? : push_jmp_history(env, cur);
9181 			err = err ? : propagate_precision(env, &sl->state);
9182 			if (err)
9183 				return err;
9184 			return 1;
9185 		}
9186 miss:
9187 		/* when new state is not going to be added do not increase miss count.
9188 		 * Otherwise several loop iterations will remove the state
9189 		 * recorded earlier. The goal of these heuristics is to have
9190 		 * states from some iterations of the loop (some in the beginning
9191 		 * and some at the end) to help pruning.
9192 		 */
9193 		if (add_new_state)
9194 			sl->miss_cnt++;
9195 		/* heuristic to determine whether this state is beneficial
9196 		 * to keep checking from state equivalence point of view.
9197 		 * Higher numbers increase max_states_per_insn and verification time,
9198 		 * but do not meaningfully decrease insn_processed.
9199 		 */
9200 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9201 			/* the state is unlikely to be useful. Remove it to
9202 			 * speed up verification
9203 			 */
9204 			*pprev = sl->next;
9205 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9206 				u32 br = sl->state.branches;
9207 
9208 				WARN_ONCE(br,
9209 					  "BUG live_done but branches_to_explore %d\n",
9210 					  br);
9211 				free_verifier_state(&sl->state, false);
9212 				kfree(sl);
9213 				env->peak_states--;
9214 			} else {
9215 				/* cannot free this state, since parentage chain may
9216 				 * walk it later. Add it for free_list instead to
9217 				 * be freed at the end of verification
9218 				 */
9219 				sl->next = env->free_list;
9220 				env->free_list = sl;
9221 			}
9222 			sl = *pprev;
9223 			continue;
9224 		}
9225 next:
9226 		pprev = &sl->next;
9227 		sl = *pprev;
9228 	}
9229 
9230 	if (env->max_states_per_insn < states_cnt)
9231 		env->max_states_per_insn = states_cnt;
9232 
9233 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9234 		return push_jmp_history(env, cur);
9235 
9236 	if (!add_new_state)
9237 		return push_jmp_history(env, cur);
9238 
9239 	/* There were no equivalent states, remember the current one.
9240 	 * Technically the current state is not proven to be safe yet,
9241 	 * but it will either reach outer most bpf_exit (which means it's safe)
9242 	 * or it will be rejected. When there are no loops the verifier won't be
9243 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9244 	 * again on the way to bpf_exit.
9245 	 * When looping the sl->state.branches will be > 0 and this state
9246 	 * will not be considered for equivalence until branches == 0.
9247 	 */
9248 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9249 	if (!new_sl)
9250 		return -ENOMEM;
9251 	env->total_states++;
9252 	env->peak_states++;
9253 	env->prev_jmps_processed = env->jmps_processed;
9254 	env->prev_insn_processed = env->insn_processed;
9255 
9256 	/* add new state to the head of linked list */
9257 	new = &new_sl->state;
9258 	err = copy_verifier_state(new, cur);
9259 	if (err) {
9260 		free_verifier_state(new, false);
9261 		kfree(new_sl);
9262 		return err;
9263 	}
9264 	new->insn_idx = insn_idx;
9265 	WARN_ONCE(new->branches != 1,
9266 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9267 
9268 	cur->parent = new;
9269 	cur->first_insn_idx = insn_idx;
9270 	clear_jmp_history(cur);
9271 	new_sl->next = *explored_state(env, insn_idx);
9272 	*explored_state(env, insn_idx) = new_sl;
9273 	/* connect new state to parentage chain. Current frame needs all
9274 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9275 	 * to the stack implicitly by JITs) so in callers' frames connect just
9276 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9277 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9278 	 * from callee with its full parentage chain, anyway.
9279 	 */
9280 	/* clear write marks in current state: the writes we did are not writes
9281 	 * our child did, so they don't screen off its reads from us.
9282 	 * (There are no read marks in current state, because reads always mark
9283 	 * their parent and current state never has children yet.  Only
9284 	 * explored_states can get read marks.)
9285 	 */
9286 	for (j = 0; j <= cur->curframe; j++) {
9287 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9288 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9289 		for (i = 0; i < BPF_REG_FP; i++)
9290 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9291 	}
9292 
9293 	/* all stack frames are accessible from callee, clear them all */
9294 	for (j = 0; j <= cur->curframe; j++) {
9295 		struct bpf_func_state *frame = cur->frame[j];
9296 		struct bpf_func_state *newframe = new->frame[j];
9297 
9298 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9299 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9300 			frame->stack[i].spilled_ptr.parent =
9301 						&newframe->stack[i].spilled_ptr;
9302 		}
9303 	}
9304 	return 0;
9305 }
9306 
9307 /* Return true if it's OK to have the same insn return a different type. */
9308 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9309 {
9310 	switch (type) {
9311 	case PTR_TO_CTX:
9312 	case PTR_TO_SOCKET:
9313 	case PTR_TO_SOCKET_OR_NULL:
9314 	case PTR_TO_SOCK_COMMON:
9315 	case PTR_TO_SOCK_COMMON_OR_NULL:
9316 	case PTR_TO_TCP_SOCK:
9317 	case PTR_TO_TCP_SOCK_OR_NULL:
9318 	case PTR_TO_XDP_SOCK:
9319 	case PTR_TO_BTF_ID:
9320 	case PTR_TO_BTF_ID_OR_NULL:
9321 		return false;
9322 	default:
9323 		return true;
9324 	}
9325 }
9326 
9327 /* If an instruction was previously used with particular pointer types, then we
9328  * need to be careful to avoid cases such as the below, where it may be ok
9329  * for one branch accessing the pointer, but not ok for the other branch:
9330  *
9331  * R1 = sock_ptr
9332  * goto X;
9333  * ...
9334  * R1 = some_other_valid_ptr;
9335  * goto X;
9336  * ...
9337  * R2 = *(u32 *)(R1 + 0);
9338  */
9339 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9340 {
9341 	return src != prev && (!reg_type_mismatch_ok(src) ||
9342 			       !reg_type_mismatch_ok(prev));
9343 }
9344 
9345 static int do_check(struct bpf_verifier_env *env)
9346 {
9347 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9348 	struct bpf_verifier_state *state = env->cur_state;
9349 	struct bpf_insn *insns = env->prog->insnsi;
9350 	struct bpf_reg_state *regs;
9351 	int insn_cnt = env->prog->len;
9352 	bool do_print_state = false;
9353 	int prev_insn_idx = -1;
9354 
9355 	for (;;) {
9356 		struct bpf_insn *insn;
9357 		u8 class;
9358 		int err;
9359 
9360 		env->prev_insn_idx = prev_insn_idx;
9361 		if (env->insn_idx >= insn_cnt) {
9362 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
9363 				env->insn_idx, insn_cnt);
9364 			return -EFAULT;
9365 		}
9366 
9367 		insn = &insns[env->insn_idx];
9368 		class = BPF_CLASS(insn->code);
9369 
9370 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9371 			verbose(env,
9372 				"BPF program is too large. Processed %d insn\n",
9373 				env->insn_processed);
9374 			return -E2BIG;
9375 		}
9376 
9377 		err = is_state_visited(env, env->insn_idx);
9378 		if (err < 0)
9379 			return err;
9380 		if (err == 1) {
9381 			/* found equivalent state, can prune the search */
9382 			if (env->log.level & BPF_LOG_LEVEL) {
9383 				if (do_print_state)
9384 					verbose(env, "\nfrom %d to %d%s: safe\n",
9385 						env->prev_insn_idx, env->insn_idx,
9386 						env->cur_state->speculative ?
9387 						" (speculative execution)" : "");
9388 				else
9389 					verbose(env, "%d: safe\n", env->insn_idx);
9390 			}
9391 			goto process_bpf_exit;
9392 		}
9393 
9394 		if (signal_pending(current))
9395 			return -EAGAIN;
9396 
9397 		if (need_resched())
9398 			cond_resched();
9399 
9400 		if (env->log.level & BPF_LOG_LEVEL2 ||
9401 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9402 			if (env->log.level & BPF_LOG_LEVEL2)
9403 				verbose(env, "%d:", env->insn_idx);
9404 			else
9405 				verbose(env, "\nfrom %d to %d%s:",
9406 					env->prev_insn_idx, env->insn_idx,
9407 					env->cur_state->speculative ?
9408 					" (speculative execution)" : "");
9409 			print_verifier_state(env, state->frame[state->curframe]);
9410 			do_print_state = false;
9411 		}
9412 
9413 		if (env->log.level & BPF_LOG_LEVEL) {
9414 			const struct bpf_insn_cbs cbs = {
9415 				.cb_print	= verbose,
9416 				.private_data	= env,
9417 			};
9418 
9419 			verbose_linfo(env, env->insn_idx, "; ");
9420 			verbose(env, "%d: ", env->insn_idx);
9421 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9422 		}
9423 
9424 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
9425 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9426 							   env->prev_insn_idx);
9427 			if (err)
9428 				return err;
9429 		}
9430 
9431 		regs = cur_regs(env);
9432 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9433 		prev_insn_idx = env->insn_idx;
9434 
9435 		if (class == BPF_ALU || class == BPF_ALU64) {
9436 			err = check_alu_op(env, insn);
9437 			if (err)
9438 				return err;
9439 
9440 		} else if (class == BPF_LDX) {
9441 			enum bpf_reg_type *prev_src_type, src_reg_type;
9442 
9443 			/* check for reserved fields is already done */
9444 
9445 			/* check src operand */
9446 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9447 			if (err)
9448 				return err;
9449 
9450 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9451 			if (err)
9452 				return err;
9453 
9454 			src_reg_type = regs[insn->src_reg].type;
9455 
9456 			/* check that memory (src_reg + off) is readable,
9457 			 * the state of dst_reg will be updated by this func
9458 			 */
9459 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
9460 					       insn->off, BPF_SIZE(insn->code),
9461 					       BPF_READ, insn->dst_reg, false);
9462 			if (err)
9463 				return err;
9464 
9465 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9466 
9467 			if (*prev_src_type == NOT_INIT) {
9468 				/* saw a valid insn
9469 				 * dst_reg = *(u32 *)(src_reg + off)
9470 				 * save type to validate intersecting paths
9471 				 */
9472 				*prev_src_type = src_reg_type;
9473 
9474 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9475 				/* ABuser program is trying to use the same insn
9476 				 * dst_reg = *(u32*) (src_reg + off)
9477 				 * with different pointer types:
9478 				 * src_reg == ctx in one branch and
9479 				 * src_reg == stack|map in some other branch.
9480 				 * Reject it.
9481 				 */
9482 				verbose(env, "same insn cannot be used with different pointers\n");
9483 				return -EINVAL;
9484 			}
9485 
9486 		} else if (class == BPF_STX) {
9487 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
9488 
9489 			if (BPF_MODE(insn->code) == BPF_XADD) {
9490 				err = check_xadd(env, env->insn_idx, insn);
9491 				if (err)
9492 					return err;
9493 				env->insn_idx++;
9494 				continue;
9495 			}
9496 
9497 			/* check src1 operand */
9498 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9499 			if (err)
9500 				return err;
9501 			/* check src2 operand */
9502 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9503 			if (err)
9504 				return err;
9505 
9506 			dst_reg_type = regs[insn->dst_reg].type;
9507 
9508 			/* check that memory (dst_reg + off) is writeable */
9509 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9510 					       insn->off, BPF_SIZE(insn->code),
9511 					       BPF_WRITE, insn->src_reg, false);
9512 			if (err)
9513 				return err;
9514 
9515 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9516 
9517 			if (*prev_dst_type == NOT_INIT) {
9518 				*prev_dst_type = dst_reg_type;
9519 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
9520 				verbose(env, "same insn cannot be used with different pointers\n");
9521 				return -EINVAL;
9522 			}
9523 
9524 		} else if (class == BPF_ST) {
9525 			if (BPF_MODE(insn->code) != BPF_MEM ||
9526 			    insn->src_reg != BPF_REG_0) {
9527 				verbose(env, "BPF_ST uses reserved fields\n");
9528 				return -EINVAL;
9529 			}
9530 			/* check src operand */
9531 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9532 			if (err)
9533 				return err;
9534 
9535 			if (is_ctx_reg(env, insn->dst_reg)) {
9536 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
9537 					insn->dst_reg,
9538 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
9539 				return -EACCES;
9540 			}
9541 
9542 			/* check that memory (dst_reg + off) is writeable */
9543 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9544 					       insn->off, BPF_SIZE(insn->code),
9545 					       BPF_WRITE, -1, false);
9546 			if (err)
9547 				return err;
9548 
9549 		} else if (class == BPF_JMP || class == BPF_JMP32) {
9550 			u8 opcode = BPF_OP(insn->code);
9551 
9552 			env->jmps_processed++;
9553 			if (opcode == BPF_CALL) {
9554 				if (BPF_SRC(insn->code) != BPF_K ||
9555 				    insn->off != 0 ||
9556 				    (insn->src_reg != BPF_REG_0 &&
9557 				     insn->src_reg != BPF_PSEUDO_CALL) ||
9558 				    insn->dst_reg != BPF_REG_0 ||
9559 				    class == BPF_JMP32) {
9560 					verbose(env, "BPF_CALL uses reserved fields\n");
9561 					return -EINVAL;
9562 				}
9563 
9564 				if (env->cur_state->active_spin_lock &&
9565 				    (insn->src_reg == BPF_PSEUDO_CALL ||
9566 				     insn->imm != BPF_FUNC_spin_unlock)) {
9567 					verbose(env, "function calls are not allowed while holding a lock\n");
9568 					return -EINVAL;
9569 				}
9570 				if (insn->src_reg == BPF_PSEUDO_CALL)
9571 					err = check_func_call(env, insn, &env->insn_idx);
9572 				else
9573 					err = check_helper_call(env, insn->imm, env->insn_idx);
9574 				if (err)
9575 					return err;
9576 
9577 			} else if (opcode == BPF_JA) {
9578 				if (BPF_SRC(insn->code) != BPF_K ||
9579 				    insn->imm != 0 ||
9580 				    insn->src_reg != BPF_REG_0 ||
9581 				    insn->dst_reg != BPF_REG_0 ||
9582 				    class == BPF_JMP32) {
9583 					verbose(env, "BPF_JA uses reserved fields\n");
9584 					return -EINVAL;
9585 				}
9586 
9587 				env->insn_idx += insn->off + 1;
9588 				continue;
9589 
9590 			} else if (opcode == BPF_EXIT) {
9591 				if (BPF_SRC(insn->code) != BPF_K ||
9592 				    insn->imm != 0 ||
9593 				    insn->src_reg != BPF_REG_0 ||
9594 				    insn->dst_reg != BPF_REG_0 ||
9595 				    class == BPF_JMP32) {
9596 					verbose(env, "BPF_EXIT uses reserved fields\n");
9597 					return -EINVAL;
9598 				}
9599 
9600 				if (env->cur_state->active_spin_lock) {
9601 					verbose(env, "bpf_spin_unlock is missing\n");
9602 					return -EINVAL;
9603 				}
9604 
9605 				if (state->curframe) {
9606 					/* exit from nested function */
9607 					err = prepare_func_exit(env, &env->insn_idx);
9608 					if (err)
9609 						return err;
9610 					do_print_state = true;
9611 					continue;
9612 				}
9613 
9614 				err = check_reference_leak(env);
9615 				if (err)
9616 					return err;
9617 
9618 				err = check_return_code(env);
9619 				if (err)
9620 					return err;
9621 process_bpf_exit:
9622 				update_branch_counts(env, env->cur_state);
9623 				err = pop_stack(env, &prev_insn_idx,
9624 						&env->insn_idx, pop_log);
9625 				if (err < 0) {
9626 					if (err != -ENOENT)
9627 						return err;
9628 					break;
9629 				} else {
9630 					do_print_state = true;
9631 					continue;
9632 				}
9633 			} else {
9634 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
9635 				if (err)
9636 					return err;
9637 			}
9638 		} else if (class == BPF_LD) {
9639 			u8 mode = BPF_MODE(insn->code);
9640 
9641 			if (mode == BPF_ABS || mode == BPF_IND) {
9642 				err = check_ld_abs(env, insn);
9643 				if (err)
9644 					return err;
9645 
9646 			} else if (mode == BPF_IMM) {
9647 				err = check_ld_imm(env, insn);
9648 				if (err)
9649 					return err;
9650 
9651 				env->insn_idx++;
9652 				env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9653 			} else {
9654 				verbose(env, "invalid BPF_LD mode\n");
9655 				return -EINVAL;
9656 			}
9657 		} else {
9658 			verbose(env, "unknown insn class %d\n", class);
9659 			return -EINVAL;
9660 		}
9661 
9662 		env->insn_idx++;
9663 	}
9664 
9665 	return 0;
9666 }
9667 
9668 /* replace pseudo btf_id with kernel symbol address */
9669 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
9670 			       struct bpf_insn *insn,
9671 			       struct bpf_insn_aux_data *aux)
9672 {
9673 	u32 datasec_id, type, id = insn->imm;
9674 	const struct btf_var_secinfo *vsi;
9675 	const struct btf_type *datasec;
9676 	const struct btf_type *t;
9677 	const char *sym_name;
9678 	bool percpu = false;
9679 	u64 addr;
9680 	int i;
9681 
9682 	if (!btf_vmlinux) {
9683 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
9684 		return -EINVAL;
9685 	}
9686 
9687 	if (insn[1].imm != 0) {
9688 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
9689 		return -EINVAL;
9690 	}
9691 
9692 	t = btf_type_by_id(btf_vmlinux, id);
9693 	if (!t) {
9694 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
9695 		return -ENOENT;
9696 	}
9697 
9698 	if (!btf_type_is_var(t)) {
9699 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
9700 			id);
9701 		return -EINVAL;
9702 	}
9703 
9704 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
9705 	addr = kallsyms_lookup_name(sym_name);
9706 	if (!addr) {
9707 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
9708 			sym_name);
9709 		return -ENOENT;
9710 	}
9711 
9712 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
9713 					   BTF_KIND_DATASEC);
9714 	if (datasec_id > 0) {
9715 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
9716 		for_each_vsi(i, datasec, vsi) {
9717 			if (vsi->type == id) {
9718 				percpu = true;
9719 				break;
9720 			}
9721 		}
9722 	}
9723 
9724 	insn[0].imm = (u32)addr;
9725 	insn[1].imm = addr >> 32;
9726 
9727 	type = t->type;
9728 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
9729 	if (percpu) {
9730 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
9731 		aux->btf_var.btf_id = type;
9732 	} else if (!btf_type_is_struct(t)) {
9733 		const struct btf_type *ret;
9734 		const char *tname;
9735 		u32 tsize;
9736 
9737 		/* resolve the type size of ksym. */
9738 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
9739 		if (IS_ERR(ret)) {
9740 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9741 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
9742 				tname, PTR_ERR(ret));
9743 			return -EINVAL;
9744 		}
9745 		aux->btf_var.reg_type = PTR_TO_MEM;
9746 		aux->btf_var.mem_size = tsize;
9747 	} else {
9748 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
9749 		aux->btf_var.btf_id = type;
9750 	}
9751 	return 0;
9752 }
9753 
9754 static int check_map_prealloc(struct bpf_map *map)
9755 {
9756 	return (map->map_type != BPF_MAP_TYPE_HASH &&
9757 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9758 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
9759 		!(map->map_flags & BPF_F_NO_PREALLOC);
9760 }
9761 
9762 static bool is_tracing_prog_type(enum bpf_prog_type type)
9763 {
9764 	switch (type) {
9765 	case BPF_PROG_TYPE_KPROBE:
9766 	case BPF_PROG_TYPE_TRACEPOINT:
9767 	case BPF_PROG_TYPE_PERF_EVENT:
9768 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9769 		return true;
9770 	default:
9771 		return false;
9772 	}
9773 }
9774 
9775 static bool is_preallocated_map(struct bpf_map *map)
9776 {
9777 	if (!check_map_prealloc(map))
9778 		return false;
9779 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9780 		return false;
9781 	return true;
9782 }
9783 
9784 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9785 					struct bpf_map *map,
9786 					struct bpf_prog *prog)
9787 
9788 {
9789 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
9790 	/*
9791 	 * Validate that trace type programs use preallocated hash maps.
9792 	 *
9793 	 * For programs attached to PERF events this is mandatory as the
9794 	 * perf NMI can hit any arbitrary code sequence.
9795 	 *
9796 	 * All other trace types using preallocated hash maps are unsafe as
9797 	 * well because tracepoint or kprobes can be inside locked regions
9798 	 * of the memory allocator or at a place where a recursion into the
9799 	 * memory allocator would see inconsistent state.
9800 	 *
9801 	 * On RT enabled kernels run-time allocation of all trace type
9802 	 * programs is strictly prohibited due to lock type constraints. On
9803 	 * !RT kernels it is allowed for backwards compatibility reasons for
9804 	 * now, but warnings are emitted so developers are made aware of
9805 	 * the unsafety and can fix their programs before this is enforced.
9806 	 */
9807 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9808 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
9809 			verbose(env, "perf_event programs can only use preallocated hash map\n");
9810 			return -EINVAL;
9811 		}
9812 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9813 			verbose(env, "trace type programs can only use preallocated hash map\n");
9814 			return -EINVAL;
9815 		}
9816 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9817 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
9818 	}
9819 
9820 	if (map_value_has_spin_lock(map)) {
9821 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
9822 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
9823 			return -EINVAL;
9824 		}
9825 
9826 		if (is_tracing_prog_type(prog_type)) {
9827 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9828 			return -EINVAL;
9829 		}
9830 
9831 		if (prog->aux->sleepable) {
9832 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
9833 			return -EINVAL;
9834 		}
9835 	}
9836 
9837 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
9838 	    !bpf_offload_prog_map_match(prog, map)) {
9839 		verbose(env, "offload device mismatch between prog and map\n");
9840 		return -EINVAL;
9841 	}
9842 
9843 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9844 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9845 		return -EINVAL;
9846 	}
9847 
9848 	if (prog->aux->sleepable)
9849 		switch (map->map_type) {
9850 		case BPF_MAP_TYPE_HASH:
9851 		case BPF_MAP_TYPE_LRU_HASH:
9852 		case BPF_MAP_TYPE_ARRAY:
9853 			if (!is_preallocated_map(map)) {
9854 				verbose(env,
9855 					"Sleepable programs can only use preallocated hash maps\n");
9856 				return -EINVAL;
9857 			}
9858 			break;
9859 		default:
9860 			verbose(env,
9861 				"Sleepable programs can only use array and hash maps\n");
9862 			return -EINVAL;
9863 		}
9864 
9865 	return 0;
9866 }
9867 
9868 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9869 {
9870 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9871 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9872 }
9873 
9874 /* find and rewrite pseudo imm in ld_imm64 instructions:
9875  *
9876  * 1. if it accesses map FD, replace it with actual map pointer.
9877  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
9878  *
9879  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
9880  */
9881 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
9882 {
9883 	struct bpf_insn *insn = env->prog->insnsi;
9884 	int insn_cnt = env->prog->len;
9885 	int i, j, err;
9886 
9887 	err = bpf_prog_calc_tag(env->prog);
9888 	if (err)
9889 		return err;
9890 
9891 	for (i = 0; i < insn_cnt; i++, insn++) {
9892 		if (BPF_CLASS(insn->code) == BPF_LDX &&
9893 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9894 			verbose(env, "BPF_LDX uses reserved fields\n");
9895 			return -EINVAL;
9896 		}
9897 
9898 		if (BPF_CLASS(insn->code) == BPF_STX &&
9899 		    ((BPF_MODE(insn->code) != BPF_MEM &&
9900 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
9901 			verbose(env, "BPF_STX uses reserved fields\n");
9902 			return -EINVAL;
9903 		}
9904 
9905 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
9906 			struct bpf_insn_aux_data *aux;
9907 			struct bpf_map *map;
9908 			struct fd f;
9909 			u64 addr;
9910 
9911 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
9912 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9913 			    insn[1].off != 0) {
9914 				verbose(env, "invalid bpf_ld_imm64 insn\n");
9915 				return -EINVAL;
9916 			}
9917 
9918 			if (insn[0].src_reg == 0)
9919 				/* valid generic load 64-bit imm */
9920 				goto next_insn;
9921 
9922 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
9923 				aux = &env->insn_aux_data[i];
9924 				err = check_pseudo_btf_id(env, insn, aux);
9925 				if (err)
9926 					return err;
9927 				goto next_insn;
9928 			}
9929 
9930 			/* In final convert_pseudo_ld_imm64() step, this is
9931 			 * converted into regular 64-bit imm load insn.
9932 			 */
9933 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9934 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9935 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9936 			     insn[1].imm != 0)) {
9937 				verbose(env,
9938 					"unrecognized bpf_ld_imm64 insn\n");
9939 				return -EINVAL;
9940 			}
9941 
9942 			f = fdget(insn[0].imm);
9943 			map = __bpf_map_get(f);
9944 			if (IS_ERR(map)) {
9945 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
9946 					insn[0].imm);
9947 				return PTR_ERR(map);
9948 			}
9949 
9950 			err = check_map_prog_compatibility(env, map, env->prog);
9951 			if (err) {
9952 				fdput(f);
9953 				return err;
9954 			}
9955 
9956 			aux = &env->insn_aux_data[i];
9957 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9958 				addr = (unsigned long)map;
9959 			} else {
9960 				u32 off = insn[1].imm;
9961 
9962 				if (off >= BPF_MAX_VAR_OFF) {
9963 					verbose(env, "direct value offset of %u is not allowed\n", off);
9964 					fdput(f);
9965 					return -EINVAL;
9966 				}
9967 
9968 				if (!map->ops->map_direct_value_addr) {
9969 					verbose(env, "no direct value access support for this map type\n");
9970 					fdput(f);
9971 					return -EINVAL;
9972 				}
9973 
9974 				err = map->ops->map_direct_value_addr(map, &addr, off);
9975 				if (err) {
9976 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9977 						map->value_size, off);
9978 					fdput(f);
9979 					return err;
9980 				}
9981 
9982 				aux->map_off = off;
9983 				addr += off;
9984 			}
9985 
9986 			insn[0].imm = (u32)addr;
9987 			insn[1].imm = addr >> 32;
9988 
9989 			/* check whether we recorded this map already */
9990 			for (j = 0; j < env->used_map_cnt; j++) {
9991 				if (env->used_maps[j] == map) {
9992 					aux->map_index = j;
9993 					fdput(f);
9994 					goto next_insn;
9995 				}
9996 			}
9997 
9998 			if (env->used_map_cnt >= MAX_USED_MAPS) {
9999 				fdput(f);
10000 				return -E2BIG;
10001 			}
10002 
10003 			/* hold the map. If the program is rejected by verifier,
10004 			 * the map will be released by release_maps() or it
10005 			 * will be used by the valid program until it's unloaded
10006 			 * and all maps are released in free_used_maps()
10007 			 */
10008 			bpf_map_inc(map);
10009 
10010 			aux->map_index = env->used_map_cnt;
10011 			env->used_maps[env->used_map_cnt++] = map;
10012 
10013 			if (bpf_map_is_cgroup_storage(map) &&
10014 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10015 				verbose(env, "only one cgroup storage of each type is allowed\n");
10016 				fdput(f);
10017 				return -EBUSY;
10018 			}
10019 
10020 			fdput(f);
10021 next_insn:
10022 			insn++;
10023 			i++;
10024 			continue;
10025 		}
10026 
10027 		/* Basic sanity check before we invest more work here. */
10028 		if (!bpf_opcode_in_insntable(insn->code)) {
10029 			verbose(env, "unknown opcode %02x\n", insn->code);
10030 			return -EINVAL;
10031 		}
10032 	}
10033 
10034 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10035 	 * 'struct bpf_map *' into a register instead of user map_fd.
10036 	 * These pointers will be used later by verifier to validate map access.
10037 	 */
10038 	return 0;
10039 }
10040 
10041 /* drop refcnt of maps used by the rejected program */
10042 static void release_maps(struct bpf_verifier_env *env)
10043 {
10044 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10045 			     env->used_map_cnt);
10046 }
10047 
10048 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10049 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10050 {
10051 	struct bpf_insn *insn = env->prog->insnsi;
10052 	int insn_cnt = env->prog->len;
10053 	int i;
10054 
10055 	for (i = 0; i < insn_cnt; i++, insn++)
10056 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10057 			insn->src_reg = 0;
10058 }
10059 
10060 /* single env->prog->insni[off] instruction was replaced with the range
10061  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10062  * [0, off) and [off, end) to new locations, so the patched range stays zero
10063  */
10064 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10065 				struct bpf_prog *new_prog, u32 off, u32 cnt)
10066 {
10067 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10068 	struct bpf_insn *insn = new_prog->insnsi;
10069 	u32 prog_len;
10070 	int i;
10071 
10072 	/* aux info at OFF always needs adjustment, no matter fast path
10073 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10074 	 * original insn at old prog.
10075 	 */
10076 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10077 
10078 	if (cnt == 1)
10079 		return 0;
10080 	prog_len = new_prog->len;
10081 	new_data = vzalloc(array_size(prog_len,
10082 				      sizeof(struct bpf_insn_aux_data)));
10083 	if (!new_data)
10084 		return -ENOMEM;
10085 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10086 	memcpy(new_data + off + cnt - 1, old_data + off,
10087 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10088 	for (i = off; i < off + cnt - 1; i++) {
10089 		new_data[i].seen = env->pass_cnt;
10090 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10091 	}
10092 	env->insn_aux_data = new_data;
10093 	vfree(old_data);
10094 	return 0;
10095 }
10096 
10097 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10098 {
10099 	int i;
10100 
10101 	if (len == 1)
10102 		return;
10103 	/* NOTE: fake 'exit' subprog should be updated as well. */
10104 	for (i = 0; i <= env->subprog_cnt; i++) {
10105 		if (env->subprog_info[i].start <= off)
10106 			continue;
10107 		env->subprog_info[i].start += len - 1;
10108 	}
10109 }
10110 
10111 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10112 {
10113 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10114 	int i, sz = prog->aux->size_poke_tab;
10115 	struct bpf_jit_poke_descriptor *desc;
10116 
10117 	for (i = 0; i < sz; i++) {
10118 		desc = &tab[i];
10119 		desc->insn_idx += len - 1;
10120 	}
10121 }
10122 
10123 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10124 					    const struct bpf_insn *patch, u32 len)
10125 {
10126 	struct bpf_prog *new_prog;
10127 
10128 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10129 	if (IS_ERR(new_prog)) {
10130 		if (PTR_ERR(new_prog) == -ERANGE)
10131 			verbose(env,
10132 				"insn %d cannot be patched due to 16-bit range\n",
10133 				env->insn_aux_data[off].orig_idx);
10134 		return NULL;
10135 	}
10136 	if (adjust_insn_aux_data(env, new_prog, off, len))
10137 		return NULL;
10138 	adjust_subprog_starts(env, off, len);
10139 	adjust_poke_descs(new_prog, len);
10140 	return new_prog;
10141 }
10142 
10143 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10144 					      u32 off, u32 cnt)
10145 {
10146 	int i, j;
10147 
10148 	/* find first prog starting at or after off (first to remove) */
10149 	for (i = 0; i < env->subprog_cnt; i++)
10150 		if (env->subprog_info[i].start >= off)
10151 			break;
10152 	/* find first prog starting at or after off + cnt (first to stay) */
10153 	for (j = i; j < env->subprog_cnt; j++)
10154 		if (env->subprog_info[j].start >= off + cnt)
10155 			break;
10156 	/* if j doesn't start exactly at off + cnt, we are just removing
10157 	 * the front of previous prog
10158 	 */
10159 	if (env->subprog_info[j].start != off + cnt)
10160 		j--;
10161 
10162 	if (j > i) {
10163 		struct bpf_prog_aux *aux = env->prog->aux;
10164 		int move;
10165 
10166 		/* move fake 'exit' subprog as well */
10167 		move = env->subprog_cnt + 1 - j;
10168 
10169 		memmove(env->subprog_info + i,
10170 			env->subprog_info + j,
10171 			sizeof(*env->subprog_info) * move);
10172 		env->subprog_cnt -= j - i;
10173 
10174 		/* remove func_info */
10175 		if (aux->func_info) {
10176 			move = aux->func_info_cnt - j;
10177 
10178 			memmove(aux->func_info + i,
10179 				aux->func_info + j,
10180 				sizeof(*aux->func_info) * move);
10181 			aux->func_info_cnt -= j - i;
10182 			/* func_info->insn_off is set after all code rewrites,
10183 			 * in adjust_btf_func() - no need to adjust
10184 			 */
10185 		}
10186 	} else {
10187 		/* convert i from "first prog to remove" to "first to adjust" */
10188 		if (env->subprog_info[i].start == off)
10189 			i++;
10190 	}
10191 
10192 	/* update fake 'exit' subprog as well */
10193 	for (; i <= env->subprog_cnt; i++)
10194 		env->subprog_info[i].start -= cnt;
10195 
10196 	return 0;
10197 }
10198 
10199 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10200 				      u32 cnt)
10201 {
10202 	struct bpf_prog *prog = env->prog;
10203 	u32 i, l_off, l_cnt, nr_linfo;
10204 	struct bpf_line_info *linfo;
10205 
10206 	nr_linfo = prog->aux->nr_linfo;
10207 	if (!nr_linfo)
10208 		return 0;
10209 
10210 	linfo = prog->aux->linfo;
10211 
10212 	/* find first line info to remove, count lines to be removed */
10213 	for (i = 0; i < nr_linfo; i++)
10214 		if (linfo[i].insn_off >= off)
10215 			break;
10216 
10217 	l_off = i;
10218 	l_cnt = 0;
10219 	for (; i < nr_linfo; i++)
10220 		if (linfo[i].insn_off < off + cnt)
10221 			l_cnt++;
10222 		else
10223 			break;
10224 
10225 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10226 	 * last removed linfo.  prog is already modified, so prog->len == off
10227 	 * means no live instructions after (tail of the program was removed).
10228 	 */
10229 	if (prog->len != off && l_cnt &&
10230 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10231 		l_cnt--;
10232 		linfo[--i].insn_off = off + cnt;
10233 	}
10234 
10235 	/* remove the line info which refer to the removed instructions */
10236 	if (l_cnt) {
10237 		memmove(linfo + l_off, linfo + i,
10238 			sizeof(*linfo) * (nr_linfo - i));
10239 
10240 		prog->aux->nr_linfo -= l_cnt;
10241 		nr_linfo = prog->aux->nr_linfo;
10242 	}
10243 
10244 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10245 	for (i = l_off; i < nr_linfo; i++)
10246 		linfo[i].insn_off -= cnt;
10247 
10248 	/* fix up all subprogs (incl. 'exit') which start >= off */
10249 	for (i = 0; i <= env->subprog_cnt; i++)
10250 		if (env->subprog_info[i].linfo_idx > l_off) {
10251 			/* program may have started in the removed region but
10252 			 * may not be fully removed
10253 			 */
10254 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10255 				env->subprog_info[i].linfo_idx -= l_cnt;
10256 			else
10257 				env->subprog_info[i].linfo_idx = l_off;
10258 		}
10259 
10260 	return 0;
10261 }
10262 
10263 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10264 {
10265 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10266 	unsigned int orig_prog_len = env->prog->len;
10267 	int err;
10268 
10269 	if (bpf_prog_is_dev_bound(env->prog->aux))
10270 		bpf_prog_offload_remove_insns(env, off, cnt);
10271 
10272 	err = bpf_remove_insns(env->prog, off, cnt);
10273 	if (err)
10274 		return err;
10275 
10276 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10277 	if (err)
10278 		return err;
10279 
10280 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10281 	if (err)
10282 		return err;
10283 
10284 	memmove(aux_data + off,	aux_data + off + cnt,
10285 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10286 
10287 	return 0;
10288 }
10289 
10290 /* The verifier does more data flow analysis than llvm and will not
10291  * explore branches that are dead at run time. Malicious programs can
10292  * have dead code too. Therefore replace all dead at-run-time code
10293  * with 'ja -1'.
10294  *
10295  * Just nops are not optimal, e.g. if they would sit at the end of the
10296  * program and through another bug we would manage to jump there, then
10297  * we'd execute beyond program memory otherwise. Returning exception
10298  * code also wouldn't work since we can have subprogs where the dead
10299  * code could be located.
10300  */
10301 static void sanitize_dead_code(struct bpf_verifier_env *env)
10302 {
10303 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10304 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10305 	struct bpf_insn *insn = env->prog->insnsi;
10306 	const int insn_cnt = env->prog->len;
10307 	int i;
10308 
10309 	for (i = 0; i < insn_cnt; i++) {
10310 		if (aux_data[i].seen)
10311 			continue;
10312 		memcpy(insn + i, &trap, sizeof(trap));
10313 	}
10314 }
10315 
10316 static bool insn_is_cond_jump(u8 code)
10317 {
10318 	u8 op;
10319 
10320 	if (BPF_CLASS(code) == BPF_JMP32)
10321 		return true;
10322 
10323 	if (BPF_CLASS(code) != BPF_JMP)
10324 		return false;
10325 
10326 	op = BPF_OP(code);
10327 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10328 }
10329 
10330 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10331 {
10332 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10333 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10334 	struct bpf_insn *insn = env->prog->insnsi;
10335 	const int insn_cnt = env->prog->len;
10336 	int i;
10337 
10338 	for (i = 0; i < insn_cnt; i++, insn++) {
10339 		if (!insn_is_cond_jump(insn->code))
10340 			continue;
10341 
10342 		if (!aux_data[i + 1].seen)
10343 			ja.off = insn->off;
10344 		else if (!aux_data[i + 1 + insn->off].seen)
10345 			ja.off = 0;
10346 		else
10347 			continue;
10348 
10349 		if (bpf_prog_is_dev_bound(env->prog->aux))
10350 			bpf_prog_offload_replace_insn(env, i, &ja);
10351 
10352 		memcpy(insn, &ja, sizeof(ja));
10353 	}
10354 }
10355 
10356 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10357 {
10358 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10359 	int insn_cnt = env->prog->len;
10360 	int i, err;
10361 
10362 	for (i = 0; i < insn_cnt; i++) {
10363 		int j;
10364 
10365 		j = 0;
10366 		while (i + j < insn_cnt && !aux_data[i + j].seen)
10367 			j++;
10368 		if (!j)
10369 			continue;
10370 
10371 		err = verifier_remove_insns(env, i, j);
10372 		if (err)
10373 			return err;
10374 		insn_cnt = env->prog->len;
10375 	}
10376 
10377 	return 0;
10378 }
10379 
10380 static int opt_remove_nops(struct bpf_verifier_env *env)
10381 {
10382 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10383 	struct bpf_insn *insn = env->prog->insnsi;
10384 	int insn_cnt = env->prog->len;
10385 	int i, err;
10386 
10387 	for (i = 0; i < insn_cnt; i++) {
10388 		if (memcmp(&insn[i], &ja, sizeof(ja)))
10389 			continue;
10390 
10391 		err = verifier_remove_insns(env, i, 1);
10392 		if (err)
10393 			return err;
10394 		insn_cnt--;
10395 		i--;
10396 	}
10397 
10398 	return 0;
10399 }
10400 
10401 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10402 					 const union bpf_attr *attr)
10403 {
10404 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10405 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
10406 	int i, patch_len, delta = 0, len = env->prog->len;
10407 	struct bpf_insn *insns = env->prog->insnsi;
10408 	struct bpf_prog *new_prog;
10409 	bool rnd_hi32;
10410 
10411 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
10412 	zext_patch[1] = BPF_ZEXT_REG(0);
10413 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10414 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10415 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
10416 	for (i = 0; i < len; i++) {
10417 		int adj_idx = i + delta;
10418 		struct bpf_insn insn;
10419 
10420 		insn = insns[adj_idx];
10421 		if (!aux[adj_idx].zext_dst) {
10422 			u8 code, class;
10423 			u32 imm_rnd;
10424 
10425 			if (!rnd_hi32)
10426 				continue;
10427 
10428 			code = insn.code;
10429 			class = BPF_CLASS(code);
10430 			if (insn_no_def(&insn))
10431 				continue;
10432 
10433 			/* NOTE: arg "reg" (the fourth one) is only used for
10434 			 *       BPF_STX which has been ruled out in above
10435 			 *       check, it is safe to pass NULL here.
10436 			 */
10437 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10438 				if (class == BPF_LD &&
10439 				    BPF_MODE(code) == BPF_IMM)
10440 					i++;
10441 				continue;
10442 			}
10443 
10444 			/* ctx load could be transformed into wider load. */
10445 			if (class == BPF_LDX &&
10446 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
10447 				continue;
10448 
10449 			imm_rnd = get_random_int();
10450 			rnd_hi32_patch[0] = insn;
10451 			rnd_hi32_patch[1].imm = imm_rnd;
10452 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10453 			patch = rnd_hi32_patch;
10454 			patch_len = 4;
10455 			goto apply_patch_buffer;
10456 		}
10457 
10458 		if (!bpf_jit_needs_zext())
10459 			continue;
10460 
10461 		zext_patch[0] = insn;
10462 		zext_patch[1].dst_reg = insn.dst_reg;
10463 		zext_patch[1].src_reg = insn.dst_reg;
10464 		patch = zext_patch;
10465 		patch_len = 2;
10466 apply_patch_buffer:
10467 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
10468 		if (!new_prog)
10469 			return -ENOMEM;
10470 		env->prog = new_prog;
10471 		insns = new_prog->insnsi;
10472 		aux = env->insn_aux_data;
10473 		delta += patch_len - 1;
10474 	}
10475 
10476 	return 0;
10477 }
10478 
10479 /* convert load instructions that access fields of a context type into a
10480  * sequence of instructions that access fields of the underlying structure:
10481  *     struct __sk_buff    -> struct sk_buff
10482  *     struct bpf_sock_ops -> struct sock
10483  */
10484 static int convert_ctx_accesses(struct bpf_verifier_env *env)
10485 {
10486 	const struct bpf_verifier_ops *ops = env->ops;
10487 	int i, cnt, size, ctx_field_size, delta = 0;
10488 	const int insn_cnt = env->prog->len;
10489 	struct bpf_insn insn_buf[16], *insn;
10490 	u32 target_size, size_default, off;
10491 	struct bpf_prog *new_prog;
10492 	enum bpf_access_type type;
10493 	bool is_narrower_load;
10494 
10495 	if (ops->gen_prologue || env->seen_direct_write) {
10496 		if (!ops->gen_prologue) {
10497 			verbose(env, "bpf verifier is misconfigured\n");
10498 			return -EINVAL;
10499 		}
10500 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10501 					env->prog);
10502 		if (cnt >= ARRAY_SIZE(insn_buf)) {
10503 			verbose(env, "bpf verifier is misconfigured\n");
10504 			return -EINVAL;
10505 		} else if (cnt) {
10506 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
10507 			if (!new_prog)
10508 				return -ENOMEM;
10509 
10510 			env->prog = new_prog;
10511 			delta += cnt - 1;
10512 		}
10513 	}
10514 
10515 	if (bpf_prog_is_dev_bound(env->prog->aux))
10516 		return 0;
10517 
10518 	insn = env->prog->insnsi + delta;
10519 
10520 	for (i = 0; i < insn_cnt; i++, insn++) {
10521 		bpf_convert_ctx_access_t convert_ctx_access;
10522 
10523 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10524 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10525 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
10526 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
10527 			type = BPF_READ;
10528 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10529 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10530 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
10531 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
10532 			type = BPF_WRITE;
10533 		else
10534 			continue;
10535 
10536 		if (type == BPF_WRITE &&
10537 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
10538 			struct bpf_insn patch[] = {
10539 				/* Sanitize suspicious stack slot with zero.
10540 				 * There are no memory dependencies for this store,
10541 				 * since it's only using frame pointer and immediate
10542 				 * constant of zero
10543 				 */
10544 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10545 					   env->insn_aux_data[i + delta].sanitize_stack_off,
10546 					   0),
10547 				/* the original STX instruction will immediately
10548 				 * overwrite the same stack slot with appropriate value
10549 				 */
10550 				*insn,
10551 			};
10552 
10553 			cnt = ARRAY_SIZE(patch);
10554 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10555 			if (!new_prog)
10556 				return -ENOMEM;
10557 
10558 			delta    += cnt - 1;
10559 			env->prog = new_prog;
10560 			insn      = new_prog->insnsi + i + delta;
10561 			continue;
10562 		}
10563 
10564 		switch (env->insn_aux_data[i + delta].ptr_type) {
10565 		case PTR_TO_CTX:
10566 			if (!ops->convert_ctx_access)
10567 				continue;
10568 			convert_ctx_access = ops->convert_ctx_access;
10569 			break;
10570 		case PTR_TO_SOCKET:
10571 		case PTR_TO_SOCK_COMMON:
10572 			convert_ctx_access = bpf_sock_convert_ctx_access;
10573 			break;
10574 		case PTR_TO_TCP_SOCK:
10575 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10576 			break;
10577 		case PTR_TO_XDP_SOCK:
10578 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10579 			break;
10580 		case PTR_TO_BTF_ID:
10581 			if (type == BPF_READ) {
10582 				insn->code = BPF_LDX | BPF_PROBE_MEM |
10583 					BPF_SIZE((insn)->code);
10584 				env->prog->aux->num_exentries++;
10585 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
10586 				verbose(env, "Writes through BTF pointers are not allowed\n");
10587 				return -EINVAL;
10588 			}
10589 			continue;
10590 		default:
10591 			continue;
10592 		}
10593 
10594 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
10595 		size = BPF_LDST_BYTES(insn);
10596 
10597 		/* If the read access is a narrower load of the field,
10598 		 * convert to a 4/8-byte load, to minimum program type specific
10599 		 * convert_ctx_access changes. If conversion is successful,
10600 		 * we will apply proper mask to the result.
10601 		 */
10602 		is_narrower_load = size < ctx_field_size;
10603 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10604 		off = insn->off;
10605 		if (is_narrower_load) {
10606 			u8 size_code;
10607 
10608 			if (type == BPF_WRITE) {
10609 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
10610 				return -EINVAL;
10611 			}
10612 
10613 			size_code = BPF_H;
10614 			if (ctx_field_size == 4)
10615 				size_code = BPF_W;
10616 			else if (ctx_field_size == 8)
10617 				size_code = BPF_DW;
10618 
10619 			insn->off = off & ~(size_default - 1);
10620 			insn->code = BPF_LDX | BPF_MEM | size_code;
10621 		}
10622 
10623 		target_size = 0;
10624 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10625 					 &target_size);
10626 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10627 		    (ctx_field_size && !target_size)) {
10628 			verbose(env, "bpf verifier is misconfigured\n");
10629 			return -EINVAL;
10630 		}
10631 
10632 		if (is_narrower_load && size < target_size) {
10633 			u8 shift = bpf_ctx_narrow_access_offset(
10634 				off, size, size_default) * 8;
10635 			if (ctx_field_size <= 4) {
10636 				if (shift)
10637 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10638 									insn->dst_reg,
10639 									shift);
10640 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
10641 								(1 << size * 8) - 1);
10642 			} else {
10643 				if (shift)
10644 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10645 									insn->dst_reg,
10646 									shift);
10647 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
10648 								(1ULL << size * 8) - 1);
10649 			}
10650 		}
10651 
10652 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10653 		if (!new_prog)
10654 			return -ENOMEM;
10655 
10656 		delta += cnt - 1;
10657 
10658 		/* keep walking new program and skip insns we just inserted */
10659 		env->prog = new_prog;
10660 		insn      = new_prog->insnsi + i + delta;
10661 	}
10662 
10663 	return 0;
10664 }
10665 
10666 static int jit_subprogs(struct bpf_verifier_env *env)
10667 {
10668 	struct bpf_prog *prog = env->prog, **func, *tmp;
10669 	int i, j, subprog_start, subprog_end = 0, len, subprog;
10670 	struct bpf_map *map_ptr;
10671 	struct bpf_insn *insn;
10672 	void *old_bpf_func;
10673 	int err, num_exentries;
10674 
10675 	if (env->subprog_cnt <= 1)
10676 		return 0;
10677 
10678 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10679 		if (insn->code != (BPF_JMP | BPF_CALL) ||
10680 		    insn->src_reg != BPF_PSEUDO_CALL)
10681 			continue;
10682 		/* Upon error here we cannot fall back to interpreter but
10683 		 * need a hard reject of the program. Thus -EFAULT is
10684 		 * propagated in any case.
10685 		 */
10686 		subprog = find_subprog(env, i + insn->imm + 1);
10687 		if (subprog < 0) {
10688 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10689 				  i + insn->imm + 1);
10690 			return -EFAULT;
10691 		}
10692 		/* temporarily remember subprog id inside insn instead of
10693 		 * aux_data, since next loop will split up all insns into funcs
10694 		 */
10695 		insn->off = subprog;
10696 		/* remember original imm in case JIT fails and fallback
10697 		 * to interpreter will be needed
10698 		 */
10699 		env->insn_aux_data[i].call_imm = insn->imm;
10700 		/* point imm to __bpf_call_base+1 from JITs point of view */
10701 		insn->imm = 1;
10702 	}
10703 
10704 	err = bpf_prog_alloc_jited_linfo(prog);
10705 	if (err)
10706 		goto out_undo_insn;
10707 
10708 	err = -ENOMEM;
10709 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
10710 	if (!func)
10711 		goto out_undo_insn;
10712 
10713 	for (i = 0; i < env->subprog_cnt; i++) {
10714 		subprog_start = subprog_end;
10715 		subprog_end = env->subprog_info[i + 1].start;
10716 
10717 		len = subprog_end - subprog_start;
10718 		/* BPF_PROG_RUN doesn't call subprogs directly,
10719 		 * hence main prog stats include the runtime of subprogs.
10720 		 * subprogs don't have IDs and not reachable via prog_get_next_id
10721 		 * func[i]->aux->stats will never be accessed and stays NULL
10722 		 */
10723 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
10724 		if (!func[i])
10725 			goto out_free;
10726 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10727 		       len * sizeof(struct bpf_insn));
10728 		func[i]->type = prog->type;
10729 		func[i]->len = len;
10730 		if (bpf_prog_calc_tag(func[i]))
10731 			goto out_free;
10732 		func[i]->is_func = 1;
10733 		func[i]->aux->func_idx = i;
10734 		/* the btf and func_info will be freed only at prog->aux */
10735 		func[i]->aux->btf = prog->aux->btf;
10736 		func[i]->aux->func_info = prog->aux->func_info;
10737 
10738 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
10739 			u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10740 			int ret;
10741 
10742 			if (!(insn_idx >= subprog_start &&
10743 			      insn_idx <= subprog_end))
10744 				continue;
10745 
10746 			ret = bpf_jit_add_poke_descriptor(func[i],
10747 							  &prog->aux->poke_tab[j]);
10748 			if (ret < 0) {
10749 				verbose(env, "adding tail call poke descriptor failed\n");
10750 				goto out_free;
10751 			}
10752 
10753 			func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10754 
10755 			map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10756 			ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10757 			if (ret < 0) {
10758 				verbose(env, "tracking tail call prog failed\n");
10759 				goto out_free;
10760 			}
10761 		}
10762 
10763 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
10764 		 * Long term would need debug info to populate names
10765 		 */
10766 		func[i]->aux->name[0] = 'F';
10767 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
10768 		func[i]->jit_requested = 1;
10769 		func[i]->aux->linfo = prog->aux->linfo;
10770 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10771 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10772 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
10773 		num_exentries = 0;
10774 		insn = func[i]->insnsi;
10775 		for (j = 0; j < func[i]->len; j++, insn++) {
10776 			if (BPF_CLASS(insn->code) == BPF_LDX &&
10777 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
10778 				num_exentries++;
10779 		}
10780 		func[i]->aux->num_exentries = num_exentries;
10781 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
10782 		func[i] = bpf_int_jit_compile(func[i]);
10783 		if (!func[i]->jited) {
10784 			err = -ENOTSUPP;
10785 			goto out_free;
10786 		}
10787 		cond_resched();
10788 	}
10789 
10790 	/* Untrack main program's aux structs so that during map_poke_run()
10791 	 * we will not stumble upon the unfilled poke descriptors; each
10792 	 * of the main program's poke descs got distributed across subprogs
10793 	 * and got tracked onto map, so we are sure that none of them will
10794 	 * be missed after the operation below
10795 	 */
10796 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
10797 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
10798 
10799 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10800 	}
10801 
10802 	/* at this point all bpf functions were successfully JITed
10803 	 * now populate all bpf_calls with correct addresses and
10804 	 * run last pass of JIT
10805 	 */
10806 	for (i = 0; i < env->subprog_cnt; i++) {
10807 		insn = func[i]->insnsi;
10808 		for (j = 0; j < func[i]->len; j++, insn++) {
10809 			if (insn->code != (BPF_JMP | BPF_CALL) ||
10810 			    insn->src_reg != BPF_PSEUDO_CALL)
10811 				continue;
10812 			subprog = insn->off;
10813 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10814 				    __bpf_call_base;
10815 		}
10816 
10817 		/* we use the aux data to keep a list of the start addresses
10818 		 * of the JITed images for each function in the program
10819 		 *
10820 		 * for some architectures, such as powerpc64, the imm field
10821 		 * might not be large enough to hold the offset of the start
10822 		 * address of the callee's JITed image from __bpf_call_base
10823 		 *
10824 		 * in such cases, we can lookup the start address of a callee
10825 		 * by using its subprog id, available from the off field of
10826 		 * the call instruction, as an index for this list
10827 		 */
10828 		func[i]->aux->func = func;
10829 		func[i]->aux->func_cnt = env->subprog_cnt;
10830 	}
10831 	for (i = 0; i < env->subprog_cnt; i++) {
10832 		old_bpf_func = func[i]->bpf_func;
10833 		tmp = bpf_int_jit_compile(func[i]);
10834 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10835 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
10836 			err = -ENOTSUPP;
10837 			goto out_free;
10838 		}
10839 		cond_resched();
10840 	}
10841 
10842 	/* finally lock prog and jit images for all functions and
10843 	 * populate kallsysm
10844 	 */
10845 	for (i = 0; i < env->subprog_cnt; i++) {
10846 		bpf_prog_lock_ro(func[i]);
10847 		bpf_prog_kallsyms_add(func[i]);
10848 	}
10849 
10850 	/* Last step: make now unused interpreter insns from main
10851 	 * prog consistent for later dump requests, so they can
10852 	 * later look the same as if they were interpreted only.
10853 	 */
10854 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10855 		if (insn->code != (BPF_JMP | BPF_CALL) ||
10856 		    insn->src_reg != BPF_PSEUDO_CALL)
10857 			continue;
10858 		insn->off = env->insn_aux_data[i].call_imm;
10859 		subprog = find_subprog(env, i + insn->off + 1);
10860 		insn->imm = subprog;
10861 	}
10862 
10863 	prog->jited = 1;
10864 	prog->bpf_func = func[0]->bpf_func;
10865 	prog->aux->func = func;
10866 	prog->aux->func_cnt = env->subprog_cnt;
10867 	bpf_prog_free_unused_jited_linfo(prog);
10868 	return 0;
10869 out_free:
10870 	for (i = 0; i < env->subprog_cnt; i++) {
10871 		if (!func[i])
10872 			continue;
10873 
10874 		for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10875 			map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10876 			map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10877 		}
10878 		bpf_jit_free(func[i]);
10879 	}
10880 	kfree(func);
10881 out_undo_insn:
10882 	/* cleanup main prog to be interpreted */
10883 	prog->jit_requested = 0;
10884 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10885 		if (insn->code != (BPF_JMP | BPF_CALL) ||
10886 		    insn->src_reg != BPF_PSEUDO_CALL)
10887 			continue;
10888 		insn->off = 0;
10889 		insn->imm = env->insn_aux_data[i].call_imm;
10890 	}
10891 	bpf_prog_free_jited_linfo(prog);
10892 	return err;
10893 }
10894 
10895 static int fixup_call_args(struct bpf_verifier_env *env)
10896 {
10897 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10898 	struct bpf_prog *prog = env->prog;
10899 	struct bpf_insn *insn = prog->insnsi;
10900 	int i, depth;
10901 #endif
10902 	int err = 0;
10903 
10904 	if (env->prog->jit_requested &&
10905 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
10906 		err = jit_subprogs(env);
10907 		if (err == 0)
10908 			return 0;
10909 		if (err == -EFAULT)
10910 			return err;
10911 	}
10912 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10913 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10914 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
10915 		 * have to be rejected, since interpreter doesn't support them yet.
10916 		 */
10917 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10918 		return -EINVAL;
10919 	}
10920 	for (i = 0; i < prog->len; i++, insn++) {
10921 		if (insn->code != (BPF_JMP | BPF_CALL) ||
10922 		    insn->src_reg != BPF_PSEUDO_CALL)
10923 			continue;
10924 		depth = get_callee_stack_depth(env, insn, i);
10925 		if (depth < 0)
10926 			return depth;
10927 		bpf_patch_call_args(insn, depth);
10928 	}
10929 	err = 0;
10930 #endif
10931 	return err;
10932 }
10933 
10934 /* fixup insn->imm field of bpf_call instructions
10935  * and inline eligible helpers as explicit sequence of BPF instructions
10936  *
10937  * this function is called after eBPF program passed verification
10938  */
10939 static int fixup_bpf_calls(struct bpf_verifier_env *env)
10940 {
10941 	struct bpf_prog *prog = env->prog;
10942 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
10943 	struct bpf_insn *insn = prog->insnsi;
10944 	const struct bpf_func_proto *fn;
10945 	const int insn_cnt = prog->len;
10946 	const struct bpf_map_ops *ops;
10947 	struct bpf_insn_aux_data *aux;
10948 	struct bpf_insn insn_buf[16];
10949 	struct bpf_prog *new_prog;
10950 	struct bpf_map *map_ptr;
10951 	int i, ret, cnt, delta = 0;
10952 
10953 	for (i = 0; i < insn_cnt; i++, insn++) {
10954 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10955 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10956 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
10957 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10958 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10959 			struct bpf_insn mask_and_div[] = {
10960 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10961 				/* Rx div 0 -> 0 */
10962 				BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10963 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10964 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10965 				*insn,
10966 			};
10967 			struct bpf_insn mask_and_mod[] = {
10968 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10969 				/* Rx mod 0 -> Rx */
10970 				BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10971 				*insn,
10972 			};
10973 			struct bpf_insn *patchlet;
10974 
10975 			if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10976 			    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10977 				patchlet = mask_and_div + (is64 ? 1 : 0);
10978 				cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10979 			} else {
10980 				patchlet = mask_and_mod + (is64 ? 1 : 0);
10981 				cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10982 			}
10983 
10984 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
10985 			if (!new_prog)
10986 				return -ENOMEM;
10987 
10988 			delta    += cnt - 1;
10989 			env->prog = prog = new_prog;
10990 			insn      = new_prog->insnsi + i + delta;
10991 			continue;
10992 		}
10993 
10994 		if (BPF_CLASS(insn->code) == BPF_LD &&
10995 		    (BPF_MODE(insn->code) == BPF_ABS ||
10996 		     BPF_MODE(insn->code) == BPF_IND)) {
10997 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
10998 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10999 				verbose(env, "bpf verifier is misconfigured\n");
11000 				return -EINVAL;
11001 			}
11002 
11003 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11004 			if (!new_prog)
11005 				return -ENOMEM;
11006 
11007 			delta    += cnt - 1;
11008 			env->prog = prog = new_prog;
11009 			insn      = new_prog->insnsi + i + delta;
11010 			continue;
11011 		}
11012 
11013 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11014 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11015 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11016 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11017 			struct bpf_insn insn_buf[16];
11018 			struct bpf_insn *patch = &insn_buf[0];
11019 			bool issrc, isneg;
11020 			u32 off_reg;
11021 
11022 			aux = &env->insn_aux_data[i + delta];
11023 			if (!aux->alu_state ||
11024 			    aux->alu_state == BPF_ALU_NON_POINTER)
11025 				continue;
11026 
11027 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11028 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11029 				BPF_ALU_SANITIZE_SRC;
11030 
11031 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11032 			if (isneg)
11033 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11034 			*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11035 			*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11036 			*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11037 			*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11038 			*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11039 			if (issrc) {
11040 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11041 							 off_reg);
11042 				insn->src_reg = BPF_REG_AX;
11043 			} else {
11044 				*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11045 							 BPF_REG_AX);
11046 			}
11047 			if (isneg)
11048 				insn->code = insn->code == code_add ?
11049 					     code_sub : code_add;
11050 			*patch++ = *insn;
11051 			if (issrc && isneg)
11052 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11053 			cnt = patch - insn_buf;
11054 
11055 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11056 			if (!new_prog)
11057 				return -ENOMEM;
11058 
11059 			delta    += cnt - 1;
11060 			env->prog = prog = new_prog;
11061 			insn      = new_prog->insnsi + i + delta;
11062 			continue;
11063 		}
11064 
11065 		if (insn->code != (BPF_JMP | BPF_CALL))
11066 			continue;
11067 		if (insn->src_reg == BPF_PSEUDO_CALL)
11068 			continue;
11069 
11070 		if (insn->imm == BPF_FUNC_get_route_realm)
11071 			prog->dst_needed = 1;
11072 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11073 			bpf_user_rnd_init_once();
11074 		if (insn->imm == BPF_FUNC_override_return)
11075 			prog->kprobe_override = 1;
11076 		if (insn->imm == BPF_FUNC_tail_call) {
11077 			/* If we tail call into other programs, we
11078 			 * cannot make any assumptions since they can
11079 			 * be replaced dynamically during runtime in
11080 			 * the program array.
11081 			 */
11082 			prog->cb_access = 1;
11083 			if (!allow_tail_call_in_subprogs(env))
11084 				prog->aux->stack_depth = MAX_BPF_STACK;
11085 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11086 
11087 			/* mark bpf_tail_call as different opcode to avoid
11088 			 * conditional branch in the interpeter for every normal
11089 			 * call and to prevent accidental JITing by JIT compiler
11090 			 * that doesn't support bpf_tail_call yet
11091 			 */
11092 			insn->imm = 0;
11093 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11094 
11095 			aux = &env->insn_aux_data[i + delta];
11096 			if (env->bpf_capable && !expect_blinding &&
11097 			    prog->jit_requested &&
11098 			    !bpf_map_key_poisoned(aux) &&
11099 			    !bpf_map_ptr_poisoned(aux) &&
11100 			    !bpf_map_ptr_unpriv(aux)) {
11101 				struct bpf_jit_poke_descriptor desc = {
11102 					.reason = BPF_POKE_REASON_TAIL_CALL,
11103 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11104 					.tail_call.key = bpf_map_key_immediate(aux),
11105 					.insn_idx = i + delta,
11106 				};
11107 
11108 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11109 				if (ret < 0) {
11110 					verbose(env, "adding tail call poke descriptor failed\n");
11111 					return ret;
11112 				}
11113 
11114 				insn->imm = ret + 1;
11115 				continue;
11116 			}
11117 
11118 			if (!bpf_map_ptr_unpriv(aux))
11119 				continue;
11120 
11121 			/* instead of changing every JIT dealing with tail_call
11122 			 * emit two extra insns:
11123 			 * if (index >= max_entries) goto out;
11124 			 * index &= array->index_mask;
11125 			 * to avoid out-of-bounds cpu speculation
11126 			 */
11127 			if (bpf_map_ptr_poisoned(aux)) {
11128 				verbose(env, "tail_call abusing map_ptr\n");
11129 				return -EINVAL;
11130 			}
11131 
11132 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11133 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11134 						  map_ptr->max_entries, 2);
11135 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11136 						    container_of(map_ptr,
11137 								 struct bpf_array,
11138 								 map)->index_mask);
11139 			insn_buf[2] = *insn;
11140 			cnt = 3;
11141 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11142 			if (!new_prog)
11143 				return -ENOMEM;
11144 
11145 			delta    += cnt - 1;
11146 			env->prog = prog = new_prog;
11147 			insn      = new_prog->insnsi + i + delta;
11148 			continue;
11149 		}
11150 
11151 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11152 		 * and other inlining handlers are currently limited to 64 bit
11153 		 * only.
11154 		 */
11155 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11156 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11157 		     insn->imm == BPF_FUNC_map_update_elem ||
11158 		     insn->imm == BPF_FUNC_map_delete_elem ||
11159 		     insn->imm == BPF_FUNC_map_push_elem   ||
11160 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11161 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11162 			aux = &env->insn_aux_data[i + delta];
11163 			if (bpf_map_ptr_poisoned(aux))
11164 				goto patch_call_imm;
11165 
11166 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11167 			ops = map_ptr->ops;
11168 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11169 			    ops->map_gen_lookup) {
11170 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11171 				if (cnt == -EOPNOTSUPP)
11172 					goto patch_map_ops_generic;
11173 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11174 					verbose(env, "bpf verifier is misconfigured\n");
11175 					return -EINVAL;
11176 				}
11177 
11178 				new_prog = bpf_patch_insn_data(env, i + delta,
11179 							       insn_buf, cnt);
11180 				if (!new_prog)
11181 					return -ENOMEM;
11182 
11183 				delta    += cnt - 1;
11184 				env->prog = prog = new_prog;
11185 				insn      = new_prog->insnsi + i + delta;
11186 				continue;
11187 			}
11188 
11189 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11190 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11191 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11192 				     (int (*)(struct bpf_map *map, void *key))NULL));
11193 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11194 				     (int (*)(struct bpf_map *map, void *key, void *value,
11195 					      u64 flags))NULL));
11196 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11197 				     (int (*)(struct bpf_map *map, void *value,
11198 					      u64 flags))NULL));
11199 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11200 				     (int (*)(struct bpf_map *map, void *value))NULL));
11201 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11202 				     (int (*)(struct bpf_map *map, void *value))NULL));
11203 patch_map_ops_generic:
11204 			switch (insn->imm) {
11205 			case BPF_FUNC_map_lookup_elem:
11206 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11207 					    __bpf_call_base;
11208 				continue;
11209 			case BPF_FUNC_map_update_elem:
11210 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11211 					    __bpf_call_base;
11212 				continue;
11213 			case BPF_FUNC_map_delete_elem:
11214 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11215 					    __bpf_call_base;
11216 				continue;
11217 			case BPF_FUNC_map_push_elem:
11218 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11219 					    __bpf_call_base;
11220 				continue;
11221 			case BPF_FUNC_map_pop_elem:
11222 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11223 					    __bpf_call_base;
11224 				continue;
11225 			case BPF_FUNC_map_peek_elem:
11226 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11227 					    __bpf_call_base;
11228 				continue;
11229 			}
11230 
11231 			goto patch_call_imm;
11232 		}
11233 
11234 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11235 		    insn->imm == BPF_FUNC_jiffies64) {
11236 			struct bpf_insn ld_jiffies_addr[2] = {
11237 				BPF_LD_IMM64(BPF_REG_0,
11238 					     (unsigned long)&jiffies),
11239 			};
11240 
11241 			insn_buf[0] = ld_jiffies_addr[0];
11242 			insn_buf[1] = ld_jiffies_addr[1];
11243 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11244 						  BPF_REG_0, 0);
11245 			cnt = 3;
11246 
11247 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11248 						       cnt);
11249 			if (!new_prog)
11250 				return -ENOMEM;
11251 
11252 			delta    += cnt - 1;
11253 			env->prog = prog = new_prog;
11254 			insn      = new_prog->insnsi + i + delta;
11255 			continue;
11256 		}
11257 
11258 patch_call_imm:
11259 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11260 		/* all functions that have prototype and verifier allowed
11261 		 * programs to call them, must be real in-kernel functions
11262 		 */
11263 		if (!fn->func) {
11264 			verbose(env,
11265 				"kernel subsystem misconfigured func %s#%d\n",
11266 				func_id_name(insn->imm), insn->imm);
11267 			return -EFAULT;
11268 		}
11269 		insn->imm = fn->func - __bpf_call_base;
11270 	}
11271 
11272 	/* Since poke tab is now finalized, publish aux to tracker. */
11273 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11274 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11275 		if (!map_ptr->ops->map_poke_track ||
11276 		    !map_ptr->ops->map_poke_untrack ||
11277 		    !map_ptr->ops->map_poke_run) {
11278 			verbose(env, "bpf verifier is misconfigured\n");
11279 			return -EINVAL;
11280 		}
11281 
11282 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11283 		if (ret < 0) {
11284 			verbose(env, "tracking tail call prog failed\n");
11285 			return ret;
11286 		}
11287 	}
11288 
11289 	return 0;
11290 }
11291 
11292 static void free_states(struct bpf_verifier_env *env)
11293 {
11294 	struct bpf_verifier_state_list *sl, *sln;
11295 	int i;
11296 
11297 	sl = env->free_list;
11298 	while (sl) {
11299 		sln = sl->next;
11300 		free_verifier_state(&sl->state, false);
11301 		kfree(sl);
11302 		sl = sln;
11303 	}
11304 	env->free_list = NULL;
11305 
11306 	if (!env->explored_states)
11307 		return;
11308 
11309 	for (i = 0; i < state_htab_size(env); i++) {
11310 		sl = env->explored_states[i];
11311 
11312 		while (sl) {
11313 			sln = sl->next;
11314 			free_verifier_state(&sl->state, false);
11315 			kfree(sl);
11316 			sl = sln;
11317 		}
11318 		env->explored_states[i] = NULL;
11319 	}
11320 }
11321 
11322 /* The verifier is using insn_aux_data[] to store temporary data during
11323  * verification and to store information for passes that run after the
11324  * verification like dead code sanitization. do_check_common() for subprogram N
11325  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11326  * temporary data after do_check_common() finds that subprogram N cannot be
11327  * verified independently. pass_cnt counts the number of times
11328  * do_check_common() was run and insn->aux->seen tells the pass number
11329  * insn_aux_data was touched. These variables are compared to clear temporary
11330  * data from failed pass. For testing and experiments do_check_common() can be
11331  * run multiple times even when prior attempt to verify is unsuccessful.
11332  */
11333 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11334 {
11335 	struct bpf_insn *insn = env->prog->insnsi;
11336 	struct bpf_insn_aux_data *aux;
11337 	int i, class;
11338 
11339 	for (i = 0; i < env->prog->len; i++) {
11340 		class = BPF_CLASS(insn[i].code);
11341 		if (class != BPF_LDX && class != BPF_STX)
11342 			continue;
11343 		aux = &env->insn_aux_data[i];
11344 		if (aux->seen != env->pass_cnt)
11345 			continue;
11346 		memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11347 	}
11348 }
11349 
11350 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11351 {
11352 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11353 	struct bpf_verifier_state *state;
11354 	struct bpf_reg_state *regs;
11355 	int ret, i;
11356 
11357 	env->prev_linfo = NULL;
11358 	env->pass_cnt++;
11359 
11360 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11361 	if (!state)
11362 		return -ENOMEM;
11363 	state->curframe = 0;
11364 	state->speculative = false;
11365 	state->branches = 1;
11366 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11367 	if (!state->frame[0]) {
11368 		kfree(state);
11369 		return -ENOMEM;
11370 	}
11371 	env->cur_state = state;
11372 	init_func_state(env, state->frame[0],
11373 			BPF_MAIN_FUNC /* callsite */,
11374 			0 /* frameno */,
11375 			subprog);
11376 
11377 	regs = state->frame[state->curframe]->regs;
11378 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11379 		ret = btf_prepare_func_args(env, subprog, regs);
11380 		if (ret)
11381 			goto out;
11382 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11383 			if (regs[i].type == PTR_TO_CTX)
11384 				mark_reg_known_zero(env, regs, i);
11385 			else if (regs[i].type == SCALAR_VALUE)
11386 				mark_reg_unknown(env, regs, i);
11387 		}
11388 	} else {
11389 		/* 1st arg to a function */
11390 		regs[BPF_REG_1].type = PTR_TO_CTX;
11391 		mark_reg_known_zero(env, regs, BPF_REG_1);
11392 		ret = btf_check_func_arg_match(env, subprog, regs);
11393 		if (ret == -EFAULT)
11394 			/* unlikely verifier bug. abort.
11395 			 * ret == 0 and ret < 0 are sadly acceptable for
11396 			 * main() function due to backward compatibility.
11397 			 * Like socket filter program may be written as:
11398 			 * int bpf_prog(struct pt_regs *ctx)
11399 			 * and never dereference that ctx in the program.
11400 			 * 'struct pt_regs' is a type mismatch for socket
11401 			 * filter that should be using 'struct __sk_buff'.
11402 			 */
11403 			goto out;
11404 	}
11405 
11406 	ret = do_check(env);
11407 out:
11408 	/* check for NULL is necessary, since cur_state can be freed inside
11409 	 * do_check() under memory pressure.
11410 	 */
11411 	if (env->cur_state) {
11412 		free_verifier_state(env->cur_state, true);
11413 		env->cur_state = NULL;
11414 	}
11415 	while (!pop_stack(env, NULL, NULL, false));
11416 	if (!ret && pop_log)
11417 		bpf_vlog_reset(&env->log, 0);
11418 	free_states(env);
11419 	if (ret)
11420 		/* clean aux data in case subprog was rejected */
11421 		sanitize_insn_aux_data(env);
11422 	return ret;
11423 }
11424 
11425 /* Verify all global functions in a BPF program one by one based on their BTF.
11426  * All global functions must pass verification. Otherwise the whole program is rejected.
11427  * Consider:
11428  * int bar(int);
11429  * int foo(int f)
11430  * {
11431  *    return bar(f);
11432  * }
11433  * int bar(int b)
11434  * {
11435  *    ...
11436  * }
11437  * foo() will be verified first for R1=any_scalar_value. During verification it
11438  * will be assumed that bar() already verified successfully and call to bar()
11439  * from foo() will be checked for type match only. Later bar() will be verified
11440  * independently to check that it's safe for R1=any_scalar_value.
11441  */
11442 static int do_check_subprogs(struct bpf_verifier_env *env)
11443 {
11444 	struct bpf_prog_aux *aux = env->prog->aux;
11445 	int i, ret;
11446 
11447 	if (!aux->func_info)
11448 		return 0;
11449 
11450 	for (i = 1; i < env->subprog_cnt; i++) {
11451 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11452 			continue;
11453 		env->insn_idx = env->subprog_info[i].start;
11454 		WARN_ON_ONCE(env->insn_idx == 0);
11455 		ret = do_check_common(env, i);
11456 		if (ret) {
11457 			return ret;
11458 		} else if (env->log.level & BPF_LOG_LEVEL) {
11459 			verbose(env,
11460 				"Func#%d is safe for any args that match its prototype\n",
11461 				i);
11462 		}
11463 	}
11464 	return 0;
11465 }
11466 
11467 static int do_check_main(struct bpf_verifier_env *env)
11468 {
11469 	int ret;
11470 
11471 	env->insn_idx = 0;
11472 	ret = do_check_common(env, 0);
11473 	if (!ret)
11474 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11475 	return ret;
11476 }
11477 
11478 
11479 static void print_verification_stats(struct bpf_verifier_env *env)
11480 {
11481 	int i;
11482 
11483 	if (env->log.level & BPF_LOG_STATS) {
11484 		verbose(env, "verification time %lld usec\n",
11485 			div_u64(env->verification_time, 1000));
11486 		verbose(env, "stack depth ");
11487 		for (i = 0; i < env->subprog_cnt; i++) {
11488 			u32 depth = env->subprog_info[i].stack_depth;
11489 
11490 			verbose(env, "%d", depth);
11491 			if (i + 1 < env->subprog_cnt)
11492 				verbose(env, "+");
11493 		}
11494 		verbose(env, "\n");
11495 	}
11496 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11497 		"total_states %d peak_states %d mark_read %d\n",
11498 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11499 		env->max_states_per_insn, env->total_states,
11500 		env->peak_states, env->longest_mark_read_walk);
11501 }
11502 
11503 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11504 {
11505 	const struct btf_type *t, *func_proto;
11506 	const struct bpf_struct_ops *st_ops;
11507 	const struct btf_member *member;
11508 	struct bpf_prog *prog = env->prog;
11509 	u32 btf_id, member_idx;
11510 	const char *mname;
11511 
11512 	btf_id = prog->aux->attach_btf_id;
11513 	st_ops = bpf_struct_ops_find(btf_id);
11514 	if (!st_ops) {
11515 		verbose(env, "attach_btf_id %u is not a supported struct\n",
11516 			btf_id);
11517 		return -ENOTSUPP;
11518 	}
11519 
11520 	t = st_ops->type;
11521 	member_idx = prog->expected_attach_type;
11522 	if (member_idx >= btf_type_vlen(t)) {
11523 		verbose(env, "attach to invalid member idx %u of struct %s\n",
11524 			member_idx, st_ops->name);
11525 		return -EINVAL;
11526 	}
11527 
11528 	member = &btf_type_member(t)[member_idx];
11529 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11530 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11531 					       NULL);
11532 	if (!func_proto) {
11533 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11534 			mname, member_idx, st_ops->name);
11535 		return -EINVAL;
11536 	}
11537 
11538 	if (st_ops->check_member) {
11539 		int err = st_ops->check_member(t, member);
11540 
11541 		if (err) {
11542 			verbose(env, "attach to unsupported member %s of struct %s\n",
11543 				mname, st_ops->name);
11544 			return err;
11545 		}
11546 	}
11547 
11548 	prog->aux->attach_func_proto = func_proto;
11549 	prog->aux->attach_func_name = mname;
11550 	env->ops = st_ops->verifier_ops;
11551 
11552 	return 0;
11553 }
11554 #define SECURITY_PREFIX "security_"
11555 
11556 static int check_attach_modify_return(unsigned long addr, const char *func_name)
11557 {
11558 	if (within_error_injection_list(addr) ||
11559 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
11560 		return 0;
11561 
11562 	return -EINVAL;
11563 }
11564 
11565 /* list of non-sleepable functions that are otherwise on
11566  * ALLOW_ERROR_INJECTION list
11567  */
11568 BTF_SET_START(btf_non_sleepable_error_inject)
11569 /* Three functions below can be called from sleepable and non-sleepable context.
11570  * Assume non-sleepable from bpf safety point of view.
11571  */
11572 BTF_ID(func, __add_to_page_cache_locked)
11573 BTF_ID(func, should_fail_alloc_page)
11574 BTF_ID(func, should_failslab)
11575 BTF_SET_END(btf_non_sleepable_error_inject)
11576 
11577 static int check_non_sleepable_error_inject(u32 btf_id)
11578 {
11579 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11580 }
11581 
11582 int bpf_check_attach_target(struct bpf_verifier_log *log,
11583 			    const struct bpf_prog *prog,
11584 			    const struct bpf_prog *tgt_prog,
11585 			    u32 btf_id,
11586 			    struct bpf_attach_target_info *tgt_info)
11587 {
11588 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
11589 	const char prefix[] = "btf_trace_";
11590 	int ret = 0, subprog = -1, i;
11591 	const struct btf_type *t;
11592 	bool conservative = true;
11593 	const char *tname;
11594 	struct btf *btf;
11595 	long addr = 0;
11596 
11597 	if (!btf_id) {
11598 		bpf_log(log, "Tracing programs must provide btf_id\n");
11599 		return -EINVAL;
11600 	}
11601 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
11602 	if (!btf) {
11603 		bpf_log(log,
11604 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11605 		return -EINVAL;
11606 	}
11607 	t = btf_type_by_id(btf, btf_id);
11608 	if (!t) {
11609 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
11610 		return -EINVAL;
11611 	}
11612 	tname = btf_name_by_offset(btf, t->name_off);
11613 	if (!tname) {
11614 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
11615 		return -EINVAL;
11616 	}
11617 	if (tgt_prog) {
11618 		struct bpf_prog_aux *aux = tgt_prog->aux;
11619 
11620 		for (i = 0; i < aux->func_info_cnt; i++)
11621 			if (aux->func_info[i].type_id == btf_id) {
11622 				subprog = i;
11623 				break;
11624 			}
11625 		if (subprog == -1) {
11626 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
11627 			return -EINVAL;
11628 		}
11629 		conservative = aux->func_info_aux[subprog].unreliable;
11630 		if (prog_extension) {
11631 			if (conservative) {
11632 				bpf_log(log,
11633 					"Cannot replace static functions\n");
11634 				return -EINVAL;
11635 			}
11636 			if (!prog->jit_requested) {
11637 				bpf_log(log,
11638 					"Extension programs should be JITed\n");
11639 				return -EINVAL;
11640 			}
11641 		}
11642 		if (!tgt_prog->jited) {
11643 			bpf_log(log, "Can attach to only JITed progs\n");
11644 			return -EINVAL;
11645 		}
11646 		if (tgt_prog->type == prog->type) {
11647 			/* Cannot fentry/fexit another fentry/fexit program.
11648 			 * Cannot attach program extension to another extension.
11649 			 * It's ok to attach fentry/fexit to extension program.
11650 			 */
11651 			bpf_log(log, "Cannot recursively attach\n");
11652 			return -EINVAL;
11653 		}
11654 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11655 		    prog_extension &&
11656 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11657 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11658 			/* Program extensions can extend all program types
11659 			 * except fentry/fexit. The reason is the following.
11660 			 * The fentry/fexit programs are used for performance
11661 			 * analysis, stats and can be attached to any program
11662 			 * type except themselves. When extension program is
11663 			 * replacing XDP function it is necessary to allow
11664 			 * performance analysis of all functions. Both original
11665 			 * XDP program and its program extension. Hence
11666 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11667 			 * allowed. If extending of fentry/fexit was allowed it
11668 			 * would be possible to create long call chain
11669 			 * fentry->extension->fentry->extension beyond
11670 			 * reasonable stack size. Hence extending fentry is not
11671 			 * allowed.
11672 			 */
11673 			bpf_log(log, "Cannot extend fentry/fexit\n");
11674 			return -EINVAL;
11675 		}
11676 	} else {
11677 		if (prog_extension) {
11678 			bpf_log(log, "Cannot replace kernel functions\n");
11679 			return -EINVAL;
11680 		}
11681 	}
11682 
11683 	switch (prog->expected_attach_type) {
11684 	case BPF_TRACE_RAW_TP:
11685 		if (tgt_prog) {
11686 			bpf_log(log,
11687 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11688 			return -EINVAL;
11689 		}
11690 		if (!btf_type_is_typedef(t)) {
11691 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
11692 				btf_id);
11693 			return -EINVAL;
11694 		}
11695 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
11696 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
11697 				btf_id, tname);
11698 			return -EINVAL;
11699 		}
11700 		tname += sizeof(prefix) - 1;
11701 		t = btf_type_by_id(btf, t->type);
11702 		if (!btf_type_is_ptr(t))
11703 			/* should never happen in valid vmlinux build */
11704 			return -EINVAL;
11705 		t = btf_type_by_id(btf, t->type);
11706 		if (!btf_type_is_func_proto(t))
11707 			/* should never happen in valid vmlinux build */
11708 			return -EINVAL;
11709 
11710 		break;
11711 	case BPF_TRACE_ITER:
11712 		if (!btf_type_is_func(t)) {
11713 			bpf_log(log, "attach_btf_id %u is not a function\n",
11714 				btf_id);
11715 			return -EINVAL;
11716 		}
11717 		t = btf_type_by_id(btf, t->type);
11718 		if (!btf_type_is_func_proto(t))
11719 			return -EINVAL;
11720 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
11721 		if (ret)
11722 			return ret;
11723 		break;
11724 	default:
11725 		if (!prog_extension)
11726 			return -EINVAL;
11727 		fallthrough;
11728 	case BPF_MODIFY_RETURN:
11729 	case BPF_LSM_MAC:
11730 	case BPF_TRACE_FENTRY:
11731 	case BPF_TRACE_FEXIT:
11732 		if (!btf_type_is_func(t)) {
11733 			bpf_log(log, "attach_btf_id %u is not a function\n",
11734 				btf_id);
11735 			return -EINVAL;
11736 		}
11737 		if (prog_extension &&
11738 		    btf_check_type_match(log, prog, btf, t))
11739 			return -EINVAL;
11740 		t = btf_type_by_id(btf, t->type);
11741 		if (!btf_type_is_func_proto(t))
11742 			return -EINVAL;
11743 
11744 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
11745 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
11746 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
11747 			return -EINVAL;
11748 
11749 		if (tgt_prog && conservative)
11750 			t = NULL;
11751 
11752 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
11753 		if (ret < 0)
11754 			return ret;
11755 
11756 		if (tgt_prog) {
11757 			if (subprog == 0)
11758 				addr = (long) tgt_prog->bpf_func;
11759 			else
11760 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
11761 		} else {
11762 			addr = kallsyms_lookup_name(tname);
11763 			if (!addr) {
11764 				bpf_log(log,
11765 					"The address of function %s cannot be found\n",
11766 					tname);
11767 				return -ENOENT;
11768 			}
11769 		}
11770 
11771 		if (prog->aux->sleepable) {
11772 			ret = -EINVAL;
11773 			switch (prog->type) {
11774 			case BPF_PROG_TYPE_TRACING:
11775 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
11776 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11777 				 */
11778 				if (!check_non_sleepable_error_inject(btf_id) &&
11779 				    within_error_injection_list(addr))
11780 					ret = 0;
11781 				break;
11782 			case BPF_PROG_TYPE_LSM:
11783 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
11784 				 * Only some of them are sleepable.
11785 				 */
11786 				if (bpf_lsm_is_sleepable_hook(btf_id))
11787 					ret = 0;
11788 				break;
11789 			default:
11790 				break;
11791 			}
11792 			if (ret) {
11793 				bpf_log(log, "%s is not sleepable\n", tname);
11794 				return ret;
11795 			}
11796 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
11797 			if (tgt_prog) {
11798 				bpf_log(log, "can't modify return codes of BPF programs\n");
11799 				return -EINVAL;
11800 			}
11801 			ret = check_attach_modify_return(addr, tname);
11802 			if (ret) {
11803 				bpf_log(log, "%s() is not modifiable\n", tname);
11804 				return ret;
11805 			}
11806 		}
11807 
11808 		break;
11809 	}
11810 	tgt_info->tgt_addr = addr;
11811 	tgt_info->tgt_name = tname;
11812 	tgt_info->tgt_type = t;
11813 	return 0;
11814 }
11815 
11816 static int check_attach_btf_id(struct bpf_verifier_env *env)
11817 {
11818 	struct bpf_prog *prog = env->prog;
11819 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
11820 	struct bpf_attach_target_info tgt_info = {};
11821 	u32 btf_id = prog->aux->attach_btf_id;
11822 	struct bpf_trampoline *tr;
11823 	int ret;
11824 	u64 key;
11825 
11826 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11827 	    prog->type != BPF_PROG_TYPE_LSM) {
11828 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11829 		return -EINVAL;
11830 	}
11831 
11832 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11833 		return check_struct_ops_btf_id(env);
11834 
11835 	if (prog->type != BPF_PROG_TYPE_TRACING &&
11836 	    prog->type != BPF_PROG_TYPE_LSM &&
11837 	    prog->type != BPF_PROG_TYPE_EXT)
11838 		return 0;
11839 
11840 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
11841 	if (ret)
11842 		return ret;
11843 
11844 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
11845 		/* to make freplace equivalent to their targets, they need to
11846 		 * inherit env->ops and expected_attach_type for the rest of the
11847 		 * verification
11848 		 */
11849 		env->ops = bpf_verifier_ops[tgt_prog->type];
11850 		prog->expected_attach_type = tgt_prog->expected_attach_type;
11851 	}
11852 
11853 	/* store info about the attachment target that will be used later */
11854 	prog->aux->attach_func_proto = tgt_info.tgt_type;
11855 	prog->aux->attach_func_name = tgt_info.tgt_name;
11856 
11857 	if (tgt_prog) {
11858 		prog->aux->saved_dst_prog_type = tgt_prog->type;
11859 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
11860 	}
11861 
11862 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
11863 		prog->aux->attach_btf_trace = true;
11864 		return 0;
11865 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
11866 		if (!bpf_iter_prog_supported(prog))
11867 			return -EINVAL;
11868 		return 0;
11869 	}
11870 
11871 	if (prog->type == BPF_PROG_TYPE_LSM) {
11872 		ret = bpf_lsm_verify_prog(&env->log, prog);
11873 		if (ret < 0)
11874 			return ret;
11875 	}
11876 
11877 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
11878 	tr = bpf_trampoline_get(key, &tgt_info);
11879 	if (!tr)
11880 		return -ENOMEM;
11881 
11882 	prog->aux->dst_trampoline = tr;
11883 	return 0;
11884 }
11885 
11886 struct btf *bpf_get_btf_vmlinux(void)
11887 {
11888 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11889 		mutex_lock(&bpf_verifier_lock);
11890 		if (!btf_vmlinux)
11891 			btf_vmlinux = btf_parse_vmlinux();
11892 		mutex_unlock(&bpf_verifier_lock);
11893 	}
11894 	return btf_vmlinux;
11895 }
11896 
11897 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11898 	      union bpf_attr __user *uattr)
11899 {
11900 	u64 start_time = ktime_get_ns();
11901 	struct bpf_verifier_env *env;
11902 	struct bpf_verifier_log *log;
11903 	int i, len, ret = -EINVAL;
11904 	bool is_priv;
11905 
11906 	/* no program is valid */
11907 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11908 		return -EINVAL;
11909 
11910 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
11911 	 * allocate/free it every time bpf_check() is called
11912 	 */
11913 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
11914 	if (!env)
11915 		return -ENOMEM;
11916 	log = &env->log;
11917 
11918 	len = (*prog)->len;
11919 	env->insn_aux_data =
11920 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
11921 	ret = -ENOMEM;
11922 	if (!env->insn_aux_data)
11923 		goto err_free_env;
11924 	for (i = 0; i < len; i++)
11925 		env->insn_aux_data[i].orig_idx = i;
11926 	env->prog = *prog;
11927 	env->ops = bpf_verifier_ops[env->prog->type];
11928 	is_priv = bpf_capable();
11929 
11930 	bpf_get_btf_vmlinux();
11931 
11932 	/* grab the mutex to protect few globals used by verifier */
11933 	if (!is_priv)
11934 		mutex_lock(&bpf_verifier_lock);
11935 
11936 	if (attr->log_level || attr->log_buf || attr->log_size) {
11937 		/* user requested verbose verifier output
11938 		 * and supplied buffer to store the verification trace
11939 		 */
11940 		log->level = attr->log_level;
11941 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11942 		log->len_total = attr->log_size;
11943 
11944 		ret = -EINVAL;
11945 		/* log attributes have to be sane */
11946 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
11947 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
11948 			goto err_unlock;
11949 	}
11950 
11951 	if (IS_ERR(btf_vmlinux)) {
11952 		/* Either gcc or pahole or kernel are broken. */
11953 		verbose(env, "in-kernel BTF is malformed\n");
11954 		ret = PTR_ERR(btf_vmlinux);
11955 		goto skip_full_check;
11956 	}
11957 
11958 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11959 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
11960 		env->strict_alignment = true;
11961 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11962 		env->strict_alignment = false;
11963 
11964 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
11965 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
11966 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
11967 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
11968 	env->bpf_capable = bpf_capable();
11969 
11970 	if (is_priv)
11971 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11972 
11973 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
11974 		ret = bpf_prog_offload_verifier_prep(env->prog);
11975 		if (ret)
11976 			goto skip_full_check;
11977 	}
11978 
11979 	env->explored_states = kvcalloc(state_htab_size(env),
11980 				       sizeof(struct bpf_verifier_state_list *),
11981 				       GFP_USER);
11982 	ret = -ENOMEM;
11983 	if (!env->explored_states)
11984 		goto skip_full_check;
11985 
11986 	ret = check_subprogs(env);
11987 	if (ret < 0)
11988 		goto skip_full_check;
11989 
11990 	ret = check_btf_info(env, attr, uattr);
11991 	if (ret < 0)
11992 		goto skip_full_check;
11993 
11994 	ret = check_attach_btf_id(env);
11995 	if (ret)
11996 		goto skip_full_check;
11997 
11998 	ret = resolve_pseudo_ldimm64(env);
11999 	if (ret < 0)
12000 		goto skip_full_check;
12001 
12002 	ret = check_cfg(env);
12003 	if (ret < 0)
12004 		goto skip_full_check;
12005 
12006 	ret = do_check_subprogs(env);
12007 	ret = ret ?: do_check_main(env);
12008 
12009 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12010 		ret = bpf_prog_offload_finalize(env);
12011 
12012 skip_full_check:
12013 	kvfree(env->explored_states);
12014 
12015 	if (ret == 0)
12016 		ret = check_max_stack_depth(env);
12017 
12018 	/* instruction rewrites happen after this point */
12019 	if (is_priv) {
12020 		if (ret == 0)
12021 			opt_hard_wire_dead_code_branches(env);
12022 		if (ret == 0)
12023 			ret = opt_remove_dead_code(env);
12024 		if (ret == 0)
12025 			ret = opt_remove_nops(env);
12026 	} else {
12027 		if (ret == 0)
12028 			sanitize_dead_code(env);
12029 	}
12030 
12031 	if (ret == 0)
12032 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12033 		ret = convert_ctx_accesses(env);
12034 
12035 	if (ret == 0)
12036 		ret = fixup_bpf_calls(env);
12037 
12038 	/* do 32-bit optimization after insn patching has done so those patched
12039 	 * insns could be handled correctly.
12040 	 */
12041 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12042 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12043 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12044 								     : false;
12045 	}
12046 
12047 	if (ret == 0)
12048 		ret = fixup_call_args(env);
12049 
12050 	env->verification_time = ktime_get_ns() - start_time;
12051 	print_verification_stats(env);
12052 
12053 	if (log->level && bpf_verifier_log_full(log))
12054 		ret = -ENOSPC;
12055 	if (log->level && !log->ubuf) {
12056 		ret = -EFAULT;
12057 		goto err_release_maps;
12058 	}
12059 
12060 	if (ret == 0 && env->used_map_cnt) {
12061 		/* if program passed verifier, update used_maps in bpf_prog_info */
12062 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12063 							  sizeof(env->used_maps[0]),
12064 							  GFP_KERNEL);
12065 
12066 		if (!env->prog->aux->used_maps) {
12067 			ret = -ENOMEM;
12068 			goto err_release_maps;
12069 		}
12070 
12071 		memcpy(env->prog->aux->used_maps, env->used_maps,
12072 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12073 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12074 
12075 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12076 		 * bpf_ld_imm64 instructions
12077 		 */
12078 		convert_pseudo_ld_imm64(env);
12079 	}
12080 
12081 	if (ret == 0)
12082 		adjust_btf_func(env);
12083 
12084 err_release_maps:
12085 	if (!env->prog->aux->used_maps)
12086 		/* if we didn't copy map pointers into bpf_prog_info, release
12087 		 * them now. Otherwise free_used_maps() will release them.
12088 		 */
12089 		release_maps(env);
12090 
12091 	/* extension progs temporarily inherit the attach_type of their targets
12092 	   for verification purposes, so set it back to zero before returning
12093 	 */
12094 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12095 		env->prog->expected_attach_type = 0;
12096 
12097 	*prog = env->prog;
12098 err_unlock:
12099 	if (!is_priv)
12100 		mutex_unlock(&bpf_verifier_lock);
12101 	vfree(env->insn_aux_data);
12102 err_free_env:
12103 	kfree(env);
12104 	return ret;
12105 }
12106