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