xref: /linux/kernel/bpf/verifier.c (revision 2c63221cd9e5c0dad0424029aeb1c40faada8330)
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 
23 #include "disasm.h"
24 
25 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
26 #define BPF_PROG_TYPE(_id, _name) \
27 	[_id] = & _name ## _verifier_ops,
28 #define BPF_MAP_TYPE(_id, _ops)
29 #include <linux/bpf_types.h>
30 #undef BPF_PROG_TYPE
31 #undef BPF_MAP_TYPE
32 };
33 
34 /* bpf_check() is a static code analyzer that walks eBPF program
35  * instruction by instruction and updates register/stack state.
36  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
37  *
38  * The first pass is depth-first-search to check that the program is a DAG.
39  * It rejects the following programs:
40  * - larger than BPF_MAXINSNS insns
41  * - if loop is present (detected via back-edge)
42  * - unreachable insns exist (shouldn't be a forest. program = one function)
43  * - out of bounds or malformed jumps
44  * The second pass is all possible path descent from the 1st insn.
45  * Since it's analyzing all pathes through the program, the length of the
46  * analysis is limited to 64k insn, which may be hit even if total number of
47  * insn is less then 4K, but there are too many branches that change stack/regs.
48  * Number of 'branches to be analyzed' is limited to 1k
49  *
50  * On entry to each instruction, each register has a type, and the instruction
51  * changes the types of the registers depending on instruction semantics.
52  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
53  * copied to R1.
54  *
55  * All registers are 64-bit.
56  * R0 - return register
57  * R1-R5 argument passing registers
58  * R6-R9 callee saved registers
59  * R10 - frame pointer read-only
60  *
61  * At the start of BPF program the register R1 contains a pointer to bpf_context
62  * and has type PTR_TO_CTX.
63  *
64  * Verifier tracks arithmetic operations on pointers in case:
65  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
66  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
67  * 1st insn copies R10 (which has FRAME_PTR) type into R1
68  * and 2nd arithmetic instruction is pattern matched to recognize
69  * that it wants to construct a pointer to some element within stack.
70  * So after 2nd insn, the register R1 has type PTR_TO_STACK
71  * (and -20 constant is saved for further stack bounds checking).
72  * Meaning that this reg is a pointer to stack plus known immediate constant.
73  *
74  * Most of the time the registers have SCALAR_VALUE type, which
75  * means the register has some value, but it's not a valid pointer.
76  * (like pointer plus pointer becomes SCALAR_VALUE type)
77  *
78  * When verifier sees load or store instructions the type of base register
79  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
80  * four pointer types recognized by check_mem_access() function.
81  *
82  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
83  * and the range of [ptr, ptr + map's value_size) is accessible.
84  *
85  * registers used to pass values to function calls are checked against
86  * function argument constraints.
87  *
88  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
89  * It means that the register type passed to this function must be
90  * PTR_TO_STACK and it will be used inside the function as
91  * 'pointer to map element key'
92  *
93  * For example the argument constraints for bpf_map_lookup_elem():
94  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
95  *   .arg1_type = ARG_CONST_MAP_PTR,
96  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
97  *
98  * ret_type says that this function returns 'pointer to map elem value or null'
99  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
100  * 2nd argument should be a pointer to stack, which will be used inside
101  * the helper function as a pointer to map element key.
102  *
103  * On the kernel side the helper function looks like:
104  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
105  * {
106  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
107  *    void *key = (void *) (unsigned long) r2;
108  *    void *value;
109  *
110  *    here kernel can access 'key' and 'map' pointers safely, knowing that
111  *    [key, key + map->key_size) bytes are valid and were initialized on
112  *    the stack of eBPF program.
113  * }
114  *
115  * Corresponding eBPF program may look like:
116  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
117  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
118  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
119  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
120  * here verifier looks at prototype of map_lookup_elem() and sees:
121  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
122  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
123  *
124  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
125  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
126  * and were initialized prior to this call.
127  * If it's ok, then verifier allows this BPF_CALL insn and looks at
128  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
129  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
130  * returns ether pointer to map value or NULL.
131  *
132  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
133  * insn, the register holding that pointer in the true branch changes state to
134  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
135  * branch. See check_cond_jmp_op().
136  *
137  * After the call R0 is set to return type of the function and registers R1-R5
138  * are set to NOT_INIT to indicate that they are no longer readable.
139  *
140  * The following reference types represent a potential reference to a kernel
141  * resource which, after first being allocated, must be checked and freed by
142  * the BPF program:
143  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
144  *
145  * When the verifier sees a helper call return a reference type, it allocates a
146  * pointer id for the reference and stores it in the current function state.
147  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
148  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
149  * passes through a NULL-check conditional. For the branch wherein the state is
150  * changed to CONST_IMM, the verifier releases the reference.
151  *
152  * For each helper function that allocates a reference, such as
153  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
154  * bpf_sk_release(). When a reference type passes into the release function,
155  * the verifier also releases the reference. If any unchecked or unreleased
156  * reference remains at the end of the program, the verifier rejects it.
157  */
158 
159 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
160 struct bpf_verifier_stack_elem {
161 	/* verifer state is 'st'
162 	 * before processing instruction 'insn_idx'
163 	 * and after processing instruction 'prev_insn_idx'
164 	 */
165 	struct bpf_verifier_state st;
166 	int insn_idx;
167 	int prev_insn_idx;
168 	struct bpf_verifier_stack_elem *next;
169 };
170 
171 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
172 #define BPF_COMPLEXITY_LIMIT_STATES	64
173 
174 #define BPF_MAP_PTR_UNPRIV	1UL
175 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
176 					  POISON_POINTER_DELTA))
177 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
178 
179 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
180 {
181 	return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
182 }
183 
184 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
185 {
186 	return aux->map_state & BPF_MAP_PTR_UNPRIV;
187 }
188 
189 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
190 			      const struct bpf_map *map, bool unpriv)
191 {
192 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
193 	unpriv |= bpf_map_ptr_unpriv(aux);
194 	aux->map_state = (unsigned long)map |
195 			 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
196 }
197 
198 struct bpf_call_arg_meta {
199 	struct bpf_map *map_ptr;
200 	bool raw_mode;
201 	bool pkt_access;
202 	int regno;
203 	int access_size;
204 	s64 msize_smax_value;
205 	u64 msize_umax_value;
206 	int ref_obj_id;
207 	int func_id;
208 	u32 btf_id;
209 };
210 
211 struct btf *btf_vmlinux;
212 
213 static DEFINE_MUTEX(bpf_verifier_lock);
214 
215 static const struct bpf_line_info *
216 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
217 {
218 	const struct bpf_line_info *linfo;
219 	const struct bpf_prog *prog;
220 	u32 i, nr_linfo;
221 
222 	prog = env->prog;
223 	nr_linfo = prog->aux->nr_linfo;
224 
225 	if (!nr_linfo || insn_off >= prog->len)
226 		return NULL;
227 
228 	linfo = prog->aux->linfo;
229 	for (i = 1; i < nr_linfo; i++)
230 		if (insn_off < linfo[i].insn_off)
231 			break;
232 
233 	return &linfo[i - 1];
234 }
235 
236 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
237 		       va_list args)
238 {
239 	unsigned int n;
240 
241 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
242 
243 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
244 		  "verifier log line truncated - local buffer too short\n");
245 
246 	n = min(log->len_total - log->len_used - 1, n);
247 	log->kbuf[n] = '\0';
248 
249 	if (log->level == BPF_LOG_KERNEL) {
250 		pr_err("BPF:%s\n", log->kbuf);
251 		return;
252 	}
253 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
254 		log->len_used += n;
255 	else
256 		log->ubuf = NULL;
257 }
258 
259 /* log_level controls verbosity level of eBPF verifier.
260  * bpf_verifier_log_write() is used to dump the verification trace to the log,
261  * so the user can figure out what's wrong with the program
262  */
263 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
264 					   const char *fmt, ...)
265 {
266 	va_list args;
267 
268 	if (!bpf_verifier_log_needed(&env->log))
269 		return;
270 
271 	va_start(args, fmt);
272 	bpf_verifier_vlog(&env->log, fmt, args);
273 	va_end(args);
274 }
275 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
276 
277 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
278 {
279 	struct bpf_verifier_env *env = private_data;
280 	va_list args;
281 
282 	if (!bpf_verifier_log_needed(&env->log))
283 		return;
284 
285 	va_start(args, fmt);
286 	bpf_verifier_vlog(&env->log, fmt, args);
287 	va_end(args);
288 }
289 
290 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
291 			    const char *fmt, ...)
292 {
293 	va_list args;
294 
295 	if (!bpf_verifier_log_needed(log))
296 		return;
297 
298 	va_start(args, fmt);
299 	bpf_verifier_vlog(log, fmt, args);
300 	va_end(args);
301 }
302 
303 static const char *ltrim(const char *s)
304 {
305 	while (isspace(*s))
306 		s++;
307 
308 	return s;
309 }
310 
311 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
312 					 u32 insn_off,
313 					 const char *prefix_fmt, ...)
314 {
315 	const struct bpf_line_info *linfo;
316 
317 	if (!bpf_verifier_log_needed(&env->log))
318 		return;
319 
320 	linfo = find_linfo(env, insn_off);
321 	if (!linfo || linfo == env->prev_linfo)
322 		return;
323 
324 	if (prefix_fmt) {
325 		va_list args;
326 
327 		va_start(args, prefix_fmt);
328 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
329 		va_end(args);
330 	}
331 
332 	verbose(env, "%s\n",
333 		ltrim(btf_name_by_offset(env->prog->aux->btf,
334 					 linfo->line_off)));
335 
336 	env->prev_linfo = linfo;
337 }
338 
339 static bool type_is_pkt_pointer(enum bpf_reg_type type)
340 {
341 	return type == PTR_TO_PACKET ||
342 	       type == PTR_TO_PACKET_META;
343 }
344 
345 static bool type_is_sk_pointer(enum bpf_reg_type type)
346 {
347 	return type == PTR_TO_SOCKET ||
348 		type == PTR_TO_SOCK_COMMON ||
349 		type == PTR_TO_TCP_SOCK ||
350 		type == PTR_TO_XDP_SOCK;
351 }
352 
353 static bool reg_type_may_be_null(enum bpf_reg_type type)
354 {
355 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
356 	       type == PTR_TO_SOCKET_OR_NULL ||
357 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
358 	       type == PTR_TO_TCP_SOCK_OR_NULL;
359 }
360 
361 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
362 {
363 	return reg->type == PTR_TO_MAP_VALUE &&
364 		map_value_has_spin_lock(reg->map_ptr);
365 }
366 
367 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
368 {
369 	return type == PTR_TO_SOCKET ||
370 		type == PTR_TO_SOCKET_OR_NULL ||
371 		type == PTR_TO_TCP_SOCK ||
372 		type == PTR_TO_TCP_SOCK_OR_NULL;
373 }
374 
375 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
376 {
377 	return type == ARG_PTR_TO_SOCK_COMMON;
378 }
379 
380 /* Determine whether the function releases some resources allocated by another
381  * function call. The first reference type argument will be assumed to be
382  * released by release_reference().
383  */
384 static bool is_release_function(enum bpf_func_id func_id)
385 {
386 	return func_id == BPF_FUNC_sk_release;
387 }
388 
389 static bool is_acquire_function(enum bpf_func_id func_id)
390 {
391 	return func_id == BPF_FUNC_sk_lookup_tcp ||
392 		func_id == BPF_FUNC_sk_lookup_udp ||
393 		func_id == BPF_FUNC_skc_lookup_tcp;
394 }
395 
396 static bool is_ptr_cast_function(enum bpf_func_id func_id)
397 {
398 	return func_id == BPF_FUNC_tcp_sock ||
399 		func_id == BPF_FUNC_sk_fullsock;
400 }
401 
402 /* string representation of 'enum bpf_reg_type' */
403 static const char * const reg_type_str[] = {
404 	[NOT_INIT]		= "?",
405 	[SCALAR_VALUE]		= "inv",
406 	[PTR_TO_CTX]		= "ctx",
407 	[CONST_PTR_TO_MAP]	= "map_ptr",
408 	[PTR_TO_MAP_VALUE]	= "map_value",
409 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
410 	[PTR_TO_STACK]		= "fp",
411 	[PTR_TO_PACKET]		= "pkt",
412 	[PTR_TO_PACKET_META]	= "pkt_meta",
413 	[PTR_TO_PACKET_END]	= "pkt_end",
414 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
415 	[PTR_TO_SOCKET]		= "sock",
416 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
417 	[PTR_TO_SOCK_COMMON]	= "sock_common",
418 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
419 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
420 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
421 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
422 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
423 	[PTR_TO_BTF_ID]		= "ptr_",
424 };
425 
426 static char slot_type_char[] = {
427 	[STACK_INVALID]	= '?',
428 	[STACK_SPILL]	= 'r',
429 	[STACK_MISC]	= 'm',
430 	[STACK_ZERO]	= '0',
431 };
432 
433 static void print_liveness(struct bpf_verifier_env *env,
434 			   enum bpf_reg_liveness live)
435 {
436 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
437 	    verbose(env, "_");
438 	if (live & REG_LIVE_READ)
439 		verbose(env, "r");
440 	if (live & REG_LIVE_WRITTEN)
441 		verbose(env, "w");
442 	if (live & REG_LIVE_DONE)
443 		verbose(env, "D");
444 }
445 
446 static struct bpf_func_state *func(struct bpf_verifier_env *env,
447 				   const struct bpf_reg_state *reg)
448 {
449 	struct bpf_verifier_state *cur = env->cur_state;
450 
451 	return cur->frame[reg->frameno];
452 }
453 
454 const char *kernel_type_name(u32 id)
455 {
456 	return btf_name_by_offset(btf_vmlinux,
457 				  btf_type_by_id(btf_vmlinux, id)->name_off);
458 }
459 
460 static void print_verifier_state(struct bpf_verifier_env *env,
461 				 const struct bpf_func_state *state)
462 {
463 	const struct bpf_reg_state *reg;
464 	enum bpf_reg_type t;
465 	int i;
466 
467 	if (state->frameno)
468 		verbose(env, " frame%d:", state->frameno);
469 	for (i = 0; i < MAX_BPF_REG; i++) {
470 		reg = &state->regs[i];
471 		t = reg->type;
472 		if (t == NOT_INIT)
473 			continue;
474 		verbose(env, " R%d", i);
475 		print_liveness(env, reg->live);
476 		verbose(env, "=%s", reg_type_str[t]);
477 		if (t == SCALAR_VALUE && reg->precise)
478 			verbose(env, "P");
479 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
480 		    tnum_is_const(reg->var_off)) {
481 			/* reg->off should be 0 for SCALAR_VALUE */
482 			verbose(env, "%lld", reg->var_off.value + reg->off);
483 		} else {
484 			if (t == PTR_TO_BTF_ID)
485 				verbose(env, "%s", kernel_type_name(reg->btf_id));
486 			verbose(env, "(id=%d", reg->id);
487 			if (reg_type_may_be_refcounted_or_null(t))
488 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
489 			if (t != SCALAR_VALUE)
490 				verbose(env, ",off=%d", reg->off);
491 			if (type_is_pkt_pointer(t))
492 				verbose(env, ",r=%d", reg->range);
493 			else if (t == CONST_PTR_TO_MAP ||
494 				 t == PTR_TO_MAP_VALUE ||
495 				 t == PTR_TO_MAP_VALUE_OR_NULL)
496 				verbose(env, ",ks=%d,vs=%d",
497 					reg->map_ptr->key_size,
498 					reg->map_ptr->value_size);
499 			if (tnum_is_const(reg->var_off)) {
500 				/* Typically an immediate SCALAR_VALUE, but
501 				 * could be a pointer whose offset is too big
502 				 * for reg->off
503 				 */
504 				verbose(env, ",imm=%llx", reg->var_off.value);
505 			} else {
506 				if (reg->smin_value != reg->umin_value &&
507 				    reg->smin_value != S64_MIN)
508 					verbose(env, ",smin_value=%lld",
509 						(long long)reg->smin_value);
510 				if (reg->smax_value != reg->umax_value &&
511 				    reg->smax_value != S64_MAX)
512 					verbose(env, ",smax_value=%lld",
513 						(long long)reg->smax_value);
514 				if (reg->umin_value != 0)
515 					verbose(env, ",umin_value=%llu",
516 						(unsigned long long)reg->umin_value);
517 				if (reg->umax_value != U64_MAX)
518 					verbose(env, ",umax_value=%llu",
519 						(unsigned long long)reg->umax_value);
520 				if (!tnum_is_unknown(reg->var_off)) {
521 					char tn_buf[48];
522 
523 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
524 					verbose(env, ",var_off=%s", tn_buf);
525 				}
526 			}
527 			verbose(env, ")");
528 		}
529 	}
530 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
531 		char types_buf[BPF_REG_SIZE + 1];
532 		bool valid = false;
533 		int j;
534 
535 		for (j = 0; j < BPF_REG_SIZE; j++) {
536 			if (state->stack[i].slot_type[j] != STACK_INVALID)
537 				valid = true;
538 			types_buf[j] = slot_type_char[
539 					state->stack[i].slot_type[j]];
540 		}
541 		types_buf[BPF_REG_SIZE] = 0;
542 		if (!valid)
543 			continue;
544 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
545 		print_liveness(env, state->stack[i].spilled_ptr.live);
546 		if (state->stack[i].slot_type[0] == STACK_SPILL) {
547 			reg = &state->stack[i].spilled_ptr;
548 			t = reg->type;
549 			verbose(env, "=%s", reg_type_str[t]);
550 			if (t == SCALAR_VALUE && reg->precise)
551 				verbose(env, "P");
552 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
553 				verbose(env, "%lld", reg->var_off.value + reg->off);
554 		} else {
555 			verbose(env, "=%s", types_buf);
556 		}
557 	}
558 	if (state->acquired_refs && state->refs[0].id) {
559 		verbose(env, " refs=%d", state->refs[0].id);
560 		for (i = 1; i < state->acquired_refs; i++)
561 			if (state->refs[i].id)
562 				verbose(env, ",%d", state->refs[i].id);
563 	}
564 	verbose(env, "\n");
565 }
566 
567 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
568 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
569 			       const struct bpf_func_state *src)	\
570 {									\
571 	if (!src->FIELD)						\
572 		return 0;						\
573 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
574 		/* internal bug, make state invalid to reject the program */ \
575 		memset(dst, 0, sizeof(*dst));				\
576 		return -EFAULT;						\
577 	}								\
578 	memcpy(dst->FIELD, src->FIELD,					\
579 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
580 	return 0;							\
581 }
582 /* copy_reference_state() */
583 COPY_STATE_FN(reference, acquired_refs, refs, 1)
584 /* copy_stack_state() */
585 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
586 #undef COPY_STATE_FN
587 
588 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
589 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
590 				  bool copy_old)			\
591 {									\
592 	u32 old_size = state->COUNT;					\
593 	struct bpf_##NAME##_state *new_##FIELD;				\
594 	int slot = size / SIZE;						\
595 									\
596 	if (size <= old_size || !size) {				\
597 		if (copy_old)						\
598 			return 0;					\
599 		state->COUNT = slot * SIZE;				\
600 		if (!size && old_size) {				\
601 			kfree(state->FIELD);				\
602 			state->FIELD = NULL;				\
603 		}							\
604 		return 0;						\
605 	}								\
606 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
607 				    GFP_KERNEL);			\
608 	if (!new_##FIELD)						\
609 		return -ENOMEM;						\
610 	if (copy_old) {							\
611 		if (state->FIELD)					\
612 			memcpy(new_##FIELD, state->FIELD,		\
613 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
614 		memset(new_##FIELD + old_size / SIZE, 0,		\
615 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
616 	}								\
617 	state->COUNT = slot * SIZE;					\
618 	kfree(state->FIELD);						\
619 	state->FIELD = new_##FIELD;					\
620 	return 0;							\
621 }
622 /* realloc_reference_state() */
623 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
624 /* realloc_stack_state() */
625 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
626 #undef REALLOC_STATE_FN
627 
628 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
629  * make it consume minimal amount of memory. check_stack_write() access from
630  * the program calls into realloc_func_state() to grow the stack size.
631  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
632  * which realloc_stack_state() copies over. It points to previous
633  * bpf_verifier_state which is never reallocated.
634  */
635 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
636 			      int refs_size, bool copy_old)
637 {
638 	int err = realloc_reference_state(state, refs_size, copy_old);
639 	if (err)
640 		return err;
641 	return realloc_stack_state(state, stack_size, copy_old);
642 }
643 
644 /* Acquire a pointer id from the env and update the state->refs to include
645  * this new pointer reference.
646  * On success, returns a valid pointer id to associate with the register
647  * On failure, returns a negative errno.
648  */
649 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
650 {
651 	struct bpf_func_state *state = cur_func(env);
652 	int new_ofs = state->acquired_refs;
653 	int id, err;
654 
655 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
656 	if (err)
657 		return err;
658 	id = ++env->id_gen;
659 	state->refs[new_ofs].id = id;
660 	state->refs[new_ofs].insn_idx = insn_idx;
661 
662 	return id;
663 }
664 
665 /* release function corresponding to acquire_reference_state(). Idempotent. */
666 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
667 {
668 	int i, last_idx;
669 
670 	last_idx = state->acquired_refs - 1;
671 	for (i = 0; i < state->acquired_refs; i++) {
672 		if (state->refs[i].id == ptr_id) {
673 			if (last_idx && i != last_idx)
674 				memcpy(&state->refs[i], &state->refs[last_idx],
675 				       sizeof(*state->refs));
676 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
677 			state->acquired_refs--;
678 			return 0;
679 		}
680 	}
681 	return -EINVAL;
682 }
683 
684 static int transfer_reference_state(struct bpf_func_state *dst,
685 				    struct bpf_func_state *src)
686 {
687 	int err = realloc_reference_state(dst, src->acquired_refs, false);
688 	if (err)
689 		return err;
690 	err = copy_reference_state(dst, src);
691 	if (err)
692 		return err;
693 	return 0;
694 }
695 
696 static void free_func_state(struct bpf_func_state *state)
697 {
698 	if (!state)
699 		return;
700 	kfree(state->refs);
701 	kfree(state->stack);
702 	kfree(state);
703 }
704 
705 static void clear_jmp_history(struct bpf_verifier_state *state)
706 {
707 	kfree(state->jmp_history);
708 	state->jmp_history = NULL;
709 	state->jmp_history_cnt = 0;
710 }
711 
712 static void free_verifier_state(struct bpf_verifier_state *state,
713 				bool free_self)
714 {
715 	int i;
716 
717 	for (i = 0; i <= state->curframe; i++) {
718 		free_func_state(state->frame[i]);
719 		state->frame[i] = NULL;
720 	}
721 	clear_jmp_history(state);
722 	if (free_self)
723 		kfree(state);
724 }
725 
726 /* copy verifier state from src to dst growing dst stack space
727  * when necessary to accommodate larger src stack
728  */
729 static int copy_func_state(struct bpf_func_state *dst,
730 			   const struct bpf_func_state *src)
731 {
732 	int err;
733 
734 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
735 				 false);
736 	if (err)
737 		return err;
738 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
739 	err = copy_reference_state(dst, src);
740 	if (err)
741 		return err;
742 	return copy_stack_state(dst, src);
743 }
744 
745 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
746 			       const struct bpf_verifier_state *src)
747 {
748 	struct bpf_func_state *dst;
749 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
750 	int i, err;
751 
752 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
753 		kfree(dst_state->jmp_history);
754 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
755 		if (!dst_state->jmp_history)
756 			return -ENOMEM;
757 	}
758 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
759 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
760 
761 	/* if dst has more stack frames then src frame, free them */
762 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
763 		free_func_state(dst_state->frame[i]);
764 		dst_state->frame[i] = NULL;
765 	}
766 	dst_state->speculative = src->speculative;
767 	dst_state->curframe = src->curframe;
768 	dst_state->active_spin_lock = src->active_spin_lock;
769 	dst_state->branches = src->branches;
770 	dst_state->parent = src->parent;
771 	dst_state->first_insn_idx = src->first_insn_idx;
772 	dst_state->last_insn_idx = src->last_insn_idx;
773 	for (i = 0; i <= src->curframe; i++) {
774 		dst = dst_state->frame[i];
775 		if (!dst) {
776 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
777 			if (!dst)
778 				return -ENOMEM;
779 			dst_state->frame[i] = dst;
780 		}
781 		err = copy_func_state(dst, src->frame[i]);
782 		if (err)
783 			return err;
784 	}
785 	return 0;
786 }
787 
788 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
789 {
790 	while (st) {
791 		u32 br = --st->branches;
792 
793 		/* WARN_ON(br > 1) technically makes sense here,
794 		 * but see comment in push_stack(), hence:
795 		 */
796 		WARN_ONCE((int)br < 0,
797 			  "BUG update_branch_counts:branches_to_explore=%d\n",
798 			  br);
799 		if (br)
800 			break;
801 		st = st->parent;
802 	}
803 }
804 
805 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
806 		     int *insn_idx)
807 {
808 	struct bpf_verifier_state *cur = env->cur_state;
809 	struct bpf_verifier_stack_elem *elem, *head = env->head;
810 	int err;
811 
812 	if (env->head == NULL)
813 		return -ENOENT;
814 
815 	if (cur) {
816 		err = copy_verifier_state(cur, &head->st);
817 		if (err)
818 			return err;
819 	}
820 	if (insn_idx)
821 		*insn_idx = head->insn_idx;
822 	if (prev_insn_idx)
823 		*prev_insn_idx = head->prev_insn_idx;
824 	elem = head->next;
825 	free_verifier_state(&head->st, false);
826 	kfree(head);
827 	env->head = elem;
828 	env->stack_size--;
829 	return 0;
830 }
831 
832 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
833 					     int insn_idx, int prev_insn_idx,
834 					     bool speculative)
835 {
836 	struct bpf_verifier_state *cur = env->cur_state;
837 	struct bpf_verifier_stack_elem *elem;
838 	int err;
839 
840 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
841 	if (!elem)
842 		goto err;
843 
844 	elem->insn_idx = insn_idx;
845 	elem->prev_insn_idx = prev_insn_idx;
846 	elem->next = env->head;
847 	env->head = elem;
848 	env->stack_size++;
849 	err = copy_verifier_state(&elem->st, cur);
850 	if (err)
851 		goto err;
852 	elem->st.speculative |= speculative;
853 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
854 		verbose(env, "The sequence of %d jumps is too complex.\n",
855 			env->stack_size);
856 		goto err;
857 	}
858 	if (elem->st.parent) {
859 		++elem->st.parent->branches;
860 		/* WARN_ON(branches > 2) technically makes sense here,
861 		 * but
862 		 * 1. speculative states will bump 'branches' for non-branch
863 		 * instructions
864 		 * 2. is_state_visited() heuristics may decide not to create
865 		 * a new state for a sequence of branches and all such current
866 		 * and cloned states will be pointing to a single parent state
867 		 * which might have large 'branches' count.
868 		 */
869 	}
870 	return &elem->st;
871 err:
872 	free_verifier_state(env->cur_state, true);
873 	env->cur_state = NULL;
874 	/* pop all elements and return */
875 	while (!pop_stack(env, NULL, NULL));
876 	return NULL;
877 }
878 
879 #define CALLER_SAVED_REGS 6
880 static const int caller_saved[CALLER_SAVED_REGS] = {
881 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
882 };
883 
884 static void __mark_reg_not_init(struct bpf_reg_state *reg);
885 
886 /* Mark the unknown part of a register (variable offset or scalar value) as
887  * known to have the value @imm.
888  */
889 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
890 {
891 	/* Clear id, off, and union(map_ptr, range) */
892 	memset(((u8 *)reg) + sizeof(reg->type), 0,
893 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
894 	reg->var_off = tnum_const(imm);
895 	reg->smin_value = (s64)imm;
896 	reg->smax_value = (s64)imm;
897 	reg->umin_value = imm;
898 	reg->umax_value = imm;
899 }
900 
901 /* Mark the 'variable offset' part of a register as zero.  This should be
902  * used only on registers holding a pointer type.
903  */
904 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
905 {
906 	__mark_reg_known(reg, 0);
907 }
908 
909 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
910 {
911 	__mark_reg_known(reg, 0);
912 	reg->type = SCALAR_VALUE;
913 }
914 
915 static void mark_reg_known_zero(struct bpf_verifier_env *env,
916 				struct bpf_reg_state *regs, u32 regno)
917 {
918 	if (WARN_ON(regno >= MAX_BPF_REG)) {
919 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
920 		/* Something bad happened, let's kill all regs */
921 		for (regno = 0; regno < MAX_BPF_REG; regno++)
922 			__mark_reg_not_init(regs + regno);
923 		return;
924 	}
925 	__mark_reg_known_zero(regs + regno);
926 }
927 
928 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
929 {
930 	return type_is_pkt_pointer(reg->type);
931 }
932 
933 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
934 {
935 	return reg_is_pkt_pointer(reg) ||
936 	       reg->type == PTR_TO_PACKET_END;
937 }
938 
939 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
940 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
941 				    enum bpf_reg_type which)
942 {
943 	/* The register can already have a range from prior markings.
944 	 * This is fine as long as it hasn't been advanced from its
945 	 * origin.
946 	 */
947 	return reg->type == which &&
948 	       reg->id == 0 &&
949 	       reg->off == 0 &&
950 	       tnum_equals_const(reg->var_off, 0);
951 }
952 
953 /* Attempts to improve min/max values based on var_off information */
954 static void __update_reg_bounds(struct bpf_reg_state *reg)
955 {
956 	/* min signed is max(sign bit) | min(other bits) */
957 	reg->smin_value = max_t(s64, reg->smin_value,
958 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
959 	/* max signed is min(sign bit) | max(other bits) */
960 	reg->smax_value = min_t(s64, reg->smax_value,
961 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
962 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
963 	reg->umax_value = min(reg->umax_value,
964 			      reg->var_off.value | reg->var_off.mask);
965 }
966 
967 /* Uses signed min/max values to inform unsigned, and vice-versa */
968 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
969 {
970 	/* Learn sign from signed bounds.
971 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
972 	 * are the same, so combine.  This works even in the negative case, e.g.
973 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
974 	 */
975 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
976 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
977 							  reg->umin_value);
978 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
979 							  reg->umax_value);
980 		return;
981 	}
982 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
983 	 * boundary, so we must be careful.
984 	 */
985 	if ((s64)reg->umax_value >= 0) {
986 		/* Positive.  We can't learn anything from the smin, but smax
987 		 * is positive, hence safe.
988 		 */
989 		reg->smin_value = reg->umin_value;
990 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
991 							  reg->umax_value);
992 	} else if ((s64)reg->umin_value < 0) {
993 		/* Negative.  We can't learn anything from the smax, but smin
994 		 * is negative, hence safe.
995 		 */
996 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
997 							  reg->umin_value);
998 		reg->smax_value = reg->umax_value;
999 	}
1000 }
1001 
1002 /* Attempts to improve var_off based on unsigned min/max information */
1003 static void __reg_bound_offset(struct bpf_reg_state *reg)
1004 {
1005 	reg->var_off = tnum_intersect(reg->var_off,
1006 				      tnum_range(reg->umin_value,
1007 						 reg->umax_value));
1008 }
1009 
1010 /* Reset the min/max bounds of a register */
1011 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1012 {
1013 	reg->smin_value = S64_MIN;
1014 	reg->smax_value = S64_MAX;
1015 	reg->umin_value = 0;
1016 	reg->umax_value = U64_MAX;
1017 }
1018 
1019 /* Mark a register as having a completely unknown (scalar) value. */
1020 static void __mark_reg_unknown(struct bpf_reg_state *reg)
1021 {
1022 	/*
1023 	 * Clear type, id, off, and union(map_ptr, range) and
1024 	 * padding between 'type' and union
1025 	 */
1026 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1027 	reg->type = SCALAR_VALUE;
1028 	reg->var_off = tnum_unknown;
1029 	reg->frameno = 0;
1030 	__mark_reg_unbounded(reg);
1031 }
1032 
1033 static void mark_reg_unknown(struct bpf_verifier_env *env,
1034 			     struct bpf_reg_state *regs, u32 regno)
1035 {
1036 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1037 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1038 		/* Something bad happened, let's kill all regs except FP */
1039 		for (regno = 0; regno < BPF_REG_FP; regno++)
1040 			__mark_reg_not_init(regs + regno);
1041 		return;
1042 	}
1043 	regs += regno;
1044 	__mark_reg_unknown(regs);
1045 	/* constant backtracking is enabled for root without bpf2bpf calls */
1046 	regs->precise = env->subprog_cnt > 1 || !env->allow_ptr_leaks ?
1047 			true : false;
1048 }
1049 
1050 static void __mark_reg_not_init(struct bpf_reg_state *reg)
1051 {
1052 	__mark_reg_unknown(reg);
1053 	reg->type = NOT_INIT;
1054 }
1055 
1056 static void mark_reg_not_init(struct bpf_verifier_env *env,
1057 			      struct bpf_reg_state *regs, u32 regno)
1058 {
1059 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1060 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1061 		/* Something bad happened, let's kill all regs except FP */
1062 		for (regno = 0; regno < BPF_REG_FP; regno++)
1063 			__mark_reg_not_init(regs + regno);
1064 		return;
1065 	}
1066 	__mark_reg_not_init(regs + regno);
1067 }
1068 
1069 #define DEF_NOT_SUBREG	(0)
1070 static void init_reg_state(struct bpf_verifier_env *env,
1071 			   struct bpf_func_state *state)
1072 {
1073 	struct bpf_reg_state *regs = state->regs;
1074 	int i;
1075 
1076 	for (i = 0; i < MAX_BPF_REG; i++) {
1077 		mark_reg_not_init(env, regs, i);
1078 		regs[i].live = REG_LIVE_NONE;
1079 		regs[i].parent = NULL;
1080 		regs[i].subreg_def = DEF_NOT_SUBREG;
1081 	}
1082 
1083 	/* frame pointer */
1084 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1085 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1086 	regs[BPF_REG_FP].frameno = state->frameno;
1087 
1088 	/* 1st arg to a function */
1089 	regs[BPF_REG_1].type = PTR_TO_CTX;
1090 	mark_reg_known_zero(env, regs, BPF_REG_1);
1091 }
1092 
1093 #define BPF_MAIN_FUNC (-1)
1094 static void init_func_state(struct bpf_verifier_env *env,
1095 			    struct bpf_func_state *state,
1096 			    int callsite, int frameno, int subprogno)
1097 {
1098 	state->callsite = callsite;
1099 	state->frameno = frameno;
1100 	state->subprogno = subprogno;
1101 	init_reg_state(env, state);
1102 }
1103 
1104 enum reg_arg_type {
1105 	SRC_OP,		/* register is used as source operand */
1106 	DST_OP,		/* register is used as destination operand */
1107 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1108 };
1109 
1110 static int cmp_subprogs(const void *a, const void *b)
1111 {
1112 	return ((struct bpf_subprog_info *)a)->start -
1113 	       ((struct bpf_subprog_info *)b)->start;
1114 }
1115 
1116 static int find_subprog(struct bpf_verifier_env *env, int off)
1117 {
1118 	struct bpf_subprog_info *p;
1119 
1120 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1121 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1122 	if (!p)
1123 		return -ENOENT;
1124 	return p - env->subprog_info;
1125 
1126 }
1127 
1128 static int add_subprog(struct bpf_verifier_env *env, int off)
1129 {
1130 	int insn_cnt = env->prog->len;
1131 	int ret;
1132 
1133 	if (off >= insn_cnt || off < 0) {
1134 		verbose(env, "call to invalid destination\n");
1135 		return -EINVAL;
1136 	}
1137 	ret = find_subprog(env, off);
1138 	if (ret >= 0)
1139 		return 0;
1140 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1141 		verbose(env, "too many subprograms\n");
1142 		return -E2BIG;
1143 	}
1144 	env->subprog_info[env->subprog_cnt++].start = off;
1145 	sort(env->subprog_info, env->subprog_cnt,
1146 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1147 	return 0;
1148 }
1149 
1150 static int check_subprogs(struct bpf_verifier_env *env)
1151 {
1152 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1153 	struct bpf_subprog_info *subprog = env->subprog_info;
1154 	struct bpf_insn *insn = env->prog->insnsi;
1155 	int insn_cnt = env->prog->len;
1156 
1157 	/* Add entry function. */
1158 	ret = add_subprog(env, 0);
1159 	if (ret < 0)
1160 		return ret;
1161 
1162 	/* determine subprog starts. The end is one before the next starts */
1163 	for (i = 0; i < insn_cnt; i++) {
1164 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1165 			continue;
1166 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1167 			continue;
1168 		if (!env->allow_ptr_leaks) {
1169 			verbose(env, "function calls to other bpf functions are allowed for root only\n");
1170 			return -EPERM;
1171 		}
1172 		ret = add_subprog(env, i + insn[i].imm + 1);
1173 		if (ret < 0)
1174 			return ret;
1175 	}
1176 
1177 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1178 	 * logic. 'subprog_cnt' should not be increased.
1179 	 */
1180 	subprog[env->subprog_cnt].start = insn_cnt;
1181 
1182 	if (env->log.level & BPF_LOG_LEVEL2)
1183 		for (i = 0; i < env->subprog_cnt; i++)
1184 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1185 
1186 	/* now check that all jumps are within the same subprog */
1187 	subprog_start = subprog[cur_subprog].start;
1188 	subprog_end = subprog[cur_subprog + 1].start;
1189 	for (i = 0; i < insn_cnt; i++) {
1190 		u8 code = insn[i].code;
1191 
1192 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1193 			goto next;
1194 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1195 			goto next;
1196 		off = i + insn[i].off + 1;
1197 		if (off < subprog_start || off >= subprog_end) {
1198 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1199 			return -EINVAL;
1200 		}
1201 next:
1202 		if (i == subprog_end - 1) {
1203 			/* to avoid fall-through from one subprog into another
1204 			 * the last insn of the subprog should be either exit
1205 			 * or unconditional jump back
1206 			 */
1207 			if (code != (BPF_JMP | BPF_EXIT) &&
1208 			    code != (BPF_JMP | BPF_JA)) {
1209 				verbose(env, "last insn is not an exit or jmp\n");
1210 				return -EINVAL;
1211 			}
1212 			subprog_start = subprog_end;
1213 			cur_subprog++;
1214 			if (cur_subprog < env->subprog_cnt)
1215 				subprog_end = subprog[cur_subprog + 1].start;
1216 		}
1217 	}
1218 	return 0;
1219 }
1220 
1221 /* Parentage chain of this register (or stack slot) should take care of all
1222  * issues like callee-saved registers, stack slot allocation time, etc.
1223  */
1224 static int mark_reg_read(struct bpf_verifier_env *env,
1225 			 const struct bpf_reg_state *state,
1226 			 struct bpf_reg_state *parent, u8 flag)
1227 {
1228 	bool writes = parent == state->parent; /* Observe write marks */
1229 	int cnt = 0;
1230 
1231 	while (parent) {
1232 		/* if read wasn't screened by an earlier write ... */
1233 		if (writes && state->live & REG_LIVE_WRITTEN)
1234 			break;
1235 		if (parent->live & REG_LIVE_DONE) {
1236 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1237 				reg_type_str[parent->type],
1238 				parent->var_off.value, parent->off);
1239 			return -EFAULT;
1240 		}
1241 		/* The first condition is more likely to be true than the
1242 		 * second, checked it first.
1243 		 */
1244 		if ((parent->live & REG_LIVE_READ) == flag ||
1245 		    parent->live & REG_LIVE_READ64)
1246 			/* The parentage chain never changes and
1247 			 * this parent was already marked as LIVE_READ.
1248 			 * There is no need to keep walking the chain again and
1249 			 * keep re-marking all parents as LIVE_READ.
1250 			 * This case happens when the same register is read
1251 			 * multiple times without writes into it in-between.
1252 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1253 			 * then no need to set the weak REG_LIVE_READ32.
1254 			 */
1255 			break;
1256 		/* ... then we depend on parent's value */
1257 		parent->live |= flag;
1258 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1259 		if (flag == REG_LIVE_READ64)
1260 			parent->live &= ~REG_LIVE_READ32;
1261 		state = parent;
1262 		parent = state->parent;
1263 		writes = true;
1264 		cnt++;
1265 	}
1266 
1267 	if (env->longest_mark_read_walk < cnt)
1268 		env->longest_mark_read_walk = cnt;
1269 	return 0;
1270 }
1271 
1272 /* This function is supposed to be used by the following 32-bit optimization
1273  * code only. It returns TRUE if the source or destination register operates
1274  * on 64-bit, otherwise return FALSE.
1275  */
1276 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1277 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1278 {
1279 	u8 code, class, op;
1280 
1281 	code = insn->code;
1282 	class = BPF_CLASS(code);
1283 	op = BPF_OP(code);
1284 	if (class == BPF_JMP) {
1285 		/* BPF_EXIT for "main" will reach here. Return TRUE
1286 		 * conservatively.
1287 		 */
1288 		if (op == BPF_EXIT)
1289 			return true;
1290 		if (op == BPF_CALL) {
1291 			/* BPF to BPF call will reach here because of marking
1292 			 * caller saved clobber with DST_OP_NO_MARK for which we
1293 			 * don't care the register def because they are anyway
1294 			 * marked as NOT_INIT already.
1295 			 */
1296 			if (insn->src_reg == BPF_PSEUDO_CALL)
1297 				return false;
1298 			/* Helper call will reach here because of arg type
1299 			 * check, conservatively return TRUE.
1300 			 */
1301 			if (t == SRC_OP)
1302 				return true;
1303 
1304 			return false;
1305 		}
1306 	}
1307 
1308 	if (class == BPF_ALU64 || class == BPF_JMP ||
1309 	    /* BPF_END always use BPF_ALU class. */
1310 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1311 		return true;
1312 
1313 	if (class == BPF_ALU || class == BPF_JMP32)
1314 		return false;
1315 
1316 	if (class == BPF_LDX) {
1317 		if (t != SRC_OP)
1318 			return BPF_SIZE(code) == BPF_DW;
1319 		/* LDX source must be ptr. */
1320 		return true;
1321 	}
1322 
1323 	if (class == BPF_STX) {
1324 		if (reg->type != SCALAR_VALUE)
1325 			return true;
1326 		return BPF_SIZE(code) == BPF_DW;
1327 	}
1328 
1329 	if (class == BPF_LD) {
1330 		u8 mode = BPF_MODE(code);
1331 
1332 		/* LD_IMM64 */
1333 		if (mode == BPF_IMM)
1334 			return true;
1335 
1336 		/* Both LD_IND and LD_ABS return 32-bit data. */
1337 		if (t != SRC_OP)
1338 			return  false;
1339 
1340 		/* Implicit ctx ptr. */
1341 		if (regno == BPF_REG_6)
1342 			return true;
1343 
1344 		/* Explicit source could be any width. */
1345 		return true;
1346 	}
1347 
1348 	if (class == BPF_ST)
1349 		/* The only source register for BPF_ST is a ptr. */
1350 		return true;
1351 
1352 	/* Conservatively return true at default. */
1353 	return true;
1354 }
1355 
1356 /* Return TRUE if INSN doesn't have explicit value define. */
1357 static bool insn_no_def(struct bpf_insn *insn)
1358 {
1359 	u8 class = BPF_CLASS(insn->code);
1360 
1361 	return (class == BPF_JMP || class == BPF_JMP32 ||
1362 		class == BPF_STX || class == BPF_ST);
1363 }
1364 
1365 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1366 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1367 {
1368 	if (insn_no_def(insn))
1369 		return false;
1370 
1371 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1372 }
1373 
1374 static void mark_insn_zext(struct bpf_verifier_env *env,
1375 			   struct bpf_reg_state *reg)
1376 {
1377 	s32 def_idx = reg->subreg_def;
1378 
1379 	if (def_idx == DEF_NOT_SUBREG)
1380 		return;
1381 
1382 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1383 	/* The dst will be zero extended, so won't be sub-register anymore. */
1384 	reg->subreg_def = DEF_NOT_SUBREG;
1385 }
1386 
1387 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1388 			 enum reg_arg_type t)
1389 {
1390 	struct bpf_verifier_state *vstate = env->cur_state;
1391 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1392 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1393 	struct bpf_reg_state *reg, *regs = state->regs;
1394 	bool rw64;
1395 
1396 	if (regno >= MAX_BPF_REG) {
1397 		verbose(env, "R%d is invalid\n", regno);
1398 		return -EINVAL;
1399 	}
1400 
1401 	reg = &regs[regno];
1402 	rw64 = is_reg64(env, insn, regno, reg, t);
1403 	if (t == SRC_OP) {
1404 		/* check whether register used as source operand can be read */
1405 		if (reg->type == NOT_INIT) {
1406 			verbose(env, "R%d !read_ok\n", regno);
1407 			return -EACCES;
1408 		}
1409 		/* We don't need to worry about FP liveness because it's read-only */
1410 		if (regno == BPF_REG_FP)
1411 			return 0;
1412 
1413 		if (rw64)
1414 			mark_insn_zext(env, reg);
1415 
1416 		return mark_reg_read(env, reg, reg->parent,
1417 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1418 	} else {
1419 		/* check whether register used as dest operand can be written to */
1420 		if (regno == BPF_REG_FP) {
1421 			verbose(env, "frame pointer is read only\n");
1422 			return -EACCES;
1423 		}
1424 		reg->live |= REG_LIVE_WRITTEN;
1425 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1426 		if (t == DST_OP)
1427 			mark_reg_unknown(env, regs, regno);
1428 	}
1429 	return 0;
1430 }
1431 
1432 /* for any branch, call, exit record the history of jmps in the given state */
1433 static int push_jmp_history(struct bpf_verifier_env *env,
1434 			    struct bpf_verifier_state *cur)
1435 {
1436 	u32 cnt = cur->jmp_history_cnt;
1437 	struct bpf_idx_pair *p;
1438 
1439 	cnt++;
1440 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1441 	if (!p)
1442 		return -ENOMEM;
1443 	p[cnt - 1].idx = env->insn_idx;
1444 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1445 	cur->jmp_history = p;
1446 	cur->jmp_history_cnt = cnt;
1447 	return 0;
1448 }
1449 
1450 /* Backtrack one insn at a time. If idx is not at the top of recorded
1451  * history then previous instruction came from straight line execution.
1452  */
1453 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1454 			     u32 *history)
1455 {
1456 	u32 cnt = *history;
1457 
1458 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1459 		i = st->jmp_history[cnt - 1].prev_idx;
1460 		(*history)--;
1461 	} else {
1462 		i--;
1463 	}
1464 	return i;
1465 }
1466 
1467 /* For given verifier state backtrack_insn() is called from the last insn to
1468  * the first insn. Its purpose is to compute a bitmask of registers and
1469  * stack slots that needs precision in the parent verifier state.
1470  */
1471 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1472 			  u32 *reg_mask, u64 *stack_mask)
1473 {
1474 	const struct bpf_insn_cbs cbs = {
1475 		.cb_print	= verbose,
1476 		.private_data	= env,
1477 	};
1478 	struct bpf_insn *insn = env->prog->insnsi + idx;
1479 	u8 class = BPF_CLASS(insn->code);
1480 	u8 opcode = BPF_OP(insn->code);
1481 	u8 mode = BPF_MODE(insn->code);
1482 	u32 dreg = 1u << insn->dst_reg;
1483 	u32 sreg = 1u << insn->src_reg;
1484 	u32 spi;
1485 
1486 	if (insn->code == 0)
1487 		return 0;
1488 	if (env->log.level & BPF_LOG_LEVEL) {
1489 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1490 		verbose(env, "%d: ", idx);
1491 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1492 	}
1493 
1494 	if (class == BPF_ALU || class == BPF_ALU64) {
1495 		if (!(*reg_mask & dreg))
1496 			return 0;
1497 		if (opcode == BPF_MOV) {
1498 			if (BPF_SRC(insn->code) == BPF_X) {
1499 				/* dreg = sreg
1500 				 * dreg needs precision after this insn
1501 				 * sreg needs precision before this insn
1502 				 */
1503 				*reg_mask &= ~dreg;
1504 				*reg_mask |= sreg;
1505 			} else {
1506 				/* dreg = K
1507 				 * dreg needs precision after this insn.
1508 				 * Corresponding register is already marked
1509 				 * as precise=true in this verifier state.
1510 				 * No further markings in parent are necessary
1511 				 */
1512 				*reg_mask &= ~dreg;
1513 			}
1514 		} else {
1515 			if (BPF_SRC(insn->code) == BPF_X) {
1516 				/* dreg += sreg
1517 				 * both dreg and sreg need precision
1518 				 * before this insn
1519 				 */
1520 				*reg_mask |= sreg;
1521 			} /* else dreg += K
1522 			   * dreg still needs precision before this insn
1523 			   */
1524 		}
1525 	} else if (class == BPF_LDX) {
1526 		if (!(*reg_mask & dreg))
1527 			return 0;
1528 		*reg_mask &= ~dreg;
1529 
1530 		/* scalars can only be spilled into stack w/o losing precision.
1531 		 * Load from any other memory can be zero extended.
1532 		 * The desire to keep that precision is already indicated
1533 		 * by 'precise' mark in corresponding register of this state.
1534 		 * No further tracking necessary.
1535 		 */
1536 		if (insn->src_reg != BPF_REG_FP)
1537 			return 0;
1538 		if (BPF_SIZE(insn->code) != BPF_DW)
1539 			return 0;
1540 
1541 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1542 		 * that [fp - off] slot contains scalar that needs to be
1543 		 * tracked with precision
1544 		 */
1545 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1546 		if (spi >= 64) {
1547 			verbose(env, "BUG spi %d\n", spi);
1548 			WARN_ONCE(1, "verifier backtracking bug");
1549 			return -EFAULT;
1550 		}
1551 		*stack_mask |= 1ull << spi;
1552 	} else if (class == BPF_STX || class == BPF_ST) {
1553 		if (*reg_mask & dreg)
1554 			/* stx & st shouldn't be using _scalar_ dst_reg
1555 			 * to access memory. It means backtracking
1556 			 * encountered a case of pointer subtraction.
1557 			 */
1558 			return -ENOTSUPP;
1559 		/* scalars can only be spilled into stack */
1560 		if (insn->dst_reg != BPF_REG_FP)
1561 			return 0;
1562 		if (BPF_SIZE(insn->code) != BPF_DW)
1563 			return 0;
1564 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1565 		if (spi >= 64) {
1566 			verbose(env, "BUG spi %d\n", spi);
1567 			WARN_ONCE(1, "verifier backtracking bug");
1568 			return -EFAULT;
1569 		}
1570 		if (!(*stack_mask & (1ull << spi)))
1571 			return 0;
1572 		*stack_mask &= ~(1ull << spi);
1573 		if (class == BPF_STX)
1574 			*reg_mask |= sreg;
1575 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1576 		if (opcode == BPF_CALL) {
1577 			if (insn->src_reg == BPF_PSEUDO_CALL)
1578 				return -ENOTSUPP;
1579 			/* regular helper call sets R0 */
1580 			*reg_mask &= ~1;
1581 			if (*reg_mask & 0x3f) {
1582 				/* if backtracing was looking for registers R1-R5
1583 				 * they should have been found already.
1584 				 */
1585 				verbose(env, "BUG regs %x\n", *reg_mask);
1586 				WARN_ONCE(1, "verifier backtracking bug");
1587 				return -EFAULT;
1588 			}
1589 		} else if (opcode == BPF_EXIT) {
1590 			return -ENOTSUPP;
1591 		}
1592 	} else if (class == BPF_LD) {
1593 		if (!(*reg_mask & dreg))
1594 			return 0;
1595 		*reg_mask &= ~dreg;
1596 		/* It's ld_imm64 or ld_abs or ld_ind.
1597 		 * For ld_imm64 no further tracking of precision
1598 		 * into parent is necessary
1599 		 */
1600 		if (mode == BPF_IND || mode == BPF_ABS)
1601 			/* to be analyzed */
1602 			return -ENOTSUPP;
1603 	}
1604 	return 0;
1605 }
1606 
1607 /* the scalar precision tracking algorithm:
1608  * . at the start all registers have precise=false.
1609  * . scalar ranges are tracked as normal through alu and jmp insns.
1610  * . once precise value of the scalar register is used in:
1611  *   .  ptr + scalar alu
1612  *   . if (scalar cond K|scalar)
1613  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1614  *   backtrack through the verifier states and mark all registers and
1615  *   stack slots with spilled constants that these scalar regisers
1616  *   should be precise.
1617  * . during state pruning two registers (or spilled stack slots)
1618  *   are equivalent if both are not precise.
1619  *
1620  * Note the verifier cannot simply walk register parentage chain,
1621  * since many different registers and stack slots could have been
1622  * used to compute single precise scalar.
1623  *
1624  * The approach of starting with precise=true for all registers and then
1625  * backtrack to mark a register as not precise when the verifier detects
1626  * that program doesn't care about specific value (e.g., when helper
1627  * takes register as ARG_ANYTHING parameter) is not safe.
1628  *
1629  * It's ok to walk single parentage chain of the verifier states.
1630  * It's possible that this backtracking will go all the way till 1st insn.
1631  * All other branches will be explored for needing precision later.
1632  *
1633  * The backtracking needs to deal with cases like:
1634  *   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)
1635  * r9 -= r8
1636  * r5 = r9
1637  * if r5 > 0x79f goto pc+7
1638  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1639  * r5 += 1
1640  * ...
1641  * call bpf_perf_event_output#25
1642  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1643  *
1644  * and this case:
1645  * r6 = 1
1646  * call foo // uses callee's r6 inside to compute r0
1647  * r0 += r6
1648  * if r0 == 0 goto
1649  *
1650  * to track above reg_mask/stack_mask needs to be independent for each frame.
1651  *
1652  * Also if parent's curframe > frame where backtracking started,
1653  * the verifier need to mark registers in both frames, otherwise callees
1654  * may incorrectly prune callers. This is similar to
1655  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1656  *
1657  * For now backtracking falls back into conservative marking.
1658  */
1659 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1660 				     struct bpf_verifier_state *st)
1661 {
1662 	struct bpf_func_state *func;
1663 	struct bpf_reg_state *reg;
1664 	int i, j;
1665 
1666 	/* big hammer: mark all scalars precise in this path.
1667 	 * pop_stack may still get !precise scalars.
1668 	 */
1669 	for (; st; st = st->parent)
1670 		for (i = 0; i <= st->curframe; i++) {
1671 			func = st->frame[i];
1672 			for (j = 0; j < BPF_REG_FP; j++) {
1673 				reg = &func->regs[j];
1674 				if (reg->type != SCALAR_VALUE)
1675 					continue;
1676 				reg->precise = true;
1677 			}
1678 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1679 				if (func->stack[j].slot_type[0] != STACK_SPILL)
1680 					continue;
1681 				reg = &func->stack[j].spilled_ptr;
1682 				if (reg->type != SCALAR_VALUE)
1683 					continue;
1684 				reg->precise = true;
1685 			}
1686 		}
1687 }
1688 
1689 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1690 				  int spi)
1691 {
1692 	struct bpf_verifier_state *st = env->cur_state;
1693 	int first_idx = st->first_insn_idx;
1694 	int last_idx = env->insn_idx;
1695 	struct bpf_func_state *func;
1696 	struct bpf_reg_state *reg;
1697 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1698 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
1699 	bool skip_first = true;
1700 	bool new_marks = false;
1701 	int i, err;
1702 
1703 	if (!env->allow_ptr_leaks)
1704 		/* backtracking is root only for now */
1705 		return 0;
1706 
1707 	func = st->frame[st->curframe];
1708 	if (regno >= 0) {
1709 		reg = &func->regs[regno];
1710 		if (reg->type != SCALAR_VALUE) {
1711 			WARN_ONCE(1, "backtracing misuse");
1712 			return -EFAULT;
1713 		}
1714 		if (!reg->precise)
1715 			new_marks = true;
1716 		else
1717 			reg_mask = 0;
1718 		reg->precise = true;
1719 	}
1720 
1721 	while (spi >= 0) {
1722 		if (func->stack[spi].slot_type[0] != STACK_SPILL) {
1723 			stack_mask = 0;
1724 			break;
1725 		}
1726 		reg = &func->stack[spi].spilled_ptr;
1727 		if (reg->type != SCALAR_VALUE) {
1728 			stack_mask = 0;
1729 			break;
1730 		}
1731 		if (!reg->precise)
1732 			new_marks = true;
1733 		else
1734 			stack_mask = 0;
1735 		reg->precise = true;
1736 		break;
1737 	}
1738 
1739 	if (!new_marks)
1740 		return 0;
1741 	if (!reg_mask && !stack_mask)
1742 		return 0;
1743 	for (;;) {
1744 		DECLARE_BITMAP(mask, 64);
1745 		u32 history = st->jmp_history_cnt;
1746 
1747 		if (env->log.level & BPF_LOG_LEVEL)
1748 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
1749 		for (i = last_idx;;) {
1750 			if (skip_first) {
1751 				err = 0;
1752 				skip_first = false;
1753 			} else {
1754 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
1755 			}
1756 			if (err == -ENOTSUPP) {
1757 				mark_all_scalars_precise(env, st);
1758 				return 0;
1759 			} else if (err) {
1760 				return err;
1761 			}
1762 			if (!reg_mask && !stack_mask)
1763 				/* Found assignment(s) into tracked register in this state.
1764 				 * Since this state is already marked, just return.
1765 				 * Nothing to be tracked further in the parent state.
1766 				 */
1767 				return 0;
1768 			if (i == first_idx)
1769 				break;
1770 			i = get_prev_insn_idx(st, i, &history);
1771 			if (i >= env->prog->len) {
1772 				/* This can happen if backtracking reached insn 0
1773 				 * and there are still reg_mask or stack_mask
1774 				 * to backtrack.
1775 				 * It means the backtracking missed the spot where
1776 				 * particular register was initialized with a constant.
1777 				 */
1778 				verbose(env, "BUG backtracking idx %d\n", i);
1779 				WARN_ONCE(1, "verifier backtracking bug");
1780 				return -EFAULT;
1781 			}
1782 		}
1783 		st = st->parent;
1784 		if (!st)
1785 			break;
1786 
1787 		new_marks = false;
1788 		func = st->frame[st->curframe];
1789 		bitmap_from_u64(mask, reg_mask);
1790 		for_each_set_bit(i, mask, 32) {
1791 			reg = &func->regs[i];
1792 			if (reg->type != SCALAR_VALUE) {
1793 				reg_mask &= ~(1u << i);
1794 				continue;
1795 			}
1796 			if (!reg->precise)
1797 				new_marks = true;
1798 			reg->precise = true;
1799 		}
1800 
1801 		bitmap_from_u64(mask, stack_mask);
1802 		for_each_set_bit(i, mask, 64) {
1803 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
1804 				/* the sequence of instructions:
1805 				 * 2: (bf) r3 = r10
1806 				 * 3: (7b) *(u64 *)(r3 -8) = r0
1807 				 * 4: (79) r4 = *(u64 *)(r10 -8)
1808 				 * doesn't contain jmps. It's backtracked
1809 				 * as a single block.
1810 				 * During backtracking insn 3 is not recognized as
1811 				 * stack access, so at the end of backtracking
1812 				 * stack slot fp-8 is still marked in stack_mask.
1813 				 * However the parent state may not have accessed
1814 				 * fp-8 and it's "unallocated" stack space.
1815 				 * In such case fallback to conservative.
1816 				 */
1817 				mark_all_scalars_precise(env, st);
1818 				return 0;
1819 			}
1820 
1821 			if (func->stack[i].slot_type[0] != STACK_SPILL) {
1822 				stack_mask &= ~(1ull << i);
1823 				continue;
1824 			}
1825 			reg = &func->stack[i].spilled_ptr;
1826 			if (reg->type != SCALAR_VALUE) {
1827 				stack_mask &= ~(1ull << i);
1828 				continue;
1829 			}
1830 			if (!reg->precise)
1831 				new_marks = true;
1832 			reg->precise = true;
1833 		}
1834 		if (env->log.level & BPF_LOG_LEVEL) {
1835 			print_verifier_state(env, func);
1836 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
1837 				new_marks ? "didn't have" : "already had",
1838 				reg_mask, stack_mask);
1839 		}
1840 
1841 		if (!reg_mask && !stack_mask)
1842 			break;
1843 		if (!new_marks)
1844 			break;
1845 
1846 		last_idx = st->last_insn_idx;
1847 		first_idx = st->first_insn_idx;
1848 	}
1849 	return 0;
1850 }
1851 
1852 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
1853 {
1854 	return __mark_chain_precision(env, regno, -1);
1855 }
1856 
1857 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
1858 {
1859 	return __mark_chain_precision(env, -1, spi);
1860 }
1861 
1862 static bool is_spillable_regtype(enum bpf_reg_type type)
1863 {
1864 	switch (type) {
1865 	case PTR_TO_MAP_VALUE:
1866 	case PTR_TO_MAP_VALUE_OR_NULL:
1867 	case PTR_TO_STACK:
1868 	case PTR_TO_CTX:
1869 	case PTR_TO_PACKET:
1870 	case PTR_TO_PACKET_META:
1871 	case PTR_TO_PACKET_END:
1872 	case PTR_TO_FLOW_KEYS:
1873 	case CONST_PTR_TO_MAP:
1874 	case PTR_TO_SOCKET:
1875 	case PTR_TO_SOCKET_OR_NULL:
1876 	case PTR_TO_SOCK_COMMON:
1877 	case PTR_TO_SOCK_COMMON_OR_NULL:
1878 	case PTR_TO_TCP_SOCK:
1879 	case PTR_TO_TCP_SOCK_OR_NULL:
1880 	case PTR_TO_XDP_SOCK:
1881 		return true;
1882 	default:
1883 		return false;
1884 	}
1885 }
1886 
1887 /* Does this register contain a constant zero? */
1888 static bool register_is_null(struct bpf_reg_state *reg)
1889 {
1890 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1891 }
1892 
1893 static bool register_is_const(struct bpf_reg_state *reg)
1894 {
1895 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
1896 }
1897 
1898 static void save_register_state(struct bpf_func_state *state,
1899 				int spi, struct bpf_reg_state *reg)
1900 {
1901 	int i;
1902 
1903 	state->stack[spi].spilled_ptr = *reg;
1904 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1905 
1906 	for (i = 0; i < BPF_REG_SIZE; i++)
1907 		state->stack[spi].slot_type[i] = STACK_SPILL;
1908 }
1909 
1910 /* check_stack_read/write functions track spill/fill of registers,
1911  * stack boundary and alignment are checked in check_mem_access()
1912  */
1913 static int check_stack_write(struct bpf_verifier_env *env,
1914 			     struct bpf_func_state *state, /* func where register points to */
1915 			     int off, int size, int value_regno, int insn_idx)
1916 {
1917 	struct bpf_func_state *cur; /* state of the current function */
1918 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1919 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
1920 	struct bpf_reg_state *reg = NULL;
1921 
1922 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1923 				 state->acquired_refs, true);
1924 	if (err)
1925 		return err;
1926 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1927 	 * so it's aligned access and [off, off + size) are within stack limits
1928 	 */
1929 	if (!env->allow_ptr_leaks &&
1930 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
1931 	    size != BPF_REG_SIZE) {
1932 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
1933 		return -EACCES;
1934 	}
1935 
1936 	cur = env->cur_state->frame[env->cur_state->curframe];
1937 	if (value_regno >= 0)
1938 		reg = &cur->regs[value_regno];
1939 
1940 	if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1941 	    !register_is_null(reg) && env->allow_ptr_leaks) {
1942 		if (dst_reg != BPF_REG_FP) {
1943 			/* The backtracking logic can only recognize explicit
1944 			 * stack slot address like [fp - 8]. Other spill of
1945 			 * scalar via different register has to be conervative.
1946 			 * Backtrack from here and mark all registers as precise
1947 			 * that contributed into 'reg' being a constant.
1948 			 */
1949 			err = mark_chain_precision(env, value_regno);
1950 			if (err)
1951 				return err;
1952 		}
1953 		save_register_state(state, spi, reg);
1954 	} else if (reg && is_spillable_regtype(reg->type)) {
1955 		/* register containing pointer is being spilled into stack */
1956 		if (size != BPF_REG_SIZE) {
1957 			verbose_linfo(env, insn_idx, "; ");
1958 			verbose(env, "invalid size of register spill\n");
1959 			return -EACCES;
1960 		}
1961 
1962 		if (state != cur && reg->type == PTR_TO_STACK) {
1963 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1964 			return -EINVAL;
1965 		}
1966 
1967 		if (!env->allow_ptr_leaks) {
1968 			bool sanitize = false;
1969 
1970 			if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1971 			    register_is_const(&state->stack[spi].spilled_ptr))
1972 				sanitize = true;
1973 			for (i = 0; i < BPF_REG_SIZE; i++)
1974 				if (state->stack[spi].slot_type[i] == STACK_MISC) {
1975 					sanitize = true;
1976 					break;
1977 				}
1978 			if (sanitize) {
1979 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1980 				int soff = (-spi - 1) * BPF_REG_SIZE;
1981 
1982 				/* detected reuse of integer stack slot with a pointer
1983 				 * which means either llvm is reusing stack slot or
1984 				 * an attacker is trying to exploit CVE-2018-3639
1985 				 * (speculative store bypass)
1986 				 * Have to sanitize that slot with preemptive
1987 				 * store of zero.
1988 				 */
1989 				if (*poff && *poff != soff) {
1990 					/* disallow programs where single insn stores
1991 					 * into two different stack slots, since verifier
1992 					 * cannot sanitize them
1993 					 */
1994 					verbose(env,
1995 						"insn %d cannot access two stack slots fp%d and fp%d",
1996 						insn_idx, *poff, soff);
1997 					return -EINVAL;
1998 				}
1999 				*poff = soff;
2000 			}
2001 		}
2002 		save_register_state(state, spi, reg);
2003 	} else {
2004 		u8 type = STACK_MISC;
2005 
2006 		/* regular write of data into stack destroys any spilled ptr */
2007 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2008 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2009 		if (state->stack[spi].slot_type[0] == STACK_SPILL)
2010 			for (i = 0; i < BPF_REG_SIZE; i++)
2011 				state->stack[spi].slot_type[i] = STACK_MISC;
2012 
2013 		/* only mark the slot as written if all 8 bytes were written
2014 		 * otherwise read propagation may incorrectly stop too soon
2015 		 * when stack slots are partially written.
2016 		 * This heuristic means that read propagation will be
2017 		 * conservative, since it will add reg_live_read marks
2018 		 * to stack slots all the way to first state when programs
2019 		 * writes+reads less than 8 bytes
2020 		 */
2021 		if (size == BPF_REG_SIZE)
2022 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2023 
2024 		/* when we zero initialize stack slots mark them as such */
2025 		if (reg && register_is_null(reg)) {
2026 			/* backtracking doesn't work for STACK_ZERO yet. */
2027 			err = mark_chain_precision(env, value_regno);
2028 			if (err)
2029 				return err;
2030 			type = STACK_ZERO;
2031 		}
2032 
2033 		/* Mark slots affected by this stack write. */
2034 		for (i = 0; i < size; i++)
2035 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2036 				type;
2037 	}
2038 	return 0;
2039 }
2040 
2041 static int check_stack_read(struct bpf_verifier_env *env,
2042 			    struct bpf_func_state *reg_state /* func where register points to */,
2043 			    int off, int size, int value_regno)
2044 {
2045 	struct bpf_verifier_state *vstate = env->cur_state;
2046 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2047 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2048 	struct bpf_reg_state *reg;
2049 	u8 *stype;
2050 
2051 	if (reg_state->allocated_stack <= slot) {
2052 		verbose(env, "invalid read from stack off %d+0 size %d\n",
2053 			off, size);
2054 		return -EACCES;
2055 	}
2056 	stype = reg_state->stack[spi].slot_type;
2057 	reg = &reg_state->stack[spi].spilled_ptr;
2058 
2059 	if (stype[0] == STACK_SPILL) {
2060 		if (size != BPF_REG_SIZE) {
2061 			if (reg->type != SCALAR_VALUE) {
2062 				verbose_linfo(env, env->insn_idx, "; ");
2063 				verbose(env, "invalid size of register fill\n");
2064 				return -EACCES;
2065 			}
2066 			if (value_regno >= 0) {
2067 				mark_reg_unknown(env, state->regs, value_regno);
2068 				state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2069 			}
2070 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2071 			return 0;
2072 		}
2073 		for (i = 1; i < BPF_REG_SIZE; i++) {
2074 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2075 				verbose(env, "corrupted spill memory\n");
2076 				return -EACCES;
2077 			}
2078 		}
2079 
2080 		if (value_regno >= 0) {
2081 			/* restore register state from stack */
2082 			state->regs[value_regno] = *reg;
2083 			/* mark reg as written since spilled pointer state likely
2084 			 * has its liveness marks cleared by is_state_visited()
2085 			 * which resets stack/reg liveness for state transitions
2086 			 */
2087 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2088 		}
2089 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2090 	} else {
2091 		int zeros = 0;
2092 
2093 		for (i = 0; i < size; i++) {
2094 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2095 				continue;
2096 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2097 				zeros++;
2098 				continue;
2099 			}
2100 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2101 				off, i, size);
2102 			return -EACCES;
2103 		}
2104 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2105 		if (value_regno >= 0) {
2106 			if (zeros == size) {
2107 				/* any size read into register is zero extended,
2108 				 * so the whole register == const_zero
2109 				 */
2110 				__mark_reg_const_zero(&state->regs[value_regno]);
2111 				/* backtracking doesn't support STACK_ZERO yet,
2112 				 * so mark it precise here, so that later
2113 				 * backtracking can stop here.
2114 				 * Backtracking may not need this if this register
2115 				 * doesn't participate in pointer adjustment.
2116 				 * Forward propagation of precise flag is not
2117 				 * necessary either. This mark is only to stop
2118 				 * backtracking. Any register that contributed
2119 				 * to const 0 was marked precise before spill.
2120 				 */
2121 				state->regs[value_regno].precise = true;
2122 			} else {
2123 				/* have read misc data from the stack */
2124 				mark_reg_unknown(env, state->regs, value_regno);
2125 			}
2126 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2127 		}
2128 	}
2129 	return 0;
2130 }
2131 
2132 static int check_stack_access(struct bpf_verifier_env *env,
2133 			      const struct bpf_reg_state *reg,
2134 			      int off, int size)
2135 {
2136 	/* Stack accesses must be at a fixed offset, so that we
2137 	 * can determine what type of data were returned. See
2138 	 * check_stack_read().
2139 	 */
2140 	if (!tnum_is_const(reg->var_off)) {
2141 		char tn_buf[48];
2142 
2143 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2144 		verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2145 			tn_buf, off, size);
2146 		return -EACCES;
2147 	}
2148 
2149 	if (off >= 0 || off < -MAX_BPF_STACK) {
2150 		verbose(env, "invalid stack off=%d size=%d\n", off, size);
2151 		return -EACCES;
2152 	}
2153 
2154 	return 0;
2155 }
2156 
2157 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2158 				 int off, int size, enum bpf_access_type type)
2159 {
2160 	struct bpf_reg_state *regs = cur_regs(env);
2161 	struct bpf_map *map = regs[regno].map_ptr;
2162 	u32 cap = bpf_map_flags_to_cap(map);
2163 
2164 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2165 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2166 			map->value_size, off, size);
2167 		return -EACCES;
2168 	}
2169 
2170 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2171 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2172 			map->value_size, off, size);
2173 		return -EACCES;
2174 	}
2175 
2176 	return 0;
2177 }
2178 
2179 /* check read/write into map element returned by bpf_map_lookup_elem() */
2180 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
2181 			      int size, bool zero_size_allowed)
2182 {
2183 	struct bpf_reg_state *regs = cur_regs(env);
2184 	struct bpf_map *map = regs[regno].map_ptr;
2185 
2186 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2187 	    off + size > map->value_size) {
2188 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2189 			map->value_size, off, size);
2190 		return -EACCES;
2191 	}
2192 	return 0;
2193 }
2194 
2195 /* check read/write into a map element with possible variable offset */
2196 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2197 			    int off, int size, bool zero_size_allowed)
2198 {
2199 	struct bpf_verifier_state *vstate = env->cur_state;
2200 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2201 	struct bpf_reg_state *reg = &state->regs[regno];
2202 	int err;
2203 
2204 	/* We may have adjusted the register to this map value, so we
2205 	 * need to try adding each of min_value and max_value to off
2206 	 * to make sure our theoretical access will be safe.
2207 	 */
2208 	if (env->log.level & BPF_LOG_LEVEL)
2209 		print_verifier_state(env, state);
2210 
2211 	/* The minimum value is only important with signed
2212 	 * comparisons where we can't assume the floor of a
2213 	 * value is 0.  If we are using signed variables for our
2214 	 * index'es we need to make sure that whatever we use
2215 	 * will have a set floor within our range.
2216 	 */
2217 	if (reg->smin_value < 0 &&
2218 	    (reg->smin_value == S64_MIN ||
2219 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2220 	      reg->smin_value + off < 0)) {
2221 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2222 			regno);
2223 		return -EACCES;
2224 	}
2225 	err = __check_map_access(env, regno, reg->smin_value + off, size,
2226 				 zero_size_allowed);
2227 	if (err) {
2228 		verbose(env, "R%d min value is outside of the array range\n",
2229 			regno);
2230 		return err;
2231 	}
2232 
2233 	/* If we haven't set a max value then we need to bail since we can't be
2234 	 * sure we won't do bad things.
2235 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
2236 	 */
2237 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2238 		verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
2239 			regno);
2240 		return -EACCES;
2241 	}
2242 	err = __check_map_access(env, regno, reg->umax_value + off, size,
2243 				 zero_size_allowed);
2244 	if (err)
2245 		verbose(env, "R%d max value is outside of the array range\n",
2246 			regno);
2247 
2248 	if (map_value_has_spin_lock(reg->map_ptr)) {
2249 		u32 lock = reg->map_ptr->spin_lock_off;
2250 
2251 		/* if any part of struct bpf_spin_lock can be touched by
2252 		 * load/store reject this program.
2253 		 * To check that [x1, x2) overlaps with [y1, y2)
2254 		 * it is sufficient to check x1 < y2 && y1 < x2.
2255 		 */
2256 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2257 		     lock < reg->umax_value + off + size) {
2258 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2259 			return -EACCES;
2260 		}
2261 	}
2262 	return err;
2263 }
2264 
2265 #define MAX_PACKET_OFF 0xffff
2266 
2267 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2268 				       const struct bpf_call_arg_meta *meta,
2269 				       enum bpf_access_type t)
2270 {
2271 	switch (env->prog->type) {
2272 	/* Program types only with direct read access go here! */
2273 	case BPF_PROG_TYPE_LWT_IN:
2274 	case BPF_PROG_TYPE_LWT_OUT:
2275 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2276 	case BPF_PROG_TYPE_SK_REUSEPORT:
2277 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2278 	case BPF_PROG_TYPE_CGROUP_SKB:
2279 		if (t == BPF_WRITE)
2280 			return false;
2281 		/* fallthrough */
2282 
2283 	/* Program types with direct read + write access go here! */
2284 	case BPF_PROG_TYPE_SCHED_CLS:
2285 	case BPF_PROG_TYPE_SCHED_ACT:
2286 	case BPF_PROG_TYPE_XDP:
2287 	case BPF_PROG_TYPE_LWT_XMIT:
2288 	case BPF_PROG_TYPE_SK_SKB:
2289 	case BPF_PROG_TYPE_SK_MSG:
2290 		if (meta)
2291 			return meta->pkt_access;
2292 
2293 		env->seen_direct_write = true;
2294 		return true;
2295 
2296 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2297 		if (t == BPF_WRITE)
2298 			env->seen_direct_write = true;
2299 
2300 		return true;
2301 
2302 	default:
2303 		return false;
2304 	}
2305 }
2306 
2307 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
2308 				 int off, int size, bool zero_size_allowed)
2309 {
2310 	struct bpf_reg_state *regs = cur_regs(env);
2311 	struct bpf_reg_state *reg = &regs[regno];
2312 
2313 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2314 	    (u64)off + size > reg->range) {
2315 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2316 			off, size, regno, reg->id, reg->off, reg->range);
2317 		return -EACCES;
2318 	}
2319 	return 0;
2320 }
2321 
2322 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2323 			       int size, bool zero_size_allowed)
2324 {
2325 	struct bpf_reg_state *regs = cur_regs(env);
2326 	struct bpf_reg_state *reg = &regs[regno];
2327 	int err;
2328 
2329 	/* We may have added a variable offset to the packet pointer; but any
2330 	 * reg->range we have comes after that.  We are only checking the fixed
2331 	 * offset.
2332 	 */
2333 
2334 	/* We don't allow negative numbers, because we aren't tracking enough
2335 	 * detail to prove they're safe.
2336 	 */
2337 	if (reg->smin_value < 0) {
2338 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2339 			regno);
2340 		return -EACCES;
2341 	}
2342 	err = __check_packet_access(env, regno, off, size, zero_size_allowed);
2343 	if (err) {
2344 		verbose(env, "R%d offset is outside of the packet\n", regno);
2345 		return err;
2346 	}
2347 
2348 	/* __check_packet_access has made sure "off + size - 1" is within u16.
2349 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2350 	 * otherwise find_good_pkt_pointers would have refused to set range info
2351 	 * that __check_packet_access would have rejected this pkt access.
2352 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2353 	 */
2354 	env->prog->aux->max_pkt_offset =
2355 		max_t(u32, env->prog->aux->max_pkt_offset,
2356 		      off + reg->umax_value + size - 1);
2357 
2358 	return err;
2359 }
2360 
2361 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
2362 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2363 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
2364 			    u32 *btf_id)
2365 {
2366 	struct bpf_insn_access_aux info = {
2367 		.reg_type = *reg_type,
2368 		.log = &env->log,
2369 	};
2370 
2371 	if (env->ops->is_valid_access &&
2372 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2373 		/* A non zero info.ctx_field_size indicates that this field is a
2374 		 * candidate for later verifier transformation to load the whole
2375 		 * field and then apply a mask when accessed with a narrower
2376 		 * access than actual ctx access size. A zero info.ctx_field_size
2377 		 * will only allow for whole field access and rejects any other
2378 		 * type of narrower access.
2379 		 */
2380 		*reg_type = info.reg_type;
2381 
2382 		if (*reg_type == PTR_TO_BTF_ID)
2383 			*btf_id = info.btf_id;
2384 		else
2385 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2386 		/* remember the offset of last byte accessed in ctx */
2387 		if (env->prog->aux->max_ctx_offset < off + size)
2388 			env->prog->aux->max_ctx_offset = off + size;
2389 		return 0;
2390 	}
2391 
2392 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2393 	return -EACCES;
2394 }
2395 
2396 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2397 				  int size)
2398 {
2399 	if (size < 0 || off < 0 ||
2400 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
2401 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
2402 			off, size);
2403 		return -EACCES;
2404 	}
2405 	return 0;
2406 }
2407 
2408 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2409 			     u32 regno, int off, int size,
2410 			     enum bpf_access_type t)
2411 {
2412 	struct bpf_reg_state *regs = cur_regs(env);
2413 	struct bpf_reg_state *reg = &regs[regno];
2414 	struct bpf_insn_access_aux info = {};
2415 	bool valid;
2416 
2417 	if (reg->smin_value < 0) {
2418 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2419 			regno);
2420 		return -EACCES;
2421 	}
2422 
2423 	switch (reg->type) {
2424 	case PTR_TO_SOCK_COMMON:
2425 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2426 		break;
2427 	case PTR_TO_SOCKET:
2428 		valid = bpf_sock_is_valid_access(off, size, t, &info);
2429 		break;
2430 	case PTR_TO_TCP_SOCK:
2431 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2432 		break;
2433 	case PTR_TO_XDP_SOCK:
2434 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2435 		break;
2436 	default:
2437 		valid = false;
2438 	}
2439 
2440 
2441 	if (valid) {
2442 		env->insn_aux_data[insn_idx].ctx_field_size =
2443 			info.ctx_field_size;
2444 		return 0;
2445 	}
2446 
2447 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
2448 		regno, reg_type_str[reg->type], off, size);
2449 
2450 	return -EACCES;
2451 }
2452 
2453 static bool __is_pointer_value(bool allow_ptr_leaks,
2454 			       const struct bpf_reg_state *reg)
2455 {
2456 	if (allow_ptr_leaks)
2457 		return false;
2458 
2459 	return reg->type != SCALAR_VALUE;
2460 }
2461 
2462 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2463 {
2464 	return cur_regs(env) + regno;
2465 }
2466 
2467 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2468 {
2469 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2470 }
2471 
2472 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2473 {
2474 	const struct bpf_reg_state *reg = reg_state(env, regno);
2475 
2476 	return reg->type == PTR_TO_CTX;
2477 }
2478 
2479 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2480 {
2481 	const struct bpf_reg_state *reg = reg_state(env, regno);
2482 
2483 	return type_is_sk_pointer(reg->type);
2484 }
2485 
2486 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2487 {
2488 	const struct bpf_reg_state *reg = reg_state(env, regno);
2489 
2490 	return type_is_pkt_pointer(reg->type);
2491 }
2492 
2493 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2494 {
2495 	const struct bpf_reg_state *reg = reg_state(env, regno);
2496 
2497 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2498 	return reg->type == PTR_TO_FLOW_KEYS;
2499 }
2500 
2501 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2502 				   const struct bpf_reg_state *reg,
2503 				   int off, int size, bool strict)
2504 {
2505 	struct tnum reg_off;
2506 	int ip_align;
2507 
2508 	/* Byte size accesses are always allowed. */
2509 	if (!strict || size == 1)
2510 		return 0;
2511 
2512 	/* For platforms that do not have a Kconfig enabling
2513 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2514 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
2515 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2516 	 * to this code only in strict mode where we want to emulate
2517 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
2518 	 * unconditional IP align value of '2'.
2519 	 */
2520 	ip_align = 2;
2521 
2522 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2523 	if (!tnum_is_aligned(reg_off, size)) {
2524 		char tn_buf[48];
2525 
2526 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2527 		verbose(env,
2528 			"misaligned packet access off %d+%s+%d+%d size %d\n",
2529 			ip_align, tn_buf, reg->off, off, size);
2530 		return -EACCES;
2531 	}
2532 
2533 	return 0;
2534 }
2535 
2536 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2537 				       const struct bpf_reg_state *reg,
2538 				       const char *pointer_desc,
2539 				       int off, int size, bool strict)
2540 {
2541 	struct tnum reg_off;
2542 
2543 	/* Byte size accesses are always allowed. */
2544 	if (!strict || size == 1)
2545 		return 0;
2546 
2547 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2548 	if (!tnum_is_aligned(reg_off, size)) {
2549 		char tn_buf[48];
2550 
2551 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2552 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2553 			pointer_desc, tn_buf, reg->off, off, size);
2554 		return -EACCES;
2555 	}
2556 
2557 	return 0;
2558 }
2559 
2560 static int check_ptr_alignment(struct bpf_verifier_env *env,
2561 			       const struct bpf_reg_state *reg, int off,
2562 			       int size, bool strict_alignment_once)
2563 {
2564 	bool strict = env->strict_alignment || strict_alignment_once;
2565 	const char *pointer_desc = "";
2566 
2567 	switch (reg->type) {
2568 	case PTR_TO_PACKET:
2569 	case PTR_TO_PACKET_META:
2570 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
2571 		 * right in front, treat it the very same way.
2572 		 */
2573 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
2574 	case PTR_TO_FLOW_KEYS:
2575 		pointer_desc = "flow keys ";
2576 		break;
2577 	case PTR_TO_MAP_VALUE:
2578 		pointer_desc = "value ";
2579 		break;
2580 	case PTR_TO_CTX:
2581 		pointer_desc = "context ";
2582 		break;
2583 	case PTR_TO_STACK:
2584 		pointer_desc = "stack ";
2585 		/* The stack spill tracking logic in check_stack_write()
2586 		 * and check_stack_read() relies on stack accesses being
2587 		 * aligned.
2588 		 */
2589 		strict = true;
2590 		break;
2591 	case PTR_TO_SOCKET:
2592 		pointer_desc = "sock ";
2593 		break;
2594 	case PTR_TO_SOCK_COMMON:
2595 		pointer_desc = "sock_common ";
2596 		break;
2597 	case PTR_TO_TCP_SOCK:
2598 		pointer_desc = "tcp_sock ";
2599 		break;
2600 	case PTR_TO_XDP_SOCK:
2601 		pointer_desc = "xdp_sock ";
2602 		break;
2603 	default:
2604 		break;
2605 	}
2606 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2607 					   strict);
2608 }
2609 
2610 static int update_stack_depth(struct bpf_verifier_env *env,
2611 			      const struct bpf_func_state *func,
2612 			      int off)
2613 {
2614 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
2615 
2616 	if (stack >= -off)
2617 		return 0;
2618 
2619 	/* update known max for given subprogram */
2620 	env->subprog_info[func->subprogno].stack_depth = -off;
2621 	return 0;
2622 }
2623 
2624 /* starting from main bpf function walk all instructions of the function
2625  * and recursively walk all callees that given function can call.
2626  * Ignore jump and exit insns.
2627  * Since recursion is prevented by check_cfg() this algorithm
2628  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2629  */
2630 static int check_max_stack_depth(struct bpf_verifier_env *env)
2631 {
2632 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2633 	struct bpf_subprog_info *subprog = env->subprog_info;
2634 	struct bpf_insn *insn = env->prog->insnsi;
2635 	int ret_insn[MAX_CALL_FRAMES];
2636 	int ret_prog[MAX_CALL_FRAMES];
2637 
2638 process_func:
2639 	/* round up to 32-bytes, since this is granularity
2640 	 * of interpreter stack size
2641 	 */
2642 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2643 	if (depth > MAX_BPF_STACK) {
2644 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
2645 			frame + 1, depth);
2646 		return -EACCES;
2647 	}
2648 continue_func:
2649 	subprog_end = subprog[idx + 1].start;
2650 	for (; i < subprog_end; i++) {
2651 		if (insn[i].code != (BPF_JMP | BPF_CALL))
2652 			continue;
2653 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
2654 			continue;
2655 		/* remember insn and function to return to */
2656 		ret_insn[frame] = i + 1;
2657 		ret_prog[frame] = idx;
2658 
2659 		/* find the callee */
2660 		i = i + insn[i].imm + 1;
2661 		idx = find_subprog(env, i);
2662 		if (idx < 0) {
2663 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2664 				  i);
2665 			return -EFAULT;
2666 		}
2667 		frame++;
2668 		if (frame >= MAX_CALL_FRAMES) {
2669 			verbose(env, "the call stack of %d frames is too deep !\n",
2670 				frame);
2671 			return -E2BIG;
2672 		}
2673 		goto process_func;
2674 	}
2675 	/* end of for() loop means the last insn of the 'subprog'
2676 	 * was reached. Doesn't matter whether it was JA or EXIT
2677 	 */
2678 	if (frame == 0)
2679 		return 0;
2680 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2681 	frame--;
2682 	i = ret_insn[frame];
2683 	idx = ret_prog[frame];
2684 	goto continue_func;
2685 }
2686 
2687 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2688 static int get_callee_stack_depth(struct bpf_verifier_env *env,
2689 				  const struct bpf_insn *insn, int idx)
2690 {
2691 	int start = idx + insn->imm + 1, subprog;
2692 
2693 	subprog = find_subprog(env, start);
2694 	if (subprog < 0) {
2695 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2696 			  start);
2697 		return -EFAULT;
2698 	}
2699 	return env->subprog_info[subprog].stack_depth;
2700 }
2701 #endif
2702 
2703 static int check_ctx_reg(struct bpf_verifier_env *env,
2704 			 const struct bpf_reg_state *reg, int regno)
2705 {
2706 	/* Access to ctx or passing it to a helper is only allowed in
2707 	 * its original, unmodified form.
2708 	 */
2709 
2710 	if (reg->off) {
2711 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2712 			regno, reg->off);
2713 		return -EACCES;
2714 	}
2715 
2716 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2717 		char tn_buf[48];
2718 
2719 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2720 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2721 		return -EACCES;
2722 	}
2723 
2724 	return 0;
2725 }
2726 
2727 static int check_tp_buffer_access(struct bpf_verifier_env *env,
2728 				  const struct bpf_reg_state *reg,
2729 				  int regno, int off, int size)
2730 {
2731 	if (off < 0) {
2732 		verbose(env,
2733 			"R%d invalid tracepoint buffer access: off=%d, size=%d",
2734 			regno, off, size);
2735 		return -EACCES;
2736 	}
2737 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2738 		char tn_buf[48];
2739 
2740 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2741 		verbose(env,
2742 			"R%d invalid variable buffer offset: off=%d, var_off=%s",
2743 			regno, off, tn_buf);
2744 		return -EACCES;
2745 	}
2746 	if (off + size > env->prog->aux->max_tp_access)
2747 		env->prog->aux->max_tp_access = off + size;
2748 
2749 	return 0;
2750 }
2751 
2752 
2753 /* truncate register to smaller size (in bytes)
2754  * must be called with size < BPF_REG_SIZE
2755  */
2756 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2757 {
2758 	u64 mask;
2759 
2760 	/* clear high bits in bit representation */
2761 	reg->var_off = tnum_cast(reg->var_off, size);
2762 
2763 	/* fix arithmetic bounds */
2764 	mask = ((u64)1 << (size * 8)) - 1;
2765 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2766 		reg->umin_value &= mask;
2767 		reg->umax_value &= mask;
2768 	} else {
2769 		reg->umin_value = 0;
2770 		reg->umax_value = mask;
2771 	}
2772 	reg->smin_value = reg->umin_value;
2773 	reg->smax_value = reg->umax_value;
2774 }
2775 
2776 static bool bpf_map_is_rdonly(const struct bpf_map *map)
2777 {
2778 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
2779 }
2780 
2781 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
2782 {
2783 	void *ptr;
2784 	u64 addr;
2785 	int err;
2786 
2787 	err = map->ops->map_direct_value_addr(map, &addr, off);
2788 	if (err)
2789 		return err;
2790 	ptr = (void *)(long)addr + off;
2791 
2792 	switch (size) {
2793 	case sizeof(u8):
2794 		*val = (u64)*(u8 *)ptr;
2795 		break;
2796 	case sizeof(u16):
2797 		*val = (u64)*(u16 *)ptr;
2798 		break;
2799 	case sizeof(u32):
2800 		*val = (u64)*(u32 *)ptr;
2801 		break;
2802 	case sizeof(u64):
2803 		*val = *(u64 *)ptr;
2804 		break;
2805 	default:
2806 		return -EINVAL;
2807 	}
2808 	return 0;
2809 }
2810 
2811 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
2812 				   struct bpf_reg_state *regs,
2813 				   int regno, int off, int size,
2814 				   enum bpf_access_type atype,
2815 				   int value_regno)
2816 {
2817 	struct bpf_reg_state *reg = regs + regno;
2818 	const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
2819 	const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
2820 	u32 btf_id;
2821 	int ret;
2822 
2823 	if (atype != BPF_READ) {
2824 		verbose(env, "only read is supported\n");
2825 		return -EACCES;
2826 	}
2827 
2828 	if (off < 0) {
2829 		verbose(env,
2830 			"R%d is ptr_%s invalid negative access: off=%d\n",
2831 			regno, tname, off);
2832 		return -EACCES;
2833 	}
2834 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2835 		char tn_buf[48];
2836 
2837 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2838 		verbose(env,
2839 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
2840 			regno, tname, off, tn_buf);
2841 		return -EACCES;
2842 	}
2843 
2844 	ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
2845 	if (ret < 0)
2846 		return ret;
2847 
2848 	if (ret == SCALAR_VALUE) {
2849 		mark_reg_unknown(env, regs, value_regno);
2850 		return 0;
2851 	}
2852 	mark_reg_known_zero(env, regs, value_regno);
2853 	regs[value_regno].type = PTR_TO_BTF_ID;
2854 	regs[value_regno].btf_id = btf_id;
2855 	return 0;
2856 }
2857 
2858 /* check whether memory at (regno + off) is accessible for t = (read | write)
2859  * if t==write, value_regno is a register which value is stored into memory
2860  * if t==read, value_regno is a register which will receive the value from memory
2861  * if t==write && value_regno==-1, some unknown value is stored into memory
2862  * if t==read && value_regno==-1, don't care what we read from memory
2863  */
2864 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2865 			    int off, int bpf_size, enum bpf_access_type t,
2866 			    int value_regno, bool strict_alignment_once)
2867 {
2868 	struct bpf_reg_state *regs = cur_regs(env);
2869 	struct bpf_reg_state *reg = regs + regno;
2870 	struct bpf_func_state *state;
2871 	int size, err = 0;
2872 
2873 	size = bpf_size_to_bytes(bpf_size);
2874 	if (size < 0)
2875 		return size;
2876 
2877 	/* alignment checks will add in reg->off themselves */
2878 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
2879 	if (err)
2880 		return err;
2881 
2882 	/* for access checks, reg->off is just part of off */
2883 	off += reg->off;
2884 
2885 	if (reg->type == PTR_TO_MAP_VALUE) {
2886 		if (t == BPF_WRITE && value_regno >= 0 &&
2887 		    is_pointer_value(env, value_regno)) {
2888 			verbose(env, "R%d leaks addr into map\n", value_regno);
2889 			return -EACCES;
2890 		}
2891 		err = check_map_access_type(env, regno, off, size, t);
2892 		if (err)
2893 			return err;
2894 		err = check_map_access(env, regno, off, size, false);
2895 		if (!err && t == BPF_READ && value_regno >= 0) {
2896 			struct bpf_map *map = reg->map_ptr;
2897 
2898 			/* if map is read-only, track its contents as scalars */
2899 			if (tnum_is_const(reg->var_off) &&
2900 			    bpf_map_is_rdonly(map) &&
2901 			    map->ops->map_direct_value_addr) {
2902 				int map_off = off + reg->var_off.value;
2903 				u64 val = 0;
2904 
2905 				err = bpf_map_direct_read(map, map_off, size,
2906 							  &val);
2907 				if (err)
2908 					return err;
2909 
2910 				regs[value_regno].type = SCALAR_VALUE;
2911 				__mark_reg_known(&regs[value_regno], val);
2912 			} else {
2913 				mark_reg_unknown(env, regs, value_regno);
2914 			}
2915 		}
2916 	} else if (reg->type == PTR_TO_CTX) {
2917 		enum bpf_reg_type reg_type = SCALAR_VALUE;
2918 		u32 btf_id = 0;
2919 
2920 		if (t == BPF_WRITE && value_regno >= 0 &&
2921 		    is_pointer_value(env, value_regno)) {
2922 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
2923 			return -EACCES;
2924 		}
2925 
2926 		err = check_ctx_reg(env, reg, regno);
2927 		if (err < 0)
2928 			return err;
2929 
2930 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
2931 		if (err)
2932 			verbose_linfo(env, insn_idx, "; ");
2933 		if (!err && t == BPF_READ && value_regno >= 0) {
2934 			/* ctx access returns either a scalar, or a
2935 			 * PTR_TO_PACKET[_META,_END]. In the latter
2936 			 * case, we know the offset is zero.
2937 			 */
2938 			if (reg_type == SCALAR_VALUE) {
2939 				mark_reg_unknown(env, regs, value_regno);
2940 			} else {
2941 				mark_reg_known_zero(env, regs,
2942 						    value_regno);
2943 				if (reg_type_may_be_null(reg_type))
2944 					regs[value_regno].id = ++env->id_gen;
2945 				/* A load of ctx field could have different
2946 				 * actual load size with the one encoded in the
2947 				 * insn. When the dst is PTR, it is for sure not
2948 				 * a sub-register.
2949 				 */
2950 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
2951 				if (reg_type == PTR_TO_BTF_ID)
2952 					regs[value_regno].btf_id = btf_id;
2953 			}
2954 			regs[value_regno].type = reg_type;
2955 		}
2956 
2957 	} else if (reg->type == PTR_TO_STACK) {
2958 		off += reg->var_off.value;
2959 		err = check_stack_access(env, reg, off, size);
2960 		if (err)
2961 			return err;
2962 
2963 		state = func(env, reg);
2964 		err = update_stack_depth(env, state, off);
2965 		if (err)
2966 			return err;
2967 
2968 		if (t == BPF_WRITE)
2969 			err = check_stack_write(env, state, off, size,
2970 						value_regno, insn_idx);
2971 		else
2972 			err = check_stack_read(env, state, off, size,
2973 					       value_regno);
2974 	} else if (reg_is_pkt_pointer(reg)) {
2975 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
2976 			verbose(env, "cannot write into packet\n");
2977 			return -EACCES;
2978 		}
2979 		if (t == BPF_WRITE && value_regno >= 0 &&
2980 		    is_pointer_value(env, value_regno)) {
2981 			verbose(env, "R%d leaks addr into packet\n",
2982 				value_regno);
2983 			return -EACCES;
2984 		}
2985 		err = check_packet_access(env, regno, off, size, false);
2986 		if (!err && t == BPF_READ && value_regno >= 0)
2987 			mark_reg_unknown(env, regs, value_regno);
2988 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
2989 		if (t == BPF_WRITE && value_regno >= 0 &&
2990 		    is_pointer_value(env, value_regno)) {
2991 			verbose(env, "R%d leaks addr into flow keys\n",
2992 				value_regno);
2993 			return -EACCES;
2994 		}
2995 
2996 		err = check_flow_keys_access(env, off, size);
2997 		if (!err && t == BPF_READ && value_regno >= 0)
2998 			mark_reg_unknown(env, regs, value_regno);
2999 	} else if (type_is_sk_pointer(reg->type)) {
3000 		if (t == BPF_WRITE) {
3001 			verbose(env, "R%d cannot write into %s\n",
3002 				regno, reg_type_str[reg->type]);
3003 			return -EACCES;
3004 		}
3005 		err = check_sock_access(env, insn_idx, regno, off, size, t);
3006 		if (!err && value_regno >= 0)
3007 			mark_reg_unknown(env, regs, value_regno);
3008 	} else if (reg->type == PTR_TO_TP_BUFFER) {
3009 		err = check_tp_buffer_access(env, reg, regno, off, size);
3010 		if (!err && t == BPF_READ && value_regno >= 0)
3011 			mark_reg_unknown(env, regs, value_regno);
3012 	} else if (reg->type == PTR_TO_BTF_ID) {
3013 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3014 					      value_regno);
3015 	} else {
3016 		verbose(env, "R%d invalid mem access '%s'\n", regno,
3017 			reg_type_str[reg->type]);
3018 		return -EACCES;
3019 	}
3020 
3021 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3022 	    regs[value_regno].type == SCALAR_VALUE) {
3023 		/* b/h/w load zero-extends, mark upper bits as known 0 */
3024 		coerce_reg_to_size(&regs[value_regno], size);
3025 	}
3026 	return err;
3027 }
3028 
3029 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3030 {
3031 	int err;
3032 
3033 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3034 	    insn->imm != 0) {
3035 		verbose(env, "BPF_XADD uses reserved fields\n");
3036 		return -EINVAL;
3037 	}
3038 
3039 	/* check src1 operand */
3040 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
3041 	if (err)
3042 		return err;
3043 
3044 	/* check src2 operand */
3045 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3046 	if (err)
3047 		return err;
3048 
3049 	if (is_pointer_value(env, insn->src_reg)) {
3050 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3051 		return -EACCES;
3052 	}
3053 
3054 	if (is_ctx_reg(env, insn->dst_reg) ||
3055 	    is_pkt_reg(env, insn->dst_reg) ||
3056 	    is_flow_key_reg(env, insn->dst_reg) ||
3057 	    is_sk_reg(env, insn->dst_reg)) {
3058 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3059 			insn->dst_reg,
3060 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
3061 		return -EACCES;
3062 	}
3063 
3064 	/* check whether atomic_add can read the memory */
3065 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3066 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
3067 	if (err)
3068 		return err;
3069 
3070 	/* check whether atomic_add can write into the same memory */
3071 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3072 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3073 }
3074 
3075 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3076 				  int off, int access_size,
3077 				  bool zero_size_allowed)
3078 {
3079 	struct bpf_reg_state *reg = reg_state(env, regno);
3080 
3081 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3082 	    access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3083 		if (tnum_is_const(reg->var_off)) {
3084 			verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3085 				regno, off, access_size);
3086 		} else {
3087 			char tn_buf[48];
3088 
3089 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3090 			verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3091 				regno, tn_buf, access_size);
3092 		}
3093 		return -EACCES;
3094 	}
3095 	return 0;
3096 }
3097 
3098 /* when register 'regno' is passed into function that will read 'access_size'
3099  * bytes from that pointer, make sure that it's within stack boundary
3100  * and all elements of stack are initialized.
3101  * Unlike most pointer bounds-checking functions, this one doesn't take an
3102  * 'off' argument, so it has to add in reg->off itself.
3103  */
3104 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3105 				int access_size, bool zero_size_allowed,
3106 				struct bpf_call_arg_meta *meta)
3107 {
3108 	struct bpf_reg_state *reg = reg_state(env, regno);
3109 	struct bpf_func_state *state = func(env, reg);
3110 	int err, min_off, max_off, i, j, slot, spi;
3111 
3112 	if (reg->type != PTR_TO_STACK) {
3113 		/* Allow zero-byte read from NULL, regardless of pointer type */
3114 		if (zero_size_allowed && access_size == 0 &&
3115 		    register_is_null(reg))
3116 			return 0;
3117 
3118 		verbose(env, "R%d type=%s expected=%s\n", regno,
3119 			reg_type_str[reg->type],
3120 			reg_type_str[PTR_TO_STACK]);
3121 		return -EACCES;
3122 	}
3123 
3124 	if (tnum_is_const(reg->var_off)) {
3125 		min_off = max_off = reg->var_off.value + reg->off;
3126 		err = __check_stack_boundary(env, regno, min_off, access_size,
3127 					     zero_size_allowed);
3128 		if (err)
3129 			return err;
3130 	} else {
3131 		/* Variable offset is prohibited for unprivileged mode for
3132 		 * simplicity since it requires corresponding support in
3133 		 * Spectre masking for stack ALU.
3134 		 * See also retrieve_ptr_limit().
3135 		 */
3136 		if (!env->allow_ptr_leaks) {
3137 			char tn_buf[48];
3138 
3139 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3140 			verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3141 				regno, tn_buf);
3142 			return -EACCES;
3143 		}
3144 		/* Only initialized buffer on stack is allowed to be accessed
3145 		 * with variable offset. With uninitialized buffer it's hard to
3146 		 * guarantee that whole memory is marked as initialized on
3147 		 * helper return since specific bounds are unknown what may
3148 		 * cause uninitialized stack leaking.
3149 		 */
3150 		if (meta && meta->raw_mode)
3151 			meta = NULL;
3152 
3153 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3154 		    reg->smax_value <= -BPF_MAX_VAR_OFF) {
3155 			verbose(env, "R%d unbounded indirect variable offset stack access\n",
3156 				regno);
3157 			return -EACCES;
3158 		}
3159 		min_off = reg->smin_value + reg->off;
3160 		max_off = reg->smax_value + reg->off;
3161 		err = __check_stack_boundary(env, regno, min_off, access_size,
3162 					     zero_size_allowed);
3163 		if (err) {
3164 			verbose(env, "R%d min value is outside of stack bound\n",
3165 				regno);
3166 			return err;
3167 		}
3168 		err = __check_stack_boundary(env, regno, max_off, access_size,
3169 					     zero_size_allowed);
3170 		if (err) {
3171 			verbose(env, "R%d max value is outside of stack bound\n",
3172 				regno);
3173 			return err;
3174 		}
3175 	}
3176 
3177 	if (meta && meta->raw_mode) {
3178 		meta->access_size = access_size;
3179 		meta->regno = regno;
3180 		return 0;
3181 	}
3182 
3183 	for (i = min_off; i < max_off + access_size; i++) {
3184 		u8 *stype;
3185 
3186 		slot = -i - 1;
3187 		spi = slot / BPF_REG_SIZE;
3188 		if (state->allocated_stack <= slot)
3189 			goto err;
3190 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3191 		if (*stype == STACK_MISC)
3192 			goto mark;
3193 		if (*stype == STACK_ZERO) {
3194 			/* helper can write anything into the stack */
3195 			*stype = STACK_MISC;
3196 			goto mark;
3197 		}
3198 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3199 		    state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3200 			__mark_reg_unknown(&state->stack[spi].spilled_ptr);
3201 			for (j = 0; j < BPF_REG_SIZE; j++)
3202 				state->stack[spi].slot_type[j] = STACK_MISC;
3203 			goto mark;
3204 		}
3205 
3206 err:
3207 		if (tnum_is_const(reg->var_off)) {
3208 			verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3209 				min_off, i - min_off, access_size);
3210 		} else {
3211 			char tn_buf[48];
3212 
3213 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3214 			verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3215 				tn_buf, i - min_off, access_size);
3216 		}
3217 		return -EACCES;
3218 mark:
3219 		/* reading any byte out of 8-byte 'spill_slot' will cause
3220 		 * the whole slot to be marked as 'read'
3221 		 */
3222 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
3223 			      state->stack[spi].spilled_ptr.parent,
3224 			      REG_LIVE_READ64);
3225 	}
3226 	return update_stack_depth(env, state, min_off);
3227 }
3228 
3229 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3230 				   int access_size, bool zero_size_allowed,
3231 				   struct bpf_call_arg_meta *meta)
3232 {
3233 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3234 
3235 	switch (reg->type) {
3236 	case PTR_TO_PACKET:
3237 	case PTR_TO_PACKET_META:
3238 		return check_packet_access(env, regno, reg->off, access_size,
3239 					   zero_size_allowed);
3240 	case PTR_TO_MAP_VALUE:
3241 		if (check_map_access_type(env, regno, reg->off, access_size,
3242 					  meta && meta->raw_mode ? BPF_WRITE :
3243 					  BPF_READ))
3244 			return -EACCES;
3245 		return check_map_access(env, regno, reg->off, access_size,
3246 					zero_size_allowed);
3247 	default: /* scalar_value|ptr_to_stack or invalid ptr */
3248 		return check_stack_boundary(env, regno, access_size,
3249 					    zero_size_allowed, meta);
3250 	}
3251 }
3252 
3253 /* Implementation details:
3254  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3255  * Two bpf_map_lookups (even with the same key) will have different reg->id.
3256  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3257  * value_or_null->value transition, since the verifier only cares about
3258  * the range of access to valid map value pointer and doesn't care about actual
3259  * address of the map element.
3260  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3261  * reg->id > 0 after value_or_null->value transition. By doing so
3262  * two bpf_map_lookups will be considered two different pointers that
3263  * point to different bpf_spin_locks.
3264  * The verifier allows taking only one bpf_spin_lock at a time to avoid
3265  * dead-locks.
3266  * Since only one bpf_spin_lock is allowed the checks are simpler than
3267  * reg_is_refcounted() logic. The verifier needs to remember only
3268  * one spin_lock instead of array of acquired_refs.
3269  * cur_state->active_spin_lock remembers which map value element got locked
3270  * and clears it after bpf_spin_unlock.
3271  */
3272 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3273 			     bool is_lock)
3274 {
3275 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3276 	struct bpf_verifier_state *cur = env->cur_state;
3277 	bool is_const = tnum_is_const(reg->var_off);
3278 	struct bpf_map *map = reg->map_ptr;
3279 	u64 val = reg->var_off.value;
3280 
3281 	if (reg->type != PTR_TO_MAP_VALUE) {
3282 		verbose(env, "R%d is not a pointer to map_value\n", regno);
3283 		return -EINVAL;
3284 	}
3285 	if (!is_const) {
3286 		verbose(env,
3287 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3288 			regno);
3289 		return -EINVAL;
3290 	}
3291 	if (!map->btf) {
3292 		verbose(env,
3293 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
3294 			map->name);
3295 		return -EINVAL;
3296 	}
3297 	if (!map_value_has_spin_lock(map)) {
3298 		if (map->spin_lock_off == -E2BIG)
3299 			verbose(env,
3300 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
3301 				map->name);
3302 		else if (map->spin_lock_off == -ENOENT)
3303 			verbose(env,
3304 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
3305 				map->name);
3306 		else
3307 			verbose(env,
3308 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3309 				map->name);
3310 		return -EINVAL;
3311 	}
3312 	if (map->spin_lock_off != val + reg->off) {
3313 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3314 			val + reg->off);
3315 		return -EINVAL;
3316 	}
3317 	if (is_lock) {
3318 		if (cur->active_spin_lock) {
3319 			verbose(env,
3320 				"Locking two bpf_spin_locks are not allowed\n");
3321 			return -EINVAL;
3322 		}
3323 		cur->active_spin_lock = reg->id;
3324 	} else {
3325 		if (!cur->active_spin_lock) {
3326 			verbose(env, "bpf_spin_unlock without taking a lock\n");
3327 			return -EINVAL;
3328 		}
3329 		if (cur->active_spin_lock != reg->id) {
3330 			verbose(env, "bpf_spin_unlock of different lock\n");
3331 			return -EINVAL;
3332 		}
3333 		cur->active_spin_lock = 0;
3334 	}
3335 	return 0;
3336 }
3337 
3338 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3339 {
3340 	return type == ARG_PTR_TO_MEM ||
3341 	       type == ARG_PTR_TO_MEM_OR_NULL ||
3342 	       type == ARG_PTR_TO_UNINIT_MEM;
3343 }
3344 
3345 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3346 {
3347 	return type == ARG_CONST_SIZE ||
3348 	       type == ARG_CONST_SIZE_OR_ZERO;
3349 }
3350 
3351 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3352 {
3353 	return type == ARG_PTR_TO_INT ||
3354 	       type == ARG_PTR_TO_LONG;
3355 }
3356 
3357 static int int_ptr_type_to_size(enum bpf_arg_type type)
3358 {
3359 	if (type == ARG_PTR_TO_INT)
3360 		return sizeof(u32);
3361 	else if (type == ARG_PTR_TO_LONG)
3362 		return sizeof(u64);
3363 
3364 	return -EINVAL;
3365 }
3366 
3367 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
3368 			  enum bpf_arg_type arg_type,
3369 			  struct bpf_call_arg_meta *meta)
3370 {
3371 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3372 	enum bpf_reg_type expected_type, type = reg->type;
3373 	int err = 0;
3374 
3375 	if (arg_type == ARG_DONTCARE)
3376 		return 0;
3377 
3378 	err = check_reg_arg(env, regno, SRC_OP);
3379 	if (err)
3380 		return err;
3381 
3382 	if (arg_type == ARG_ANYTHING) {
3383 		if (is_pointer_value(env, regno)) {
3384 			verbose(env, "R%d leaks addr into helper function\n",
3385 				regno);
3386 			return -EACCES;
3387 		}
3388 		return 0;
3389 	}
3390 
3391 	if (type_is_pkt_pointer(type) &&
3392 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
3393 		verbose(env, "helper access to the packet is not allowed\n");
3394 		return -EACCES;
3395 	}
3396 
3397 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
3398 	    arg_type == ARG_PTR_TO_MAP_VALUE ||
3399 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3400 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3401 		expected_type = PTR_TO_STACK;
3402 		if (register_is_null(reg) &&
3403 		    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3404 			/* final test in check_stack_boundary() */;
3405 		else if (!type_is_pkt_pointer(type) &&
3406 			 type != PTR_TO_MAP_VALUE &&
3407 			 type != expected_type)
3408 			goto err_type;
3409 	} else if (arg_type == ARG_CONST_SIZE ||
3410 		   arg_type == ARG_CONST_SIZE_OR_ZERO) {
3411 		expected_type = SCALAR_VALUE;
3412 		if (type != expected_type)
3413 			goto err_type;
3414 	} else if (arg_type == ARG_CONST_MAP_PTR) {
3415 		expected_type = CONST_PTR_TO_MAP;
3416 		if (type != expected_type)
3417 			goto err_type;
3418 	} else if (arg_type == ARG_PTR_TO_CTX) {
3419 		expected_type = PTR_TO_CTX;
3420 		if (type != expected_type)
3421 			goto err_type;
3422 		err = check_ctx_reg(env, reg, regno);
3423 		if (err < 0)
3424 			return err;
3425 	} else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3426 		expected_type = PTR_TO_SOCK_COMMON;
3427 		/* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3428 		if (!type_is_sk_pointer(type))
3429 			goto err_type;
3430 		if (reg->ref_obj_id) {
3431 			if (meta->ref_obj_id) {
3432 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3433 					regno, reg->ref_obj_id,
3434 					meta->ref_obj_id);
3435 				return -EFAULT;
3436 			}
3437 			meta->ref_obj_id = reg->ref_obj_id;
3438 		}
3439 	} else if (arg_type == ARG_PTR_TO_SOCKET) {
3440 		expected_type = PTR_TO_SOCKET;
3441 		if (type != expected_type)
3442 			goto err_type;
3443 	} else if (arg_type == ARG_PTR_TO_BTF_ID) {
3444 		expected_type = PTR_TO_BTF_ID;
3445 		if (type != expected_type)
3446 			goto err_type;
3447 		if (reg->btf_id != meta->btf_id) {
3448 			verbose(env, "Helper has type %s got %s in R%d\n",
3449 				kernel_type_name(meta->btf_id),
3450 				kernel_type_name(reg->btf_id), regno);
3451 
3452 			return -EACCES;
3453 		}
3454 		if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3455 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3456 				regno);
3457 			return -EACCES;
3458 		}
3459 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3460 		if (meta->func_id == BPF_FUNC_spin_lock) {
3461 			if (process_spin_lock(env, regno, true))
3462 				return -EACCES;
3463 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
3464 			if (process_spin_lock(env, regno, false))
3465 				return -EACCES;
3466 		} else {
3467 			verbose(env, "verifier internal error\n");
3468 			return -EFAULT;
3469 		}
3470 	} else if (arg_type_is_mem_ptr(arg_type)) {
3471 		expected_type = PTR_TO_STACK;
3472 		/* One exception here. In case function allows for NULL to be
3473 		 * passed in as argument, it's a SCALAR_VALUE type. Final test
3474 		 * happens during stack boundary checking.
3475 		 */
3476 		if (register_is_null(reg) &&
3477 		    arg_type == ARG_PTR_TO_MEM_OR_NULL)
3478 			/* final test in check_stack_boundary() */;
3479 		else if (!type_is_pkt_pointer(type) &&
3480 			 type != PTR_TO_MAP_VALUE &&
3481 			 type != expected_type)
3482 			goto err_type;
3483 		meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
3484 	} else if (arg_type_is_int_ptr(arg_type)) {
3485 		expected_type = PTR_TO_STACK;
3486 		if (!type_is_pkt_pointer(type) &&
3487 		    type != PTR_TO_MAP_VALUE &&
3488 		    type != expected_type)
3489 			goto err_type;
3490 	} else {
3491 		verbose(env, "unsupported arg_type %d\n", arg_type);
3492 		return -EFAULT;
3493 	}
3494 
3495 	if (arg_type == ARG_CONST_MAP_PTR) {
3496 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3497 		meta->map_ptr = reg->map_ptr;
3498 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3499 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
3500 		 * check that [key, key + map->key_size) are within
3501 		 * stack limits and initialized
3502 		 */
3503 		if (!meta->map_ptr) {
3504 			/* in function declaration map_ptr must come before
3505 			 * map_key, so that it's verified and known before
3506 			 * we have to check map_key here. Otherwise it means
3507 			 * that kernel subsystem misconfigured verifier
3508 			 */
3509 			verbose(env, "invalid map_ptr to access map->key\n");
3510 			return -EACCES;
3511 		}
3512 		err = check_helper_mem_access(env, regno,
3513 					      meta->map_ptr->key_size, false,
3514 					      NULL);
3515 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3516 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3517 		    !register_is_null(reg)) ||
3518 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
3519 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
3520 		 * check [value, value + map->value_size) validity
3521 		 */
3522 		if (!meta->map_ptr) {
3523 			/* kernel subsystem misconfigured verifier */
3524 			verbose(env, "invalid map_ptr to access map->value\n");
3525 			return -EACCES;
3526 		}
3527 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
3528 		err = check_helper_mem_access(env, regno,
3529 					      meta->map_ptr->value_size, false,
3530 					      meta);
3531 	} else if (arg_type_is_mem_size(arg_type)) {
3532 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
3533 
3534 		/* remember the mem_size which may be used later
3535 		 * to refine return values.
3536 		 */
3537 		meta->msize_smax_value = reg->smax_value;
3538 		meta->msize_umax_value = reg->umax_value;
3539 
3540 		/* The register is SCALAR_VALUE; the access check
3541 		 * happens using its boundaries.
3542 		 */
3543 		if (!tnum_is_const(reg->var_off))
3544 			/* For unprivileged variable accesses, disable raw
3545 			 * mode so that the program is required to
3546 			 * initialize all the memory that the helper could
3547 			 * just partially fill up.
3548 			 */
3549 			meta = NULL;
3550 
3551 		if (reg->smin_value < 0) {
3552 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3553 				regno);
3554 			return -EACCES;
3555 		}
3556 
3557 		if (reg->umin_value == 0) {
3558 			err = check_helper_mem_access(env, regno - 1, 0,
3559 						      zero_size_allowed,
3560 						      meta);
3561 			if (err)
3562 				return err;
3563 		}
3564 
3565 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
3566 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3567 				regno);
3568 			return -EACCES;
3569 		}
3570 		err = check_helper_mem_access(env, regno - 1,
3571 					      reg->umax_value,
3572 					      zero_size_allowed, meta);
3573 		if (!err)
3574 			err = mark_chain_precision(env, regno);
3575 	} else if (arg_type_is_int_ptr(arg_type)) {
3576 		int size = int_ptr_type_to_size(arg_type);
3577 
3578 		err = check_helper_mem_access(env, regno, size, false, meta);
3579 		if (err)
3580 			return err;
3581 		err = check_ptr_alignment(env, reg, 0, size, true);
3582 	}
3583 
3584 	return err;
3585 err_type:
3586 	verbose(env, "R%d type=%s expected=%s\n", regno,
3587 		reg_type_str[type], reg_type_str[expected_type]);
3588 	return -EACCES;
3589 }
3590 
3591 static int check_map_func_compatibility(struct bpf_verifier_env *env,
3592 					struct bpf_map *map, int func_id)
3593 {
3594 	if (!map)
3595 		return 0;
3596 
3597 	/* We need a two way check, first is from map perspective ... */
3598 	switch (map->map_type) {
3599 	case BPF_MAP_TYPE_PROG_ARRAY:
3600 		if (func_id != BPF_FUNC_tail_call)
3601 			goto error;
3602 		break;
3603 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
3604 		if (func_id != BPF_FUNC_perf_event_read &&
3605 		    func_id != BPF_FUNC_perf_event_output &&
3606 		    func_id != BPF_FUNC_skb_output &&
3607 		    func_id != BPF_FUNC_perf_event_read_value)
3608 			goto error;
3609 		break;
3610 	case BPF_MAP_TYPE_STACK_TRACE:
3611 		if (func_id != BPF_FUNC_get_stackid)
3612 			goto error;
3613 		break;
3614 	case BPF_MAP_TYPE_CGROUP_ARRAY:
3615 		if (func_id != BPF_FUNC_skb_under_cgroup &&
3616 		    func_id != BPF_FUNC_current_task_under_cgroup)
3617 			goto error;
3618 		break;
3619 	case BPF_MAP_TYPE_CGROUP_STORAGE:
3620 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
3621 		if (func_id != BPF_FUNC_get_local_storage)
3622 			goto error;
3623 		break;
3624 	case BPF_MAP_TYPE_DEVMAP:
3625 	case BPF_MAP_TYPE_DEVMAP_HASH:
3626 		if (func_id != BPF_FUNC_redirect_map &&
3627 		    func_id != BPF_FUNC_map_lookup_elem)
3628 			goto error;
3629 		break;
3630 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
3631 	 * appear.
3632 	 */
3633 	case BPF_MAP_TYPE_CPUMAP:
3634 		if (func_id != BPF_FUNC_redirect_map)
3635 			goto error;
3636 		break;
3637 	case BPF_MAP_TYPE_XSKMAP:
3638 		if (func_id != BPF_FUNC_redirect_map &&
3639 		    func_id != BPF_FUNC_map_lookup_elem)
3640 			goto error;
3641 		break;
3642 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
3643 	case BPF_MAP_TYPE_HASH_OF_MAPS:
3644 		if (func_id != BPF_FUNC_map_lookup_elem)
3645 			goto error;
3646 		break;
3647 	case BPF_MAP_TYPE_SOCKMAP:
3648 		if (func_id != BPF_FUNC_sk_redirect_map &&
3649 		    func_id != BPF_FUNC_sock_map_update &&
3650 		    func_id != BPF_FUNC_map_delete_elem &&
3651 		    func_id != BPF_FUNC_msg_redirect_map)
3652 			goto error;
3653 		break;
3654 	case BPF_MAP_TYPE_SOCKHASH:
3655 		if (func_id != BPF_FUNC_sk_redirect_hash &&
3656 		    func_id != BPF_FUNC_sock_hash_update &&
3657 		    func_id != BPF_FUNC_map_delete_elem &&
3658 		    func_id != BPF_FUNC_msg_redirect_hash)
3659 			goto error;
3660 		break;
3661 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
3662 		if (func_id != BPF_FUNC_sk_select_reuseport)
3663 			goto error;
3664 		break;
3665 	case BPF_MAP_TYPE_QUEUE:
3666 	case BPF_MAP_TYPE_STACK:
3667 		if (func_id != BPF_FUNC_map_peek_elem &&
3668 		    func_id != BPF_FUNC_map_pop_elem &&
3669 		    func_id != BPF_FUNC_map_push_elem)
3670 			goto error;
3671 		break;
3672 	case BPF_MAP_TYPE_SK_STORAGE:
3673 		if (func_id != BPF_FUNC_sk_storage_get &&
3674 		    func_id != BPF_FUNC_sk_storage_delete)
3675 			goto error;
3676 		break;
3677 	default:
3678 		break;
3679 	}
3680 
3681 	/* ... and second from the function itself. */
3682 	switch (func_id) {
3683 	case BPF_FUNC_tail_call:
3684 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3685 			goto error;
3686 		if (env->subprog_cnt > 1) {
3687 			verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3688 			return -EINVAL;
3689 		}
3690 		break;
3691 	case BPF_FUNC_perf_event_read:
3692 	case BPF_FUNC_perf_event_output:
3693 	case BPF_FUNC_perf_event_read_value:
3694 	case BPF_FUNC_skb_output:
3695 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3696 			goto error;
3697 		break;
3698 	case BPF_FUNC_get_stackid:
3699 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3700 			goto error;
3701 		break;
3702 	case BPF_FUNC_current_task_under_cgroup:
3703 	case BPF_FUNC_skb_under_cgroup:
3704 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3705 			goto error;
3706 		break;
3707 	case BPF_FUNC_redirect_map:
3708 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
3709 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
3710 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
3711 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
3712 			goto error;
3713 		break;
3714 	case BPF_FUNC_sk_redirect_map:
3715 	case BPF_FUNC_msg_redirect_map:
3716 	case BPF_FUNC_sock_map_update:
3717 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3718 			goto error;
3719 		break;
3720 	case BPF_FUNC_sk_redirect_hash:
3721 	case BPF_FUNC_msg_redirect_hash:
3722 	case BPF_FUNC_sock_hash_update:
3723 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
3724 			goto error;
3725 		break;
3726 	case BPF_FUNC_get_local_storage:
3727 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3728 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
3729 			goto error;
3730 		break;
3731 	case BPF_FUNC_sk_select_reuseport:
3732 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
3733 			goto error;
3734 		break;
3735 	case BPF_FUNC_map_peek_elem:
3736 	case BPF_FUNC_map_pop_elem:
3737 	case BPF_FUNC_map_push_elem:
3738 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
3739 		    map->map_type != BPF_MAP_TYPE_STACK)
3740 			goto error;
3741 		break;
3742 	case BPF_FUNC_sk_storage_get:
3743 	case BPF_FUNC_sk_storage_delete:
3744 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
3745 			goto error;
3746 		break;
3747 	default:
3748 		break;
3749 	}
3750 
3751 	return 0;
3752 error:
3753 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
3754 		map->map_type, func_id_name(func_id), func_id);
3755 	return -EINVAL;
3756 }
3757 
3758 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
3759 {
3760 	int count = 0;
3761 
3762 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
3763 		count++;
3764 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
3765 		count++;
3766 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
3767 		count++;
3768 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
3769 		count++;
3770 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
3771 		count++;
3772 
3773 	/* We only support one arg being in raw mode at the moment,
3774 	 * which is sufficient for the helper functions we have
3775 	 * right now.
3776 	 */
3777 	return count <= 1;
3778 }
3779 
3780 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
3781 				    enum bpf_arg_type arg_next)
3782 {
3783 	return (arg_type_is_mem_ptr(arg_curr) &&
3784 	        !arg_type_is_mem_size(arg_next)) ||
3785 	       (!arg_type_is_mem_ptr(arg_curr) &&
3786 		arg_type_is_mem_size(arg_next));
3787 }
3788 
3789 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
3790 {
3791 	/* bpf_xxx(..., buf, len) call will access 'len'
3792 	 * bytes from memory 'buf'. Both arg types need
3793 	 * to be paired, so make sure there's no buggy
3794 	 * helper function specification.
3795 	 */
3796 	if (arg_type_is_mem_size(fn->arg1_type) ||
3797 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
3798 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
3799 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
3800 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
3801 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
3802 		return false;
3803 
3804 	return true;
3805 }
3806 
3807 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
3808 {
3809 	int count = 0;
3810 
3811 	if (arg_type_may_be_refcounted(fn->arg1_type))
3812 		count++;
3813 	if (arg_type_may_be_refcounted(fn->arg2_type))
3814 		count++;
3815 	if (arg_type_may_be_refcounted(fn->arg3_type))
3816 		count++;
3817 	if (arg_type_may_be_refcounted(fn->arg4_type))
3818 		count++;
3819 	if (arg_type_may_be_refcounted(fn->arg5_type))
3820 		count++;
3821 
3822 	/* A reference acquiring function cannot acquire
3823 	 * another refcounted ptr.
3824 	 */
3825 	if (is_acquire_function(func_id) && count)
3826 		return false;
3827 
3828 	/* We only support one arg being unreferenced at the moment,
3829 	 * which is sufficient for the helper functions we have right now.
3830 	 */
3831 	return count <= 1;
3832 }
3833 
3834 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
3835 {
3836 	return check_raw_mode_ok(fn) &&
3837 	       check_arg_pair_ok(fn) &&
3838 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
3839 }
3840 
3841 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
3842  * are now invalid, so turn them into unknown SCALAR_VALUE.
3843  */
3844 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
3845 				     struct bpf_func_state *state)
3846 {
3847 	struct bpf_reg_state *regs = state->regs, *reg;
3848 	int i;
3849 
3850 	for (i = 0; i < MAX_BPF_REG; i++)
3851 		if (reg_is_pkt_pointer_any(&regs[i]))
3852 			mark_reg_unknown(env, regs, i);
3853 
3854 	bpf_for_each_spilled_reg(i, state, reg) {
3855 		if (!reg)
3856 			continue;
3857 		if (reg_is_pkt_pointer_any(reg))
3858 			__mark_reg_unknown(reg);
3859 	}
3860 }
3861 
3862 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
3863 {
3864 	struct bpf_verifier_state *vstate = env->cur_state;
3865 	int i;
3866 
3867 	for (i = 0; i <= vstate->curframe; i++)
3868 		__clear_all_pkt_pointers(env, vstate->frame[i]);
3869 }
3870 
3871 static void release_reg_references(struct bpf_verifier_env *env,
3872 				   struct bpf_func_state *state,
3873 				   int ref_obj_id)
3874 {
3875 	struct bpf_reg_state *regs = state->regs, *reg;
3876 	int i;
3877 
3878 	for (i = 0; i < MAX_BPF_REG; i++)
3879 		if (regs[i].ref_obj_id == ref_obj_id)
3880 			mark_reg_unknown(env, regs, i);
3881 
3882 	bpf_for_each_spilled_reg(i, state, reg) {
3883 		if (!reg)
3884 			continue;
3885 		if (reg->ref_obj_id == ref_obj_id)
3886 			__mark_reg_unknown(reg);
3887 	}
3888 }
3889 
3890 /* The pointer with the specified id has released its reference to kernel
3891  * resources. Identify all copies of the same pointer and clear the reference.
3892  */
3893 static int release_reference(struct bpf_verifier_env *env,
3894 			     int ref_obj_id)
3895 {
3896 	struct bpf_verifier_state *vstate = env->cur_state;
3897 	int err;
3898 	int i;
3899 
3900 	err = release_reference_state(cur_func(env), ref_obj_id);
3901 	if (err)
3902 		return err;
3903 
3904 	for (i = 0; i <= vstate->curframe; i++)
3905 		release_reg_references(env, vstate->frame[i], ref_obj_id);
3906 
3907 	return 0;
3908 }
3909 
3910 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3911 			   int *insn_idx)
3912 {
3913 	struct bpf_verifier_state *state = env->cur_state;
3914 	struct bpf_func_state *caller, *callee;
3915 	int i, err, subprog, target_insn;
3916 
3917 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
3918 		verbose(env, "the call stack of %d frames is too deep\n",
3919 			state->curframe + 2);
3920 		return -E2BIG;
3921 	}
3922 
3923 	target_insn = *insn_idx + insn->imm;
3924 	subprog = find_subprog(env, target_insn + 1);
3925 	if (subprog < 0) {
3926 		verbose(env, "verifier bug. No program starts at insn %d\n",
3927 			target_insn + 1);
3928 		return -EFAULT;
3929 	}
3930 
3931 	caller = state->frame[state->curframe];
3932 	if (state->frame[state->curframe + 1]) {
3933 		verbose(env, "verifier bug. Frame %d already allocated\n",
3934 			state->curframe + 1);
3935 		return -EFAULT;
3936 	}
3937 
3938 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
3939 	if (!callee)
3940 		return -ENOMEM;
3941 	state->frame[state->curframe + 1] = callee;
3942 
3943 	/* callee cannot access r0, r6 - r9 for reading and has to write
3944 	 * into its own stack before reading from it.
3945 	 * callee can read/write into caller's stack
3946 	 */
3947 	init_func_state(env, callee,
3948 			/* remember the callsite, it will be used by bpf_exit */
3949 			*insn_idx /* callsite */,
3950 			state->curframe + 1 /* frameno within this callchain */,
3951 			subprog /* subprog number within this prog */);
3952 
3953 	/* Transfer references to the callee */
3954 	err = transfer_reference_state(callee, caller);
3955 	if (err)
3956 		return err;
3957 
3958 	/* copy r1 - r5 args that callee can access.  The copy includes parent
3959 	 * pointers, which connects us up to the liveness chain
3960 	 */
3961 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3962 		callee->regs[i] = caller->regs[i];
3963 
3964 	/* after the call registers r0 - r5 were scratched */
3965 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
3966 		mark_reg_not_init(env, caller->regs, caller_saved[i]);
3967 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3968 	}
3969 
3970 	/* only increment it after check_reg_arg() finished */
3971 	state->curframe++;
3972 
3973 	/* and go analyze first insn of the callee */
3974 	*insn_idx = target_insn;
3975 
3976 	if (env->log.level & BPF_LOG_LEVEL) {
3977 		verbose(env, "caller:\n");
3978 		print_verifier_state(env, caller);
3979 		verbose(env, "callee:\n");
3980 		print_verifier_state(env, callee);
3981 	}
3982 	return 0;
3983 }
3984 
3985 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
3986 {
3987 	struct bpf_verifier_state *state = env->cur_state;
3988 	struct bpf_func_state *caller, *callee;
3989 	struct bpf_reg_state *r0;
3990 	int err;
3991 
3992 	callee = state->frame[state->curframe];
3993 	r0 = &callee->regs[BPF_REG_0];
3994 	if (r0->type == PTR_TO_STACK) {
3995 		/* technically it's ok to return caller's stack pointer
3996 		 * (or caller's caller's pointer) back to the caller,
3997 		 * since these pointers are valid. Only current stack
3998 		 * pointer will be invalid as soon as function exits,
3999 		 * but let's be conservative
4000 		 */
4001 		verbose(env, "cannot return stack pointer to the caller\n");
4002 		return -EINVAL;
4003 	}
4004 
4005 	state->curframe--;
4006 	caller = state->frame[state->curframe];
4007 	/* return to the caller whatever r0 had in the callee */
4008 	caller->regs[BPF_REG_0] = *r0;
4009 
4010 	/* Transfer references to the caller */
4011 	err = transfer_reference_state(caller, callee);
4012 	if (err)
4013 		return err;
4014 
4015 	*insn_idx = callee->callsite + 1;
4016 	if (env->log.level & BPF_LOG_LEVEL) {
4017 		verbose(env, "returning from callee:\n");
4018 		print_verifier_state(env, callee);
4019 		verbose(env, "to caller at %d:\n", *insn_idx);
4020 		print_verifier_state(env, caller);
4021 	}
4022 	/* clear everything in the callee */
4023 	free_func_state(callee);
4024 	state->frame[state->curframe + 1] = NULL;
4025 	return 0;
4026 }
4027 
4028 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4029 				   int func_id,
4030 				   struct bpf_call_arg_meta *meta)
4031 {
4032 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4033 
4034 	if (ret_type != RET_INTEGER ||
4035 	    (func_id != BPF_FUNC_get_stack &&
4036 	     func_id != BPF_FUNC_probe_read_str))
4037 		return;
4038 
4039 	ret_reg->smax_value = meta->msize_smax_value;
4040 	ret_reg->umax_value = meta->msize_umax_value;
4041 	__reg_deduce_bounds(ret_reg);
4042 	__reg_bound_offset(ret_reg);
4043 }
4044 
4045 static int
4046 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4047 		int func_id, int insn_idx)
4048 {
4049 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4050 	struct bpf_map *map = meta->map_ptr;
4051 
4052 	if (func_id != BPF_FUNC_tail_call &&
4053 	    func_id != BPF_FUNC_map_lookup_elem &&
4054 	    func_id != BPF_FUNC_map_update_elem &&
4055 	    func_id != BPF_FUNC_map_delete_elem &&
4056 	    func_id != BPF_FUNC_map_push_elem &&
4057 	    func_id != BPF_FUNC_map_pop_elem &&
4058 	    func_id != BPF_FUNC_map_peek_elem)
4059 		return 0;
4060 
4061 	if (map == NULL) {
4062 		verbose(env, "kernel subsystem misconfigured verifier\n");
4063 		return -EINVAL;
4064 	}
4065 
4066 	/* In case of read-only, some additional restrictions
4067 	 * need to be applied in order to prevent altering the
4068 	 * state of the map from program side.
4069 	 */
4070 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4071 	    (func_id == BPF_FUNC_map_delete_elem ||
4072 	     func_id == BPF_FUNC_map_update_elem ||
4073 	     func_id == BPF_FUNC_map_push_elem ||
4074 	     func_id == BPF_FUNC_map_pop_elem)) {
4075 		verbose(env, "write into map forbidden\n");
4076 		return -EACCES;
4077 	}
4078 
4079 	if (!BPF_MAP_PTR(aux->map_state))
4080 		bpf_map_ptr_store(aux, meta->map_ptr,
4081 				  meta->map_ptr->unpriv_array);
4082 	else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
4083 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4084 				  meta->map_ptr->unpriv_array);
4085 	return 0;
4086 }
4087 
4088 static int check_reference_leak(struct bpf_verifier_env *env)
4089 {
4090 	struct bpf_func_state *state = cur_func(env);
4091 	int i;
4092 
4093 	for (i = 0; i < state->acquired_refs; i++) {
4094 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4095 			state->refs[i].id, state->refs[i].insn_idx);
4096 	}
4097 	return state->acquired_refs ? -EINVAL : 0;
4098 }
4099 
4100 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
4101 {
4102 	const struct bpf_func_proto *fn = NULL;
4103 	struct bpf_reg_state *regs;
4104 	struct bpf_call_arg_meta meta;
4105 	bool changes_data;
4106 	int i, err;
4107 
4108 	/* find function prototype */
4109 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
4110 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4111 			func_id);
4112 		return -EINVAL;
4113 	}
4114 
4115 	if (env->ops->get_func_proto)
4116 		fn = env->ops->get_func_proto(func_id, env->prog);
4117 	if (!fn) {
4118 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4119 			func_id);
4120 		return -EINVAL;
4121 	}
4122 
4123 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
4124 	if (!env->prog->gpl_compatible && fn->gpl_only) {
4125 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
4126 		return -EINVAL;
4127 	}
4128 
4129 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
4130 	changes_data = bpf_helper_changes_pkt_data(fn->func);
4131 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4132 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4133 			func_id_name(func_id), func_id);
4134 		return -EINVAL;
4135 	}
4136 
4137 	memset(&meta, 0, sizeof(meta));
4138 	meta.pkt_access = fn->pkt_access;
4139 
4140 	err = check_func_proto(fn, func_id);
4141 	if (err) {
4142 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
4143 			func_id_name(func_id), func_id);
4144 		return err;
4145 	}
4146 
4147 	meta.func_id = func_id;
4148 	/* check args */
4149 	for (i = 0; i < 5; i++) {
4150 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID) {
4151 			if (!fn->btf_id[i])
4152 				fn->btf_id[i] = btf_resolve_helper_id(&env->log, fn->func, i);
4153 			meta.btf_id = fn->btf_id[i];
4154 		}
4155 		err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4156 		if (err)
4157 			return err;
4158 	}
4159 
4160 	err = record_func_map(env, &meta, func_id, insn_idx);
4161 	if (err)
4162 		return err;
4163 
4164 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
4165 	 * is inferred from register state.
4166 	 */
4167 	for (i = 0; i < meta.access_size; i++) {
4168 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4169 				       BPF_WRITE, -1, false);
4170 		if (err)
4171 			return err;
4172 	}
4173 
4174 	if (func_id == BPF_FUNC_tail_call) {
4175 		err = check_reference_leak(env);
4176 		if (err) {
4177 			verbose(env, "tail_call would lead to reference leak\n");
4178 			return err;
4179 		}
4180 	} else if (is_release_function(func_id)) {
4181 		err = release_reference(env, meta.ref_obj_id);
4182 		if (err) {
4183 			verbose(env, "func %s#%d reference has not been acquired before\n",
4184 				func_id_name(func_id), func_id);
4185 			return err;
4186 		}
4187 	}
4188 
4189 	regs = cur_regs(env);
4190 
4191 	/* check that flags argument in get_local_storage(map, flags) is 0,
4192 	 * this is required because get_local_storage() can't return an error.
4193 	 */
4194 	if (func_id == BPF_FUNC_get_local_storage &&
4195 	    !register_is_null(&regs[BPF_REG_2])) {
4196 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4197 		return -EINVAL;
4198 	}
4199 
4200 	/* reset caller saved regs */
4201 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
4202 		mark_reg_not_init(env, regs, caller_saved[i]);
4203 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4204 	}
4205 
4206 	/* helper call returns 64-bit value. */
4207 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4208 
4209 	/* update return register (already marked as written above) */
4210 	if (fn->ret_type == RET_INTEGER) {
4211 		/* sets type to SCALAR_VALUE */
4212 		mark_reg_unknown(env, regs, BPF_REG_0);
4213 	} else if (fn->ret_type == RET_VOID) {
4214 		regs[BPF_REG_0].type = NOT_INIT;
4215 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4216 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4217 		/* There is no offset yet applied, variable or fixed */
4218 		mark_reg_known_zero(env, regs, BPF_REG_0);
4219 		/* remember map_ptr, so that check_map_access()
4220 		 * can check 'value_size' boundary of memory access
4221 		 * to map element returned from bpf_map_lookup_elem()
4222 		 */
4223 		if (meta.map_ptr == NULL) {
4224 			verbose(env,
4225 				"kernel subsystem misconfigured verifier\n");
4226 			return -EINVAL;
4227 		}
4228 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
4229 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4230 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
4231 			if (map_value_has_spin_lock(meta.map_ptr))
4232 				regs[BPF_REG_0].id = ++env->id_gen;
4233 		} else {
4234 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4235 			regs[BPF_REG_0].id = ++env->id_gen;
4236 		}
4237 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4238 		mark_reg_known_zero(env, regs, BPF_REG_0);
4239 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
4240 		regs[BPF_REG_0].id = ++env->id_gen;
4241 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4242 		mark_reg_known_zero(env, regs, BPF_REG_0);
4243 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4244 		regs[BPF_REG_0].id = ++env->id_gen;
4245 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4246 		mark_reg_known_zero(env, regs, BPF_REG_0);
4247 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4248 		regs[BPF_REG_0].id = ++env->id_gen;
4249 	} else {
4250 		verbose(env, "unknown return type %d of func %s#%d\n",
4251 			fn->ret_type, func_id_name(func_id), func_id);
4252 		return -EINVAL;
4253 	}
4254 
4255 	if (is_ptr_cast_function(func_id)) {
4256 		/* For release_reference() */
4257 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
4258 	} else if (is_acquire_function(func_id)) {
4259 		int id = acquire_reference_state(env, insn_idx);
4260 
4261 		if (id < 0)
4262 			return id;
4263 		/* For mark_ptr_or_null_reg() */
4264 		regs[BPF_REG_0].id = id;
4265 		/* For release_reference() */
4266 		regs[BPF_REG_0].ref_obj_id = id;
4267 	}
4268 
4269 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4270 
4271 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
4272 	if (err)
4273 		return err;
4274 
4275 	if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4276 		const char *err_str;
4277 
4278 #ifdef CONFIG_PERF_EVENTS
4279 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
4280 		err_str = "cannot get callchain buffer for func %s#%d\n";
4281 #else
4282 		err = -ENOTSUPP;
4283 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4284 #endif
4285 		if (err) {
4286 			verbose(env, err_str, func_id_name(func_id), func_id);
4287 			return err;
4288 		}
4289 
4290 		env->prog->has_callchain_buf = true;
4291 	}
4292 
4293 	if (changes_data)
4294 		clear_all_pkt_pointers(env);
4295 	return 0;
4296 }
4297 
4298 static bool signed_add_overflows(s64 a, s64 b)
4299 {
4300 	/* Do the add in u64, where overflow is well-defined */
4301 	s64 res = (s64)((u64)a + (u64)b);
4302 
4303 	if (b < 0)
4304 		return res > a;
4305 	return res < a;
4306 }
4307 
4308 static bool signed_sub_overflows(s64 a, s64 b)
4309 {
4310 	/* Do the sub in u64, where overflow is well-defined */
4311 	s64 res = (s64)((u64)a - (u64)b);
4312 
4313 	if (b < 0)
4314 		return res < a;
4315 	return res > a;
4316 }
4317 
4318 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4319 				  const struct bpf_reg_state *reg,
4320 				  enum bpf_reg_type type)
4321 {
4322 	bool known = tnum_is_const(reg->var_off);
4323 	s64 val = reg->var_off.value;
4324 	s64 smin = reg->smin_value;
4325 
4326 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4327 		verbose(env, "math between %s pointer and %lld is not allowed\n",
4328 			reg_type_str[type], val);
4329 		return false;
4330 	}
4331 
4332 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4333 		verbose(env, "%s pointer offset %d is not allowed\n",
4334 			reg_type_str[type], reg->off);
4335 		return false;
4336 	}
4337 
4338 	if (smin == S64_MIN) {
4339 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4340 			reg_type_str[type]);
4341 		return false;
4342 	}
4343 
4344 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4345 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
4346 			smin, reg_type_str[type]);
4347 		return false;
4348 	}
4349 
4350 	return true;
4351 }
4352 
4353 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4354 {
4355 	return &env->insn_aux_data[env->insn_idx];
4356 }
4357 
4358 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4359 			      u32 *ptr_limit, u8 opcode, bool off_is_neg)
4360 {
4361 	bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
4362 			    (opcode == BPF_SUB && !off_is_neg);
4363 	u32 off;
4364 
4365 	switch (ptr_reg->type) {
4366 	case PTR_TO_STACK:
4367 		/* Indirect variable offset stack access is prohibited in
4368 		 * unprivileged mode so it's not handled here.
4369 		 */
4370 		off = ptr_reg->off + ptr_reg->var_off.value;
4371 		if (mask_to_left)
4372 			*ptr_limit = MAX_BPF_STACK + off;
4373 		else
4374 			*ptr_limit = -off;
4375 		return 0;
4376 	case PTR_TO_MAP_VALUE:
4377 		if (mask_to_left) {
4378 			*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4379 		} else {
4380 			off = ptr_reg->smin_value + ptr_reg->off;
4381 			*ptr_limit = ptr_reg->map_ptr->value_size - off;
4382 		}
4383 		return 0;
4384 	default:
4385 		return -EINVAL;
4386 	}
4387 }
4388 
4389 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4390 				    const struct bpf_insn *insn)
4391 {
4392 	return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4393 }
4394 
4395 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4396 				       u32 alu_state, u32 alu_limit)
4397 {
4398 	/* If we arrived here from different branches with different
4399 	 * state or limits to sanitize, then this won't work.
4400 	 */
4401 	if (aux->alu_state &&
4402 	    (aux->alu_state != alu_state ||
4403 	     aux->alu_limit != alu_limit))
4404 		return -EACCES;
4405 
4406 	/* Corresponding fixup done in fixup_bpf_calls(). */
4407 	aux->alu_state = alu_state;
4408 	aux->alu_limit = alu_limit;
4409 	return 0;
4410 }
4411 
4412 static int sanitize_val_alu(struct bpf_verifier_env *env,
4413 			    struct bpf_insn *insn)
4414 {
4415 	struct bpf_insn_aux_data *aux = cur_aux(env);
4416 
4417 	if (can_skip_alu_sanitation(env, insn))
4418 		return 0;
4419 
4420 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4421 }
4422 
4423 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4424 			    struct bpf_insn *insn,
4425 			    const struct bpf_reg_state *ptr_reg,
4426 			    struct bpf_reg_state *dst_reg,
4427 			    bool off_is_neg)
4428 {
4429 	struct bpf_verifier_state *vstate = env->cur_state;
4430 	struct bpf_insn_aux_data *aux = cur_aux(env);
4431 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
4432 	u8 opcode = BPF_OP(insn->code);
4433 	u32 alu_state, alu_limit;
4434 	struct bpf_reg_state tmp;
4435 	bool ret;
4436 
4437 	if (can_skip_alu_sanitation(env, insn))
4438 		return 0;
4439 
4440 	/* We already marked aux for masking from non-speculative
4441 	 * paths, thus we got here in the first place. We only care
4442 	 * to explore bad access from here.
4443 	 */
4444 	if (vstate->speculative)
4445 		goto do_sim;
4446 
4447 	alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4448 	alu_state |= ptr_is_dst_reg ?
4449 		     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4450 
4451 	if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4452 		return 0;
4453 	if (update_alu_sanitation_state(aux, alu_state, alu_limit))
4454 		return -EACCES;
4455 do_sim:
4456 	/* Simulate and find potential out-of-bounds access under
4457 	 * speculative execution from truncation as a result of
4458 	 * masking when off was not within expected range. If off
4459 	 * sits in dst, then we temporarily need to move ptr there
4460 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4461 	 * for cases where we use K-based arithmetic in one direction
4462 	 * and truncated reg-based in the other in order to explore
4463 	 * bad access.
4464 	 */
4465 	if (!ptr_is_dst_reg) {
4466 		tmp = *dst_reg;
4467 		*dst_reg = *ptr_reg;
4468 	}
4469 	ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
4470 	if (!ptr_is_dst_reg && ret)
4471 		*dst_reg = tmp;
4472 	return !ret ? -EFAULT : 0;
4473 }
4474 
4475 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4476  * Caller should also handle BPF_MOV case separately.
4477  * If we return -EACCES, caller may want to try again treating pointer as a
4478  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
4479  */
4480 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4481 				   struct bpf_insn *insn,
4482 				   const struct bpf_reg_state *ptr_reg,
4483 				   const struct bpf_reg_state *off_reg)
4484 {
4485 	struct bpf_verifier_state *vstate = env->cur_state;
4486 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4487 	struct bpf_reg_state *regs = state->regs, *dst_reg;
4488 	bool known = tnum_is_const(off_reg->var_off);
4489 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4490 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4491 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4492 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
4493 	u32 dst = insn->dst_reg, src = insn->src_reg;
4494 	u8 opcode = BPF_OP(insn->code);
4495 	int ret;
4496 
4497 	dst_reg = &regs[dst];
4498 
4499 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4500 	    smin_val > smax_val || umin_val > umax_val) {
4501 		/* Taint dst register if offset had invalid bounds derived from
4502 		 * e.g. dead branches.
4503 		 */
4504 		__mark_reg_unknown(dst_reg);
4505 		return 0;
4506 	}
4507 
4508 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
4509 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
4510 		verbose(env,
4511 			"R%d 32-bit pointer arithmetic prohibited\n",
4512 			dst);
4513 		return -EACCES;
4514 	}
4515 
4516 	switch (ptr_reg->type) {
4517 	case PTR_TO_MAP_VALUE_OR_NULL:
4518 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4519 			dst, reg_type_str[ptr_reg->type]);
4520 		return -EACCES;
4521 	case CONST_PTR_TO_MAP:
4522 	case PTR_TO_PACKET_END:
4523 	case PTR_TO_SOCKET:
4524 	case PTR_TO_SOCKET_OR_NULL:
4525 	case PTR_TO_SOCK_COMMON:
4526 	case PTR_TO_SOCK_COMMON_OR_NULL:
4527 	case PTR_TO_TCP_SOCK:
4528 	case PTR_TO_TCP_SOCK_OR_NULL:
4529 	case PTR_TO_XDP_SOCK:
4530 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4531 			dst, reg_type_str[ptr_reg->type]);
4532 		return -EACCES;
4533 	case PTR_TO_MAP_VALUE:
4534 		if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
4535 			verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4536 				off_reg == dst_reg ? dst : src);
4537 			return -EACCES;
4538 		}
4539 		/* fall-through */
4540 	default:
4541 		break;
4542 	}
4543 
4544 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4545 	 * The id may be overwritten later if we create a new variable offset.
4546 	 */
4547 	dst_reg->type = ptr_reg->type;
4548 	dst_reg->id = ptr_reg->id;
4549 
4550 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4551 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4552 		return -EINVAL;
4553 
4554 	switch (opcode) {
4555 	case BPF_ADD:
4556 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4557 		if (ret < 0) {
4558 			verbose(env, "R%d tried to add from different maps or paths\n", dst);
4559 			return ret;
4560 		}
4561 		/* We can take a fixed offset as long as it doesn't overflow
4562 		 * the s32 'off' field
4563 		 */
4564 		if (known && (ptr_reg->off + smin_val ==
4565 			      (s64)(s32)(ptr_reg->off + smin_val))) {
4566 			/* pointer += K.  Accumulate it into fixed offset */
4567 			dst_reg->smin_value = smin_ptr;
4568 			dst_reg->smax_value = smax_ptr;
4569 			dst_reg->umin_value = umin_ptr;
4570 			dst_reg->umax_value = umax_ptr;
4571 			dst_reg->var_off = ptr_reg->var_off;
4572 			dst_reg->off = ptr_reg->off + smin_val;
4573 			dst_reg->raw = ptr_reg->raw;
4574 			break;
4575 		}
4576 		/* A new variable offset is created.  Note that off_reg->off
4577 		 * == 0, since it's a scalar.
4578 		 * dst_reg gets the pointer type and since some positive
4579 		 * integer value was added to the pointer, give it a new 'id'
4580 		 * if it's a PTR_TO_PACKET.
4581 		 * this creates a new 'base' pointer, off_reg (variable) gets
4582 		 * added into the variable offset, and we copy the fixed offset
4583 		 * from ptr_reg.
4584 		 */
4585 		if (signed_add_overflows(smin_ptr, smin_val) ||
4586 		    signed_add_overflows(smax_ptr, smax_val)) {
4587 			dst_reg->smin_value = S64_MIN;
4588 			dst_reg->smax_value = S64_MAX;
4589 		} else {
4590 			dst_reg->smin_value = smin_ptr + smin_val;
4591 			dst_reg->smax_value = smax_ptr + smax_val;
4592 		}
4593 		if (umin_ptr + umin_val < umin_ptr ||
4594 		    umax_ptr + umax_val < umax_ptr) {
4595 			dst_reg->umin_value = 0;
4596 			dst_reg->umax_value = U64_MAX;
4597 		} else {
4598 			dst_reg->umin_value = umin_ptr + umin_val;
4599 			dst_reg->umax_value = umax_ptr + umax_val;
4600 		}
4601 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4602 		dst_reg->off = ptr_reg->off;
4603 		dst_reg->raw = ptr_reg->raw;
4604 		if (reg_is_pkt_pointer(ptr_reg)) {
4605 			dst_reg->id = ++env->id_gen;
4606 			/* something was added to pkt_ptr, set range to zero */
4607 			dst_reg->raw = 0;
4608 		}
4609 		break;
4610 	case BPF_SUB:
4611 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4612 		if (ret < 0) {
4613 			verbose(env, "R%d tried to sub from different maps or paths\n", dst);
4614 			return ret;
4615 		}
4616 		if (dst_reg == off_reg) {
4617 			/* scalar -= pointer.  Creates an unknown scalar */
4618 			verbose(env, "R%d tried to subtract pointer from scalar\n",
4619 				dst);
4620 			return -EACCES;
4621 		}
4622 		/* We don't allow subtraction from FP, because (according to
4623 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
4624 		 * be able to deal with it.
4625 		 */
4626 		if (ptr_reg->type == PTR_TO_STACK) {
4627 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
4628 				dst);
4629 			return -EACCES;
4630 		}
4631 		if (known && (ptr_reg->off - smin_val ==
4632 			      (s64)(s32)(ptr_reg->off - smin_val))) {
4633 			/* pointer -= K.  Subtract it from fixed offset */
4634 			dst_reg->smin_value = smin_ptr;
4635 			dst_reg->smax_value = smax_ptr;
4636 			dst_reg->umin_value = umin_ptr;
4637 			dst_reg->umax_value = umax_ptr;
4638 			dst_reg->var_off = ptr_reg->var_off;
4639 			dst_reg->id = ptr_reg->id;
4640 			dst_reg->off = ptr_reg->off - smin_val;
4641 			dst_reg->raw = ptr_reg->raw;
4642 			break;
4643 		}
4644 		/* A new variable offset is created.  If the subtrahend is known
4645 		 * nonnegative, then any reg->range we had before is still good.
4646 		 */
4647 		if (signed_sub_overflows(smin_ptr, smax_val) ||
4648 		    signed_sub_overflows(smax_ptr, smin_val)) {
4649 			/* Overflow possible, we know nothing */
4650 			dst_reg->smin_value = S64_MIN;
4651 			dst_reg->smax_value = S64_MAX;
4652 		} else {
4653 			dst_reg->smin_value = smin_ptr - smax_val;
4654 			dst_reg->smax_value = smax_ptr - smin_val;
4655 		}
4656 		if (umin_ptr < umax_val) {
4657 			/* Overflow possible, we know nothing */
4658 			dst_reg->umin_value = 0;
4659 			dst_reg->umax_value = U64_MAX;
4660 		} else {
4661 			/* Cannot overflow (as long as bounds are consistent) */
4662 			dst_reg->umin_value = umin_ptr - umax_val;
4663 			dst_reg->umax_value = umax_ptr - umin_val;
4664 		}
4665 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
4666 		dst_reg->off = ptr_reg->off;
4667 		dst_reg->raw = ptr_reg->raw;
4668 		if (reg_is_pkt_pointer(ptr_reg)) {
4669 			dst_reg->id = ++env->id_gen;
4670 			/* something was added to pkt_ptr, set range to zero */
4671 			if (smin_val < 0)
4672 				dst_reg->raw = 0;
4673 		}
4674 		break;
4675 	case BPF_AND:
4676 	case BPF_OR:
4677 	case BPF_XOR:
4678 		/* bitwise ops on pointers are troublesome, prohibit. */
4679 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4680 			dst, bpf_alu_string[opcode >> 4]);
4681 		return -EACCES;
4682 	default:
4683 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
4684 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4685 			dst, bpf_alu_string[opcode >> 4]);
4686 		return -EACCES;
4687 	}
4688 
4689 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4690 		return -EINVAL;
4691 
4692 	__update_reg_bounds(dst_reg);
4693 	__reg_deduce_bounds(dst_reg);
4694 	__reg_bound_offset(dst_reg);
4695 
4696 	/* For unprivileged we require that resulting offset must be in bounds
4697 	 * in order to be able to sanitize access later on.
4698 	 */
4699 	if (!env->allow_ptr_leaks) {
4700 		if (dst_reg->type == PTR_TO_MAP_VALUE &&
4701 		    check_map_access(env, dst, dst_reg->off, 1, false)) {
4702 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4703 				"prohibited for !root\n", dst);
4704 			return -EACCES;
4705 		} else if (dst_reg->type == PTR_TO_STACK &&
4706 			   check_stack_access(env, dst_reg, dst_reg->off +
4707 					      dst_reg->var_off.value, 1)) {
4708 			verbose(env, "R%d stack pointer arithmetic goes out of range, "
4709 				"prohibited for !root\n", dst);
4710 			return -EACCES;
4711 		}
4712 	}
4713 
4714 	return 0;
4715 }
4716 
4717 /* WARNING: This function does calculations on 64-bit values, but the actual
4718  * execution may occur on 32-bit values. Therefore, things like bitshifts
4719  * need extra checks in the 32-bit case.
4720  */
4721 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
4722 				      struct bpf_insn *insn,
4723 				      struct bpf_reg_state *dst_reg,
4724 				      struct bpf_reg_state src_reg)
4725 {
4726 	struct bpf_reg_state *regs = cur_regs(env);
4727 	u8 opcode = BPF_OP(insn->code);
4728 	bool src_known, dst_known;
4729 	s64 smin_val, smax_val;
4730 	u64 umin_val, umax_val;
4731 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
4732 	u32 dst = insn->dst_reg;
4733 	int ret;
4734 
4735 	if (insn_bitness == 32) {
4736 		/* Relevant for 32-bit RSH: Information can propagate towards
4737 		 * LSB, so it isn't sufficient to only truncate the output to
4738 		 * 32 bits.
4739 		 */
4740 		coerce_reg_to_size(dst_reg, 4);
4741 		coerce_reg_to_size(&src_reg, 4);
4742 	}
4743 
4744 	smin_val = src_reg.smin_value;
4745 	smax_val = src_reg.smax_value;
4746 	umin_val = src_reg.umin_value;
4747 	umax_val = src_reg.umax_value;
4748 	src_known = tnum_is_const(src_reg.var_off);
4749 	dst_known = tnum_is_const(dst_reg->var_off);
4750 
4751 	if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
4752 	    smin_val > smax_val || umin_val > umax_val) {
4753 		/* Taint dst register if offset had invalid bounds derived from
4754 		 * e.g. dead branches.
4755 		 */
4756 		__mark_reg_unknown(dst_reg);
4757 		return 0;
4758 	}
4759 
4760 	if (!src_known &&
4761 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
4762 		__mark_reg_unknown(dst_reg);
4763 		return 0;
4764 	}
4765 
4766 	switch (opcode) {
4767 	case BPF_ADD:
4768 		ret = sanitize_val_alu(env, insn);
4769 		if (ret < 0) {
4770 			verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
4771 			return ret;
4772 		}
4773 		if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4774 		    signed_add_overflows(dst_reg->smax_value, smax_val)) {
4775 			dst_reg->smin_value = S64_MIN;
4776 			dst_reg->smax_value = S64_MAX;
4777 		} else {
4778 			dst_reg->smin_value += smin_val;
4779 			dst_reg->smax_value += smax_val;
4780 		}
4781 		if (dst_reg->umin_value + umin_val < umin_val ||
4782 		    dst_reg->umax_value + umax_val < umax_val) {
4783 			dst_reg->umin_value = 0;
4784 			dst_reg->umax_value = U64_MAX;
4785 		} else {
4786 			dst_reg->umin_value += umin_val;
4787 			dst_reg->umax_value += umax_val;
4788 		}
4789 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
4790 		break;
4791 	case BPF_SUB:
4792 		ret = sanitize_val_alu(env, insn);
4793 		if (ret < 0) {
4794 			verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
4795 			return ret;
4796 		}
4797 		if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4798 		    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4799 			/* Overflow possible, we know nothing */
4800 			dst_reg->smin_value = S64_MIN;
4801 			dst_reg->smax_value = S64_MAX;
4802 		} else {
4803 			dst_reg->smin_value -= smax_val;
4804 			dst_reg->smax_value -= smin_val;
4805 		}
4806 		if (dst_reg->umin_value < umax_val) {
4807 			/* Overflow possible, we know nothing */
4808 			dst_reg->umin_value = 0;
4809 			dst_reg->umax_value = U64_MAX;
4810 		} else {
4811 			/* Cannot overflow (as long as bounds are consistent) */
4812 			dst_reg->umin_value -= umax_val;
4813 			dst_reg->umax_value -= umin_val;
4814 		}
4815 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
4816 		break;
4817 	case BPF_MUL:
4818 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
4819 		if (smin_val < 0 || dst_reg->smin_value < 0) {
4820 			/* Ain't nobody got time to multiply that sign */
4821 			__mark_reg_unbounded(dst_reg);
4822 			__update_reg_bounds(dst_reg);
4823 			break;
4824 		}
4825 		/* Both values are positive, so we can work with unsigned and
4826 		 * copy the result to signed (unless it exceeds S64_MAX).
4827 		 */
4828 		if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4829 			/* Potential overflow, we know nothing */
4830 			__mark_reg_unbounded(dst_reg);
4831 			/* (except what we can learn from the var_off) */
4832 			__update_reg_bounds(dst_reg);
4833 			break;
4834 		}
4835 		dst_reg->umin_value *= umin_val;
4836 		dst_reg->umax_value *= umax_val;
4837 		if (dst_reg->umax_value > S64_MAX) {
4838 			/* Overflow possible, we know nothing */
4839 			dst_reg->smin_value = S64_MIN;
4840 			dst_reg->smax_value = S64_MAX;
4841 		} else {
4842 			dst_reg->smin_value = dst_reg->umin_value;
4843 			dst_reg->smax_value = dst_reg->umax_value;
4844 		}
4845 		break;
4846 	case BPF_AND:
4847 		if (src_known && dst_known) {
4848 			__mark_reg_known(dst_reg, dst_reg->var_off.value &
4849 						  src_reg.var_off.value);
4850 			break;
4851 		}
4852 		/* We get our minimum from the var_off, since that's inherently
4853 		 * bitwise.  Our maximum is the minimum of the operands' maxima.
4854 		 */
4855 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
4856 		dst_reg->umin_value = dst_reg->var_off.value;
4857 		dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4858 		if (dst_reg->smin_value < 0 || smin_val < 0) {
4859 			/* Lose signed bounds when ANDing negative numbers,
4860 			 * ain't nobody got time for that.
4861 			 */
4862 			dst_reg->smin_value = S64_MIN;
4863 			dst_reg->smax_value = S64_MAX;
4864 		} else {
4865 			/* ANDing two positives gives a positive, so safe to
4866 			 * cast result into s64.
4867 			 */
4868 			dst_reg->smin_value = dst_reg->umin_value;
4869 			dst_reg->smax_value = dst_reg->umax_value;
4870 		}
4871 		/* We may learn something more from the var_off */
4872 		__update_reg_bounds(dst_reg);
4873 		break;
4874 	case BPF_OR:
4875 		if (src_known && dst_known) {
4876 			__mark_reg_known(dst_reg, dst_reg->var_off.value |
4877 						  src_reg.var_off.value);
4878 			break;
4879 		}
4880 		/* We get our maximum from the var_off, and our minimum is the
4881 		 * maximum of the operands' minima
4882 		 */
4883 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
4884 		dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4885 		dst_reg->umax_value = dst_reg->var_off.value |
4886 				      dst_reg->var_off.mask;
4887 		if (dst_reg->smin_value < 0 || smin_val < 0) {
4888 			/* Lose signed bounds when ORing negative numbers,
4889 			 * ain't nobody got time for that.
4890 			 */
4891 			dst_reg->smin_value = S64_MIN;
4892 			dst_reg->smax_value = S64_MAX;
4893 		} else {
4894 			/* ORing two positives gives a positive, so safe to
4895 			 * cast result into s64.
4896 			 */
4897 			dst_reg->smin_value = dst_reg->umin_value;
4898 			dst_reg->smax_value = dst_reg->umax_value;
4899 		}
4900 		/* We may learn something more from the var_off */
4901 		__update_reg_bounds(dst_reg);
4902 		break;
4903 	case BPF_LSH:
4904 		if (umax_val >= insn_bitness) {
4905 			/* Shifts greater than 31 or 63 are undefined.
4906 			 * This includes shifts by a negative number.
4907 			 */
4908 			mark_reg_unknown(env, regs, insn->dst_reg);
4909 			break;
4910 		}
4911 		/* We lose all sign bit information (except what we can pick
4912 		 * up from var_off)
4913 		 */
4914 		dst_reg->smin_value = S64_MIN;
4915 		dst_reg->smax_value = S64_MAX;
4916 		/* If we might shift our top bit out, then we know nothing */
4917 		if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
4918 			dst_reg->umin_value = 0;
4919 			dst_reg->umax_value = U64_MAX;
4920 		} else {
4921 			dst_reg->umin_value <<= umin_val;
4922 			dst_reg->umax_value <<= umax_val;
4923 		}
4924 		dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
4925 		/* We may learn something more from the var_off */
4926 		__update_reg_bounds(dst_reg);
4927 		break;
4928 	case BPF_RSH:
4929 		if (umax_val >= insn_bitness) {
4930 			/* Shifts greater than 31 or 63 are undefined.
4931 			 * This includes shifts by a negative number.
4932 			 */
4933 			mark_reg_unknown(env, regs, insn->dst_reg);
4934 			break;
4935 		}
4936 		/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
4937 		 * be negative, then either:
4938 		 * 1) src_reg might be zero, so the sign bit of the result is
4939 		 *    unknown, so we lose our signed bounds
4940 		 * 2) it's known negative, thus the unsigned bounds capture the
4941 		 *    signed bounds
4942 		 * 3) the signed bounds cross zero, so they tell us nothing
4943 		 *    about the result
4944 		 * If the value in dst_reg is known nonnegative, then again the
4945 		 * unsigned bounts capture the signed bounds.
4946 		 * Thus, in all cases it suffices to blow away our signed bounds
4947 		 * and rely on inferring new ones from the unsigned bounds and
4948 		 * var_off of the result.
4949 		 */
4950 		dst_reg->smin_value = S64_MIN;
4951 		dst_reg->smax_value = S64_MAX;
4952 		dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
4953 		dst_reg->umin_value >>= umax_val;
4954 		dst_reg->umax_value >>= umin_val;
4955 		/* We may learn something more from the var_off */
4956 		__update_reg_bounds(dst_reg);
4957 		break;
4958 	case BPF_ARSH:
4959 		if (umax_val >= insn_bitness) {
4960 			/* Shifts greater than 31 or 63 are undefined.
4961 			 * This includes shifts by a negative number.
4962 			 */
4963 			mark_reg_unknown(env, regs, insn->dst_reg);
4964 			break;
4965 		}
4966 
4967 		/* Upon reaching here, src_known is true and
4968 		 * umax_val is equal to umin_val.
4969 		 */
4970 		dst_reg->smin_value >>= umin_val;
4971 		dst_reg->smax_value >>= umin_val;
4972 		dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
4973 
4974 		/* blow away the dst_reg umin_value/umax_value and rely on
4975 		 * dst_reg var_off to refine the result.
4976 		 */
4977 		dst_reg->umin_value = 0;
4978 		dst_reg->umax_value = U64_MAX;
4979 		__update_reg_bounds(dst_reg);
4980 		break;
4981 	default:
4982 		mark_reg_unknown(env, regs, insn->dst_reg);
4983 		break;
4984 	}
4985 
4986 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
4987 		/* 32-bit ALU ops are (32,32)->32 */
4988 		coerce_reg_to_size(dst_reg, 4);
4989 	}
4990 
4991 	__reg_deduce_bounds(dst_reg);
4992 	__reg_bound_offset(dst_reg);
4993 	return 0;
4994 }
4995 
4996 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
4997  * and var_off.
4998  */
4999 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5000 				   struct bpf_insn *insn)
5001 {
5002 	struct bpf_verifier_state *vstate = env->cur_state;
5003 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5004 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
5005 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5006 	u8 opcode = BPF_OP(insn->code);
5007 	int err;
5008 
5009 	dst_reg = &regs[insn->dst_reg];
5010 	src_reg = NULL;
5011 	if (dst_reg->type != SCALAR_VALUE)
5012 		ptr_reg = dst_reg;
5013 	if (BPF_SRC(insn->code) == BPF_X) {
5014 		src_reg = &regs[insn->src_reg];
5015 		if (src_reg->type != SCALAR_VALUE) {
5016 			if (dst_reg->type != SCALAR_VALUE) {
5017 				/* Combining two pointers by any ALU op yields
5018 				 * an arbitrary scalar. Disallow all math except
5019 				 * pointer subtraction
5020 				 */
5021 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5022 					mark_reg_unknown(env, regs, insn->dst_reg);
5023 					return 0;
5024 				}
5025 				verbose(env, "R%d pointer %s pointer prohibited\n",
5026 					insn->dst_reg,
5027 					bpf_alu_string[opcode >> 4]);
5028 				return -EACCES;
5029 			} else {
5030 				/* scalar += pointer
5031 				 * This is legal, but we have to reverse our
5032 				 * src/dest handling in computing the range
5033 				 */
5034 				err = mark_chain_precision(env, insn->dst_reg);
5035 				if (err)
5036 					return err;
5037 				return adjust_ptr_min_max_vals(env, insn,
5038 							       src_reg, dst_reg);
5039 			}
5040 		} else if (ptr_reg) {
5041 			/* pointer += scalar */
5042 			err = mark_chain_precision(env, insn->src_reg);
5043 			if (err)
5044 				return err;
5045 			return adjust_ptr_min_max_vals(env, insn,
5046 						       dst_reg, src_reg);
5047 		}
5048 	} else {
5049 		/* Pretend the src is a reg with a known value, since we only
5050 		 * need to be able to read from this state.
5051 		 */
5052 		off_reg.type = SCALAR_VALUE;
5053 		__mark_reg_known(&off_reg, insn->imm);
5054 		src_reg = &off_reg;
5055 		if (ptr_reg) /* pointer += K */
5056 			return adjust_ptr_min_max_vals(env, insn,
5057 						       ptr_reg, src_reg);
5058 	}
5059 
5060 	/* Got here implies adding two SCALAR_VALUEs */
5061 	if (WARN_ON_ONCE(ptr_reg)) {
5062 		print_verifier_state(env, state);
5063 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
5064 		return -EINVAL;
5065 	}
5066 	if (WARN_ON(!src_reg)) {
5067 		print_verifier_state(env, state);
5068 		verbose(env, "verifier internal error: no src_reg\n");
5069 		return -EINVAL;
5070 	}
5071 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
5072 }
5073 
5074 /* check validity of 32-bit and 64-bit arithmetic operations */
5075 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
5076 {
5077 	struct bpf_reg_state *regs = cur_regs(env);
5078 	u8 opcode = BPF_OP(insn->code);
5079 	int err;
5080 
5081 	if (opcode == BPF_END || opcode == BPF_NEG) {
5082 		if (opcode == BPF_NEG) {
5083 			if (BPF_SRC(insn->code) != 0 ||
5084 			    insn->src_reg != BPF_REG_0 ||
5085 			    insn->off != 0 || insn->imm != 0) {
5086 				verbose(env, "BPF_NEG uses reserved fields\n");
5087 				return -EINVAL;
5088 			}
5089 		} else {
5090 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
5091 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5092 			    BPF_CLASS(insn->code) == BPF_ALU64) {
5093 				verbose(env, "BPF_END uses reserved fields\n");
5094 				return -EINVAL;
5095 			}
5096 		}
5097 
5098 		/* check src operand */
5099 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5100 		if (err)
5101 			return err;
5102 
5103 		if (is_pointer_value(env, insn->dst_reg)) {
5104 			verbose(env, "R%d pointer arithmetic prohibited\n",
5105 				insn->dst_reg);
5106 			return -EACCES;
5107 		}
5108 
5109 		/* check dest operand */
5110 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
5111 		if (err)
5112 			return err;
5113 
5114 	} else if (opcode == BPF_MOV) {
5115 
5116 		if (BPF_SRC(insn->code) == BPF_X) {
5117 			if (insn->imm != 0 || insn->off != 0) {
5118 				verbose(env, "BPF_MOV uses reserved fields\n");
5119 				return -EINVAL;
5120 			}
5121 
5122 			/* check src operand */
5123 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
5124 			if (err)
5125 				return err;
5126 		} else {
5127 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5128 				verbose(env, "BPF_MOV uses reserved fields\n");
5129 				return -EINVAL;
5130 			}
5131 		}
5132 
5133 		/* check dest operand, mark as required later */
5134 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5135 		if (err)
5136 			return err;
5137 
5138 		if (BPF_SRC(insn->code) == BPF_X) {
5139 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
5140 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5141 
5142 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
5143 				/* case: R1 = R2
5144 				 * copy register state to dest reg
5145 				 */
5146 				*dst_reg = *src_reg;
5147 				dst_reg->live |= REG_LIVE_WRITTEN;
5148 				dst_reg->subreg_def = DEF_NOT_SUBREG;
5149 			} else {
5150 				/* R1 = (u32) R2 */
5151 				if (is_pointer_value(env, insn->src_reg)) {
5152 					verbose(env,
5153 						"R%d partial copy of pointer\n",
5154 						insn->src_reg);
5155 					return -EACCES;
5156 				} else if (src_reg->type == SCALAR_VALUE) {
5157 					*dst_reg = *src_reg;
5158 					dst_reg->live |= REG_LIVE_WRITTEN;
5159 					dst_reg->subreg_def = env->insn_idx + 1;
5160 				} else {
5161 					mark_reg_unknown(env, regs,
5162 							 insn->dst_reg);
5163 				}
5164 				coerce_reg_to_size(dst_reg, 4);
5165 			}
5166 		} else {
5167 			/* case: R = imm
5168 			 * remember the value we stored into this reg
5169 			 */
5170 			/* clear any state __mark_reg_known doesn't set */
5171 			mark_reg_unknown(env, regs, insn->dst_reg);
5172 			regs[insn->dst_reg].type = SCALAR_VALUE;
5173 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
5174 				__mark_reg_known(regs + insn->dst_reg,
5175 						 insn->imm);
5176 			} else {
5177 				__mark_reg_known(regs + insn->dst_reg,
5178 						 (u32)insn->imm);
5179 			}
5180 		}
5181 
5182 	} else if (opcode > BPF_END) {
5183 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
5184 		return -EINVAL;
5185 
5186 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
5187 
5188 		if (BPF_SRC(insn->code) == BPF_X) {
5189 			if (insn->imm != 0 || insn->off != 0) {
5190 				verbose(env, "BPF_ALU uses reserved fields\n");
5191 				return -EINVAL;
5192 			}
5193 			/* check src1 operand */
5194 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
5195 			if (err)
5196 				return err;
5197 		} else {
5198 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5199 				verbose(env, "BPF_ALU uses reserved fields\n");
5200 				return -EINVAL;
5201 			}
5202 		}
5203 
5204 		/* check src2 operand */
5205 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5206 		if (err)
5207 			return err;
5208 
5209 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5210 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
5211 			verbose(env, "div by zero\n");
5212 			return -EINVAL;
5213 		}
5214 
5215 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5216 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5217 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5218 
5219 			if (insn->imm < 0 || insn->imm >= size) {
5220 				verbose(env, "invalid shift %d\n", insn->imm);
5221 				return -EINVAL;
5222 			}
5223 		}
5224 
5225 		/* check dest operand */
5226 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5227 		if (err)
5228 			return err;
5229 
5230 		return adjust_reg_min_max_vals(env, insn);
5231 	}
5232 
5233 	return 0;
5234 }
5235 
5236 static void __find_good_pkt_pointers(struct bpf_func_state *state,
5237 				     struct bpf_reg_state *dst_reg,
5238 				     enum bpf_reg_type type, u16 new_range)
5239 {
5240 	struct bpf_reg_state *reg;
5241 	int i;
5242 
5243 	for (i = 0; i < MAX_BPF_REG; i++) {
5244 		reg = &state->regs[i];
5245 		if (reg->type == type && reg->id == dst_reg->id)
5246 			/* keep the maximum range already checked */
5247 			reg->range = max(reg->range, new_range);
5248 	}
5249 
5250 	bpf_for_each_spilled_reg(i, state, reg) {
5251 		if (!reg)
5252 			continue;
5253 		if (reg->type == type && reg->id == dst_reg->id)
5254 			reg->range = max(reg->range, new_range);
5255 	}
5256 }
5257 
5258 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
5259 				   struct bpf_reg_state *dst_reg,
5260 				   enum bpf_reg_type type,
5261 				   bool range_right_open)
5262 {
5263 	u16 new_range;
5264 	int i;
5265 
5266 	if (dst_reg->off < 0 ||
5267 	    (dst_reg->off == 0 && range_right_open))
5268 		/* This doesn't give us any range */
5269 		return;
5270 
5271 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
5272 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
5273 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
5274 		 * than pkt_end, but that's because it's also less than pkt.
5275 		 */
5276 		return;
5277 
5278 	new_range = dst_reg->off;
5279 	if (range_right_open)
5280 		new_range--;
5281 
5282 	/* Examples for register markings:
5283 	 *
5284 	 * pkt_data in dst register:
5285 	 *
5286 	 *   r2 = r3;
5287 	 *   r2 += 8;
5288 	 *   if (r2 > pkt_end) goto <handle exception>
5289 	 *   <access okay>
5290 	 *
5291 	 *   r2 = r3;
5292 	 *   r2 += 8;
5293 	 *   if (r2 < pkt_end) goto <access okay>
5294 	 *   <handle exception>
5295 	 *
5296 	 *   Where:
5297 	 *     r2 == dst_reg, pkt_end == src_reg
5298 	 *     r2=pkt(id=n,off=8,r=0)
5299 	 *     r3=pkt(id=n,off=0,r=0)
5300 	 *
5301 	 * pkt_data in src register:
5302 	 *
5303 	 *   r2 = r3;
5304 	 *   r2 += 8;
5305 	 *   if (pkt_end >= r2) goto <access okay>
5306 	 *   <handle exception>
5307 	 *
5308 	 *   r2 = r3;
5309 	 *   r2 += 8;
5310 	 *   if (pkt_end <= r2) goto <handle exception>
5311 	 *   <access okay>
5312 	 *
5313 	 *   Where:
5314 	 *     pkt_end == dst_reg, r2 == src_reg
5315 	 *     r2=pkt(id=n,off=8,r=0)
5316 	 *     r3=pkt(id=n,off=0,r=0)
5317 	 *
5318 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
5319 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
5320 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
5321 	 * the check.
5322 	 */
5323 
5324 	/* If our ids match, then we must have the same max_value.  And we
5325 	 * don't care about the other reg's fixed offset, since if it's too big
5326 	 * the range won't allow anything.
5327 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
5328 	 */
5329 	for (i = 0; i <= vstate->curframe; i++)
5330 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
5331 					 new_range);
5332 }
5333 
5334 /* compute branch direction of the expression "if (reg opcode val) goto target;"
5335  * and return:
5336  *  1 - branch will be taken and "goto target" will be executed
5337  *  0 - branch will not be taken and fall-through to next insn
5338  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
5339  */
5340 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
5341 			   bool is_jmp32)
5342 {
5343 	struct bpf_reg_state reg_lo;
5344 	s64 sval;
5345 
5346 	if (__is_pointer_value(false, reg))
5347 		return -1;
5348 
5349 	if (is_jmp32) {
5350 		reg_lo = *reg;
5351 		reg = &reg_lo;
5352 		/* For JMP32, only low 32 bits are compared, coerce_reg_to_size
5353 		 * could truncate high bits and update umin/umax according to
5354 		 * information of low bits.
5355 		 */
5356 		coerce_reg_to_size(reg, 4);
5357 		/* smin/smax need special handling. For example, after coerce,
5358 		 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
5359 		 * used as operand to JMP32. It is a negative number from s32's
5360 		 * point of view, while it is a positive number when seen as
5361 		 * s64. The smin/smax are kept as s64, therefore, when used with
5362 		 * JMP32, they need to be transformed into s32, then sign
5363 		 * extended back to s64.
5364 		 *
5365 		 * Also, smin/smax were copied from umin/umax. If umin/umax has
5366 		 * different sign bit, then min/max relationship doesn't
5367 		 * maintain after casting into s32, for this case, set smin/smax
5368 		 * to safest range.
5369 		 */
5370 		if ((reg->umax_value ^ reg->umin_value) &
5371 		    (1ULL << 31)) {
5372 			reg->smin_value = S32_MIN;
5373 			reg->smax_value = S32_MAX;
5374 		}
5375 		reg->smin_value = (s64)(s32)reg->smin_value;
5376 		reg->smax_value = (s64)(s32)reg->smax_value;
5377 
5378 		val = (u32)val;
5379 		sval = (s64)(s32)val;
5380 	} else {
5381 		sval = (s64)val;
5382 	}
5383 
5384 	switch (opcode) {
5385 	case BPF_JEQ:
5386 		if (tnum_is_const(reg->var_off))
5387 			return !!tnum_equals_const(reg->var_off, val);
5388 		break;
5389 	case BPF_JNE:
5390 		if (tnum_is_const(reg->var_off))
5391 			return !tnum_equals_const(reg->var_off, val);
5392 		break;
5393 	case BPF_JSET:
5394 		if ((~reg->var_off.mask & reg->var_off.value) & val)
5395 			return 1;
5396 		if (!((reg->var_off.mask | reg->var_off.value) & val))
5397 			return 0;
5398 		break;
5399 	case BPF_JGT:
5400 		if (reg->umin_value > val)
5401 			return 1;
5402 		else if (reg->umax_value <= val)
5403 			return 0;
5404 		break;
5405 	case BPF_JSGT:
5406 		if (reg->smin_value > sval)
5407 			return 1;
5408 		else if (reg->smax_value < sval)
5409 			return 0;
5410 		break;
5411 	case BPF_JLT:
5412 		if (reg->umax_value < val)
5413 			return 1;
5414 		else if (reg->umin_value >= val)
5415 			return 0;
5416 		break;
5417 	case BPF_JSLT:
5418 		if (reg->smax_value < sval)
5419 			return 1;
5420 		else if (reg->smin_value >= sval)
5421 			return 0;
5422 		break;
5423 	case BPF_JGE:
5424 		if (reg->umin_value >= val)
5425 			return 1;
5426 		else if (reg->umax_value < val)
5427 			return 0;
5428 		break;
5429 	case BPF_JSGE:
5430 		if (reg->smin_value >= sval)
5431 			return 1;
5432 		else if (reg->smax_value < sval)
5433 			return 0;
5434 		break;
5435 	case BPF_JLE:
5436 		if (reg->umax_value <= val)
5437 			return 1;
5438 		else if (reg->umin_value > val)
5439 			return 0;
5440 		break;
5441 	case BPF_JSLE:
5442 		if (reg->smax_value <= sval)
5443 			return 1;
5444 		else if (reg->smin_value > sval)
5445 			return 0;
5446 		break;
5447 	}
5448 
5449 	return -1;
5450 }
5451 
5452 /* Generate min value of the high 32-bit from TNUM info. */
5453 static u64 gen_hi_min(struct tnum var)
5454 {
5455 	return var.value & ~0xffffffffULL;
5456 }
5457 
5458 /* Generate max value of the high 32-bit from TNUM info. */
5459 static u64 gen_hi_max(struct tnum var)
5460 {
5461 	return (var.value | var.mask) & ~0xffffffffULL;
5462 }
5463 
5464 /* Return true if VAL is compared with a s64 sign extended from s32, and they
5465  * are with the same signedness.
5466  */
5467 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
5468 {
5469 	return ((s32)sval >= 0 &&
5470 		reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
5471 	       ((s32)sval < 0 &&
5472 		reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
5473 }
5474 
5475 /* Adjusts the register min/max values in the case that the dst_reg is the
5476  * variable register that we are working on, and src_reg is a constant or we're
5477  * simply doing a BPF_K check.
5478  * In JEQ/JNE cases we also adjust the var_off values.
5479  */
5480 static void reg_set_min_max(struct bpf_reg_state *true_reg,
5481 			    struct bpf_reg_state *false_reg, u64 val,
5482 			    u8 opcode, bool is_jmp32)
5483 {
5484 	s64 sval;
5485 
5486 	/* If the dst_reg is a pointer, we can't learn anything about its
5487 	 * variable offset from the compare (unless src_reg were a pointer into
5488 	 * the same object, but we don't bother with that.
5489 	 * Since false_reg and true_reg have the same type by construction, we
5490 	 * only need to check one of them for pointerness.
5491 	 */
5492 	if (__is_pointer_value(false, false_reg))
5493 		return;
5494 
5495 	val = is_jmp32 ? (u32)val : val;
5496 	sval = is_jmp32 ? (s64)(s32)val : (s64)val;
5497 
5498 	switch (opcode) {
5499 	case BPF_JEQ:
5500 	case BPF_JNE:
5501 	{
5502 		struct bpf_reg_state *reg =
5503 			opcode == BPF_JEQ ? true_reg : false_reg;
5504 
5505 		/* For BPF_JEQ, if this is false we know nothing Jon Snow, but
5506 		 * if it is true we know the value for sure. Likewise for
5507 		 * BPF_JNE.
5508 		 */
5509 		if (is_jmp32) {
5510 			u64 old_v = reg->var_off.value;
5511 			u64 hi_mask = ~0xffffffffULL;
5512 
5513 			reg->var_off.value = (old_v & hi_mask) | val;
5514 			reg->var_off.mask &= hi_mask;
5515 		} else {
5516 			__mark_reg_known(reg, val);
5517 		}
5518 		break;
5519 	}
5520 	case BPF_JSET:
5521 		false_reg->var_off = tnum_and(false_reg->var_off,
5522 					      tnum_const(~val));
5523 		if (is_power_of_2(val))
5524 			true_reg->var_off = tnum_or(true_reg->var_off,
5525 						    tnum_const(val));
5526 		break;
5527 	case BPF_JGE:
5528 	case BPF_JGT:
5529 	{
5530 		u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
5531 		u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
5532 
5533 		if (is_jmp32) {
5534 			false_umax += gen_hi_max(false_reg->var_off);
5535 			true_umin += gen_hi_min(true_reg->var_off);
5536 		}
5537 		false_reg->umax_value = min(false_reg->umax_value, false_umax);
5538 		true_reg->umin_value = max(true_reg->umin_value, true_umin);
5539 		break;
5540 	}
5541 	case BPF_JSGE:
5542 	case BPF_JSGT:
5543 	{
5544 		s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
5545 		s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
5546 
5547 		/* If the full s64 was not sign-extended from s32 then don't
5548 		 * deduct further info.
5549 		 */
5550 		if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5551 			break;
5552 		false_reg->smax_value = min(false_reg->smax_value, false_smax);
5553 		true_reg->smin_value = max(true_reg->smin_value, true_smin);
5554 		break;
5555 	}
5556 	case BPF_JLE:
5557 	case BPF_JLT:
5558 	{
5559 		u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
5560 		u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
5561 
5562 		if (is_jmp32) {
5563 			false_umin += gen_hi_min(false_reg->var_off);
5564 			true_umax += gen_hi_max(true_reg->var_off);
5565 		}
5566 		false_reg->umin_value = max(false_reg->umin_value, false_umin);
5567 		true_reg->umax_value = min(true_reg->umax_value, true_umax);
5568 		break;
5569 	}
5570 	case BPF_JSLE:
5571 	case BPF_JSLT:
5572 	{
5573 		s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
5574 		s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
5575 
5576 		if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5577 			break;
5578 		false_reg->smin_value = max(false_reg->smin_value, false_smin);
5579 		true_reg->smax_value = min(true_reg->smax_value, true_smax);
5580 		break;
5581 	}
5582 	default:
5583 		break;
5584 	}
5585 
5586 	__reg_deduce_bounds(false_reg);
5587 	__reg_deduce_bounds(true_reg);
5588 	/* We might have learned some bits from the bounds. */
5589 	__reg_bound_offset(false_reg);
5590 	__reg_bound_offset(true_reg);
5591 	/* Intersecting with the old var_off might have improved our bounds
5592 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5593 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
5594 	 */
5595 	__update_reg_bounds(false_reg);
5596 	__update_reg_bounds(true_reg);
5597 }
5598 
5599 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
5600  * the variable reg.
5601  */
5602 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
5603 				struct bpf_reg_state *false_reg, u64 val,
5604 				u8 opcode, bool is_jmp32)
5605 {
5606 	s64 sval;
5607 
5608 	if (__is_pointer_value(false, false_reg))
5609 		return;
5610 
5611 	val = is_jmp32 ? (u32)val : val;
5612 	sval = is_jmp32 ? (s64)(s32)val : (s64)val;
5613 
5614 	switch (opcode) {
5615 	case BPF_JEQ:
5616 	case BPF_JNE:
5617 	{
5618 		struct bpf_reg_state *reg =
5619 			opcode == BPF_JEQ ? true_reg : false_reg;
5620 
5621 		if (is_jmp32) {
5622 			u64 old_v = reg->var_off.value;
5623 			u64 hi_mask = ~0xffffffffULL;
5624 
5625 			reg->var_off.value = (old_v & hi_mask) | val;
5626 			reg->var_off.mask &= hi_mask;
5627 		} else {
5628 			__mark_reg_known(reg, val);
5629 		}
5630 		break;
5631 	}
5632 	case BPF_JSET:
5633 		false_reg->var_off = tnum_and(false_reg->var_off,
5634 					      tnum_const(~val));
5635 		if (is_power_of_2(val))
5636 			true_reg->var_off = tnum_or(true_reg->var_off,
5637 						    tnum_const(val));
5638 		break;
5639 	case BPF_JGE:
5640 	case BPF_JGT:
5641 	{
5642 		u64 false_umin = opcode == BPF_JGT ? val    : val + 1;
5643 		u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
5644 
5645 		if (is_jmp32) {
5646 			false_umin += gen_hi_min(false_reg->var_off);
5647 			true_umax += gen_hi_max(true_reg->var_off);
5648 		}
5649 		false_reg->umin_value = max(false_reg->umin_value, false_umin);
5650 		true_reg->umax_value = min(true_reg->umax_value, true_umax);
5651 		break;
5652 	}
5653 	case BPF_JSGE:
5654 	case BPF_JSGT:
5655 	{
5656 		s64 false_smin = opcode == BPF_JSGT ? sval    : sval + 1;
5657 		s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
5658 
5659 		if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5660 			break;
5661 		false_reg->smin_value = max(false_reg->smin_value, false_smin);
5662 		true_reg->smax_value = min(true_reg->smax_value, true_smax);
5663 		break;
5664 	}
5665 	case BPF_JLE:
5666 	case BPF_JLT:
5667 	{
5668 		u64 false_umax = opcode == BPF_JLT ? val    : val - 1;
5669 		u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
5670 
5671 		if (is_jmp32) {
5672 			false_umax += gen_hi_max(false_reg->var_off);
5673 			true_umin += gen_hi_min(true_reg->var_off);
5674 		}
5675 		false_reg->umax_value = min(false_reg->umax_value, false_umax);
5676 		true_reg->umin_value = max(true_reg->umin_value, true_umin);
5677 		break;
5678 	}
5679 	case BPF_JSLE:
5680 	case BPF_JSLT:
5681 	{
5682 		s64 false_smax = opcode == BPF_JSLT ? sval    : sval - 1;
5683 		s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
5684 
5685 		if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5686 			break;
5687 		false_reg->smax_value = min(false_reg->smax_value, false_smax);
5688 		true_reg->smin_value = max(true_reg->smin_value, true_smin);
5689 		break;
5690 	}
5691 	default:
5692 		break;
5693 	}
5694 
5695 	__reg_deduce_bounds(false_reg);
5696 	__reg_deduce_bounds(true_reg);
5697 	/* We might have learned some bits from the bounds. */
5698 	__reg_bound_offset(false_reg);
5699 	__reg_bound_offset(true_reg);
5700 	/* Intersecting with the old var_off might have improved our bounds
5701 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5702 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
5703 	 */
5704 	__update_reg_bounds(false_reg);
5705 	__update_reg_bounds(true_reg);
5706 }
5707 
5708 /* Regs are known to be equal, so intersect their min/max/var_off */
5709 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5710 				  struct bpf_reg_state *dst_reg)
5711 {
5712 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5713 							dst_reg->umin_value);
5714 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5715 							dst_reg->umax_value);
5716 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5717 							dst_reg->smin_value);
5718 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5719 							dst_reg->smax_value);
5720 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5721 							     dst_reg->var_off);
5722 	/* We might have learned new bounds from the var_off. */
5723 	__update_reg_bounds(src_reg);
5724 	__update_reg_bounds(dst_reg);
5725 	/* We might have learned something about the sign bit. */
5726 	__reg_deduce_bounds(src_reg);
5727 	__reg_deduce_bounds(dst_reg);
5728 	/* We might have learned some bits from the bounds. */
5729 	__reg_bound_offset(src_reg);
5730 	__reg_bound_offset(dst_reg);
5731 	/* Intersecting with the old var_off might have improved our bounds
5732 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5733 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
5734 	 */
5735 	__update_reg_bounds(src_reg);
5736 	__update_reg_bounds(dst_reg);
5737 }
5738 
5739 static void reg_combine_min_max(struct bpf_reg_state *true_src,
5740 				struct bpf_reg_state *true_dst,
5741 				struct bpf_reg_state *false_src,
5742 				struct bpf_reg_state *false_dst,
5743 				u8 opcode)
5744 {
5745 	switch (opcode) {
5746 	case BPF_JEQ:
5747 		__reg_combine_min_max(true_src, true_dst);
5748 		break;
5749 	case BPF_JNE:
5750 		__reg_combine_min_max(false_src, false_dst);
5751 		break;
5752 	}
5753 }
5754 
5755 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5756 				 struct bpf_reg_state *reg, u32 id,
5757 				 bool is_null)
5758 {
5759 	if (reg_type_may_be_null(reg->type) && reg->id == id) {
5760 		/* Old offset (both fixed and variable parts) should
5761 		 * have been known-zero, because we don't allow pointer
5762 		 * arithmetic on pointers that might be NULL.
5763 		 */
5764 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5765 				 !tnum_equals_const(reg->var_off, 0) ||
5766 				 reg->off)) {
5767 			__mark_reg_known_zero(reg);
5768 			reg->off = 0;
5769 		}
5770 		if (is_null) {
5771 			reg->type = SCALAR_VALUE;
5772 		} else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5773 			if (reg->map_ptr->inner_map_meta) {
5774 				reg->type = CONST_PTR_TO_MAP;
5775 				reg->map_ptr = reg->map_ptr->inner_map_meta;
5776 			} else if (reg->map_ptr->map_type ==
5777 				   BPF_MAP_TYPE_XSKMAP) {
5778 				reg->type = PTR_TO_XDP_SOCK;
5779 			} else {
5780 				reg->type = PTR_TO_MAP_VALUE;
5781 			}
5782 		} else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5783 			reg->type = PTR_TO_SOCKET;
5784 		} else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5785 			reg->type = PTR_TO_SOCK_COMMON;
5786 		} else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5787 			reg->type = PTR_TO_TCP_SOCK;
5788 		}
5789 		if (is_null) {
5790 			/* We don't need id and ref_obj_id from this point
5791 			 * onwards anymore, thus we should better reset it,
5792 			 * so that state pruning has chances to take effect.
5793 			 */
5794 			reg->id = 0;
5795 			reg->ref_obj_id = 0;
5796 		} else if (!reg_may_point_to_spin_lock(reg)) {
5797 			/* For not-NULL ptr, reg->ref_obj_id will be reset
5798 			 * in release_reg_references().
5799 			 *
5800 			 * reg->id is still used by spin_lock ptr. Other
5801 			 * than spin_lock ptr type, reg->id can be reset.
5802 			 */
5803 			reg->id = 0;
5804 		}
5805 	}
5806 }
5807 
5808 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5809 				    bool is_null)
5810 {
5811 	struct bpf_reg_state *reg;
5812 	int i;
5813 
5814 	for (i = 0; i < MAX_BPF_REG; i++)
5815 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5816 
5817 	bpf_for_each_spilled_reg(i, state, reg) {
5818 		if (!reg)
5819 			continue;
5820 		mark_ptr_or_null_reg(state, reg, id, is_null);
5821 	}
5822 }
5823 
5824 /* The logic is similar to find_good_pkt_pointers(), both could eventually
5825  * be folded together at some point.
5826  */
5827 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
5828 				  bool is_null)
5829 {
5830 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5831 	struct bpf_reg_state *regs = state->regs;
5832 	u32 ref_obj_id = regs[regno].ref_obj_id;
5833 	u32 id = regs[regno].id;
5834 	int i;
5835 
5836 	if (ref_obj_id && ref_obj_id == id && is_null)
5837 		/* regs[regno] is in the " == NULL" branch.
5838 		 * No one could have freed the reference state before
5839 		 * doing the NULL check.
5840 		 */
5841 		WARN_ON_ONCE(release_reference_state(state, id));
5842 
5843 	for (i = 0; i <= vstate->curframe; i++)
5844 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
5845 }
5846 
5847 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
5848 				   struct bpf_reg_state *dst_reg,
5849 				   struct bpf_reg_state *src_reg,
5850 				   struct bpf_verifier_state *this_branch,
5851 				   struct bpf_verifier_state *other_branch)
5852 {
5853 	if (BPF_SRC(insn->code) != BPF_X)
5854 		return false;
5855 
5856 	/* Pointers are always 64-bit. */
5857 	if (BPF_CLASS(insn->code) == BPF_JMP32)
5858 		return false;
5859 
5860 	switch (BPF_OP(insn->code)) {
5861 	case BPF_JGT:
5862 		if ((dst_reg->type == PTR_TO_PACKET &&
5863 		     src_reg->type == PTR_TO_PACKET_END) ||
5864 		    (dst_reg->type == PTR_TO_PACKET_META &&
5865 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5866 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
5867 			find_good_pkt_pointers(this_branch, dst_reg,
5868 					       dst_reg->type, false);
5869 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
5870 			    src_reg->type == PTR_TO_PACKET) ||
5871 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5872 			    src_reg->type == PTR_TO_PACKET_META)) {
5873 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
5874 			find_good_pkt_pointers(other_branch, src_reg,
5875 					       src_reg->type, true);
5876 		} else {
5877 			return false;
5878 		}
5879 		break;
5880 	case BPF_JLT:
5881 		if ((dst_reg->type == PTR_TO_PACKET &&
5882 		     src_reg->type == PTR_TO_PACKET_END) ||
5883 		    (dst_reg->type == PTR_TO_PACKET_META &&
5884 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5885 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
5886 			find_good_pkt_pointers(other_branch, dst_reg,
5887 					       dst_reg->type, true);
5888 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
5889 			    src_reg->type == PTR_TO_PACKET) ||
5890 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5891 			    src_reg->type == PTR_TO_PACKET_META)) {
5892 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
5893 			find_good_pkt_pointers(this_branch, src_reg,
5894 					       src_reg->type, false);
5895 		} else {
5896 			return false;
5897 		}
5898 		break;
5899 	case BPF_JGE:
5900 		if ((dst_reg->type == PTR_TO_PACKET &&
5901 		     src_reg->type == PTR_TO_PACKET_END) ||
5902 		    (dst_reg->type == PTR_TO_PACKET_META &&
5903 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5904 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
5905 			find_good_pkt_pointers(this_branch, dst_reg,
5906 					       dst_reg->type, true);
5907 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
5908 			    src_reg->type == PTR_TO_PACKET) ||
5909 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5910 			    src_reg->type == PTR_TO_PACKET_META)) {
5911 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
5912 			find_good_pkt_pointers(other_branch, src_reg,
5913 					       src_reg->type, false);
5914 		} else {
5915 			return false;
5916 		}
5917 		break;
5918 	case BPF_JLE:
5919 		if ((dst_reg->type == PTR_TO_PACKET &&
5920 		     src_reg->type == PTR_TO_PACKET_END) ||
5921 		    (dst_reg->type == PTR_TO_PACKET_META &&
5922 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5923 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
5924 			find_good_pkt_pointers(other_branch, dst_reg,
5925 					       dst_reg->type, false);
5926 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
5927 			    src_reg->type == PTR_TO_PACKET) ||
5928 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5929 			    src_reg->type == PTR_TO_PACKET_META)) {
5930 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
5931 			find_good_pkt_pointers(this_branch, src_reg,
5932 					       src_reg->type, true);
5933 		} else {
5934 			return false;
5935 		}
5936 		break;
5937 	default:
5938 		return false;
5939 	}
5940 
5941 	return true;
5942 }
5943 
5944 static int check_cond_jmp_op(struct bpf_verifier_env *env,
5945 			     struct bpf_insn *insn, int *insn_idx)
5946 {
5947 	struct bpf_verifier_state *this_branch = env->cur_state;
5948 	struct bpf_verifier_state *other_branch;
5949 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
5950 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
5951 	u8 opcode = BPF_OP(insn->code);
5952 	bool is_jmp32;
5953 	int pred = -1;
5954 	int err;
5955 
5956 	/* Only conditional jumps are expected to reach here. */
5957 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
5958 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
5959 		return -EINVAL;
5960 	}
5961 
5962 	if (BPF_SRC(insn->code) == BPF_X) {
5963 		if (insn->imm != 0) {
5964 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
5965 			return -EINVAL;
5966 		}
5967 
5968 		/* check src1 operand */
5969 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
5970 		if (err)
5971 			return err;
5972 
5973 		if (is_pointer_value(env, insn->src_reg)) {
5974 			verbose(env, "R%d pointer comparison prohibited\n",
5975 				insn->src_reg);
5976 			return -EACCES;
5977 		}
5978 		src_reg = &regs[insn->src_reg];
5979 	} else {
5980 		if (insn->src_reg != BPF_REG_0) {
5981 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
5982 			return -EINVAL;
5983 		}
5984 	}
5985 
5986 	/* check src2 operand */
5987 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5988 	if (err)
5989 		return err;
5990 
5991 	dst_reg = &regs[insn->dst_reg];
5992 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
5993 
5994 	if (BPF_SRC(insn->code) == BPF_K)
5995 		pred = is_branch_taken(dst_reg, insn->imm,
5996 				       opcode, is_jmp32);
5997 	else if (src_reg->type == SCALAR_VALUE &&
5998 		 tnum_is_const(src_reg->var_off))
5999 		pred = is_branch_taken(dst_reg, src_reg->var_off.value,
6000 				       opcode, is_jmp32);
6001 	if (pred >= 0) {
6002 		err = mark_chain_precision(env, insn->dst_reg);
6003 		if (BPF_SRC(insn->code) == BPF_X && !err)
6004 			err = mark_chain_precision(env, insn->src_reg);
6005 		if (err)
6006 			return err;
6007 	}
6008 	if (pred == 1) {
6009 		/* only follow the goto, ignore fall-through */
6010 		*insn_idx += insn->off;
6011 		return 0;
6012 	} else if (pred == 0) {
6013 		/* only follow fall-through branch, since
6014 		 * that's where the program will go
6015 		 */
6016 		return 0;
6017 	}
6018 
6019 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6020 				  false);
6021 	if (!other_branch)
6022 		return -EFAULT;
6023 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
6024 
6025 	/* detect if we are comparing against a constant value so we can adjust
6026 	 * our min/max values for our dst register.
6027 	 * this is only legit if both are scalars (or pointers to the same
6028 	 * object, I suppose, but we don't support that right now), because
6029 	 * otherwise the different base pointers mean the offsets aren't
6030 	 * comparable.
6031 	 */
6032 	if (BPF_SRC(insn->code) == BPF_X) {
6033 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6034 		struct bpf_reg_state lo_reg0 = *dst_reg;
6035 		struct bpf_reg_state lo_reg1 = *src_reg;
6036 		struct bpf_reg_state *src_lo, *dst_lo;
6037 
6038 		dst_lo = &lo_reg0;
6039 		src_lo = &lo_reg1;
6040 		coerce_reg_to_size(dst_lo, 4);
6041 		coerce_reg_to_size(src_lo, 4);
6042 
6043 		if (dst_reg->type == SCALAR_VALUE &&
6044 		    src_reg->type == SCALAR_VALUE) {
6045 			if (tnum_is_const(src_reg->var_off) ||
6046 			    (is_jmp32 && tnum_is_const(src_lo->var_off)))
6047 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
6048 						dst_reg,
6049 						is_jmp32
6050 						? src_lo->var_off.value
6051 						: src_reg->var_off.value,
6052 						opcode, is_jmp32);
6053 			else if (tnum_is_const(dst_reg->var_off) ||
6054 				 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
6055 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
6056 						    src_reg,
6057 						    is_jmp32
6058 						    ? dst_lo->var_off.value
6059 						    : dst_reg->var_off.value,
6060 						    opcode, is_jmp32);
6061 			else if (!is_jmp32 &&
6062 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
6063 				/* Comparing for equality, we can combine knowledge */
6064 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
6065 						    &other_branch_regs[insn->dst_reg],
6066 						    src_reg, dst_reg, opcode);
6067 		}
6068 	} else if (dst_reg->type == SCALAR_VALUE) {
6069 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
6070 					dst_reg, insn->imm, opcode, is_jmp32);
6071 	}
6072 
6073 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6074 	 * NOTE: these optimizations below are related with pointer comparison
6075 	 *       which will never be JMP32.
6076 	 */
6077 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
6078 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
6079 	    reg_type_may_be_null(dst_reg->type)) {
6080 		/* Mark all identical registers in each branch as either
6081 		 * safe or unknown depending R == 0 or R != 0 conditional.
6082 		 */
6083 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6084 				      opcode == BPF_JNE);
6085 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6086 				      opcode == BPF_JEQ);
6087 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
6088 					   this_branch, other_branch) &&
6089 		   is_pointer_value(env, insn->dst_reg)) {
6090 		verbose(env, "R%d pointer comparison prohibited\n",
6091 			insn->dst_reg);
6092 		return -EACCES;
6093 	}
6094 	if (env->log.level & BPF_LOG_LEVEL)
6095 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
6096 	return 0;
6097 }
6098 
6099 /* verify BPF_LD_IMM64 instruction */
6100 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
6101 {
6102 	struct bpf_insn_aux_data *aux = cur_aux(env);
6103 	struct bpf_reg_state *regs = cur_regs(env);
6104 	struct bpf_map *map;
6105 	int err;
6106 
6107 	if (BPF_SIZE(insn->code) != BPF_DW) {
6108 		verbose(env, "invalid BPF_LD_IMM insn\n");
6109 		return -EINVAL;
6110 	}
6111 	if (insn->off != 0) {
6112 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
6113 		return -EINVAL;
6114 	}
6115 
6116 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
6117 	if (err)
6118 		return err;
6119 
6120 	if (insn->src_reg == 0) {
6121 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6122 
6123 		regs[insn->dst_reg].type = SCALAR_VALUE;
6124 		__mark_reg_known(&regs[insn->dst_reg], imm);
6125 		return 0;
6126 	}
6127 
6128 	map = env->used_maps[aux->map_index];
6129 	mark_reg_known_zero(env, regs, insn->dst_reg);
6130 	regs[insn->dst_reg].map_ptr = map;
6131 
6132 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6133 		regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6134 		regs[insn->dst_reg].off = aux->map_off;
6135 		if (map_value_has_spin_lock(map))
6136 			regs[insn->dst_reg].id = ++env->id_gen;
6137 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6138 		regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6139 	} else {
6140 		verbose(env, "bpf verifier is misconfigured\n");
6141 		return -EINVAL;
6142 	}
6143 
6144 	return 0;
6145 }
6146 
6147 static bool may_access_skb(enum bpf_prog_type type)
6148 {
6149 	switch (type) {
6150 	case BPF_PROG_TYPE_SOCKET_FILTER:
6151 	case BPF_PROG_TYPE_SCHED_CLS:
6152 	case BPF_PROG_TYPE_SCHED_ACT:
6153 		return true;
6154 	default:
6155 		return false;
6156 	}
6157 }
6158 
6159 /* verify safety of LD_ABS|LD_IND instructions:
6160  * - they can only appear in the programs where ctx == skb
6161  * - since they are wrappers of function calls, they scratch R1-R5 registers,
6162  *   preserve R6-R9, and store return value into R0
6163  *
6164  * Implicit input:
6165  *   ctx == skb == R6 == CTX
6166  *
6167  * Explicit input:
6168  *   SRC == any register
6169  *   IMM == 32-bit immediate
6170  *
6171  * Output:
6172  *   R0 - 8/16/32-bit skb data converted to cpu endianness
6173  */
6174 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
6175 {
6176 	struct bpf_reg_state *regs = cur_regs(env);
6177 	u8 mode = BPF_MODE(insn->code);
6178 	int i, err;
6179 
6180 	if (!may_access_skb(env->prog->type)) {
6181 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
6182 		return -EINVAL;
6183 	}
6184 
6185 	if (!env->ops->gen_ld_abs) {
6186 		verbose(env, "bpf verifier is misconfigured\n");
6187 		return -EINVAL;
6188 	}
6189 
6190 	if (env->subprog_cnt > 1) {
6191 		/* when program has LD_ABS insn JITs and interpreter assume
6192 		 * that r1 == ctx == skb which is not the case for callees
6193 		 * that can have arbitrary arguments. It's problematic
6194 		 * for main prog as well since JITs would need to analyze
6195 		 * all functions in order to make proper register save/restore
6196 		 * decisions in the main prog. Hence disallow LD_ABS with calls
6197 		 */
6198 		verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6199 		return -EINVAL;
6200 	}
6201 
6202 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
6203 	    BPF_SIZE(insn->code) == BPF_DW ||
6204 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
6205 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
6206 		return -EINVAL;
6207 	}
6208 
6209 	/* check whether implicit source operand (register R6) is readable */
6210 	err = check_reg_arg(env, BPF_REG_6, SRC_OP);
6211 	if (err)
6212 		return err;
6213 
6214 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6215 	 * gen_ld_abs() may terminate the program at runtime, leading to
6216 	 * reference leak.
6217 	 */
6218 	err = check_reference_leak(env);
6219 	if (err) {
6220 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6221 		return err;
6222 	}
6223 
6224 	if (env->cur_state->active_spin_lock) {
6225 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6226 		return -EINVAL;
6227 	}
6228 
6229 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
6230 		verbose(env,
6231 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
6232 		return -EINVAL;
6233 	}
6234 
6235 	if (mode == BPF_IND) {
6236 		/* check explicit source operand */
6237 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
6238 		if (err)
6239 			return err;
6240 	}
6241 
6242 	/* reset caller saved regs to unreadable */
6243 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6244 		mark_reg_not_init(env, regs, caller_saved[i]);
6245 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6246 	}
6247 
6248 	/* mark destination R0 register as readable, since it contains
6249 	 * the value fetched from the packet.
6250 	 * Already marked as written above.
6251 	 */
6252 	mark_reg_unknown(env, regs, BPF_REG_0);
6253 	/* ld_abs load up to 32-bit skb data. */
6254 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
6255 	return 0;
6256 }
6257 
6258 static int check_return_code(struct bpf_verifier_env *env)
6259 {
6260 	struct tnum enforce_attach_type_range = tnum_unknown;
6261 	struct bpf_reg_state *reg;
6262 	struct tnum range = tnum_range(0, 1);
6263 
6264 	switch (env->prog->type) {
6265 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6266 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
6267 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
6268 			range = tnum_range(1, 1);
6269 		break;
6270 	case BPF_PROG_TYPE_CGROUP_SKB:
6271 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
6272 			range = tnum_range(0, 3);
6273 			enforce_attach_type_range = tnum_range(2, 3);
6274 		}
6275 		break;
6276 	case BPF_PROG_TYPE_CGROUP_SOCK:
6277 	case BPF_PROG_TYPE_SOCK_OPS:
6278 	case BPF_PROG_TYPE_CGROUP_DEVICE:
6279 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
6280 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6281 		break;
6282 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6283 		if (!env->prog->aux->attach_btf_id)
6284 			return 0;
6285 		range = tnum_const(0);
6286 		break;
6287 	default:
6288 		return 0;
6289 	}
6290 
6291 	reg = cur_regs(env) + BPF_REG_0;
6292 	if (reg->type != SCALAR_VALUE) {
6293 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
6294 			reg_type_str[reg->type]);
6295 		return -EINVAL;
6296 	}
6297 
6298 	if (!tnum_in(range, reg->var_off)) {
6299 		char tn_buf[48];
6300 
6301 		verbose(env, "At program exit the register R0 ");
6302 		if (!tnum_is_unknown(reg->var_off)) {
6303 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6304 			verbose(env, "has value %s", tn_buf);
6305 		} else {
6306 			verbose(env, "has unknown scalar value");
6307 		}
6308 		tnum_strn(tn_buf, sizeof(tn_buf), range);
6309 		verbose(env, " should have been in %s\n", tn_buf);
6310 		return -EINVAL;
6311 	}
6312 
6313 	if (!tnum_is_unknown(enforce_attach_type_range) &&
6314 	    tnum_in(enforce_attach_type_range, reg->var_off))
6315 		env->prog->enforce_expected_attach_type = 1;
6316 	return 0;
6317 }
6318 
6319 /* non-recursive DFS pseudo code
6320  * 1  procedure DFS-iterative(G,v):
6321  * 2      label v as discovered
6322  * 3      let S be a stack
6323  * 4      S.push(v)
6324  * 5      while S is not empty
6325  * 6            t <- S.pop()
6326  * 7            if t is what we're looking for:
6327  * 8                return t
6328  * 9            for all edges e in G.adjacentEdges(t) do
6329  * 10               if edge e is already labelled
6330  * 11                   continue with the next edge
6331  * 12               w <- G.adjacentVertex(t,e)
6332  * 13               if vertex w is not discovered and not explored
6333  * 14                   label e as tree-edge
6334  * 15                   label w as discovered
6335  * 16                   S.push(w)
6336  * 17                   continue at 5
6337  * 18               else if vertex w is discovered
6338  * 19                   label e as back-edge
6339  * 20               else
6340  * 21                   // vertex w is explored
6341  * 22                   label e as forward- or cross-edge
6342  * 23           label t as explored
6343  * 24           S.pop()
6344  *
6345  * convention:
6346  * 0x10 - discovered
6347  * 0x11 - discovered and fall-through edge labelled
6348  * 0x12 - discovered and fall-through and branch edges labelled
6349  * 0x20 - explored
6350  */
6351 
6352 enum {
6353 	DISCOVERED = 0x10,
6354 	EXPLORED = 0x20,
6355 	FALLTHROUGH = 1,
6356 	BRANCH = 2,
6357 };
6358 
6359 static u32 state_htab_size(struct bpf_verifier_env *env)
6360 {
6361 	return env->prog->len;
6362 }
6363 
6364 static struct bpf_verifier_state_list **explored_state(
6365 					struct bpf_verifier_env *env,
6366 					int idx)
6367 {
6368 	struct bpf_verifier_state *cur = env->cur_state;
6369 	struct bpf_func_state *state = cur->frame[cur->curframe];
6370 
6371 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
6372 }
6373 
6374 static void init_explored_state(struct bpf_verifier_env *env, int idx)
6375 {
6376 	env->insn_aux_data[idx].prune_point = true;
6377 }
6378 
6379 /* t, w, e - match pseudo-code above:
6380  * t - index of current instruction
6381  * w - next instruction
6382  * e - edge
6383  */
6384 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
6385 		     bool loop_ok)
6386 {
6387 	int *insn_stack = env->cfg.insn_stack;
6388 	int *insn_state = env->cfg.insn_state;
6389 
6390 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
6391 		return 0;
6392 
6393 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
6394 		return 0;
6395 
6396 	if (w < 0 || w >= env->prog->len) {
6397 		verbose_linfo(env, t, "%d: ", t);
6398 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
6399 		return -EINVAL;
6400 	}
6401 
6402 	if (e == BRANCH)
6403 		/* mark branch target for state pruning */
6404 		init_explored_state(env, w);
6405 
6406 	if (insn_state[w] == 0) {
6407 		/* tree-edge */
6408 		insn_state[t] = DISCOVERED | e;
6409 		insn_state[w] = DISCOVERED;
6410 		if (env->cfg.cur_stack >= env->prog->len)
6411 			return -E2BIG;
6412 		insn_stack[env->cfg.cur_stack++] = w;
6413 		return 1;
6414 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
6415 		if (loop_ok && env->allow_ptr_leaks)
6416 			return 0;
6417 		verbose_linfo(env, t, "%d: ", t);
6418 		verbose_linfo(env, w, "%d: ", w);
6419 		verbose(env, "back-edge from insn %d to %d\n", t, w);
6420 		return -EINVAL;
6421 	} else if (insn_state[w] == EXPLORED) {
6422 		/* forward- or cross-edge */
6423 		insn_state[t] = DISCOVERED | e;
6424 	} else {
6425 		verbose(env, "insn state internal bug\n");
6426 		return -EFAULT;
6427 	}
6428 	return 0;
6429 }
6430 
6431 /* non-recursive depth-first-search to detect loops in BPF program
6432  * loop == back-edge in directed graph
6433  */
6434 static int check_cfg(struct bpf_verifier_env *env)
6435 {
6436 	struct bpf_insn *insns = env->prog->insnsi;
6437 	int insn_cnt = env->prog->len;
6438 	int *insn_stack, *insn_state;
6439 	int ret = 0;
6440 	int i, t;
6441 
6442 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
6443 	if (!insn_state)
6444 		return -ENOMEM;
6445 
6446 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
6447 	if (!insn_stack) {
6448 		kvfree(insn_state);
6449 		return -ENOMEM;
6450 	}
6451 
6452 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
6453 	insn_stack[0] = 0; /* 0 is the first instruction */
6454 	env->cfg.cur_stack = 1;
6455 
6456 peek_stack:
6457 	if (env->cfg.cur_stack == 0)
6458 		goto check_state;
6459 	t = insn_stack[env->cfg.cur_stack - 1];
6460 
6461 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
6462 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
6463 		u8 opcode = BPF_OP(insns[t].code);
6464 
6465 		if (opcode == BPF_EXIT) {
6466 			goto mark_explored;
6467 		} else if (opcode == BPF_CALL) {
6468 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
6469 			if (ret == 1)
6470 				goto peek_stack;
6471 			else if (ret < 0)
6472 				goto err_free;
6473 			if (t + 1 < insn_cnt)
6474 				init_explored_state(env, t + 1);
6475 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
6476 				init_explored_state(env, t);
6477 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
6478 						env, false);
6479 				if (ret == 1)
6480 					goto peek_stack;
6481 				else if (ret < 0)
6482 					goto err_free;
6483 			}
6484 		} else if (opcode == BPF_JA) {
6485 			if (BPF_SRC(insns[t].code) != BPF_K) {
6486 				ret = -EINVAL;
6487 				goto err_free;
6488 			}
6489 			/* unconditional jump with single edge */
6490 			ret = push_insn(t, t + insns[t].off + 1,
6491 					FALLTHROUGH, env, true);
6492 			if (ret == 1)
6493 				goto peek_stack;
6494 			else if (ret < 0)
6495 				goto err_free;
6496 			/* unconditional jmp is not a good pruning point,
6497 			 * but it's marked, since backtracking needs
6498 			 * to record jmp history in is_state_visited().
6499 			 */
6500 			init_explored_state(env, t + insns[t].off + 1);
6501 			/* tell verifier to check for equivalent states
6502 			 * after every call and jump
6503 			 */
6504 			if (t + 1 < insn_cnt)
6505 				init_explored_state(env, t + 1);
6506 		} else {
6507 			/* conditional jump with two edges */
6508 			init_explored_state(env, t);
6509 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
6510 			if (ret == 1)
6511 				goto peek_stack;
6512 			else if (ret < 0)
6513 				goto err_free;
6514 
6515 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
6516 			if (ret == 1)
6517 				goto peek_stack;
6518 			else if (ret < 0)
6519 				goto err_free;
6520 		}
6521 	} else {
6522 		/* all other non-branch instructions with single
6523 		 * fall-through edge
6524 		 */
6525 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
6526 		if (ret == 1)
6527 			goto peek_stack;
6528 		else if (ret < 0)
6529 			goto err_free;
6530 	}
6531 
6532 mark_explored:
6533 	insn_state[t] = EXPLORED;
6534 	if (env->cfg.cur_stack-- <= 0) {
6535 		verbose(env, "pop stack internal bug\n");
6536 		ret = -EFAULT;
6537 		goto err_free;
6538 	}
6539 	goto peek_stack;
6540 
6541 check_state:
6542 	for (i = 0; i < insn_cnt; i++) {
6543 		if (insn_state[i] != EXPLORED) {
6544 			verbose(env, "unreachable insn %d\n", i);
6545 			ret = -EINVAL;
6546 			goto err_free;
6547 		}
6548 	}
6549 	ret = 0; /* cfg looks good */
6550 
6551 err_free:
6552 	kvfree(insn_state);
6553 	kvfree(insn_stack);
6554 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
6555 	return ret;
6556 }
6557 
6558 /* The minimum supported BTF func info size */
6559 #define MIN_BPF_FUNCINFO_SIZE	8
6560 #define MAX_FUNCINFO_REC_SIZE	252
6561 
6562 static int check_btf_func(struct bpf_verifier_env *env,
6563 			  const union bpf_attr *attr,
6564 			  union bpf_attr __user *uattr)
6565 {
6566 	u32 i, nfuncs, urec_size, min_size;
6567 	u32 krec_size = sizeof(struct bpf_func_info);
6568 	struct bpf_func_info *krecord;
6569 	const struct btf_type *type;
6570 	struct bpf_prog *prog;
6571 	const struct btf *btf;
6572 	void __user *urecord;
6573 	u32 prev_offset = 0;
6574 	int ret = 0;
6575 
6576 	nfuncs = attr->func_info_cnt;
6577 	if (!nfuncs)
6578 		return 0;
6579 
6580 	if (nfuncs != env->subprog_cnt) {
6581 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
6582 		return -EINVAL;
6583 	}
6584 
6585 	urec_size = attr->func_info_rec_size;
6586 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
6587 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
6588 	    urec_size % sizeof(u32)) {
6589 		verbose(env, "invalid func info rec size %u\n", urec_size);
6590 		return -EINVAL;
6591 	}
6592 
6593 	prog = env->prog;
6594 	btf = prog->aux->btf;
6595 
6596 	urecord = u64_to_user_ptr(attr->func_info);
6597 	min_size = min_t(u32, krec_size, urec_size);
6598 
6599 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
6600 	if (!krecord)
6601 		return -ENOMEM;
6602 
6603 	for (i = 0; i < nfuncs; i++) {
6604 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
6605 		if (ret) {
6606 			if (ret == -E2BIG) {
6607 				verbose(env, "nonzero tailing record in func info");
6608 				/* set the size kernel expects so loader can zero
6609 				 * out the rest of the record.
6610 				 */
6611 				if (put_user(min_size, &uattr->func_info_rec_size))
6612 					ret = -EFAULT;
6613 			}
6614 			goto err_free;
6615 		}
6616 
6617 		if (copy_from_user(&krecord[i], urecord, min_size)) {
6618 			ret = -EFAULT;
6619 			goto err_free;
6620 		}
6621 
6622 		/* check insn_off */
6623 		if (i == 0) {
6624 			if (krecord[i].insn_off) {
6625 				verbose(env,
6626 					"nonzero insn_off %u for the first func info record",
6627 					krecord[i].insn_off);
6628 				ret = -EINVAL;
6629 				goto err_free;
6630 			}
6631 		} else if (krecord[i].insn_off <= prev_offset) {
6632 			verbose(env,
6633 				"same or smaller insn offset (%u) than previous func info record (%u)",
6634 				krecord[i].insn_off, prev_offset);
6635 			ret = -EINVAL;
6636 			goto err_free;
6637 		}
6638 
6639 		if (env->subprog_info[i].start != krecord[i].insn_off) {
6640 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
6641 			ret = -EINVAL;
6642 			goto err_free;
6643 		}
6644 
6645 		/* check type_id */
6646 		type = btf_type_by_id(btf, krecord[i].type_id);
6647 		if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
6648 			verbose(env, "invalid type id %d in func info",
6649 				krecord[i].type_id);
6650 			ret = -EINVAL;
6651 			goto err_free;
6652 		}
6653 
6654 		prev_offset = krecord[i].insn_off;
6655 		urecord += urec_size;
6656 	}
6657 
6658 	prog->aux->func_info = krecord;
6659 	prog->aux->func_info_cnt = nfuncs;
6660 	return 0;
6661 
6662 err_free:
6663 	kvfree(krecord);
6664 	return ret;
6665 }
6666 
6667 static void adjust_btf_func(struct bpf_verifier_env *env)
6668 {
6669 	int i;
6670 
6671 	if (!env->prog->aux->func_info)
6672 		return;
6673 
6674 	for (i = 0; i < env->subprog_cnt; i++)
6675 		env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
6676 }
6677 
6678 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
6679 		sizeof(((struct bpf_line_info *)(0))->line_col))
6680 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
6681 
6682 static int check_btf_line(struct bpf_verifier_env *env,
6683 			  const union bpf_attr *attr,
6684 			  union bpf_attr __user *uattr)
6685 {
6686 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
6687 	struct bpf_subprog_info *sub;
6688 	struct bpf_line_info *linfo;
6689 	struct bpf_prog *prog;
6690 	const struct btf *btf;
6691 	void __user *ulinfo;
6692 	int err;
6693 
6694 	nr_linfo = attr->line_info_cnt;
6695 	if (!nr_linfo)
6696 		return 0;
6697 
6698 	rec_size = attr->line_info_rec_size;
6699 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
6700 	    rec_size > MAX_LINEINFO_REC_SIZE ||
6701 	    rec_size & (sizeof(u32) - 1))
6702 		return -EINVAL;
6703 
6704 	/* Need to zero it in case the userspace may
6705 	 * pass in a smaller bpf_line_info object.
6706 	 */
6707 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6708 			 GFP_KERNEL | __GFP_NOWARN);
6709 	if (!linfo)
6710 		return -ENOMEM;
6711 
6712 	prog = env->prog;
6713 	btf = prog->aux->btf;
6714 
6715 	s = 0;
6716 	sub = env->subprog_info;
6717 	ulinfo = u64_to_user_ptr(attr->line_info);
6718 	expected_size = sizeof(struct bpf_line_info);
6719 	ncopy = min_t(u32, expected_size, rec_size);
6720 	for (i = 0; i < nr_linfo; i++) {
6721 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6722 		if (err) {
6723 			if (err == -E2BIG) {
6724 				verbose(env, "nonzero tailing record in line_info");
6725 				if (put_user(expected_size,
6726 					     &uattr->line_info_rec_size))
6727 					err = -EFAULT;
6728 			}
6729 			goto err_free;
6730 		}
6731 
6732 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6733 			err = -EFAULT;
6734 			goto err_free;
6735 		}
6736 
6737 		/*
6738 		 * Check insn_off to ensure
6739 		 * 1) strictly increasing AND
6740 		 * 2) bounded by prog->len
6741 		 *
6742 		 * The linfo[0].insn_off == 0 check logically falls into
6743 		 * the later "missing bpf_line_info for func..." case
6744 		 * because the first linfo[0].insn_off must be the
6745 		 * first sub also and the first sub must have
6746 		 * subprog_info[0].start == 0.
6747 		 */
6748 		if ((i && linfo[i].insn_off <= prev_offset) ||
6749 		    linfo[i].insn_off >= prog->len) {
6750 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6751 				i, linfo[i].insn_off, prev_offset,
6752 				prog->len);
6753 			err = -EINVAL;
6754 			goto err_free;
6755 		}
6756 
6757 		if (!prog->insnsi[linfo[i].insn_off].code) {
6758 			verbose(env,
6759 				"Invalid insn code at line_info[%u].insn_off\n",
6760 				i);
6761 			err = -EINVAL;
6762 			goto err_free;
6763 		}
6764 
6765 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6766 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
6767 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6768 			err = -EINVAL;
6769 			goto err_free;
6770 		}
6771 
6772 		if (s != env->subprog_cnt) {
6773 			if (linfo[i].insn_off == sub[s].start) {
6774 				sub[s].linfo_idx = i;
6775 				s++;
6776 			} else if (sub[s].start < linfo[i].insn_off) {
6777 				verbose(env, "missing bpf_line_info for func#%u\n", s);
6778 				err = -EINVAL;
6779 				goto err_free;
6780 			}
6781 		}
6782 
6783 		prev_offset = linfo[i].insn_off;
6784 		ulinfo += rec_size;
6785 	}
6786 
6787 	if (s != env->subprog_cnt) {
6788 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
6789 			env->subprog_cnt - s, s);
6790 		err = -EINVAL;
6791 		goto err_free;
6792 	}
6793 
6794 	prog->aux->linfo = linfo;
6795 	prog->aux->nr_linfo = nr_linfo;
6796 
6797 	return 0;
6798 
6799 err_free:
6800 	kvfree(linfo);
6801 	return err;
6802 }
6803 
6804 static int check_btf_info(struct bpf_verifier_env *env,
6805 			  const union bpf_attr *attr,
6806 			  union bpf_attr __user *uattr)
6807 {
6808 	struct btf *btf;
6809 	int err;
6810 
6811 	if (!attr->func_info_cnt && !attr->line_info_cnt)
6812 		return 0;
6813 
6814 	btf = btf_get_by_fd(attr->prog_btf_fd);
6815 	if (IS_ERR(btf))
6816 		return PTR_ERR(btf);
6817 	env->prog->aux->btf = btf;
6818 
6819 	err = check_btf_func(env, attr, uattr);
6820 	if (err)
6821 		return err;
6822 
6823 	err = check_btf_line(env, attr, uattr);
6824 	if (err)
6825 		return err;
6826 
6827 	return 0;
6828 }
6829 
6830 /* check %cur's range satisfies %old's */
6831 static bool range_within(struct bpf_reg_state *old,
6832 			 struct bpf_reg_state *cur)
6833 {
6834 	return old->umin_value <= cur->umin_value &&
6835 	       old->umax_value >= cur->umax_value &&
6836 	       old->smin_value <= cur->smin_value &&
6837 	       old->smax_value >= cur->smax_value;
6838 }
6839 
6840 /* Maximum number of register states that can exist at once */
6841 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
6842 struct idpair {
6843 	u32 old;
6844 	u32 cur;
6845 };
6846 
6847 /* If in the old state two registers had the same id, then they need to have
6848  * the same id in the new state as well.  But that id could be different from
6849  * the old state, so we need to track the mapping from old to new ids.
6850  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
6851  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
6852  * regs with a different old id could still have new id 9, we don't care about
6853  * that.
6854  * So we look through our idmap to see if this old id has been seen before.  If
6855  * so, we require the new id to match; otherwise, we add the id pair to the map.
6856  */
6857 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
6858 {
6859 	unsigned int i;
6860 
6861 	for (i = 0; i < ID_MAP_SIZE; i++) {
6862 		if (!idmap[i].old) {
6863 			/* Reached an empty slot; haven't seen this id before */
6864 			idmap[i].old = old_id;
6865 			idmap[i].cur = cur_id;
6866 			return true;
6867 		}
6868 		if (idmap[i].old == old_id)
6869 			return idmap[i].cur == cur_id;
6870 	}
6871 	/* We ran out of idmap slots, which should be impossible */
6872 	WARN_ON_ONCE(1);
6873 	return false;
6874 }
6875 
6876 static void clean_func_state(struct bpf_verifier_env *env,
6877 			     struct bpf_func_state *st)
6878 {
6879 	enum bpf_reg_liveness live;
6880 	int i, j;
6881 
6882 	for (i = 0; i < BPF_REG_FP; i++) {
6883 		live = st->regs[i].live;
6884 		/* liveness must not touch this register anymore */
6885 		st->regs[i].live |= REG_LIVE_DONE;
6886 		if (!(live & REG_LIVE_READ))
6887 			/* since the register is unused, clear its state
6888 			 * to make further comparison simpler
6889 			 */
6890 			__mark_reg_not_init(&st->regs[i]);
6891 	}
6892 
6893 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
6894 		live = st->stack[i].spilled_ptr.live;
6895 		/* liveness must not touch this stack slot anymore */
6896 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
6897 		if (!(live & REG_LIVE_READ)) {
6898 			__mark_reg_not_init(&st->stack[i].spilled_ptr);
6899 			for (j = 0; j < BPF_REG_SIZE; j++)
6900 				st->stack[i].slot_type[j] = STACK_INVALID;
6901 		}
6902 	}
6903 }
6904 
6905 static void clean_verifier_state(struct bpf_verifier_env *env,
6906 				 struct bpf_verifier_state *st)
6907 {
6908 	int i;
6909 
6910 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
6911 		/* all regs in this state in all frames were already marked */
6912 		return;
6913 
6914 	for (i = 0; i <= st->curframe; i++)
6915 		clean_func_state(env, st->frame[i]);
6916 }
6917 
6918 /* the parentage chains form a tree.
6919  * the verifier states are added to state lists at given insn and
6920  * pushed into state stack for future exploration.
6921  * when the verifier reaches bpf_exit insn some of the verifer states
6922  * stored in the state lists have their final liveness state already,
6923  * but a lot of states will get revised from liveness point of view when
6924  * the verifier explores other branches.
6925  * Example:
6926  * 1: r0 = 1
6927  * 2: if r1 == 100 goto pc+1
6928  * 3: r0 = 2
6929  * 4: exit
6930  * when the verifier reaches exit insn the register r0 in the state list of
6931  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
6932  * of insn 2 and goes exploring further. At the insn 4 it will walk the
6933  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
6934  *
6935  * Since the verifier pushes the branch states as it sees them while exploring
6936  * the program the condition of walking the branch instruction for the second
6937  * time means that all states below this branch were already explored and
6938  * their final liveness markes are already propagated.
6939  * Hence when the verifier completes the search of state list in is_state_visited()
6940  * we can call this clean_live_states() function to mark all liveness states
6941  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
6942  * will not be used.
6943  * This function also clears the registers and stack for states that !READ
6944  * to simplify state merging.
6945  *
6946  * Important note here that walking the same branch instruction in the callee
6947  * doesn't meant that the states are DONE. The verifier has to compare
6948  * the callsites
6949  */
6950 static void clean_live_states(struct bpf_verifier_env *env, int insn,
6951 			      struct bpf_verifier_state *cur)
6952 {
6953 	struct bpf_verifier_state_list *sl;
6954 	int i;
6955 
6956 	sl = *explored_state(env, insn);
6957 	while (sl) {
6958 		if (sl->state.branches)
6959 			goto next;
6960 		if (sl->state.insn_idx != insn ||
6961 		    sl->state.curframe != cur->curframe)
6962 			goto next;
6963 		for (i = 0; i <= cur->curframe; i++)
6964 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
6965 				goto next;
6966 		clean_verifier_state(env, &sl->state);
6967 next:
6968 		sl = sl->next;
6969 	}
6970 }
6971 
6972 /* Returns true if (rold safe implies rcur safe) */
6973 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
6974 		    struct idpair *idmap)
6975 {
6976 	bool equal;
6977 
6978 	if (!(rold->live & REG_LIVE_READ))
6979 		/* explored state didn't use this */
6980 		return true;
6981 
6982 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
6983 
6984 	if (rold->type == PTR_TO_STACK)
6985 		/* two stack pointers are equal only if they're pointing to
6986 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
6987 		 */
6988 		return equal && rold->frameno == rcur->frameno;
6989 
6990 	if (equal)
6991 		return true;
6992 
6993 	if (rold->type == NOT_INIT)
6994 		/* explored state can't have used this */
6995 		return true;
6996 	if (rcur->type == NOT_INIT)
6997 		return false;
6998 	switch (rold->type) {
6999 	case SCALAR_VALUE:
7000 		if (rcur->type == SCALAR_VALUE) {
7001 			if (!rold->precise && !rcur->precise)
7002 				return true;
7003 			/* new val must satisfy old val knowledge */
7004 			return range_within(rold, rcur) &&
7005 			       tnum_in(rold->var_off, rcur->var_off);
7006 		} else {
7007 			/* We're trying to use a pointer in place of a scalar.
7008 			 * Even if the scalar was unbounded, this could lead to
7009 			 * pointer leaks because scalars are allowed to leak
7010 			 * while pointers are not. We could make this safe in
7011 			 * special cases if root is calling us, but it's
7012 			 * probably not worth the hassle.
7013 			 */
7014 			return false;
7015 		}
7016 	case PTR_TO_MAP_VALUE:
7017 		/* If the new min/max/var_off satisfy the old ones and
7018 		 * everything else matches, we are OK.
7019 		 * 'id' is not compared, since it's only used for maps with
7020 		 * bpf_spin_lock inside map element and in such cases if
7021 		 * the rest of the prog is valid for one map element then
7022 		 * it's valid for all map elements regardless of the key
7023 		 * used in bpf_map_lookup()
7024 		 */
7025 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7026 		       range_within(rold, rcur) &&
7027 		       tnum_in(rold->var_off, rcur->var_off);
7028 	case PTR_TO_MAP_VALUE_OR_NULL:
7029 		/* a PTR_TO_MAP_VALUE could be safe to use as a
7030 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7031 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7032 		 * checked, doing so could have affected others with the same
7033 		 * id, and we can't check for that because we lost the id when
7034 		 * we converted to a PTR_TO_MAP_VALUE.
7035 		 */
7036 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7037 			return false;
7038 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7039 			return false;
7040 		/* Check our ids match any regs they're supposed to */
7041 		return check_ids(rold->id, rcur->id, idmap);
7042 	case PTR_TO_PACKET_META:
7043 	case PTR_TO_PACKET:
7044 		if (rcur->type != rold->type)
7045 			return false;
7046 		/* We must have at least as much range as the old ptr
7047 		 * did, so that any accesses which were safe before are
7048 		 * still safe.  This is true even if old range < old off,
7049 		 * since someone could have accessed through (ptr - k), or
7050 		 * even done ptr -= k in a register, to get a safe access.
7051 		 */
7052 		if (rold->range > rcur->range)
7053 			return false;
7054 		/* If the offsets don't match, we can't trust our alignment;
7055 		 * nor can we be sure that we won't fall out of range.
7056 		 */
7057 		if (rold->off != rcur->off)
7058 			return false;
7059 		/* id relations must be preserved */
7060 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7061 			return false;
7062 		/* new val must satisfy old val knowledge */
7063 		return range_within(rold, rcur) &&
7064 		       tnum_in(rold->var_off, rcur->var_off);
7065 	case PTR_TO_CTX:
7066 	case CONST_PTR_TO_MAP:
7067 	case PTR_TO_PACKET_END:
7068 	case PTR_TO_FLOW_KEYS:
7069 	case PTR_TO_SOCKET:
7070 	case PTR_TO_SOCKET_OR_NULL:
7071 	case PTR_TO_SOCK_COMMON:
7072 	case PTR_TO_SOCK_COMMON_OR_NULL:
7073 	case PTR_TO_TCP_SOCK:
7074 	case PTR_TO_TCP_SOCK_OR_NULL:
7075 	case PTR_TO_XDP_SOCK:
7076 		/* Only valid matches are exact, which memcmp() above
7077 		 * would have accepted
7078 		 */
7079 	default:
7080 		/* Don't know what's going on, just say it's not safe */
7081 		return false;
7082 	}
7083 
7084 	/* Shouldn't get here; if we do, say it's not safe */
7085 	WARN_ON_ONCE(1);
7086 	return false;
7087 }
7088 
7089 static bool stacksafe(struct bpf_func_state *old,
7090 		      struct bpf_func_state *cur,
7091 		      struct idpair *idmap)
7092 {
7093 	int i, spi;
7094 
7095 	/* walk slots of the explored stack and ignore any additional
7096 	 * slots in the current stack, since explored(safe) state
7097 	 * didn't use them
7098 	 */
7099 	for (i = 0; i < old->allocated_stack; i++) {
7100 		spi = i / BPF_REG_SIZE;
7101 
7102 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7103 			i += BPF_REG_SIZE - 1;
7104 			/* explored state didn't use this */
7105 			continue;
7106 		}
7107 
7108 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7109 			continue;
7110 
7111 		/* explored stack has more populated slots than current stack
7112 		 * and these slots were used
7113 		 */
7114 		if (i >= cur->allocated_stack)
7115 			return false;
7116 
7117 		/* if old state was safe with misc data in the stack
7118 		 * it will be safe with zero-initialized stack.
7119 		 * The opposite is not true
7120 		 */
7121 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7122 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7123 			continue;
7124 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7125 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7126 			/* Ex: old explored (safe) state has STACK_SPILL in
7127 			 * this stack slot, but current has has STACK_MISC ->
7128 			 * this verifier states are not equivalent,
7129 			 * return false to continue verification of this path
7130 			 */
7131 			return false;
7132 		if (i % BPF_REG_SIZE)
7133 			continue;
7134 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
7135 			continue;
7136 		if (!regsafe(&old->stack[spi].spilled_ptr,
7137 			     &cur->stack[spi].spilled_ptr,
7138 			     idmap))
7139 			/* when explored and current stack slot are both storing
7140 			 * spilled registers, check that stored pointers types
7141 			 * are the same as well.
7142 			 * Ex: explored safe path could have stored
7143 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7144 			 * but current path has stored:
7145 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7146 			 * such verifier states are not equivalent.
7147 			 * return false to continue verification of this path
7148 			 */
7149 			return false;
7150 	}
7151 	return true;
7152 }
7153 
7154 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7155 {
7156 	if (old->acquired_refs != cur->acquired_refs)
7157 		return false;
7158 	return !memcmp(old->refs, cur->refs,
7159 		       sizeof(*old->refs) * old->acquired_refs);
7160 }
7161 
7162 /* compare two verifier states
7163  *
7164  * all states stored in state_list are known to be valid, since
7165  * verifier reached 'bpf_exit' instruction through them
7166  *
7167  * this function is called when verifier exploring different branches of
7168  * execution popped from the state stack. If it sees an old state that has
7169  * more strict register state and more strict stack state then this execution
7170  * branch doesn't need to be explored further, since verifier already
7171  * concluded that more strict state leads to valid finish.
7172  *
7173  * Therefore two states are equivalent if register state is more conservative
7174  * and explored stack state is more conservative than the current one.
7175  * Example:
7176  *       explored                   current
7177  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7178  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7179  *
7180  * In other words if current stack state (one being explored) has more
7181  * valid slots than old one that already passed validation, it means
7182  * the verifier can stop exploring and conclude that current state is valid too
7183  *
7184  * Similarly with registers. If explored state has register type as invalid
7185  * whereas register type in current state is meaningful, it means that
7186  * the current state will reach 'bpf_exit' instruction safely
7187  */
7188 static bool func_states_equal(struct bpf_func_state *old,
7189 			      struct bpf_func_state *cur)
7190 {
7191 	struct idpair *idmap;
7192 	bool ret = false;
7193 	int i;
7194 
7195 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
7196 	/* If we failed to allocate the idmap, just say it's not safe */
7197 	if (!idmap)
7198 		return false;
7199 
7200 	for (i = 0; i < MAX_BPF_REG; i++) {
7201 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
7202 			goto out_free;
7203 	}
7204 
7205 	if (!stacksafe(old, cur, idmap))
7206 		goto out_free;
7207 
7208 	if (!refsafe(old, cur))
7209 		goto out_free;
7210 	ret = true;
7211 out_free:
7212 	kfree(idmap);
7213 	return ret;
7214 }
7215 
7216 static bool states_equal(struct bpf_verifier_env *env,
7217 			 struct bpf_verifier_state *old,
7218 			 struct bpf_verifier_state *cur)
7219 {
7220 	int i;
7221 
7222 	if (old->curframe != cur->curframe)
7223 		return false;
7224 
7225 	/* Verification state from speculative execution simulation
7226 	 * must never prune a non-speculative execution one.
7227 	 */
7228 	if (old->speculative && !cur->speculative)
7229 		return false;
7230 
7231 	if (old->active_spin_lock != cur->active_spin_lock)
7232 		return false;
7233 
7234 	/* for states to be equal callsites have to be the same
7235 	 * and all frame states need to be equivalent
7236 	 */
7237 	for (i = 0; i <= old->curframe; i++) {
7238 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
7239 			return false;
7240 		if (!func_states_equal(old->frame[i], cur->frame[i]))
7241 			return false;
7242 	}
7243 	return true;
7244 }
7245 
7246 /* Return 0 if no propagation happened. Return negative error code if error
7247  * happened. Otherwise, return the propagated bit.
7248  */
7249 static int propagate_liveness_reg(struct bpf_verifier_env *env,
7250 				  struct bpf_reg_state *reg,
7251 				  struct bpf_reg_state *parent_reg)
7252 {
7253 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
7254 	u8 flag = reg->live & REG_LIVE_READ;
7255 	int err;
7256 
7257 	/* When comes here, read flags of PARENT_REG or REG could be any of
7258 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
7259 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
7260 	 */
7261 	if (parent_flag == REG_LIVE_READ64 ||
7262 	    /* Or if there is no read flag from REG. */
7263 	    !flag ||
7264 	    /* Or if the read flag from REG is the same as PARENT_REG. */
7265 	    parent_flag == flag)
7266 		return 0;
7267 
7268 	err = mark_reg_read(env, reg, parent_reg, flag);
7269 	if (err)
7270 		return err;
7271 
7272 	return flag;
7273 }
7274 
7275 /* A write screens off any subsequent reads; but write marks come from the
7276  * straight-line code between a state and its parent.  When we arrive at an
7277  * equivalent state (jump target or such) we didn't arrive by the straight-line
7278  * code, so read marks in the state must propagate to the parent regardless
7279  * of the state's write marks. That's what 'parent == state->parent' comparison
7280  * in mark_reg_read() is for.
7281  */
7282 static int propagate_liveness(struct bpf_verifier_env *env,
7283 			      const struct bpf_verifier_state *vstate,
7284 			      struct bpf_verifier_state *vparent)
7285 {
7286 	struct bpf_reg_state *state_reg, *parent_reg;
7287 	struct bpf_func_state *state, *parent;
7288 	int i, frame, err = 0;
7289 
7290 	if (vparent->curframe != vstate->curframe) {
7291 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
7292 		     vparent->curframe, vstate->curframe);
7293 		return -EFAULT;
7294 	}
7295 	/* Propagate read liveness of registers... */
7296 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
7297 	for (frame = 0; frame <= vstate->curframe; frame++) {
7298 		parent = vparent->frame[frame];
7299 		state = vstate->frame[frame];
7300 		parent_reg = parent->regs;
7301 		state_reg = state->regs;
7302 		/* We don't need to worry about FP liveness, it's read-only */
7303 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
7304 			err = propagate_liveness_reg(env, &state_reg[i],
7305 						     &parent_reg[i]);
7306 			if (err < 0)
7307 				return err;
7308 			if (err == REG_LIVE_READ64)
7309 				mark_insn_zext(env, &parent_reg[i]);
7310 		}
7311 
7312 		/* Propagate stack slots. */
7313 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
7314 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
7315 			parent_reg = &parent->stack[i].spilled_ptr;
7316 			state_reg = &state->stack[i].spilled_ptr;
7317 			err = propagate_liveness_reg(env, state_reg,
7318 						     parent_reg);
7319 			if (err < 0)
7320 				return err;
7321 		}
7322 	}
7323 	return 0;
7324 }
7325 
7326 /* find precise scalars in the previous equivalent state and
7327  * propagate them into the current state
7328  */
7329 static int propagate_precision(struct bpf_verifier_env *env,
7330 			       const struct bpf_verifier_state *old)
7331 {
7332 	struct bpf_reg_state *state_reg;
7333 	struct bpf_func_state *state;
7334 	int i, err = 0;
7335 
7336 	state = old->frame[old->curframe];
7337 	state_reg = state->regs;
7338 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
7339 		if (state_reg->type != SCALAR_VALUE ||
7340 		    !state_reg->precise)
7341 			continue;
7342 		if (env->log.level & BPF_LOG_LEVEL2)
7343 			verbose(env, "propagating r%d\n", i);
7344 		err = mark_chain_precision(env, i);
7345 		if (err < 0)
7346 			return err;
7347 	}
7348 
7349 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
7350 		if (state->stack[i].slot_type[0] != STACK_SPILL)
7351 			continue;
7352 		state_reg = &state->stack[i].spilled_ptr;
7353 		if (state_reg->type != SCALAR_VALUE ||
7354 		    !state_reg->precise)
7355 			continue;
7356 		if (env->log.level & BPF_LOG_LEVEL2)
7357 			verbose(env, "propagating fp%d\n",
7358 				(-i - 1) * BPF_REG_SIZE);
7359 		err = mark_chain_precision_stack(env, i);
7360 		if (err < 0)
7361 			return err;
7362 	}
7363 	return 0;
7364 }
7365 
7366 static bool states_maybe_looping(struct bpf_verifier_state *old,
7367 				 struct bpf_verifier_state *cur)
7368 {
7369 	struct bpf_func_state *fold, *fcur;
7370 	int i, fr = cur->curframe;
7371 
7372 	if (old->curframe != fr)
7373 		return false;
7374 
7375 	fold = old->frame[fr];
7376 	fcur = cur->frame[fr];
7377 	for (i = 0; i < MAX_BPF_REG; i++)
7378 		if (memcmp(&fold->regs[i], &fcur->regs[i],
7379 			   offsetof(struct bpf_reg_state, parent)))
7380 			return false;
7381 	return true;
7382 }
7383 
7384 
7385 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
7386 {
7387 	struct bpf_verifier_state_list *new_sl;
7388 	struct bpf_verifier_state_list *sl, **pprev;
7389 	struct bpf_verifier_state *cur = env->cur_state, *new;
7390 	int i, j, err, states_cnt = 0;
7391 	bool add_new_state = env->test_state_freq ? true : false;
7392 
7393 	cur->last_insn_idx = env->prev_insn_idx;
7394 	if (!env->insn_aux_data[insn_idx].prune_point)
7395 		/* this 'insn_idx' instruction wasn't marked, so we will not
7396 		 * be doing state search here
7397 		 */
7398 		return 0;
7399 
7400 	/* bpf progs typically have pruning point every 4 instructions
7401 	 * http://vger.kernel.org/bpfconf2019.html#session-1
7402 	 * Do not add new state for future pruning if the verifier hasn't seen
7403 	 * at least 2 jumps and at least 8 instructions.
7404 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
7405 	 * In tests that amounts to up to 50% reduction into total verifier
7406 	 * memory consumption and 20% verifier time speedup.
7407 	 */
7408 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
7409 	    env->insn_processed - env->prev_insn_processed >= 8)
7410 		add_new_state = true;
7411 
7412 	pprev = explored_state(env, insn_idx);
7413 	sl = *pprev;
7414 
7415 	clean_live_states(env, insn_idx, cur);
7416 
7417 	while (sl) {
7418 		states_cnt++;
7419 		if (sl->state.insn_idx != insn_idx)
7420 			goto next;
7421 		if (sl->state.branches) {
7422 			if (states_maybe_looping(&sl->state, cur) &&
7423 			    states_equal(env, &sl->state, cur)) {
7424 				verbose_linfo(env, insn_idx, "; ");
7425 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
7426 				return -EINVAL;
7427 			}
7428 			/* if the verifier is processing a loop, avoid adding new state
7429 			 * too often, since different loop iterations have distinct
7430 			 * states and may not help future pruning.
7431 			 * This threshold shouldn't be too low to make sure that
7432 			 * a loop with large bound will be rejected quickly.
7433 			 * The most abusive loop will be:
7434 			 * r1 += 1
7435 			 * if r1 < 1000000 goto pc-2
7436 			 * 1M insn_procssed limit / 100 == 10k peak states.
7437 			 * This threshold shouldn't be too high either, since states
7438 			 * at the end of the loop are likely to be useful in pruning.
7439 			 */
7440 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
7441 			    env->insn_processed - env->prev_insn_processed < 100)
7442 				add_new_state = false;
7443 			goto miss;
7444 		}
7445 		if (states_equal(env, &sl->state, cur)) {
7446 			sl->hit_cnt++;
7447 			/* reached equivalent register/stack state,
7448 			 * prune the search.
7449 			 * Registers read by the continuation are read by us.
7450 			 * If we have any write marks in env->cur_state, they
7451 			 * will prevent corresponding reads in the continuation
7452 			 * from reaching our parent (an explored_state).  Our
7453 			 * own state will get the read marks recorded, but
7454 			 * they'll be immediately forgotten as we're pruning
7455 			 * this state and will pop a new one.
7456 			 */
7457 			err = propagate_liveness(env, &sl->state, cur);
7458 
7459 			/* if previous state reached the exit with precision and
7460 			 * current state is equivalent to it (except precsion marks)
7461 			 * the precision needs to be propagated back in
7462 			 * the current state.
7463 			 */
7464 			err = err ? : push_jmp_history(env, cur);
7465 			err = err ? : propagate_precision(env, &sl->state);
7466 			if (err)
7467 				return err;
7468 			return 1;
7469 		}
7470 miss:
7471 		/* when new state is not going to be added do not increase miss count.
7472 		 * Otherwise several loop iterations will remove the state
7473 		 * recorded earlier. The goal of these heuristics is to have
7474 		 * states from some iterations of the loop (some in the beginning
7475 		 * and some at the end) to help pruning.
7476 		 */
7477 		if (add_new_state)
7478 			sl->miss_cnt++;
7479 		/* heuristic to determine whether this state is beneficial
7480 		 * to keep checking from state equivalence point of view.
7481 		 * Higher numbers increase max_states_per_insn and verification time,
7482 		 * but do not meaningfully decrease insn_processed.
7483 		 */
7484 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
7485 			/* the state is unlikely to be useful. Remove it to
7486 			 * speed up verification
7487 			 */
7488 			*pprev = sl->next;
7489 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
7490 				u32 br = sl->state.branches;
7491 
7492 				WARN_ONCE(br,
7493 					  "BUG live_done but branches_to_explore %d\n",
7494 					  br);
7495 				free_verifier_state(&sl->state, false);
7496 				kfree(sl);
7497 				env->peak_states--;
7498 			} else {
7499 				/* cannot free this state, since parentage chain may
7500 				 * walk it later. Add it for free_list instead to
7501 				 * be freed at the end of verification
7502 				 */
7503 				sl->next = env->free_list;
7504 				env->free_list = sl;
7505 			}
7506 			sl = *pprev;
7507 			continue;
7508 		}
7509 next:
7510 		pprev = &sl->next;
7511 		sl = *pprev;
7512 	}
7513 
7514 	if (env->max_states_per_insn < states_cnt)
7515 		env->max_states_per_insn = states_cnt;
7516 
7517 	if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
7518 		return push_jmp_history(env, cur);
7519 
7520 	if (!add_new_state)
7521 		return push_jmp_history(env, cur);
7522 
7523 	/* There were no equivalent states, remember the current one.
7524 	 * Technically the current state is not proven to be safe yet,
7525 	 * but it will either reach outer most bpf_exit (which means it's safe)
7526 	 * or it will be rejected. When there are no loops the verifier won't be
7527 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
7528 	 * again on the way to bpf_exit.
7529 	 * When looping the sl->state.branches will be > 0 and this state
7530 	 * will not be considered for equivalence until branches == 0.
7531 	 */
7532 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
7533 	if (!new_sl)
7534 		return -ENOMEM;
7535 	env->total_states++;
7536 	env->peak_states++;
7537 	env->prev_jmps_processed = env->jmps_processed;
7538 	env->prev_insn_processed = env->insn_processed;
7539 
7540 	/* add new state to the head of linked list */
7541 	new = &new_sl->state;
7542 	err = copy_verifier_state(new, cur);
7543 	if (err) {
7544 		free_verifier_state(new, false);
7545 		kfree(new_sl);
7546 		return err;
7547 	}
7548 	new->insn_idx = insn_idx;
7549 	WARN_ONCE(new->branches != 1,
7550 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
7551 
7552 	cur->parent = new;
7553 	cur->first_insn_idx = insn_idx;
7554 	clear_jmp_history(cur);
7555 	new_sl->next = *explored_state(env, insn_idx);
7556 	*explored_state(env, insn_idx) = new_sl;
7557 	/* connect new state to parentage chain. Current frame needs all
7558 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
7559 	 * to the stack implicitly by JITs) so in callers' frames connect just
7560 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
7561 	 * the state of the call instruction (with WRITTEN set), and r0 comes
7562 	 * from callee with its full parentage chain, anyway.
7563 	 */
7564 	/* clear write marks in current state: the writes we did are not writes
7565 	 * our child did, so they don't screen off its reads from us.
7566 	 * (There are no read marks in current state, because reads always mark
7567 	 * their parent and current state never has children yet.  Only
7568 	 * explored_states can get read marks.)
7569 	 */
7570 	for (j = 0; j <= cur->curframe; j++) {
7571 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
7572 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
7573 		for (i = 0; i < BPF_REG_FP; i++)
7574 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
7575 	}
7576 
7577 	/* all stack frames are accessible from callee, clear them all */
7578 	for (j = 0; j <= cur->curframe; j++) {
7579 		struct bpf_func_state *frame = cur->frame[j];
7580 		struct bpf_func_state *newframe = new->frame[j];
7581 
7582 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
7583 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
7584 			frame->stack[i].spilled_ptr.parent =
7585 						&newframe->stack[i].spilled_ptr;
7586 		}
7587 	}
7588 	return 0;
7589 }
7590 
7591 /* Return true if it's OK to have the same insn return a different type. */
7592 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
7593 {
7594 	switch (type) {
7595 	case PTR_TO_CTX:
7596 	case PTR_TO_SOCKET:
7597 	case PTR_TO_SOCKET_OR_NULL:
7598 	case PTR_TO_SOCK_COMMON:
7599 	case PTR_TO_SOCK_COMMON_OR_NULL:
7600 	case PTR_TO_TCP_SOCK:
7601 	case PTR_TO_TCP_SOCK_OR_NULL:
7602 	case PTR_TO_XDP_SOCK:
7603 	case PTR_TO_BTF_ID:
7604 		return false;
7605 	default:
7606 		return true;
7607 	}
7608 }
7609 
7610 /* If an instruction was previously used with particular pointer types, then we
7611  * need to be careful to avoid cases such as the below, where it may be ok
7612  * for one branch accessing the pointer, but not ok for the other branch:
7613  *
7614  * R1 = sock_ptr
7615  * goto X;
7616  * ...
7617  * R1 = some_other_valid_ptr;
7618  * goto X;
7619  * ...
7620  * R2 = *(u32 *)(R1 + 0);
7621  */
7622 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
7623 {
7624 	return src != prev && (!reg_type_mismatch_ok(src) ||
7625 			       !reg_type_mismatch_ok(prev));
7626 }
7627 
7628 static int do_check(struct bpf_verifier_env *env)
7629 {
7630 	struct bpf_verifier_state *state;
7631 	struct bpf_insn *insns = env->prog->insnsi;
7632 	struct bpf_reg_state *regs;
7633 	int insn_cnt = env->prog->len;
7634 	bool do_print_state = false;
7635 	int prev_insn_idx = -1;
7636 
7637 	env->prev_linfo = NULL;
7638 
7639 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
7640 	if (!state)
7641 		return -ENOMEM;
7642 	state->curframe = 0;
7643 	state->speculative = false;
7644 	state->branches = 1;
7645 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
7646 	if (!state->frame[0]) {
7647 		kfree(state);
7648 		return -ENOMEM;
7649 	}
7650 	env->cur_state = state;
7651 	init_func_state(env, state->frame[0],
7652 			BPF_MAIN_FUNC /* callsite */,
7653 			0 /* frameno */,
7654 			0 /* subprogno, zero == main subprog */);
7655 
7656 	for (;;) {
7657 		struct bpf_insn *insn;
7658 		u8 class;
7659 		int err;
7660 
7661 		env->prev_insn_idx = prev_insn_idx;
7662 		if (env->insn_idx >= insn_cnt) {
7663 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
7664 				env->insn_idx, insn_cnt);
7665 			return -EFAULT;
7666 		}
7667 
7668 		insn = &insns[env->insn_idx];
7669 		class = BPF_CLASS(insn->code);
7670 
7671 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
7672 			verbose(env,
7673 				"BPF program is too large. Processed %d insn\n",
7674 				env->insn_processed);
7675 			return -E2BIG;
7676 		}
7677 
7678 		err = is_state_visited(env, env->insn_idx);
7679 		if (err < 0)
7680 			return err;
7681 		if (err == 1) {
7682 			/* found equivalent state, can prune the search */
7683 			if (env->log.level & BPF_LOG_LEVEL) {
7684 				if (do_print_state)
7685 					verbose(env, "\nfrom %d to %d%s: safe\n",
7686 						env->prev_insn_idx, env->insn_idx,
7687 						env->cur_state->speculative ?
7688 						" (speculative execution)" : "");
7689 				else
7690 					verbose(env, "%d: safe\n", env->insn_idx);
7691 			}
7692 			goto process_bpf_exit;
7693 		}
7694 
7695 		if (signal_pending(current))
7696 			return -EAGAIN;
7697 
7698 		if (need_resched())
7699 			cond_resched();
7700 
7701 		if (env->log.level & BPF_LOG_LEVEL2 ||
7702 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
7703 			if (env->log.level & BPF_LOG_LEVEL2)
7704 				verbose(env, "%d:", env->insn_idx);
7705 			else
7706 				verbose(env, "\nfrom %d to %d%s:",
7707 					env->prev_insn_idx, env->insn_idx,
7708 					env->cur_state->speculative ?
7709 					" (speculative execution)" : "");
7710 			print_verifier_state(env, state->frame[state->curframe]);
7711 			do_print_state = false;
7712 		}
7713 
7714 		if (env->log.level & BPF_LOG_LEVEL) {
7715 			const struct bpf_insn_cbs cbs = {
7716 				.cb_print	= verbose,
7717 				.private_data	= env,
7718 			};
7719 
7720 			verbose_linfo(env, env->insn_idx, "; ");
7721 			verbose(env, "%d: ", env->insn_idx);
7722 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
7723 		}
7724 
7725 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
7726 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
7727 							   env->prev_insn_idx);
7728 			if (err)
7729 				return err;
7730 		}
7731 
7732 		regs = cur_regs(env);
7733 		env->insn_aux_data[env->insn_idx].seen = true;
7734 		prev_insn_idx = env->insn_idx;
7735 
7736 		if (class == BPF_ALU || class == BPF_ALU64) {
7737 			err = check_alu_op(env, insn);
7738 			if (err)
7739 				return err;
7740 
7741 		} else if (class == BPF_LDX) {
7742 			enum bpf_reg_type *prev_src_type, src_reg_type;
7743 
7744 			/* check for reserved fields is already done */
7745 
7746 			/* check src operand */
7747 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7748 			if (err)
7749 				return err;
7750 
7751 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7752 			if (err)
7753 				return err;
7754 
7755 			src_reg_type = regs[insn->src_reg].type;
7756 
7757 			/* check that memory (src_reg + off) is readable,
7758 			 * the state of dst_reg will be updated by this func
7759 			 */
7760 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
7761 					       insn->off, BPF_SIZE(insn->code),
7762 					       BPF_READ, insn->dst_reg, false);
7763 			if (err)
7764 				return err;
7765 
7766 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
7767 
7768 			if (*prev_src_type == NOT_INIT) {
7769 				/* saw a valid insn
7770 				 * dst_reg = *(u32 *)(src_reg + off)
7771 				 * save type to validate intersecting paths
7772 				 */
7773 				*prev_src_type = src_reg_type;
7774 
7775 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
7776 				/* ABuser program is trying to use the same insn
7777 				 * dst_reg = *(u32*) (src_reg + off)
7778 				 * with different pointer types:
7779 				 * src_reg == ctx in one branch and
7780 				 * src_reg == stack|map in some other branch.
7781 				 * Reject it.
7782 				 */
7783 				verbose(env, "same insn cannot be used with different pointers\n");
7784 				return -EINVAL;
7785 			}
7786 
7787 		} else if (class == BPF_STX) {
7788 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
7789 
7790 			if (BPF_MODE(insn->code) == BPF_XADD) {
7791 				err = check_xadd(env, env->insn_idx, insn);
7792 				if (err)
7793 					return err;
7794 				env->insn_idx++;
7795 				continue;
7796 			}
7797 
7798 			/* check src1 operand */
7799 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7800 			if (err)
7801 				return err;
7802 			/* check src2 operand */
7803 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7804 			if (err)
7805 				return err;
7806 
7807 			dst_reg_type = regs[insn->dst_reg].type;
7808 
7809 			/* check that memory (dst_reg + off) is writeable */
7810 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7811 					       insn->off, BPF_SIZE(insn->code),
7812 					       BPF_WRITE, insn->src_reg, false);
7813 			if (err)
7814 				return err;
7815 
7816 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
7817 
7818 			if (*prev_dst_type == NOT_INIT) {
7819 				*prev_dst_type = dst_reg_type;
7820 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
7821 				verbose(env, "same insn cannot be used with different pointers\n");
7822 				return -EINVAL;
7823 			}
7824 
7825 		} else if (class == BPF_ST) {
7826 			if (BPF_MODE(insn->code) != BPF_MEM ||
7827 			    insn->src_reg != BPF_REG_0) {
7828 				verbose(env, "BPF_ST uses reserved fields\n");
7829 				return -EINVAL;
7830 			}
7831 			/* check src operand */
7832 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7833 			if (err)
7834 				return err;
7835 
7836 			if (is_ctx_reg(env, insn->dst_reg)) {
7837 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
7838 					insn->dst_reg,
7839 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
7840 				return -EACCES;
7841 			}
7842 
7843 			/* check that memory (dst_reg + off) is writeable */
7844 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7845 					       insn->off, BPF_SIZE(insn->code),
7846 					       BPF_WRITE, -1, false);
7847 			if (err)
7848 				return err;
7849 
7850 		} else if (class == BPF_JMP || class == BPF_JMP32) {
7851 			u8 opcode = BPF_OP(insn->code);
7852 
7853 			env->jmps_processed++;
7854 			if (opcode == BPF_CALL) {
7855 				if (BPF_SRC(insn->code) != BPF_K ||
7856 				    insn->off != 0 ||
7857 				    (insn->src_reg != BPF_REG_0 &&
7858 				     insn->src_reg != BPF_PSEUDO_CALL) ||
7859 				    insn->dst_reg != BPF_REG_0 ||
7860 				    class == BPF_JMP32) {
7861 					verbose(env, "BPF_CALL uses reserved fields\n");
7862 					return -EINVAL;
7863 				}
7864 
7865 				if (env->cur_state->active_spin_lock &&
7866 				    (insn->src_reg == BPF_PSEUDO_CALL ||
7867 				     insn->imm != BPF_FUNC_spin_unlock)) {
7868 					verbose(env, "function calls are not allowed while holding a lock\n");
7869 					return -EINVAL;
7870 				}
7871 				if (insn->src_reg == BPF_PSEUDO_CALL)
7872 					err = check_func_call(env, insn, &env->insn_idx);
7873 				else
7874 					err = check_helper_call(env, insn->imm, env->insn_idx);
7875 				if (err)
7876 					return err;
7877 
7878 			} else if (opcode == BPF_JA) {
7879 				if (BPF_SRC(insn->code) != BPF_K ||
7880 				    insn->imm != 0 ||
7881 				    insn->src_reg != BPF_REG_0 ||
7882 				    insn->dst_reg != BPF_REG_0 ||
7883 				    class == BPF_JMP32) {
7884 					verbose(env, "BPF_JA uses reserved fields\n");
7885 					return -EINVAL;
7886 				}
7887 
7888 				env->insn_idx += insn->off + 1;
7889 				continue;
7890 
7891 			} else if (opcode == BPF_EXIT) {
7892 				if (BPF_SRC(insn->code) != BPF_K ||
7893 				    insn->imm != 0 ||
7894 				    insn->src_reg != BPF_REG_0 ||
7895 				    insn->dst_reg != BPF_REG_0 ||
7896 				    class == BPF_JMP32) {
7897 					verbose(env, "BPF_EXIT uses reserved fields\n");
7898 					return -EINVAL;
7899 				}
7900 
7901 				if (env->cur_state->active_spin_lock) {
7902 					verbose(env, "bpf_spin_unlock is missing\n");
7903 					return -EINVAL;
7904 				}
7905 
7906 				if (state->curframe) {
7907 					/* exit from nested function */
7908 					err = prepare_func_exit(env, &env->insn_idx);
7909 					if (err)
7910 						return err;
7911 					do_print_state = true;
7912 					continue;
7913 				}
7914 
7915 				err = check_reference_leak(env);
7916 				if (err)
7917 					return err;
7918 
7919 				/* eBPF calling convetion is such that R0 is used
7920 				 * to return the value from eBPF program.
7921 				 * Make sure that it's readable at this time
7922 				 * of bpf_exit, which means that program wrote
7923 				 * something into it earlier
7924 				 */
7925 				err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7926 				if (err)
7927 					return err;
7928 
7929 				if (is_pointer_value(env, BPF_REG_0)) {
7930 					verbose(env, "R0 leaks addr as return value\n");
7931 					return -EACCES;
7932 				}
7933 
7934 				err = check_return_code(env);
7935 				if (err)
7936 					return err;
7937 process_bpf_exit:
7938 				update_branch_counts(env, env->cur_state);
7939 				err = pop_stack(env, &prev_insn_idx,
7940 						&env->insn_idx);
7941 				if (err < 0) {
7942 					if (err != -ENOENT)
7943 						return err;
7944 					break;
7945 				} else {
7946 					do_print_state = true;
7947 					continue;
7948 				}
7949 			} else {
7950 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
7951 				if (err)
7952 					return err;
7953 			}
7954 		} else if (class == BPF_LD) {
7955 			u8 mode = BPF_MODE(insn->code);
7956 
7957 			if (mode == BPF_ABS || mode == BPF_IND) {
7958 				err = check_ld_abs(env, insn);
7959 				if (err)
7960 					return err;
7961 
7962 			} else if (mode == BPF_IMM) {
7963 				err = check_ld_imm(env, insn);
7964 				if (err)
7965 					return err;
7966 
7967 				env->insn_idx++;
7968 				env->insn_aux_data[env->insn_idx].seen = true;
7969 			} else {
7970 				verbose(env, "invalid BPF_LD mode\n");
7971 				return -EINVAL;
7972 			}
7973 		} else {
7974 			verbose(env, "unknown insn class %d\n", class);
7975 			return -EINVAL;
7976 		}
7977 
7978 		env->insn_idx++;
7979 	}
7980 
7981 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
7982 	return 0;
7983 }
7984 
7985 static int check_map_prealloc(struct bpf_map *map)
7986 {
7987 	return (map->map_type != BPF_MAP_TYPE_HASH &&
7988 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7989 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
7990 		!(map->map_flags & BPF_F_NO_PREALLOC);
7991 }
7992 
7993 static bool is_tracing_prog_type(enum bpf_prog_type type)
7994 {
7995 	switch (type) {
7996 	case BPF_PROG_TYPE_KPROBE:
7997 	case BPF_PROG_TYPE_TRACEPOINT:
7998 	case BPF_PROG_TYPE_PERF_EVENT:
7999 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8000 		return true;
8001 	default:
8002 		return false;
8003 	}
8004 }
8005 
8006 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8007 					struct bpf_map *map,
8008 					struct bpf_prog *prog)
8009 
8010 {
8011 	/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
8012 	 * preallocated hash maps, since doing memory allocation
8013 	 * in overflow_handler can crash depending on where nmi got
8014 	 * triggered.
8015 	 */
8016 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8017 		if (!check_map_prealloc(map)) {
8018 			verbose(env, "perf_event programs can only use preallocated hash map\n");
8019 			return -EINVAL;
8020 		}
8021 		if (map->inner_map_meta &&
8022 		    !check_map_prealloc(map->inner_map_meta)) {
8023 			verbose(env, "perf_event programs can only use preallocated inner hash map\n");
8024 			return -EINVAL;
8025 		}
8026 	}
8027 
8028 	if ((is_tracing_prog_type(prog->type) ||
8029 	     prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8030 	    map_value_has_spin_lock(map)) {
8031 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8032 		return -EINVAL;
8033 	}
8034 
8035 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
8036 	    !bpf_offload_prog_map_match(prog, map)) {
8037 		verbose(env, "offload device mismatch between prog and map\n");
8038 		return -EINVAL;
8039 	}
8040 
8041 	return 0;
8042 }
8043 
8044 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8045 {
8046 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8047 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8048 }
8049 
8050 /* look for pseudo eBPF instructions that access map FDs and
8051  * replace them with actual map pointers
8052  */
8053 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
8054 {
8055 	struct bpf_insn *insn = env->prog->insnsi;
8056 	int insn_cnt = env->prog->len;
8057 	int i, j, err;
8058 
8059 	err = bpf_prog_calc_tag(env->prog);
8060 	if (err)
8061 		return err;
8062 
8063 	for (i = 0; i < insn_cnt; i++, insn++) {
8064 		if (BPF_CLASS(insn->code) == BPF_LDX &&
8065 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
8066 			verbose(env, "BPF_LDX uses reserved fields\n");
8067 			return -EINVAL;
8068 		}
8069 
8070 		if (BPF_CLASS(insn->code) == BPF_STX &&
8071 		    ((BPF_MODE(insn->code) != BPF_MEM &&
8072 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
8073 			verbose(env, "BPF_STX uses reserved fields\n");
8074 			return -EINVAL;
8075 		}
8076 
8077 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
8078 			struct bpf_insn_aux_data *aux;
8079 			struct bpf_map *map;
8080 			struct fd f;
8081 			u64 addr;
8082 
8083 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
8084 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8085 			    insn[1].off != 0) {
8086 				verbose(env, "invalid bpf_ld_imm64 insn\n");
8087 				return -EINVAL;
8088 			}
8089 
8090 			if (insn[0].src_reg == 0)
8091 				/* valid generic load 64-bit imm */
8092 				goto next_insn;
8093 
8094 			/* In final convert_pseudo_ld_imm64() step, this is
8095 			 * converted into regular 64-bit imm load insn.
8096 			 */
8097 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8098 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8099 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8100 			     insn[1].imm != 0)) {
8101 				verbose(env,
8102 					"unrecognized bpf_ld_imm64 insn\n");
8103 				return -EINVAL;
8104 			}
8105 
8106 			f = fdget(insn[0].imm);
8107 			map = __bpf_map_get(f);
8108 			if (IS_ERR(map)) {
8109 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
8110 					insn[0].imm);
8111 				return PTR_ERR(map);
8112 			}
8113 
8114 			err = check_map_prog_compatibility(env, map, env->prog);
8115 			if (err) {
8116 				fdput(f);
8117 				return err;
8118 			}
8119 
8120 			aux = &env->insn_aux_data[i];
8121 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8122 				addr = (unsigned long)map;
8123 			} else {
8124 				u32 off = insn[1].imm;
8125 
8126 				if (off >= BPF_MAX_VAR_OFF) {
8127 					verbose(env, "direct value offset of %u is not allowed\n", off);
8128 					fdput(f);
8129 					return -EINVAL;
8130 				}
8131 
8132 				if (!map->ops->map_direct_value_addr) {
8133 					verbose(env, "no direct value access support for this map type\n");
8134 					fdput(f);
8135 					return -EINVAL;
8136 				}
8137 
8138 				err = map->ops->map_direct_value_addr(map, &addr, off);
8139 				if (err) {
8140 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8141 						map->value_size, off);
8142 					fdput(f);
8143 					return err;
8144 				}
8145 
8146 				aux->map_off = off;
8147 				addr += off;
8148 			}
8149 
8150 			insn[0].imm = (u32)addr;
8151 			insn[1].imm = addr >> 32;
8152 
8153 			/* check whether we recorded this map already */
8154 			for (j = 0; j < env->used_map_cnt; j++) {
8155 				if (env->used_maps[j] == map) {
8156 					aux->map_index = j;
8157 					fdput(f);
8158 					goto next_insn;
8159 				}
8160 			}
8161 
8162 			if (env->used_map_cnt >= MAX_USED_MAPS) {
8163 				fdput(f);
8164 				return -E2BIG;
8165 			}
8166 
8167 			/* hold the map. If the program is rejected by verifier,
8168 			 * the map will be released by release_maps() or it
8169 			 * will be used by the valid program until it's unloaded
8170 			 * and all maps are released in free_used_maps()
8171 			 */
8172 			map = bpf_map_inc(map, false);
8173 			if (IS_ERR(map)) {
8174 				fdput(f);
8175 				return PTR_ERR(map);
8176 			}
8177 
8178 			aux->map_index = env->used_map_cnt;
8179 			env->used_maps[env->used_map_cnt++] = map;
8180 
8181 			if (bpf_map_is_cgroup_storage(map) &&
8182 			    bpf_cgroup_storage_assign(env->prog, map)) {
8183 				verbose(env, "only one cgroup storage of each type is allowed\n");
8184 				fdput(f);
8185 				return -EBUSY;
8186 			}
8187 
8188 			fdput(f);
8189 next_insn:
8190 			insn++;
8191 			i++;
8192 			continue;
8193 		}
8194 
8195 		/* Basic sanity check before we invest more work here. */
8196 		if (!bpf_opcode_in_insntable(insn->code)) {
8197 			verbose(env, "unknown opcode %02x\n", insn->code);
8198 			return -EINVAL;
8199 		}
8200 	}
8201 
8202 	/* now all pseudo BPF_LD_IMM64 instructions load valid
8203 	 * 'struct bpf_map *' into a register instead of user map_fd.
8204 	 * These pointers will be used later by verifier to validate map access.
8205 	 */
8206 	return 0;
8207 }
8208 
8209 /* drop refcnt of maps used by the rejected program */
8210 static void release_maps(struct bpf_verifier_env *env)
8211 {
8212 	enum bpf_cgroup_storage_type stype;
8213 	int i;
8214 
8215 	for_each_cgroup_storage_type(stype) {
8216 		if (!env->prog->aux->cgroup_storage[stype])
8217 			continue;
8218 		bpf_cgroup_storage_release(env->prog,
8219 			env->prog->aux->cgroup_storage[stype]);
8220 	}
8221 
8222 	for (i = 0; i < env->used_map_cnt; i++)
8223 		bpf_map_put(env->used_maps[i]);
8224 }
8225 
8226 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
8227 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
8228 {
8229 	struct bpf_insn *insn = env->prog->insnsi;
8230 	int insn_cnt = env->prog->len;
8231 	int i;
8232 
8233 	for (i = 0; i < insn_cnt; i++, insn++)
8234 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8235 			insn->src_reg = 0;
8236 }
8237 
8238 /* single env->prog->insni[off] instruction was replaced with the range
8239  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
8240  * [0, off) and [off, end) to new locations, so the patched range stays zero
8241  */
8242 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
8243 				struct bpf_prog *new_prog, u32 off, u32 cnt)
8244 {
8245 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
8246 	struct bpf_insn *insn = new_prog->insnsi;
8247 	u32 prog_len;
8248 	int i;
8249 
8250 	/* aux info at OFF always needs adjustment, no matter fast path
8251 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
8252 	 * original insn at old prog.
8253 	 */
8254 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
8255 
8256 	if (cnt == 1)
8257 		return 0;
8258 	prog_len = new_prog->len;
8259 	new_data = vzalloc(array_size(prog_len,
8260 				      sizeof(struct bpf_insn_aux_data)));
8261 	if (!new_data)
8262 		return -ENOMEM;
8263 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
8264 	memcpy(new_data + off + cnt - 1, old_data + off,
8265 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
8266 	for (i = off; i < off + cnt - 1; i++) {
8267 		new_data[i].seen = true;
8268 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
8269 	}
8270 	env->insn_aux_data = new_data;
8271 	vfree(old_data);
8272 	return 0;
8273 }
8274 
8275 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
8276 {
8277 	int i;
8278 
8279 	if (len == 1)
8280 		return;
8281 	/* NOTE: fake 'exit' subprog should be updated as well. */
8282 	for (i = 0; i <= env->subprog_cnt; i++) {
8283 		if (env->subprog_info[i].start <= off)
8284 			continue;
8285 		env->subprog_info[i].start += len - 1;
8286 	}
8287 }
8288 
8289 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
8290 					    const struct bpf_insn *patch, u32 len)
8291 {
8292 	struct bpf_prog *new_prog;
8293 
8294 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
8295 	if (IS_ERR(new_prog)) {
8296 		if (PTR_ERR(new_prog) == -ERANGE)
8297 			verbose(env,
8298 				"insn %d cannot be patched due to 16-bit range\n",
8299 				env->insn_aux_data[off].orig_idx);
8300 		return NULL;
8301 	}
8302 	if (adjust_insn_aux_data(env, new_prog, off, len))
8303 		return NULL;
8304 	adjust_subprog_starts(env, off, len);
8305 	return new_prog;
8306 }
8307 
8308 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
8309 					      u32 off, u32 cnt)
8310 {
8311 	int i, j;
8312 
8313 	/* find first prog starting at or after off (first to remove) */
8314 	for (i = 0; i < env->subprog_cnt; i++)
8315 		if (env->subprog_info[i].start >= off)
8316 			break;
8317 	/* find first prog starting at or after off + cnt (first to stay) */
8318 	for (j = i; j < env->subprog_cnt; j++)
8319 		if (env->subprog_info[j].start >= off + cnt)
8320 			break;
8321 	/* if j doesn't start exactly at off + cnt, we are just removing
8322 	 * the front of previous prog
8323 	 */
8324 	if (env->subprog_info[j].start != off + cnt)
8325 		j--;
8326 
8327 	if (j > i) {
8328 		struct bpf_prog_aux *aux = env->prog->aux;
8329 		int move;
8330 
8331 		/* move fake 'exit' subprog as well */
8332 		move = env->subprog_cnt + 1 - j;
8333 
8334 		memmove(env->subprog_info + i,
8335 			env->subprog_info + j,
8336 			sizeof(*env->subprog_info) * move);
8337 		env->subprog_cnt -= j - i;
8338 
8339 		/* remove func_info */
8340 		if (aux->func_info) {
8341 			move = aux->func_info_cnt - j;
8342 
8343 			memmove(aux->func_info + i,
8344 				aux->func_info + j,
8345 				sizeof(*aux->func_info) * move);
8346 			aux->func_info_cnt -= j - i;
8347 			/* func_info->insn_off is set after all code rewrites,
8348 			 * in adjust_btf_func() - no need to adjust
8349 			 */
8350 		}
8351 	} else {
8352 		/* convert i from "first prog to remove" to "first to adjust" */
8353 		if (env->subprog_info[i].start == off)
8354 			i++;
8355 	}
8356 
8357 	/* update fake 'exit' subprog as well */
8358 	for (; i <= env->subprog_cnt; i++)
8359 		env->subprog_info[i].start -= cnt;
8360 
8361 	return 0;
8362 }
8363 
8364 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
8365 				      u32 cnt)
8366 {
8367 	struct bpf_prog *prog = env->prog;
8368 	u32 i, l_off, l_cnt, nr_linfo;
8369 	struct bpf_line_info *linfo;
8370 
8371 	nr_linfo = prog->aux->nr_linfo;
8372 	if (!nr_linfo)
8373 		return 0;
8374 
8375 	linfo = prog->aux->linfo;
8376 
8377 	/* find first line info to remove, count lines to be removed */
8378 	for (i = 0; i < nr_linfo; i++)
8379 		if (linfo[i].insn_off >= off)
8380 			break;
8381 
8382 	l_off = i;
8383 	l_cnt = 0;
8384 	for (; i < nr_linfo; i++)
8385 		if (linfo[i].insn_off < off + cnt)
8386 			l_cnt++;
8387 		else
8388 			break;
8389 
8390 	/* First live insn doesn't match first live linfo, it needs to "inherit"
8391 	 * last removed linfo.  prog is already modified, so prog->len == off
8392 	 * means no live instructions after (tail of the program was removed).
8393 	 */
8394 	if (prog->len != off && l_cnt &&
8395 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
8396 		l_cnt--;
8397 		linfo[--i].insn_off = off + cnt;
8398 	}
8399 
8400 	/* remove the line info which refer to the removed instructions */
8401 	if (l_cnt) {
8402 		memmove(linfo + l_off, linfo + i,
8403 			sizeof(*linfo) * (nr_linfo - i));
8404 
8405 		prog->aux->nr_linfo -= l_cnt;
8406 		nr_linfo = prog->aux->nr_linfo;
8407 	}
8408 
8409 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
8410 	for (i = l_off; i < nr_linfo; i++)
8411 		linfo[i].insn_off -= cnt;
8412 
8413 	/* fix up all subprogs (incl. 'exit') which start >= off */
8414 	for (i = 0; i <= env->subprog_cnt; i++)
8415 		if (env->subprog_info[i].linfo_idx > l_off) {
8416 			/* program may have started in the removed region but
8417 			 * may not be fully removed
8418 			 */
8419 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
8420 				env->subprog_info[i].linfo_idx -= l_cnt;
8421 			else
8422 				env->subprog_info[i].linfo_idx = l_off;
8423 		}
8424 
8425 	return 0;
8426 }
8427 
8428 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
8429 {
8430 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8431 	unsigned int orig_prog_len = env->prog->len;
8432 	int err;
8433 
8434 	if (bpf_prog_is_dev_bound(env->prog->aux))
8435 		bpf_prog_offload_remove_insns(env, off, cnt);
8436 
8437 	err = bpf_remove_insns(env->prog, off, cnt);
8438 	if (err)
8439 		return err;
8440 
8441 	err = adjust_subprog_starts_after_remove(env, off, cnt);
8442 	if (err)
8443 		return err;
8444 
8445 	err = bpf_adj_linfo_after_remove(env, off, cnt);
8446 	if (err)
8447 		return err;
8448 
8449 	memmove(aux_data + off,	aux_data + off + cnt,
8450 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
8451 
8452 	return 0;
8453 }
8454 
8455 /* The verifier does more data flow analysis than llvm and will not
8456  * explore branches that are dead at run time. Malicious programs can
8457  * have dead code too. Therefore replace all dead at-run-time code
8458  * with 'ja -1'.
8459  *
8460  * Just nops are not optimal, e.g. if they would sit at the end of the
8461  * program and through another bug we would manage to jump there, then
8462  * we'd execute beyond program memory otherwise. Returning exception
8463  * code also wouldn't work since we can have subprogs where the dead
8464  * code could be located.
8465  */
8466 static void sanitize_dead_code(struct bpf_verifier_env *env)
8467 {
8468 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8469 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
8470 	struct bpf_insn *insn = env->prog->insnsi;
8471 	const int insn_cnt = env->prog->len;
8472 	int i;
8473 
8474 	for (i = 0; i < insn_cnt; i++) {
8475 		if (aux_data[i].seen)
8476 			continue;
8477 		memcpy(insn + i, &trap, sizeof(trap));
8478 	}
8479 }
8480 
8481 static bool insn_is_cond_jump(u8 code)
8482 {
8483 	u8 op;
8484 
8485 	if (BPF_CLASS(code) == BPF_JMP32)
8486 		return true;
8487 
8488 	if (BPF_CLASS(code) != BPF_JMP)
8489 		return false;
8490 
8491 	op = BPF_OP(code);
8492 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
8493 }
8494 
8495 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
8496 {
8497 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8498 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8499 	struct bpf_insn *insn = env->prog->insnsi;
8500 	const int insn_cnt = env->prog->len;
8501 	int i;
8502 
8503 	for (i = 0; i < insn_cnt; i++, insn++) {
8504 		if (!insn_is_cond_jump(insn->code))
8505 			continue;
8506 
8507 		if (!aux_data[i + 1].seen)
8508 			ja.off = insn->off;
8509 		else if (!aux_data[i + 1 + insn->off].seen)
8510 			ja.off = 0;
8511 		else
8512 			continue;
8513 
8514 		if (bpf_prog_is_dev_bound(env->prog->aux))
8515 			bpf_prog_offload_replace_insn(env, i, &ja);
8516 
8517 		memcpy(insn, &ja, sizeof(ja));
8518 	}
8519 }
8520 
8521 static int opt_remove_dead_code(struct bpf_verifier_env *env)
8522 {
8523 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8524 	int insn_cnt = env->prog->len;
8525 	int i, err;
8526 
8527 	for (i = 0; i < insn_cnt; i++) {
8528 		int j;
8529 
8530 		j = 0;
8531 		while (i + j < insn_cnt && !aux_data[i + j].seen)
8532 			j++;
8533 		if (!j)
8534 			continue;
8535 
8536 		err = verifier_remove_insns(env, i, j);
8537 		if (err)
8538 			return err;
8539 		insn_cnt = env->prog->len;
8540 	}
8541 
8542 	return 0;
8543 }
8544 
8545 static int opt_remove_nops(struct bpf_verifier_env *env)
8546 {
8547 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8548 	struct bpf_insn *insn = env->prog->insnsi;
8549 	int insn_cnt = env->prog->len;
8550 	int i, err;
8551 
8552 	for (i = 0; i < insn_cnt; i++) {
8553 		if (memcmp(&insn[i], &ja, sizeof(ja)))
8554 			continue;
8555 
8556 		err = verifier_remove_insns(env, i, 1);
8557 		if (err)
8558 			return err;
8559 		insn_cnt--;
8560 		i--;
8561 	}
8562 
8563 	return 0;
8564 }
8565 
8566 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
8567 					 const union bpf_attr *attr)
8568 {
8569 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
8570 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
8571 	int i, patch_len, delta = 0, len = env->prog->len;
8572 	struct bpf_insn *insns = env->prog->insnsi;
8573 	struct bpf_prog *new_prog;
8574 	bool rnd_hi32;
8575 
8576 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
8577 	zext_patch[1] = BPF_ZEXT_REG(0);
8578 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
8579 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
8580 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
8581 	for (i = 0; i < len; i++) {
8582 		int adj_idx = i + delta;
8583 		struct bpf_insn insn;
8584 
8585 		insn = insns[adj_idx];
8586 		if (!aux[adj_idx].zext_dst) {
8587 			u8 code, class;
8588 			u32 imm_rnd;
8589 
8590 			if (!rnd_hi32)
8591 				continue;
8592 
8593 			code = insn.code;
8594 			class = BPF_CLASS(code);
8595 			if (insn_no_def(&insn))
8596 				continue;
8597 
8598 			/* NOTE: arg "reg" (the fourth one) is only used for
8599 			 *       BPF_STX which has been ruled out in above
8600 			 *       check, it is safe to pass NULL here.
8601 			 */
8602 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
8603 				if (class == BPF_LD &&
8604 				    BPF_MODE(code) == BPF_IMM)
8605 					i++;
8606 				continue;
8607 			}
8608 
8609 			/* ctx load could be transformed into wider load. */
8610 			if (class == BPF_LDX &&
8611 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
8612 				continue;
8613 
8614 			imm_rnd = get_random_int();
8615 			rnd_hi32_patch[0] = insn;
8616 			rnd_hi32_patch[1].imm = imm_rnd;
8617 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
8618 			patch = rnd_hi32_patch;
8619 			patch_len = 4;
8620 			goto apply_patch_buffer;
8621 		}
8622 
8623 		if (!bpf_jit_needs_zext())
8624 			continue;
8625 
8626 		zext_patch[0] = insn;
8627 		zext_patch[1].dst_reg = insn.dst_reg;
8628 		zext_patch[1].src_reg = insn.dst_reg;
8629 		patch = zext_patch;
8630 		patch_len = 2;
8631 apply_patch_buffer:
8632 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
8633 		if (!new_prog)
8634 			return -ENOMEM;
8635 		env->prog = new_prog;
8636 		insns = new_prog->insnsi;
8637 		aux = env->insn_aux_data;
8638 		delta += patch_len - 1;
8639 	}
8640 
8641 	return 0;
8642 }
8643 
8644 /* convert load instructions that access fields of a context type into a
8645  * sequence of instructions that access fields of the underlying structure:
8646  *     struct __sk_buff    -> struct sk_buff
8647  *     struct bpf_sock_ops -> struct sock
8648  */
8649 static int convert_ctx_accesses(struct bpf_verifier_env *env)
8650 {
8651 	const struct bpf_verifier_ops *ops = env->ops;
8652 	int i, cnt, size, ctx_field_size, delta = 0;
8653 	const int insn_cnt = env->prog->len;
8654 	struct bpf_insn insn_buf[16], *insn;
8655 	u32 target_size, size_default, off;
8656 	struct bpf_prog *new_prog;
8657 	enum bpf_access_type type;
8658 	bool is_narrower_load;
8659 
8660 	if (ops->gen_prologue || env->seen_direct_write) {
8661 		if (!ops->gen_prologue) {
8662 			verbose(env, "bpf verifier is misconfigured\n");
8663 			return -EINVAL;
8664 		}
8665 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
8666 					env->prog);
8667 		if (cnt >= ARRAY_SIZE(insn_buf)) {
8668 			verbose(env, "bpf verifier is misconfigured\n");
8669 			return -EINVAL;
8670 		} else if (cnt) {
8671 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
8672 			if (!new_prog)
8673 				return -ENOMEM;
8674 
8675 			env->prog = new_prog;
8676 			delta += cnt - 1;
8677 		}
8678 	}
8679 
8680 	if (bpf_prog_is_dev_bound(env->prog->aux))
8681 		return 0;
8682 
8683 	insn = env->prog->insnsi + delta;
8684 
8685 	for (i = 0; i < insn_cnt; i++, insn++) {
8686 		bpf_convert_ctx_access_t convert_ctx_access;
8687 
8688 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
8689 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
8690 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
8691 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
8692 			type = BPF_READ;
8693 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
8694 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
8695 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
8696 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
8697 			type = BPF_WRITE;
8698 		else
8699 			continue;
8700 
8701 		if (type == BPF_WRITE &&
8702 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
8703 			struct bpf_insn patch[] = {
8704 				/* Sanitize suspicious stack slot with zero.
8705 				 * There are no memory dependencies for this store,
8706 				 * since it's only using frame pointer and immediate
8707 				 * constant of zero
8708 				 */
8709 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
8710 					   env->insn_aux_data[i + delta].sanitize_stack_off,
8711 					   0),
8712 				/* the original STX instruction will immediately
8713 				 * overwrite the same stack slot with appropriate value
8714 				 */
8715 				*insn,
8716 			};
8717 
8718 			cnt = ARRAY_SIZE(patch);
8719 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
8720 			if (!new_prog)
8721 				return -ENOMEM;
8722 
8723 			delta    += cnt - 1;
8724 			env->prog = new_prog;
8725 			insn      = new_prog->insnsi + i + delta;
8726 			continue;
8727 		}
8728 
8729 		switch (env->insn_aux_data[i + delta].ptr_type) {
8730 		case PTR_TO_CTX:
8731 			if (!ops->convert_ctx_access)
8732 				continue;
8733 			convert_ctx_access = ops->convert_ctx_access;
8734 			break;
8735 		case PTR_TO_SOCKET:
8736 		case PTR_TO_SOCK_COMMON:
8737 			convert_ctx_access = bpf_sock_convert_ctx_access;
8738 			break;
8739 		case PTR_TO_TCP_SOCK:
8740 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
8741 			break;
8742 		case PTR_TO_XDP_SOCK:
8743 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
8744 			break;
8745 		case PTR_TO_BTF_ID:
8746 			if (type == BPF_WRITE) {
8747 				verbose(env, "Writes through BTF pointers are not allowed\n");
8748 				return -EINVAL;
8749 			}
8750 			insn->code = BPF_LDX | BPF_PROBE_MEM | BPF_SIZE((insn)->code);
8751 			env->prog->aux->num_exentries++;
8752 			continue;
8753 		default:
8754 			continue;
8755 		}
8756 
8757 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
8758 		size = BPF_LDST_BYTES(insn);
8759 
8760 		/* If the read access is a narrower load of the field,
8761 		 * convert to a 4/8-byte load, to minimum program type specific
8762 		 * convert_ctx_access changes. If conversion is successful,
8763 		 * we will apply proper mask to the result.
8764 		 */
8765 		is_narrower_load = size < ctx_field_size;
8766 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
8767 		off = insn->off;
8768 		if (is_narrower_load) {
8769 			u8 size_code;
8770 
8771 			if (type == BPF_WRITE) {
8772 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
8773 				return -EINVAL;
8774 			}
8775 
8776 			size_code = BPF_H;
8777 			if (ctx_field_size == 4)
8778 				size_code = BPF_W;
8779 			else if (ctx_field_size == 8)
8780 				size_code = BPF_DW;
8781 
8782 			insn->off = off & ~(size_default - 1);
8783 			insn->code = BPF_LDX | BPF_MEM | size_code;
8784 		}
8785 
8786 		target_size = 0;
8787 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
8788 					 &target_size);
8789 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
8790 		    (ctx_field_size && !target_size)) {
8791 			verbose(env, "bpf verifier is misconfigured\n");
8792 			return -EINVAL;
8793 		}
8794 
8795 		if (is_narrower_load && size < target_size) {
8796 			u8 shift = bpf_ctx_narrow_access_offset(
8797 				off, size, size_default) * 8;
8798 			if (ctx_field_size <= 4) {
8799 				if (shift)
8800 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
8801 									insn->dst_reg,
8802 									shift);
8803 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
8804 								(1 << size * 8) - 1);
8805 			} else {
8806 				if (shift)
8807 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
8808 									insn->dst_reg,
8809 									shift);
8810 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
8811 								(1ULL << size * 8) - 1);
8812 			}
8813 		}
8814 
8815 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8816 		if (!new_prog)
8817 			return -ENOMEM;
8818 
8819 		delta += cnt - 1;
8820 
8821 		/* keep walking new program and skip insns we just inserted */
8822 		env->prog = new_prog;
8823 		insn      = new_prog->insnsi + i + delta;
8824 	}
8825 
8826 	return 0;
8827 }
8828 
8829 static int jit_subprogs(struct bpf_verifier_env *env)
8830 {
8831 	struct bpf_prog *prog = env->prog, **func, *tmp;
8832 	int i, j, subprog_start, subprog_end = 0, len, subprog;
8833 	struct bpf_insn *insn;
8834 	void *old_bpf_func;
8835 	int err;
8836 
8837 	if (env->subprog_cnt <= 1)
8838 		return 0;
8839 
8840 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8841 		if (insn->code != (BPF_JMP | BPF_CALL) ||
8842 		    insn->src_reg != BPF_PSEUDO_CALL)
8843 			continue;
8844 		/* Upon error here we cannot fall back to interpreter but
8845 		 * need a hard reject of the program. Thus -EFAULT is
8846 		 * propagated in any case.
8847 		 */
8848 		subprog = find_subprog(env, i + insn->imm + 1);
8849 		if (subprog < 0) {
8850 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
8851 				  i + insn->imm + 1);
8852 			return -EFAULT;
8853 		}
8854 		/* temporarily remember subprog id inside insn instead of
8855 		 * aux_data, since next loop will split up all insns into funcs
8856 		 */
8857 		insn->off = subprog;
8858 		/* remember original imm in case JIT fails and fallback
8859 		 * to interpreter will be needed
8860 		 */
8861 		env->insn_aux_data[i].call_imm = insn->imm;
8862 		/* point imm to __bpf_call_base+1 from JITs point of view */
8863 		insn->imm = 1;
8864 	}
8865 
8866 	err = bpf_prog_alloc_jited_linfo(prog);
8867 	if (err)
8868 		goto out_undo_insn;
8869 
8870 	err = -ENOMEM;
8871 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
8872 	if (!func)
8873 		goto out_undo_insn;
8874 
8875 	for (i = 0; i < env->subprog_cnt; i++) {
8876 		subprog_start = subprog_end;
8877 		subprog_end = env->subprog_info[i + 1].start;
8878 
8879 		len = subprog_end - subprog_start;
8880 		/* BPF_PROG_RUN doesn't call subprogs directly,
8881 		 * hence main prog stats include the runtime of subprogs.
8882 		 * subprogs don't have IDs and not reachable via prog_get_next_id
8883 		 * func[i]->aux->stats will never be accessed and stays NULL
8884 		 */
8885 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
8886 		if (!func[i])
8887 			goto out_free;
8888 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
8889 		       len * sizeof(struct bpf_insn));
8890 		func[i]->type = prog->type;
8891 		func[i]->len = len;
8892 		if (bpf_prog_calc_tag(func[i]))
8893 			goto out_free;
8894 		func[i]->is_func = 1;
8895 		func[i]->aux->func_idx = i;
8896 		/* the btf and func_info will be freed only at prog->aux */
8897 		func[i]->aux->btf = prog->aux->btf;
8898 		func[i]->aux->func_info = prog->aux->func_info;
8899 
8900 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
8901 		 * Long term would need debug info to populate names
8902 		 */
8903 		func[i]->aux->name[0] = 'F';
8904 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
8905 		func[i]->jit_requested = 1;
8906 		func[i]->aux->linfo = prog->aux->linfo;
8907 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
8908 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
8909 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
8910 		func[i] = bpf_int_jit_compile(func[i]);
8911 		if (!func[i]->jited) {
8912 			err = -ENOTSUPP;
8913 			goto out_free;
8914 		}
8915 		cond_resched();
8916 	}
8917 	/* at this point all bpf functions were successfully JITed
8918 	 * now populate all bpf_calls with correct addresses and
8919 	 * run last pass of JIT
8920 	 */
8921 	for (i = 0; i < env->subprog_cnt; i++) {
8922 		insn = func[i]->insnsi;
8923 		for (j = 0; j < func[i]->len; j++, insn++) {
8924 			if (insn->code != (BPF_JMP | BPF_CALL) ||
8925 			    insn->src_reg != BPF_PSEUDO_CALL)
8926 				continue;
8927 			subprog = insn->off;
8928 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
8929 				    __bpf_call_base;
8930 		}
8931 
8932 		/* we use the aux data to keep a list of the start addresses
8933 		 * of the JITed images for each function in the program
8934 		 *
8935 		 * for some architectures, such as powerpc64, the imm field
8936 		 * might not be large enough to hold the offset of the start
8937 		 * address of the callee's JITed image from __bpf_call_base
8938 		 *
8939 		 * in such cases, we can lookup the start address of a callee
8940 		 * by using its subprog id, available from the off field of
8941 		 * the call instruction, as an index for this list
8942 		 */
8943 		func[i]->aux->func = func;
8944 		func[i]->aux->func_cnt = env->subprog_cnt;
8945 	}
8946 	for (i = 0; i < env->subprog_cnt; i++) {
8947 		old_bpf_func = func[i]->bpf_func;
8948 		tmp = bpf_int_jit_compile(func[i]);
8949 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
8950 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
8951 			err = -ENOTSUPP;
8952 			goto out_free;
8953 		}
8954 		cond_resched();
8955 	}
8956 
8957 	/* finally lock prog and jit images for all functions and
8958 	 * populate kallsysm
8959 	 */
8960 	for (i = 0; i < env->subprog_cnt; i++) {
8961 		bpf_prog_lock_ro(func[i]);
8962 		bpf_prog_kallsyms_add(func[i]);
8963 	}
8964 
8965 	/* Last step: make now unused interpreter insns from main
8966 	 * prog consistent for later dump requests, so they can
8967 	 * later look the same as if they were interpreted only.
8968 	 */
8969 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8970 		if (insn->code != (BPF_JMP | BPF_CALL) ||
8971 		    insn->src_reg != BPF_PSEUDO_CALL)
8972 			continue;
8973 		insn->off = env->insn_aux_data[i].call_imm;
8974 		subprog = find_subprog(env, i + insn->off + 1);
8975 		insn->imm = subprog;
8976 	}
8977 
8978 	prog->jited = 1;
8979 	prog->bpf_func = func[0]->bpf_func;
8980 	prog->aux->func = func;
8981 	prog->aux->func_cnt = env->subprog_cnt;
8982 	bpf_prog_free_unused_jited_linfo(prog);
8983 	return 0;
8984 out_free:
8985 	for (i = 0; i < env->subprog_cnt; i++)
8986 		if (func[i])
8987 			bpf_jit_free(func[i]);
8988 	kfree(func);
8989 out_undo_insn:
8990 	/* cleanup main prog to be interpreted */
8991 	prog->jit_requested = 0;
8992 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8993 		if (insn->code != (BPF_JMP | BPF_CALL) ||
8994 		    insn->src_reg != BPF_PSEUDO_CALL)
8995 			continue;
8996 		insn->off = 0;
8997 		insn->imm = env->insn_aux_data[i].call_imm;
8998 	}
8999 	bpf_prog_free_jited_linfo(prog);
9000 	return err;
9001 }
9002 
9003 static int fixup_call_args(struct bpf_verifier_env *env)
9004 {
9005 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9006 	struct bpf_prog *prog = env->prog;
9007 	struct bpf_insn *insn = prog->insnsi;
9008 	int i, depth;
9009 #endif
9010 	int err = 0;
9011 
9012 	if (env->prog->jit_requested &&
9013 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
9014 		err = jit_subprogs(env);
9015 		if (err == 0)
9016 			return 0;
9017 		if (err == -EFAULT)
9018 			return err;
9019 	}
9020 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9021 	for (i = 0; i < prog->len; i++, insn++) {
9022 		if (insn->code != (BPF_JMP | BPF_CALL) ||
9023 		    insn->src_reg != BPF_PSEUDO_CALL)
9024 			continue;
9025 		depth = get_callee_stack_depth(env, insn, i);
9026 		if (depth < 0)
9027 			return depth;
9028 		bpf_patch_call_args(insn, depth);
9029 	}
9030 	err = 0;
9031 #endif
9032 	return err;
9033 }
9034 
9035 /* fixup insn->imm field of bpf_call instructions
9036  * and inline eligible helpers as explicit sequence of BPF instructions
9037  *
9038  * this function is called after eBPF program passed verification
9039  */
9040 static int fixup_bpf_calls(struct bpf_verifier_env *env)
9041 {
9042 	struct bpf_prog *prog = env->prog;
9043 	struct bpf_insn *insn = prog->insnsi;
9044 	const struct bpf_func_proto *fn;
9045 	const int insn_cnt = prog->len;
9046 	const struct bpf_map_ops *ops;
9047 	struct bpf_insn_aux_data *aux;
9048 	struct bpf_insn insn_buf[16];
9049 	struct bpf_prog *new_prog;
9050 	struct bpf_map *map_ptr;
9051 	int i, cnt, delta = 0;
9052 
9053 	for (i = 0; i < insn_cnt; i++, insn++) {
9054 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9055 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9056 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
9057 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9058 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9059 			struct bpf_insn mask_and_div[] = {
9060 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9061 				/* Rx div 0 -> 0 */
9062 				BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
9063 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9064 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9065 				*insn,
9066 			};
9067 			struct bpf_insn mask_and_mod[] = {
9068 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9069 				/* Rx mod 0 -> Rx */
9070 				BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
9071 				*insn,
9072 			};
9073 			struct bpf_insn *patchlet;
9074 
9075 			if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9076 			    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9077 				patchlet = mask_and_div + (is64 ? 1 : 0);
9078 				cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
9079 			} else {
9080 				patchlet = mask_and_mod + (is64 ? 1 : 0);
9081 				cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
9082 			}
9083 
9084 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
9085 			if (!new_prog)
9086 				return -ENOMEM;
9087 
9088 			delta    += cnt - 1;
9089 			env->prog = prog = new_prog;
9090 			insn      = new_prog->insnsi + i + delta;
9091 			continue;
9092 		}
9093 
9094 		if (BPF_CLASS(insn->code) == BPF_LD &&
9095 		    (BPF_MODE(insn->code) == BPF_ABS ||
9096 		     BPF_MODE(insn->code) == BPF_IND)) {
9097 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
9098 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9099 				verbose(env, "bpf verifier is misconfigured\n");
9100 				return -EINVAL;
9101 			}
9102 
9103 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9104 			if (!new_prog)
9105 				return -ENOMEM;
9106 
9107 			delta    += cnt - 1;
9108 			env->prog = prog = new_prog;
9109 			insn      = new_prog->insnsi + i + delta;
9110 			continue;
9111 		}
9112 
9113 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9114 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9115 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9116 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9117 			struct bpf_insn insn_buf[16];
9118 			struct bpf_insn *patch = &insn_buf[0];
9119 			bool issrc, isneg;
9120 			u32 off_reg;
9121 
9122 			aux = &env->insn_aux_data[i + delta];
9123 			if (!aux->alu_state ||
9124 			    aux->alu_state == BPF_ALU_NON_POINTER)
9125 				continue;
9126 
9127 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9128 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9129 				BPF_ALU_SANITIZE_SRC;
9130 
9131 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
9132 			if (isneg)
9133 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9134 			*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
9135 			*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9136 			*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9137 			*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9138 			*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9139 			if (issrc) {
9140 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
9141 							 off_reg);
9142 				insn->src_reg = BPF_REG_AX;
9143 			} else {
9144 				*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
9145 							 BPF_REG_AX);
9146 			}
9147 			if (isneg)
9148 				insn->code = insn->code == code_add ?
9149 					     code_sub : code_add;
9150 			*patch++ = *insn;
9151 			if (issrc && isneg)
9152 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9153 			cnt = patch - insn_buf;
9154 
9155 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9156 			if (!new_prog)
9157 				return -ENOMEM;
9158 
9159 			delta    += cnt - 1;
9160 			env->prog = prog = new_prog;
9161 			insn      = new_prog->insnsi + i + delta;
9162 			continue;
9163 		}
9164 
9165 		if (insn->code != (BPF_JMP | BPF_CALL))
9166 			continue;
9167 		if (insn->src_reg == BPF_PSEUDO_CALL)
9168 			continue;
9169 
9170 		if (insn->imm == BPF_FUNC_get_route_realm)
9171 			prog->dst_needed = 1;
9172 		if (insn->imm == BPF_FUNC_get_prandom_u32)
9173 			bpf_user_rnd_init_once();
9174 		if (insn->imm == BPF_FUNC_override_return)
9175 			prog->kprobe_override = 1;
9176 		if (insn->imm == BPF_FUNC_tail_call) {
9177 			/* If we tail call into other programs, we
9178 			 * cannot make any assumptions since they can
9179 			 * be replaced dynamically during runtime in
9180 			 * the program array.
9181 			 */
9182 			prog->cb_access = 1;
9183 			env->prog->aux->stack_depth = MAX_BPF_STACK;
9184 			env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
9185 
9186 			/* mark bpf_tail_call as different opcode to avoid
9187 			 * conditional branch in the interpeter for every normal
9188 			 * call and to prevent accidental JITing by JIT compiler
9189 			 * that doesn't support bpf_tail_call yet
9190 			 */
9191 			insn->imm = 0;
9192 			insn->code = BPF_JMP | BPF_TAIL_CALL;
9193 
9194 			aux = &env->insn_aux_data[i + delta];
9195 			if (!bpf_map_ptr_unpriv(aux))
9196 				continue;
9197 
9198 			/* instead of changing every JIT dealing with tail_call
9199 			 * emit two extra insns:
9200 			 * if (index >= max_entries) goto out;
9201 			 * index &= array->index_mask;
9202 			 * to avoid out-of-bounds cpu speculation
9203 			 */
9204 			if (bpf_map_ptr_poisoned(aux)) {
9205 				verbose(env, "tail_call abusing map_ptr\n");
9206 				return -EINVAL;
9207 			}
9208 
9209 			map_ptr = BPF_MAP_PTR(aux->map_state);
9210 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9211 						  map_ptr->max_entries, 2);
9212 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9213 						    container_of(map_ptr,
9214 								 struct bpf_array,
9215 								 map)->index_mask);
9216 			insn_buf[2] = *insn;
9217 			cnt = 3;
9218 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9219 			if (!new_prog)
9220 				return -ENOMEM;
9221 
9222 			delta    += cnt - 1;
9223 			env->prog = prog = new_prog;
9224 			insn      = new_prog->insnsi + i + delta;
9225 			continue;
9226 		}
9227 
9228 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
9229 		 * and other inlining handlers are currently limited to 64 bit
9230 		 * only.
9231 		 */
9232 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
9233 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
9234 		     insn->imm == BPF_FUNC_map_update_elem ||
9235 		     insn->imm == BPF_FUNC_map_delete_elem ||
9236 		     insn->imm == BPF_FUNC_map_push_elem   ||
9237 		     insn->imm == BPF_FUNC_map_pop_elem    ||
9238 		     insn->imm == BPF_FUNC_map_peek_elem)) {
9239 			aux = &env->insn_aux_data[i + delta];
9240 			if (bpf_map_ptr_poisoned(aux))
9241 				goto patch_call_imm;
9242 
9243 			map_ptr = BPF_MAP_PTR(aux->map_state);
9244 			ops = map_ptr->ops;
9245 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
9246 			    ops->map_gen_lookup) {
9247 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
9248 				if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9249 					verbose(env, "bpf verifier is misconfigured\n");
9250 					return -EINVAL;
9251 				}
9252 
9253 				new_prog = bpf_patch_insn_data(env, i + delta,
9254 							       insn_buf, cnt);
9255 				if (!new_prog)
9256 					return -ENOMEM;
9257 
9258 				delta    += cnt - 1;
9259 				env->prog = prog = new_prog;
9260 				insn      = new_prog->insnsi + i + delta;
9261 				continue;
9262 			}
9263 
9264 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
9265 				     (void *(*)(struct bpf_map *map, void *key))NULL));
9266 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
9267 				     (int (*)(struct bpf_map *map, void *key))NULL));
9268 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
9269 				     (int (*)(struct bpf_map *map, void *key, void *value,
9270 					      u64 flags))NULL));
9271 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
9272 				     (int (*)(struct bpf_map *map, void *value,
9273 					      u64 flags))NULL));
9274 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
9275 				     (int (*)(struct bpf_map *map, void *value))NULL));
9276 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
9277 				     (int (*)(struct bpf_map *map, void *value))NULL));
9278 
9279 			switch (insn->imm) {
9280 			case BPF_FUNC_map_lookup_elem:
9281 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
9282 					    __bpf_call_base;
9283 				continue;
9284 			case BPF_FUNC_map_update_elem:
9285 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
9286 					    __bpf_call_base;
9287 				continue;
9288 			case BPF_FUNC_map_delete_elem:
9289 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
9290 					    __bpf_call_base;
9291 				continue;
9292 			case BPF_FUNC_map_push_elem:
9293 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
9294 					    __bpf_call_base;
9295 				continue;
9296 			case BPF_FUNC_map_pop_elem:
9297 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
9298 					    __bpf_call_base;
9299 				continue;
9300 			case BPF_FUNC_map_peek_elem:
9301 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
9302 					    __bpf_call_base;
9303 				continue;
9304 			}
9305 
9306 			goto patch_call_imm;
9307 		}
9308 
9309 patch_call_imm:
9310 		fn = env->ops->get_func_proto(insn->imm, env->prog);
9311 		/* all functions that have prototype and verifier allowed
9312 		 * programs to call them, must be real in-kernel functions
9313 		 */
9314 		if (!fn->func) {
9315 			verbose(env,
9316 				"kernel subsystem misconfigured func %s#%d\n",
9317 				func_id_name(insn->imm), insn->imm);
9318 			return -EFAULT;
9319 		}
9320 		insn->imm = fn->func - __bpf_call_base;
9321 	}
9322 
9323 	return 0;
9324 }
9325 
9326 static void free_states(struct bpf_verifier_env *env)
9327 {
9328 	struct bpf_verifier_state_list *sl, *sln;
9329 	int i;
9330 
9331 	sl = env->free_list;
9332 	while (sl) {
9333 		sln = sl->next;
9334 		free_verifier_state(&sl->state, false);
9335 		kfree(sl);
9336 		sl = sln;
9337 	}
9338 
9339 	if (!env->explored_states)
9340 		return;
9341 
9342 	for (i = 0; i < state_htab_size(env); i++) {
9343 		sl = env->explored_states[i];
9344 
9345 		while (sl) {
9346 			sln = sl->next;
9347 			free_verifier_state(&sl->state, false);
9348 			kfree(sl);
9349 			sl = sln;
9350 		}
9351 	}
9352 
9353 	kvfree(env->explored_states);
9354 }
9355 
9356 static void print_verification_stats(struct bpf_verifier_env *env)
9357 {
9358 	int i;
9359 
9360 	if (env->log.level & BPF_LOG_STATS) {
9361 		verbose(env, "verification time %lld usec\n",
9362 			div_u64(env->verification_time, 1000));
9363 		verbose(env, "stack depth ");
9364 		for (i = 0; i < env->subprog_cnt; i++) {
9365 			u32 depth = env->subprog_info[i].stack_depth;
9366 
9367 			verbose(env, "%d", depth);
9368 			if (i + 1 < env->subprog_cnt)
9369 				verbose(env, "+");
9370 		}
9371 		verbose(env, "\n");
9372 	}
9373 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
9374 		"total_states %d peak_states %d mark_read %d\n",
9375 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
9376 		env->max_states_per_insn, env->total_states,
9377 		env->peak_states, env->longest_mark_read_walk);
9378 }
9379 
9380 static int check_attach_btf_id(struct bpf_verifier_env *env)
9381 {
9382 	struct bpf_prog *prog = env->prog;
9383 	u32 btf_id = prog->aux->attach_btf_id;
9384 	const char prefix[] = "btf_trace_";
9385 	const struct btf_type *t;
9386 	const char *tname;
9387 
9388 	if (prog->type != BPF_PROG_TYPE_TRACING)
9389 		return 0;
9390 
9391 	if (!btf_id) {
9392 		verbose(env, "Tracing programs must provide btf_id\n");
9393 		return -EINVAL;
9394 	}
9395 	t = btf_type_by_id(btf_vmlinux, btf_id);
9396 	if (!t) {
9397 		verbose(env, "attach_btf_id %u is invalid\n", btf_id);
9398 		return -EINVAL;
9399 	}
9400 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9401 	if (!tname) {
9402 		verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
9403 		return -EINVAL;
9404 	}
9405 
9406 	switch (prog->expected_attach_type) {
9407 	case BPF_TRACE_RAW_TP:
9408 		if (!btf_type_is_typedef(t)) {
9409 			verbose(env, "attach_btf_id %u is not a typedef\n",
9410 				btf_id);
9411 			return -EINVAL;
9412 		}
9413 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
9414 			verbose(env, "attach_btf_id %u points to wrong type name %s\n",
9415 				btf_id, tname);
9416 			return -EINVAL;
9417 		}
9418 		tname += sizeof(prefix) - 1;
9419 		t = btf_type_by_id(btf_vmlinux, t->type);
9420 		if (!btf_type_is_ptr(t))
9421 			/* should never happen in valid vmlinux build */
9422 			return -EINVAL;
9423 		t = btf_type_by_id(btf_vmlinux, t->type);
9424 		if (!btf_type_is_func_proto(t))
9425 			/* should never happen in valid vmlinux build */
9426 			return -EINVAL;
9427 
9428 		/* remember two read only pointers that are valid for
9429 		 * the life time of the kernel
9430 		 */
9431 		prog->aux->attach_func_name = tname;
9432 		prog->aux->attach_func_proto = t;
9433 		prog->aux->attach_btf_trace = true;
9434 		return 0;
9435 	default:
9436 		return -EINVAL;
9437 	}
9438 }
9439 
9440 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
9441 	      union bpf_attr __user *uattr)
9442 {
9443 	u64 start_time = ktime_get_ns();
9444 	struct bpf_verifier_env *env;
9445 	struct bpf_verifier_log *log;
9446 	int i, len, ret = -EINVAL;
9447 	bool is_priv;
9448 
9449 	/* no program is valid */
9450 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
9451 		return -EINVAL;
9452 
9453 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
9454 	 * allocate/free it every time bpf_check() is called
9455 	 */
9456 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
9457 	if (!env)
9458 		return -ENOMEM;
9459 	log = &env->log;
9460 
9461 	len = (*prog)->len;
9462 	env->insn_aux_data =
9463 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
9464 	ret = -ENOMEM;
9465 	if (!env->insn_aux_data)
9466 		goto err_free_env;
9467 	for (i = 0; i < len; i++)
9468 		env->insn_aux_data[i].orig_idx = i;
9469 	env->prog = *prog;
9470 	env->ops = bpf_verifier_ops[env->prog->type];
9471 	is_priv = capable(CAP_SYS_ADMIN);
9472 
9473 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
9474 		mutex_lock(&bpf_verifier_lock);
9475 		if (!btf_vmlinux)
9476 			btf_vmlinux = btf_parse_vmlinux();
9477 		mutex_unlock(&bpf_verifier_lock);
9478 	}
9479 
9480 	/* grab the mutex to protect few globals used by verifier */
9481 	if (!is_priv)
9482 		mutex_lock(&bpf_verifier_lock);
9483 
9484 	if (attr->log_level || attr->log_buf || attr->log_size) {
9485 		/* user requested verbose verifier output
9486 		 * and supplied buffer to store the verification trace
9487 		 */
9488 		log->level = attr->log_level;
9489 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
9490 		log->len_total = attr->log_size;
9491 
9492 		ret = -EINVAL;
9493 		/* log attributes have to be sane */
9494 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
9495 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
9496 			goto err_unlock;
9497 	}
9498 
9499 	if (IS_ERR(btf_vmlinux)) {
9500 		/* Either gcc or pahole or kernel are broken. */
9501 		verbose(env, "in-kernel BTF is malformed\n");
9502 		ret = PTR_ERR(btf_vmlinux);
9503 		goto skip_full_check;
9504 	}
9505 
9506 	ret = check_attach_btf_id(env);
9507 	if (ret)
9508 		goto skip_full_check;
9509 
9510 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
9511 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
9512 		env->strict_alignment = true;
9513 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
9514 		env->strict_alignment = false;
9515 
9516 	env->allow_ptr_leaks = is_priv;
9517 
9518 	if (is_priv)
9519 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
9520 
9521 	ret = replace_map_fd_with_map_ptr(env);
9522 	if (ret < 0)
9523 		goto skip_full_check;
9524 
9525 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
9526 		ret = bpf_prog_offload_verifier_prep(env->prog);
9527 		if (ret)
9528 			goto skip_full_check;
9529 	}
9530 
9531 	env->explored_states = kvcalloc(state_htab_size(env),
9532 				       sizeof(struct bpf_verifier_state_list *),
9533 				       GFP_USER);
9534 	ret = -ENOMEM;
9535 	if (!env->explored_states)
9536 		goto skip_full_check;
9537 
9538 	ret = check_subprogs(env);
9539 	if (ret < 0)
9540 		goto skip_full_check;
9541 
9542 	ret = check_btf_info(env, attr, uattr);
9543 	if (ret < 0)
9544 		goto skip_full_check;
9545 
9546 	ret = check_cfg(env);
9547 	if (ret < 0)
9548 		goto skip_full_check;
9549 
9550 	ret = do_check(env);
9551 	if (env->cur_state) {
9552 		free_verifier_state(env->cur_state, true);
9553 		env->cur_state = NULL;
9554 	}
9555 
9556 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
9557 		ret = bpf_prog_offload_finalize(env);
9558 
9559 skip_full_check:
9560 	while (!pop_stack(env, NULL, NULL));
9561 	free_states(env);
9562 
9563 	if (ret == 0)
9564 		ret = check_max_stack_depth(env);
9565 
9566 	/* instruction rewrites happen after this point */
9567 	if (is_priv) {
9568 		if (ret == 0)
9569 			opt_hard_wire_dead_code_branches(env);
9570 		if (ret == 0)
9571 			ret = opt_remove_dead_code(env);
9572 		if (ret == 0)
9573 			ret = opt_remove_nops(env);
9574 	} else {
9575 		if (ret == 0)
9576 			sanitize_dead_code(env);
9577 	}
9578 
9579 	if (ret == 0)
9580 		/* program is valid, convert *(u32*)(ctx + off) accesses */
9581 		ret = convert_ctx_accesses(env);
9582 
9583 	if (ret == 0)
9584 		ret = fixup_bpf_calls(env);
9585 
9586 	/* do 32-bit optimization after insn patching has done so those patched
9587 	 * insns could be handled correctly.
9588 	 */
9589 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
9590 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
9591 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
9592 								     : false;
9593 	}
9594 
9595 	if (ret == 0)
9596 		ret = fixup_call_args(env);
9597 
9598 	env->verification_time = ktime_get_ns() - start_time;
9599 	print_verification_stats(env);
9600 
9601 	if (log->level && bpf_verifier_log_full(log))
9602 		ret = -ENOSPC;
9603 	if (log->level && !log->ubuf) {
9604 		ret = -EFAULT;
9605 		goto err_release_maps;
9606 	}
9607 
9608 	if (ret == 0 && env->used_map_cnt) {
9609 		/* if program passed verifier, update used_maps in bpf_prog_info */
9610 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
9611 							  sizeof(env->used_maps[0]),
9612 							  GFP_KERNEL);
9613 
9614 		if (!env->prog->aux->used_maps) {
9615 			ret = -ENOMEM;
9616 			goto err_release_maps;
9617 		}
9618 
9619 		memcpy(env->prog->aux->used_maps, env->used_maps,
9620 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
9621 		env->prog->aux->used_map_cnt = env->used_map_cnt;
9622 
9623 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
9624 		 * bpf_ld_imm64 instructions
9625 		 */
9626 		convert_pseudo_ld_imm64(env);
9627 	}
9628 
9629 	if (ret == 0)
9630 		adjust_btf_func(env);
9631 
9632 err_release_maps:
9633 	if (!env->prog->aux->used_maps)
9634 		/* if we didn't copy map pointers into bpf_prog_info, release
9635 		 * them now. Otherwise free_used_maps() will release them.
9636 		 */
9637 		release_maps(env);
9638 	*prog = env->prog;
9639 err_unlock:
9640 	if (!is_priv)
9641 		mutex_unlock(&bpf_verifier_lock);
9642 	vfree(env->insn_aux_data);
9643 err_free_env:
9644 	kfree(env);
9645 	return ret;
9646 }
9647