xref: /openbmc/linux/kernel/bpf/verifier.c (revision 6a6d6681ac1add9655b7ab5dd0b46b54aeb1b44f)
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2  * Copyright (c) 2016 Facebook
3  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 2 of the GNU General Public
7  * License as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * General Public License for more details.
13  */
14 #include <uapi/linux/btf.h>
15 #include <linux/kernel.h>
16 #include <linux/types.h>
17 #include <linux/slab.h>
18 #include <linux/bpf.h>
19 #include <linux/btf.h>
20 #include <linux/bpf_verifier.h>
21 #include <linux/filter.h>
22 #include <net/netlink.h>
23 #include <linux/file.h>
24 #include <linux/vmalloc.h>
25 #include <linux/stringify.h>
26 #include <linux/bsearch.h>
27 #include <linux/sort.h>
28 #include <linux/perf_event.h>
29 
30 #include "disasm.h"
31 
32 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
33 #define BPF_PROG_TYPE(_id, _name) \
34 	[_id] = & _name ## _verifier_ops,
35 #define BPF_MAP_TYPE(_id, _ops)
36 #include <linux/bpf_types.h>
37 #undef BPF_PROG_TYPE
38 #undef BPF_MAP_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all pathes through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns ether pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_INSNS	131072
179 #define BPF_COMPLEXITY_LIMIT_STACK	1024
180 
181 #define BPF_MAP_PTR_UNPRIV	1UL
182 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
183 					  POISON_POINTER_DELTA))
184 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
185 
186 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
187 {
188 	return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
189 }
190 
191 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
192 {
193 	return aux->map_state & BPF_MAP_PTR_UNPRIV;
194 }
195 
196 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
197 			      const struct bpf_map *map, bool unpriv)
198 {
199 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
200 	unpriv |= bpf_map_ptr_unpriv(aux);
201 	aux->map_state = (unsigned long)map |
202 			 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
203 }
204 
205 struct bpf_call_arg_meta {
206 	struct bpf_map *map_ptr;
207 	bool raw_mode;
208 	bool pkt_access;
209 	int regno;
210 	int access_size;
211 	s64 msize_smax_value;
212 	u64 msize_umax_value;
213 	int ptr_id;
214 };
215 
216 static DEFINE_MUTEX(bpf_verifier_lock);
217 
218 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
219 		       va_list args)
220 {
221 	unsigned int n;
222 
223 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
224 
225 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
226 		  "verifier log line truncated - local buffer too short\n");
227 
228 	n = min(log->len_total - log->len_used - 1, n);
229 	log->kbuf[n] = '\0';
230 
231 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
232 		log->len_used += n;
233 	else
234 		log->ubuf = NULL;
235 }
236 
237 /* log_level controls verbosity level of eBPF verifier.
238  * bpf_verifier_log_write() is used to dump the verification trace to the log,
239  * so the user can figure out what's wrong with the program
240  */
241 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
242 					   const char *fmt, ...)
243 {
244 	va_list args;
245 
246 	if (!bpf_verifier_log_needed(&env->log))
247 		return;
248 
249 	va_start(args, fmt);
250 	bpf_verifier_vlog(&env->log, fmt, args);
251 	va_end(args);
252 }
253 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
254 
255 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
256 {
257 	struct bpf_verifier_env *env = private_data;
258 	va_list args;
259 
260 	if (!bpf_verifier_log_needed(&env->log))
261 		return;
262 
263 	va_start(args, fmt);
264 	bpf_verifier_vlog(&env->log, fmt, args);
265 	va_end(args);
266 }
267 
268 static bool type_is_pkt_pointer(enum bpf_reg_type type)
269 {
270 	return type == PTR_TO_PACKET ||
271 	       type == PTR_TO_PACKET_META;
272 }
273 
274 static bool reg_type_may_be_null(enum bpf_reg_type type)
275 {
276 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
277 	       type == PTR_TO_SOCKET_OR_NULL;
278 }
279 
280 static bool type_is_refcounted(enum bpf_reg_type type)
281 {
282 	return type == PTR_TO_SOCKET;
283 }
284 
285 static bool type_is_refcounted_or_null(enum bpf_reg_type type)
286 {
287 	return type == PTR_TO_SOCKET || type == PTR_TO_SOCKET_OR_NULL;
288 }
289 
290 static bool reg_is_refcounted(const struct bpf_reg_state *reg)
291 {
292 	return type_is_refcounted(reg->type);
293 }
294 
295 static bool reg_is_refcounted_or_null(const struct bpf_reg_state *reg)
296 {
297 	return type_is_refcounted_or_null(reg->type);
298 }
299 
300 static bool arg_type_is_refcounted(enum bpf_arg_type type)
301 {
302 	return type == ARG_PTR_TO_SOCKET;
303 }
304 
305 /* Determine whether the function releases some resources allocated by another
306  * function call. The first reference type argument will be assumed to be
307  * released by release_reference().
308  */
309 static bool is_release_function(enum bpf_func_id func_id)
310 {
311 	return func_id == BPF_FUNC_sk_release;
312 }
313 
314 /* string representation of 'enum bpf_reg_type' */
315 static const char * const reg_type_str[] = {
316 	[NOT_INIT]		= "?",
317 	[SCALAR_VALUE]		= "inv",
318 	[PTR_TO_CTX]		= "ctx",
319 	[CONST_PTR_TO_MAP]	= "map_ptr",
320 	[PTR_TO_MAP_VALUE]	= "map_value",
321 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
322 	[PTR_TO_STACK]		= "fp",
323 	[PTR_TO_PACKET]		= "pkt",
324 	[PTR_TO_PACKET_META]	= "pkt_meta",
325 	[PTR_TO_PACKET_END]	= "pkt_end",
326 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
327 	[PTR_TO_SOCKET]		= "sock",
328 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
329 };
330 
331 static char slot_type_char[] = {
332 	[STACK_INVALID]	= '?',
333 	[STACK_SPILL]	= 'r',
334 	[STACK_MISC]	= 'm',
335 	[STACK_ZERO]	= '0',
336 };
337 
338 static void print_liveness(struct bpf_verifier_env *env,
339 			   enum bpf_reg_liveness live)
340 {
341 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
342 	    verbose(env, "_");
343 	if (live & REG_LIVE_READ)
344 		verbose(env, "r");
345 	if (live & REG_LIVE_WRITTEN)
346 		verbose(env, "w");
347 }
348 
349 static struct bpf_func_state *func(struct bpf_verifier_env *env,
350 				   const struct bpf_reg_state *reg)
351 {
352 	struct bpf_verifier_state *cur = env->cur_state;
353 
354 	return cur->frame[reg->frameno];
355 }
356 
357 static void print_verifier_state(struct bpf_verifier_env *env,
358 				 const struct bpf_func_state *state)
359 {
360 	const struct bpf_reg_state *reg;
361 	enum bpf_reg_type t;
362 	int i;
363 
364 	if (state->frameno)
365 		verbose(env, " frame%d:", state->frameno);
366 	for (i = 0; i < MAX_BPF_REG; i++) {
367 		reg = &state->regs[i];
368 		t = reg->type;
369 		if (t == NOT_INIT)
370 			continue;
371 		verbose(env, " R%d", i);
372 		print_liveness(env, reg->live);
373 		verbose(env, "=%s", reg_type_str[t]);
374 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
375 		    tnum_is_const(reg->var_off)) {
376 			/* reg->off should be 0 for SCALAR_VALUE */
377 			verbose(env, "%lld", reg->var_off.value + reg->off);
378 			if (t == PTR_TO_STACK)
379 				verbose(env, ",call_%d", func(env, reg)->callsite);
380 		} else {
381 			verbose(env, "(id=%d", reg->id);
382 			if (t != SCALAR_VALUE)
383 				verbose(env, ",off=%d", reg->off);
384 			if (type_is_pkt_pointer(t))
385 				verbose(env, ",r=%d", reg->range);
386 			else if (t == CONST_PTR_TO_MAP ||
387 				 t == PTR_TO_MAP_VALUE ||
388 				 t == PTR_TO_MAP_VALUE_OR_NULL)
389 				verbose(env, ",ks=%d,vs=%d",
390 					reg->map_ptr->key_size,
391 					reg->map_ptr->value_size);
392 			if (tnum_is_const(reg->var_off)) {
393 				/* Typically an immediate SCALAR_VALUE, but
394 				 * could be a pointer whose offset is too big
395 				 * for reg->off
396 				 */
397 				verbose(env, ",imm=%llx", reg->var_off.value);
398 			} else {
399 				if (reg->smin_value != reg->umin_value &&
400 				    reg->smin_value != S64_MIN)
401 					verbose(env, ",smin_value=%lld",
402 						(long long)reg->smin_value);
403 				if (reg->smax_value != reg->umax_value &&
404 				    reg->smax_value != S64_MAX)
405 					verbose(env, ",smax_value=%lld",
406 						(long long)reg->smax_value);
407 				if (reg->umin_value != 0)
408 					verbose(env, ",umin_value=%llu",
409 						(unsigned long long)reg->umin_value);
410 				if (reg->umax_value != U64_MAX)
411 					verbose(env, ",umax_value=%llu",
412 						(unsigned long long)reg->umax_value);
413 				if (!tnum_is_unknown(reg->var_off)) {
414 					char tn_buf[48];
415 
416 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
417 					verbose(env, ",var_off=%s", tn_buf);
418 				}
419 			}
420 			verbose(env, ")");
421 		}
422 	}
423 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
424 		char types_buf[BPF_REG_SIZE + 1];
425 		bool valid = false;
426 		int j;
427 
428 		for (j = 0; j < BPF_REG_SIZE; j++) {
429 			if (state->stack[i].slot_type[j] != STACK_INVALID)
430 				valid = true;
431 			types_buf[j] = slot_type_char[
432 					state->stack[i].slot_type[j]];
433 		}
434 		types_buf[BPF_REG_SIZE] = 0;
435 		if (!valid)
436 			continue;
437 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
438 		print_liveness(env, state->stack[i].spilled_ptr.live);
439 		if (state->stack[i].slot_type[0] == STACK_SPILL)
440 			verbose(env, "=%s",
441 				reg_type_str[state->stack[i].spilled_ptr.type]);
442 		else
443 			verbose(env, "=%s", types_buf);
444 	}
445 	if (state->acquired_refs && state->refs[0].id) {
446 		verbose(env, " refs=%d", state->refs[0].id);
447 		for (i = 1; i < state->acquired_refs; i++)
448 			if (state->refs[i].id)
449 				verbose(env, ",%d", state->refs[i].id);
450 	}
451 	verbose(env, "\n");
452 }
453 
454 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
455 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
456 			       const struct bpf_func_state *src)	\
457 {									\
458 	if (!src->FIELD)						\
459 		return 0;						\
460 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
461 		/* internal bug, make state invalid to reject the program */ \
462 		memset(dst, 0, sizeof(*dst));				\
463 		return -EFAULT;						\
464 	}								\
465 	memcpy(dst->FIELD, src->FIELD,					\
466 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
467 	return 0;							\
468 }
469 /* copy_reference_state() */
470 COPY_STATE_FN(reference, acquired_refs, refs, 1)
471 /* copy_stack_state() */
472 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
473 #undef COPY_STATE_FN
474 
475 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
476 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
477 				  bool copy_old)			\
478 {									\
479 	u32 old_size = state->COUNT;					\
480 	struct bpf_##NAME##_state *new_##FIELD;				\
481 	int slot = size / SIZE;						\
482 									\
483 	if (size <= old_size || !size) {				\
484 		if (copy_old)						\
485 			return 0;					\
486 		state->COUNT = slot * SIZE;				\
487 		if (!size && old_size) {				\
488 			kfree(state->FIELD);				\
489 			state->FIELD = NULL;				\
490 		}							\
491 		return 0;						\
492 	}								\
493 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
494 				    GFP_KERNEL);			\
495 	if (!new_##FIELD)						\
496 		return -ENOMEM;						\
497 	if (copy_old) {							\
498 		if (state->FIELD)					\
499 			memcpy(new_##FIELD, state->FIELD,		\
500 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
501 		memset(new_##FIELD + old_size / SIZE, 0,		\
502 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
503 	}								\
504 	state->COUNT = slot * SIZE;					\
505 	kfree(state->FIELD);						\
506 	state->FIELD = new_##FIELD;					\
507 	return 0;							\
508 }
509 /* realloc_reference_state() */
510 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
511 /* realloc_stack_state() */
512 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
513 #undef REALLOC_STATE_FN
514 
515 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
516  * make it consume minimal amount of memory. check_stack_write() access from
517  * the program calls into realloc_func_state() to grow the stack size.
518  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
519  * which realloc_stack_state() copies over. It points to previous
520  * bpf_verifier_state which is never reallocated.
521  */
522 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
523 			      int refs_size, bool copy_old)
524 {
525 	int err = realloc_reference_state(state, refs_size, copy_old);
526 	if (err)
527 		return err;
528 	return realloc_stack_state(state, stack_size, copy_old);
529 }
530 
531 /* Acquire a pointer id from the env and update the state->refs to include
532  * this new pointer reference.
533  * On success, returns a valid pointer id to associate with the register
534  * On failure, returns a negative errno.
535  */
536 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
537 {
538 	struct bpf_func_state *state = cur_func(env);
539 	int new_ofs = state->acquired_refs;
540 	int id, err;
541 
542 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
543 	if (err)
544 		return err;
545 	id = ++env->id_gen;
546 	state->refs[new_ofs].id = id;
547 	state->refs[new_ofs].insn_idx = insn_idx;
548 
549 	return id;
550 }
551 
552 /* release function corresponding to acquire_reference_state(). Idempotent. */
553 static int __release_reference_state(struct bpf_func_state *state, int ptr_id)
554 {
555 	int i, last_idx;
556 
557 	if (!ptr_id)
558 		return -EFAULT;
559 
560 	last_idx = state->acquired_refs - 1;
561 	for (i = 0; i < state->acquired_refs; i++) {
562 		if (state->refs[i].id == ptr_id) {
563 			if (last_idx && i != last_idx)
564 				memcpy(&state->refs[i], &state->refs[last_idx],
565 				       sizeof(*state->refs));
566 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
567 			state->acquired_refs--;
568 			return 0;
569 		}
570 	}
571 	return -EFAULT;
572 }
573 
574 /* variation on the above for cases where we expect that there must be an
575  * outstanding reference for the specified ptr_id.
576  */
577 static int release_reference_state(struct bpf_verifier_env *env, int ptr_id)
578 {
579 	struct bpf_func_state *state = cur_func(env);
580 	int err;
581 
582 	err = __release_reference_state(state, ptr_id);
583 	if (WARN_ON_ONCE(err != 0))
584 		verbose(env, "verifier internal error: can't release reference\n");
585 	return err;
586 }
587 
588 static int transfer_reference_state(struct bpf_func_state *dst,
589 				    struct bpf_func_state *src)
590 {
591 	int err = realloc_reference_state(dst, src->acquired_refs, false);
592 	if (err)
593 		return err;
594 	err = copy_reference_state(dst, src);
595 	if (err)
596 		return err;
597 	return 0;
598 }
599 
600 static void free_func_state(struct bpf_func_state *state)
601 {
602 	if (!state)
603 		return;
604 	kfree(state->refs);
605 	kfree(state->stack);
606 	kfree(state);
607 }
608 
609 static void free_verifier_state(struct bpf_verifier_state *state,
610 				bool free_self)
611 {
612 	int i;
613 
614 	for (i = 0; i <= state->curframe; i++) {
615 		free_func_state(state->frame[i]);
616 		state->frame[i] = NULL;
617 	}
618 	if (free_self)
619 		kfree(state);
620 }
621 
622 /* copy verifier state from src to dst growing dst stack space
623  * when necessary to accommodate larger src stack
624  */
625 static int copy_func_state(struct bpf_func_state *dst,
626 			   const struct bpf_func_state *src)
627 {
628 	int err;
629 
630 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
631 				 false);
632 	if (err)
633 		return err;
634 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
635 	err = copy_reference_state(dst, src);
636 	if (err)
637 		return err;
638 	return copy_stack_state(dst, src);
639 }
640 
641 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
642 			       const struct bpf_verifier_state *src)
643 {
644 	struct bpf_func_state *dst;
645 	int i, err;
646 
647 	/* if dst has more stack frames then src frame, free them */
648 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
649 		free_func_state(dst_state->frame[i]);
650 		dst_state->frame[i] = NULL;
651 	}
652 	dst_state->curframe = src->curframe;
653 	for (i = 0; i <= src->curframe; i++) {
654 		dst = dst_state->frame[i];
655 		if (!dst) {
656 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
657 			if (!dst)
658 				return -ENOMEM;
659 			dst_state->frame[i] = dst;
660 		}
661 		err = copy_func_state(dst, src->frame[i]);
662 		if (err)
663 			return err;
664 	}
665 	return 0;
666 }
667 
668 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
669 		     int *insn_idx)
670 {
671 	struct bpf_verifier_state *cur = env->cur_state;
672 	struct bpf_verifier_stack_elem *elem, *head = env->head;
673 	int err;
674 
675 	if (env->head == NULL)
676 		return -ENOENT;
677 
678 	if (cur) {
679 		err = copy_verifier_state(cur, &head->st);
680 		if (err)
681 			return err;
682 	}
683 	if (insn_idx)
684 		*insn_idx = head->insn_idx;
685 	if (prev_insn_idx)
686 		*prev_insn_idx = head->prev_insn_idx;
687 	elem = head->next;
688 	free_verifier_state(&head->st, false);
689 	kfree(head);
690 	env->head = elem;
691 	env->stack_size--;
692 	return 0;
693 }
694 
695 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
696 					     int insn_idx, int prev_insn_idx)
697 {
698 	struct bpf_verifier_state *cur = env->cur_state;
699 	struct bpf_verifier_stack_elem *elem;
700 	int err;
701 
702 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
703 	if (!elem)
704 		goto err;
705 
706 	elem->insn_idx = insn_idx;
707 	elem->prev_insn_idx = prev_insn_idx;
708 	elem->next = env->head;
709 	env->head = elem;
710 	env->stack_size++;
711 	err = copy_verifier_state(&elem->st, cur);
712 	if (err)
713 		goto err;
714 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
715 		verbose(env, "BPF program is too complex\n");
716 		goto err;
717 	}
718 	return &elem->st;
719 err:
720 	free_verifier_state(env->cur_state, true);
721 	env->cur_state = NULL;
722 	/* pop all elements and return */
723 	while (!pop_stack(env, NULL, NULL));
724 	return NULL;
725 }
726 
727 #define CALLER_SAVED_REGS 6
728 static const int caller_saved[CALLER_SAVED_REGS] = {
729 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
730 };
731 
732 static void __mark_reg_not_init(struct bpf_reg_state *reg);
733 
734 /* Mark the unknown part of a register (variable offset or scalar value) as
735  * known to have the value @imm.
736  */
737 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
738 {
739 	/* Clear id, off, and union(map_ptr, range) */
740 	memset(((u8 *)reg) + sizeof(reg->type), 0,
741 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
742 	reg->var_off = tnum_const(imm);
743 	reg->smin_value = (s64)imm;
744 	reg->smax_value = (s64)imm;
745 	reg->umin_value = imm;
746 	reg->umax_value = imm;
747 }
748 
749 /* Mark the 'variable offset' part of a register as zero.  This should be
750  * used only on registers holding a pointer type.
751  */
752 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
753 {
754 	__mark_reg_known(reg, 0);
755 }
756 
757 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
758 {
759 	__mark_reg_known(reg, 0);
760 	reg->type = SCALAR_VALUE;
761 }
762 
763 static void mark_reg_known_zero(struct bpf_verifier_env *env,
764 				struct bpf_reg_state *regs, u32 regno)
765 {
766 	if (WARN_ON(regno >= MAX_BPF_REG)) {
767 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
768 		/* Something bad happened, let's kill all regs */
769 		for (regno = 0; regno < MAX_BPF_REG; regno++)
770 			__mark_reg_not_init(regs + regno);
771 		return;
772 	}
773 	__mark_reg_known_zero(regs + regno);
774 }
775 
776 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
777 {
778 	return type_is_pkt_pointer(reg->type);
779 }
780 
781 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
782 {
783 	return reg_is_pkt_pointer(reg) ||
784 	       reg->type == PTR_TO_PACKET_END;
785 }
786 
787 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
788 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
789 				    enum bpf_reg_type which)
790 {
791 	/* The register can already have a range from prior markings.
792 	 * This is fine as long as it hasn't been advanced from its
793 	 * origin.
794 	 */
795 	return reg->type == which &&
796 	       reg->id == 0 &&
797 	       reg->off == 0 &&
798 	       tnum_equals_const(reg->var_off, 0);
799 }
800 
801 /* Attempts to improve min/max values based on var_off information */
802 static void __update_reg_bounds(struct bpf_reg_state *reg)
803 {
804 	/* min signed is max(sign bit) | min(other bits) */
805 	reg->smin_value = max_t(s64, reg->smin_value,
806 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
807 	/* max signed is min(sign bit) | max(other bits) */
808 	reg->smax_value = min_t(s64, reg->smax_value,
809 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
810 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
811 	reg->umax_value = min(reg->umax_value,
812 			      reg->var_off.value | reg->var_off.mask);
813 }
814 
815 /* Uses signed min/max values to inform unsigned, and vice-versa */
816 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
817 {
818 	/* Learn sign from signed bounds.
819 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
820 	 * are the same, so combine.  This works even in the negative case, e.g.
821 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
822 	 */
823 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
824 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
825 							  reg->umin_value);
826 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
827 							  reg->umax_value);
828 		return;
829 	}
830 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
831 	 * boundary, so we must be careful.
832 	 */
833 	if ((s64)reg->umax_value >= 0) {
834 		/* Positive.  We can't learn anything from the smin, but smax
835 		 * is positive, hence safe.
836 		 */
837 		reg->smin_value = reg->umin_value;
838 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
839 							  reg->umax_value);
840 	} else if ((s64)reg->umin_value < 0) {
841 		/* Negative.  We can't learn anything from the smax, but smin
842 		 * is negative, hence safe.
843 		 */
844 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
845 							  reg->umin_value);
846 		reg->smax_value = reg->umax_value;
847 	}
848 }
849 
850 /* Attempts to improve var_off based on unsigned min/max information */
851 static void __reg_bound_offset(struct bpf_reg_state *reg)
852 {
853 	reg->var_off = tnum_intersect(reg->var_off,
854 				      tnum_range(reg->umin_value,
855 						 reg->umax_value));
856 }
857 
858 /* Reset the min/max bounds of a register */
859 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
860 {
861 	reg->smin_value = S64_MIN;
862 	reg->smax_value = S64_MAX;
863 	reg->umin_value = 0;
864 	reg->umax_value = U64_MAX;
865 }
866 
867 /* Mark a register as having a completely unknown (scalar) value. */
868 static void __mark_reg_unknown(struct bpf_reg_state *reg)
869 {
870 	/*
871 	 * Clear type, id, off, and union(map_ptr, range) and
872 	 * padding between 'type' and union
873 	 */
874 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
875 	reg->type = SCALAR_VALUE;
876 	reg->var_off = tnum_unknown;
877 	reg->frameno = 0;
878 	__mark_reg_unbounded(reg);
879 }
880 
881 static void mark_reg_unknown(struct bpf_verifier_env *env,
882 			     struct bpf_reg_state *regs, u32 regno)
883 {
884 	if (WARN_ON(regno >= MAX_BPF_REG)) {
885 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
886 		/* Something bad happened, let's kill all regs except FP */
887 		for (regno = 0; regno < BPF_REG_FP; regno++)
888 			__mark_reg_not_init(regs + regno);
889 		return;
890 	}
891 	__mark_reg_unknown(regs + regno);
892 }
893 
894 static void __mark_reg_not_init(struct bpf_reg_state *reg)
895 {
896 	__mark_reg_unknown(reg);
897 	reg->type = NOT_INIT;
898 }
899 
900 static void mark_reg_not_init(struct bpf_verifier_env *env,
901 			      struct bpf_reg_state *regs, u32 regno)
902 {
903 	if (WARN_ON(regno >= MAX_BPF_REG)) {
904 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
905 		/* Something bad happened, let's kill all regs except FP */
906 		for (regno = 0; regno < BPF_REG_FP; regno++)
907 			__mark_reg_not_init(regs + regno);
908 		return;
909 	}
910 	__mark_reg_not_init(regs + regno);
911 }
912 
913 static void init_reg_state(struct bpf_verifier_env *env,
914 			   struct bpf_func_state *state)
915 {
916 	struct bpf_reg_state *regs = state->regs;
917 	int i;
918 
919 	for (i = 0; i < MAX_BPF_REG; i++) {
920 		mark_reg_not_init(env, regs, i);
921 		regs[i].live = REG_LIVE_NONE;
922 		regs[i].parent = NULL;
923 	}
924 
925 	/* frame pointer */
926 	regs[BPF_REG_FP].type = PTR_TO_STACK;
927 	mark_reg_known_zero(env, regs, BPF_REG_FP);
928 	regs[BPF_REG_FP].frameno = state->frameno;
929 
930 	/* 1st arg to a function */
931 	regs[BPF_REG_1].type = PTR_TO_CTX;
932 	mark_reg_known_zero(env, regs, BPF_REG_1);
933 }
934 
935 #define BPF_MAIN_FUNC (-1)
936 static void init_func_state(struct bpf_verifier_env *env,
937 			    struct bpf_func_state *state,
938 			    int callsite, int frameno, int subprogno)
939 {
940 	state->callsite = callsite;
941 	state->frameno = frameno;
942 	state->subprogno = subprogno;
943 	init_reg_state(env, state);
944 }
945 
946 enum reg_arg_type {
947 	SRC_OP,		/* register is used as source operand */
948 	DST_OP,		/* register is used as destination operand */
949 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
950 };
951 
952 static int cmp_subprogs(const void *a, const void *b)
953 {
954 	return ((struct bpf_subprog_info *)a)->start -
955 	       ((struct bpf_subprog_info *)b)->start;
956 }
957 
958 static int find_subprog(struct bpf_verifier_env *env, int off)
959 {
960 	struct bpf_subprog_info *p;
961 
962 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
963 		    sizeof(env->subprog_info[0]), cmp_subprogs);
964 	if (!p)
965 		return -ENOENT;
966 	return p - env->subprog_info;
967 
968 }
969 
970 static int add_subprog(struct bpf_verifier_env *env, int off)
971 {
972 	int insn_cnt = env->prog->len;
973 	int ret;
974 
975 	if (off >= insn_cnt || off < 0) {
976 		verbose(env, "call to invalid destination\n");
977 		return -EINVAL;
978 	}
979 	ret = find_subprog(env, off);
980 	if (ret >= 0)
981 		return 0;
982 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
983 		verbose(env, "too many subprograms\n");
984 		return -E2BIG;
985 	}
986 	env->subprog_info[env->subprog_cnt++].start = off;
987 	sort(env->subprog_info, env->subprog_cnt,
988 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
989 	return 0;
990 }
991 
992 static int check_subprogs(struct bpf_verifier_env *env)
993 {
994 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
995 	struct bpf_subprog_info *subprog = env->subprog_info;
996 	struct bpf_insn *insn = env->prog->insnsi;
997 	int insn_cnt = env->prog->len;
998 
999 	/* Add entry function. */
1000 	ret = add_subprog(env, 0);
1001 	if (ret < 0)
1002 		return ret;
1003 
1004 	/* determine subprog starts. The end is one before the next starts */
1005 	for (i = 0; i < insn_cnt; i++) {
1006 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1007 			continue;
1008 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1009 			continue;
1010 		if (!env->allow_ptr_leaks) {
1011 			verbose(env, "function calls to other bpf functions are allowed for root only\n");
1012 			return -EPERM;
1013 		}
1014 		ret = add_subprog(env, i + insn[i].imm + 1);
1015 		if (ret < 0)
1016 			return ret;
1017 	}
1018 
1019 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1020 	 * logic. 'subprog_cnt' should not be increased.
1021 	 */
1022 	subprog[env->subprog_cnt].start = insn_cnt;
1023 
1024 	if (env->log.level > 1)
1025 		for (i = 0; i < env->subprog_cnt; i++)
1026 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1027 
1028 	/* now check that all jumps are within the same subprog */
1029 	subprog_start = subprog[cur_subprog].start;
1030 	subprog_end = subprog[cur_subprog + 1].start;
1031 	for (i = 0; i < insn_cnt; i++) {
1032 		u8 code = insn[i].code;
1033 
1034 		if (BPF_CLASS(code) != BPF_JMP)
1035 			goto next;
1036 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1037 			goto next;
1038 		off = i + insn[i].off + 1;
1039 		if (off < subprog_start || off >= subprog_end) {
1040 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1041 			return -EINVAL;
1042 		}
1043 next:
1044 		if (i == subprog_end - 1) {
1045 			/* to avoid fall-through from one subprog into another
1046 			 * the last insn of the subprog should be either exit
1047 			 * or unconditional jump back
1048 			 */
1049 			if (code != (BPF_JMP | BPF_EXIT) &&
1050 			    code != (BPF_JMP | BPF_JA)) {
1051 				verbose(env, "last insn is not an exit or jmp\n");
1052 				return -EINVAL;
1053 			}
1054 			subprog_start = subprog_end;
1055 			cur_subprog++;
1056 			if (cur_subprog < env->subprog_cnt)
1057 				subprog_end = subprog[cur_subprog + 1].start;
1058 		}
1059 	}
1060 	return 0;
1061 }
1062 
1063 /* Parentage chain of this register (or stack slot) should take care of all
1064  * issues like callee-saved registers, stack slot allocation time, etc.
1065  */
1066 static int mark_reg_read(struct bpf_verifier_env *env,
1067 			 const struct bpf_reg_state *state,
1068 			 struct bpf_reg_state *parent)
1069 {
1070 	bool writes = parent == state->parent; /* Observe write marks */
1071 
1072 	while (parent) {
1073 		/* if read wasn't screened by an earlier write ... */
1074 		if (writes && state->live & REG_LIVE_WRITTEN)
1075 			break;
1076 		/* ... then we depend on parent's value */
1077 		parent->live |= REG_LIVE_READ;
1078 		state = parent;
1079 		parent = state->parent;
1080 		writes = true;
1081 	}
1082 	return 0;
1083 }
1084 
1085 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1086 			 enum reg_arg_type t)
1087 {
1088 	struct bpf_verifier_state *vstate = env->cur_state;
1089 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1090 	struct bpf_reg_state *regs = state->regs;
1091 
1092 	if (regno >= MAX_BPF_REG) {
1093 		verbose(env, "R%d is invalid\n", regno);
1094 		return -EINVAL;
1095 	}
1096 
1097 	if (t == SRC_OP) {
1098 		/* check whether register used as source operand can be read */
1099 		if (regs[regno].type == NOT_INIT) {
1100 			verbose(env, "R%d !read_ok\n", regno);
1101 			return -EACCES;
1102 		}
1103 		/* We don't need to worry about FP liveness because it's read-only */
1104 		if (regno != BPF_REG_FP)
1105 			return mark_reg_read(env, &regs[regno],
1106 					     regs[regno].parent);
1107 	} else {
1108 		/* check whether register used as dest operand can be written to */
1109 		if (regno == BPF_REG_FP) {
1110 			verbose(env, "frame pointer is read only\n");
1111 			return -EACCES;
1112 		}
1113 		regs[regno].live |= REG_LIVE_WRITTEN;
1114 		if (t == DST_OP)
1115 			mark_reg_unknown(env, regs, regno);
1116 	}
1117 	return 0;
1118 }
1119 
1120 static bool is_spillable_regtype(enum bpf_reg_type type)
1121 {
1122 	switch (type) {
1123 	case PTR_TO_MAP_VALUE:
1124 	case PTR_TO_MAP_VALUE_OR_NULL:
1125 	case PTR_TO_STACK:
1126 	case PTR_TO_CTX:
1127 	case PTR_TO_PACKET:
1128 	case PTR_TO_PACKET_META:
1129 	case PTR_TO_PACKET_END:
1130 	case PTR_TO_FLOW_KEYS:
1131 	case CONST_PTR_TO_MAP:
1132 	case PTR_TO_SOCKET:
1133 	case PTR_TO_SOCKET_OR_NULL:
1134 		return true;
1135 	default:
1136 		return false;
1137 	}
1138 }
1139 
1140 /* Does this register contain a constant zero? */
1141 static bool register_is_null(struct bpf_reg_state *reg)
1142 {
1143 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1144 }
1145 
1146 /* check_stack_read/write functions track spill/fill of registers,
1147  * stack boundary and alignment are checked in check_mem_access()
1148  */
1149 static int check_stack_write(struct bpf_verifier_env *env,
1150 			     struct bpf_func_state *state, /* func where register points to */
1151 			     int off, int size, int value_regno, int insn_idx)
1152 {
1153 	struct bpf_func_state *cur; /* state of the current function */
1154 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1155 	enum bpf_reg_type type;
1156 
1157 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1158 				 state->acquired_refs, true);
1159 	if (err)
1160 		return err;
1161 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1162 	 * so it's aligned access and [off, off + size) are within stack limits
1163 	 */
1164 	if (!env->allow_ptr_leaks &&
1165 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
1166 	    size != BPF_REG_SIZE) {
1167 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
1168 		return -EACCES;
1169 	}
1170 
1171 	cur = env->cur_state->frame[env->cur_state->curframe];
1172 	if (value_regno >= 0 &&
1173 	    is_spillable_regtype((type = cur->regs[value_regno].type))) {
1174 
1175 		/* register containing pointer is being spilled into stack */
1176 		if (size != BPF_REG_SIZE) {
1177 			verbose(env, "invalid size of register spill\n");
1178 			return -EACCES;
1179 		}
1180 
1181 		if (state != cur && type == PTR_TO_STACK) {
1182 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1183 			return -EINVAL;
1184 		}
1185 
1186 		/* save register state */
1187 		state->stack[spi].spilled_ptr = cur->regs[value_regno];
1188 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1189 
1190 		for (i = 0; i < BPF_REG_SIZE; i++) {
1191 			if (state->stack[spi].slot_type[i] == STACK_MISC &&
1192 			    !env->allow_ptr_leaks) {
1193 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1194 				int soff = (-spi - 1) * BPF_REG_SIZE;
1195 
1196 				/* detected reuse of integer stack slot with a pointer
1197 				 * which means either llvm is reusing stack slot or
1198 				 * an attacker is trying to exploit CVE-2018-3639
1199 				 * (speculative store bypass)
1200 				 * Have to sanitize that slot with preemptive
1201 				 * store of zero.
1202 				 */
1203 				if (*poff && *poff != soff) {
1204 					/* disallow programs where single insn stores
1205 					 * into two different stack slots, since verifier
1206 					 * cannot sanitize them
1207 					 */
1208 					verbose(env,
1209 						"insn %d cannot access two stack slots fp%d and fp%d",
1210 						insn_idx, *poff, soff);
1211 					return -EINVAL;
1212 				}
1213 				*poff = soff;
1214 			}
1215 			state->stack[spi].slot_type[i] = STACK_SPILL;
1216 		}
1217 	} else {
1218 		u8 type = STACK_MISC;
1219 
1220 		/* regular write of data into stack destroys any spilled ptr */
1221 		state->stack[spi].spilled_ptr.type = NOT_INIT;
1222 
1223 		/* only mark the slot as written if all 8 bytes were written
1224 		 * otherwise read propagation may incorrectly stop too soon
1225 		 * when stack slots are partially written.
1226 		 * This heuristic means that read propagation will be
1227 		 * conservative, since it will add reg_live_read marks
1228 		 * to stack slots all the way to first state when programs
1229 		 * writes+reads less than 8 bytes
1230 		 */
1231 		if (size == BPF_REG_SIZE)
1232 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1233 
1234 		/* when we zero initialize stack slots mark them as such */
1235 		if (value_regno >= 0 &&
1236 		    register_is_null(&cur->regs[value_regno]))
1237 			type = STACK_ZERO;
1238 
1239 		for (i = 0; i < size; i++)
1240 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1241 				type;
1242 	}
1243 	return 0;
1244 }
1245 
1246 static int check_stack_read(struct bpf_verifier_env *env,
1247 			    struct bpf_func_state *reg_state /* func where register points to */,
1248 			    int off, int size, int value_regno)
1249 {
1250 	struct bpf_verifier_state *vstate = env->cur_state;
1251 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1252 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1253 	u8 *stype;
1254 
1255 	if (reg_state->allocated_stack <= slot) {
1256 		verbose(env, "invalid read from stack off %d+0 size %d\n",
1257 			off, size);
1258 		return -EACCES;
1259 	}
1260 	stype = reg_state->stack[spi].slot_type;
1261 
1262 	if (stype[0] == STACK_SPILL) {
1263 		if (size != BPF_REG_SIZE) {
1264 			verbose(env, "invalid size of register spill\n");
1265 			return -EACCES;
1266 		}
1267 		for (i = 1; i < BPF_REG_SIZE; i++) {
1268 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1269 				verbose(env, "corrupted spill memory\n");
1270 				return -EACCES;
1271 			}
1272 		}
1273 
1274 		if (value_regno >= 0) {
1275 			/* restore register state from stack */
1276 			state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1277 			/* mark reg as written since spilled pointer state likely
1278 			 * has its liveness marks cleared by is_state_visited()
1279 			 * which resets stack/reg liveness for state transitions
1280 			 */
1281 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1282 		}
1283 		mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1284 			      reg_state->stack[spi].spilled_ptr.parent);
1285 		return 0;
1286 	} else {
1287 		int zeros = 0;
1288 
1289 		for (i = 0; i < size; i++) {
1290 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1291 				continue;
1292 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1293 				zeros++;
1294 				continue;
1295 			}
1296 			verbose(env, "invalid read from stack off %d+%d size %d\n",
1297 				off, i, size);
1298 			return -EACCES;
1299 		}
1300 		mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1301 			      reg_state->stack[spi].spilled_ptr.parent);
1302 		if (value_regno >= 0) {
1303 			if (zeros == size) {
1304 				/* any size read into register is zero extended,
1305 				 * so the whole register == const_zero
1306 				 */
1307 				__mark_reg_const_zero(&state->regs[value_regno]);
1308 			} else {
1309 				/* have read misc data from the stack */
1310 				mark_reg_unknown(env, state->regs, value_regno);
1311 			}
1312 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1313 		}
1314 		return 0;
1315 	}
1316 }
1317 
1318 /* check read/write into map element returned by bpf_map_lookup_elem() */
1319 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1320 			      int size, bool zero_size_allowed)
1321 {
1322 	struct bpf_reg_state *regs = cur_regs(env);
1323 	struct bpf_map *map = regs[regno].map_ptr;
1324 
1325 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1326 	    off + size > map->value_size) {
1327 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1328 			map->value_size, off, size);
1329 		return -EACCES;
1330 	}
1331 	return 0;
1332 }
1333 
1334 /* check read/write into a map element with possible variable offset */
1335 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1336 			    int off, int size, bool zero_size_allowed)
1337 {
1338 	struct bpf_verifier_state *vstate = env->cur_state;
1339 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1340 	struct bpf_reg_state *reg = &state->regs[regno];
1341 	int err;
1342 
1343 	/* We may have adjusted the register to this map value, so we
1344 	 * need to try adding each of min_value and max_value to off
1345 	 * to make sure our theoretical access will be safe.
1346 	 */
1347 	if (env->log.level)
1348 		print_verifier_state(env, state);
1349 	/* The minimum value is only important with signed
1350 	 * comparisons where we can't assume the floor of a
1351 	 * value is 0.  If we are using signed variables for our
1352 	 * index'es we need to make sure that whatever we use
1353 	 * will have a set floor within our range.
1354 	 */
1355 	if (reg->smin_value < 0) {
1356 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1357 			regno);
1358 		return -EACCES;
1359 	}
1360 	err = __check_map_access(env, regno, reg->smin_value + off, size,
1361 				 zero_size_allowed);
1362 	if (err) {
1363 		verbose(env, "R%d min value is outside of the array range\n",
1364 			regno);
1365 		return err;
1366 	}
1367 
1368 	/* If we haven't set a max value then we need to bail since we can't be
1369 	 * sure we won't do bad things.
1370 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
1371 	 */
1372 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1373 		verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1374 			regno);
1375 		return -EACCES;
1376 	}
1377 	err = __check_map_access(env, regno, reg->umax_value + off, size,
1378 				 zero_size_allowed);
1379 	if (err)
1380 		verbose(env, "R%d max value is outside of the array range\n",
1381 			regno);
1382 	return err;
1383 }
1384 
1385 #define MAX_PACKET_OFF 0xffff
1386 
1387 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1388 				       const struct bpf_call_arg_meta *meta,
1389 				       enum bpf_access_type t)
1390 {
1391 	switch (env->prog->type) {
1392 	/* Program types only with direct read access go here! */
1393 	case BPF_PROG_TYPE_LWT_IN:
1394 	case BPF_PROG_TYPE_LWT_OUT:
1395 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1396 	case BPF_PROG_TYPE_SK_REUSEPORT:
1397 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
1398 	case BPF_PROG_TYPE_CGROUP_SKB:
1399 		if (t == BPF_WRITE)
1400 			return false;
1401 		/* fallthrough */
1402 
1403 	/* Program types with direct read + write access go here! */
1404 	case BPF_PROG_TYPE_SCHED_CLS:
1405 	case BPF_PROG_TYPE_SCHED_ACT:
1406 	case BPF_PROG_TYPE_XDP:
1407 	case BPF_PROG_TYPE_LWT_XMIT:
1408 	case BPF_PROG_TYPE_SK_SKB:
1409 	case BPF_PROG_TYPE_SK_MSG:
1410 		if (meta)
1411 			return meta->pkt_access;
1412 
1413 		env->seen_direct_write = true;
1414 		return true;
1415 	default:
1416 		return false;
1417 	}
1418 }
1419 
1420 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1421 				 int off, int size, bool zero_size_allowed)
1422 {
1423 	struct bpf_reg_state *regs = cur_regs(env);
1424 	struct bpf_reg_state *reg = &regs[regno];
1425 
1426 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1427 	    (u64)off + size > reg->range) {
1428 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1429 			off, size, regno, reg->id, reg->off, reg->range);
1430 		return -EACCES;
1431 	}
1432 	return 0;
1433 }
1434 
1435 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1436 			       int size, bool zero_size_allowed)
1437 {
1438 	struct bpf_reg_state *regs = cur_regs(env);
1439 	struct bpf_reg_state *reg = &regs[regno];
1440 	int err;
1441 
1442 	/* We may have added a variable offset to the packet pointer; but any
1443 	 * reg->range we have comes after that.  We are only checking the fixed
1444 	 * offset.
1445 	 */
1446 
1447 	/* We don't allow negative numbers, because we aren't tracking enough
1448 	 * detail to prove they're safe.
1449 	 */
1450 	if (reg->smin_value < 0) {
1451 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1452 			regno);
1453 		return -EACCES;
1454 	}
1455 	err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1456 	if (err) {
1457 		verbose(env, "R%d offset is outside of the packet\n", regno);
1458 		return err;
1459 	}
1460 
1461 	/* __check_packet_access has made sure "off + size - 1" is within u16.
1462 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
1463 	 * otherwise find_good_pkt_pointers would have refused to set range info
1464 	 * that __check_packet_access would have rejected this pkt access.
1465 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
1466 	 */
1467 	env->prog->aux->max_pkt_offset =
1468 		max_t(u32, env->prog->aux->max_pkt_offset,
1469 		      off + reg->umax_value + size - 1);
1470 
1471 	return err;
1472 }
1473 
1474 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
1475 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1476 			    enum bpf_access_type t, enum bpf_reg_type *reg_type)
1477 {
1478 	struct bpf_insn_access_aux info = {
1479 		.reg_type = *reg_type,
1480 	};
1481 
1482 	if (env->ops->is_valid_access &&
1483 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1484 		/* A non zero info.ctx_field_size indicates that this field is a
1485 		 * candidate for later verifier transformation to load the whole
1486 		 * field and then apply a mask when accessed with a narrower
1487 		 * access than actual ctx access size. A zero info.ctx_field_size
1488 		 * will only allow for whole field access and rejects any other
1489 		 * type of narrower access.
1490 		 */
1491 		*reg_type = info.reg_type;
1492 
1493 		env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1494 		/* remember the offset of last byte accessed in ctx */
1495 		if (env->prog->aux->max_ctx_offset < off + size)
1496 			env->prog->aux->max_ctx_offset = off + size;
1497 		return 0;
1498 	}
1499 
1500 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1501 	return -EACCES;
1502 }
1503 
1504 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
1505 				  int size)
1506 {
1507 	if (size < 0 || off < 0 ||
1508 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
1509 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
1510 			off, size);
1511 		return -EACCES;
1512 	}
1513 	return 0;
1514 }
1515 
1516 static int check_sock_access(struct bpf_verifier_env *env, u32 regno, int off,
1517 			     int size, enum bpf_access_type t)
1518 {
1519 	struct bpf_reg_state *regs = cur_regs(env);
1520 	struct bpf_reg_state *reg = &regs[regno];
1521 	struct bpf_insn_access_aux info;
1522 
1523 	if (reg->smin_value < 0) {
1524 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1525 			regno);
1526 		return -EACCES;
1527 	}
1528 
1529 	if (!bpf_sock_is_valid_access(off, size, t, &info)) {
1530 		verbose(env, "invalid bpf_sock access off=%d size=%d\n",
1531 			off, size);
1532 		return -EACCES;
1533 	}
1534 
1535 	return 0;
1536 }
1537 
1538 static bool __is_pointer_value(bool allow_ptr_leaks,
1539 			       const struct bpf_reg_state *reg)
1540 {
1541 	if (allow_ptr_leaks)
1542 		return false;
1543 
1544 	return reg->type != SCALAR_VALUE;
1545 }
1546 
1547 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
1548 {
1549 	return cur_regs(env) + regno;
1550 }
1551 
1552 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1553 {
1554 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
1555 }
1556 
1557 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1558 {
1559 	const struct bpf_reg_state *reg = reg_state(env, regno);
1560 
1561 	return reg->type == PTR_TO_CTX ||
1562 	       reg->type == PTR_TO_SOCKET;
1563 }
1564 
1565 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1566 {
1567 	const struct bpf_reg_state *reg = reg_state(env, regno);
1568 
1569 	return type_is_pkt_pointer(reg->type);
1570 }
1571 
1572 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
1573 {
1574 	const struct bpf_reg_state *reg = reg_state(env, regno);
1575 
1576 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
1577 	return reg->type == PTR_TO_FLOW_KEYS;
1578 }
1579 
1580 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1581 				   const struct bpf_reg_state *reg,
1582 				   int off, int size, bool strict)
1583 {
1584 	struct tnum reg_off;
1585 	int ip_align;
1586 
1587 	/* Byte size accesses are always allowed. */
1588 	if (!strict || size == 1)
1589 		return 0;
1590 
1591 	/* For platforms that do not have a Kconfig enabling
1592 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1593 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
1594 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1595 	 * to this code only in strict mode where we want to emulate
1596 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
1597 	 * unconditional IP align value of '2'.
1598 	 */
1599 	ip_align = 2;
1600 
1601 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1602 	if (!tnum_is_aligned(reg_off, size)) {
1603 		char tn_buf[48];
1604 
1605 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1606 		verbose(env,
1607 			"misaligned packet access off %d+%s+%d+%d size %d\n",
1608 			ip_align, tn_buf, reg->off, off, size);
1609 		return -EACCES;
1610 	}
1611 
1612 	return 0;
1613 }
1614 
1615 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1616 				       const struct bpf_reg_state *reg,
1617 				       const char *pointer_desc,
1618 				       int off, int size, bool strict)
1619 {
1620 	struct tnum reg_off;
1621 
1622 	/* Byte size accesses are always allowed. */
1623 	if (!strict || size == 1)
1624 		return 0;
1625 
1626 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1627 	if (!tnum_is_aligned(reg_off, size)) {
1628 		char tn_buf[48];
1629 
1630 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1631 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1632 			pointer_desc, tn_buf, reg->off, off, size);
1633 		return -EACCES;
1634 	}
1635 
1636 	return 0;
1637 }
1638 
1639 static int check_ptr_alignment(struct bpf_verifier_env *env,
1640 			       const struct bpf_reg_state *reg, int off,
1641 			       int size, bool strict_alignment_once)
1642 {
1643 	bool strict = env->strict_alignment || strict_alignment_once;
1644 	const char *pointer_desc = "";
1645 
1646 	switch (reg->type) {
1647 	case PTR_TO_PACKET:
1648 	case PTR_TO_PACKET_META:
1649 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
1650 		 * right in front, treat it the very same way.
1651 		 */
1652 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
1653 	case PTR_TO_FLOW_KEYS:
1654 		pointer_desc = "flow keys ";
1655 		break;
1656 	case PTR_TO_MAP_VALUE:
1657 		pointer_desc = "value ";
1658 		break;
1659 	case PTR_TO_CTX:
1660 		pointer_desc = "context ";
1661 		break;
1662 	case PTR_TO_STACK:
1663 		pointer_desc = "stack ";
1664 		/* The stack spill tracking logic in check_stack_write()
1665 		 * and check_stack_read() relies on stack accesses being
1666 		 * aligned.
1667 		 */
1668 		strict = true;
1669 		break;
1670 	case PTR_TO_SOCKET:
1671 		pointer_desc = "sock ";
1672 		break;
1673 	default:
1674 		break;
1675 	}
1676 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1677 					   strict);
1678 }
1679 
1680 static int update_stack_depth(struct bpf_verifier_env *env,
1681 			      const struct bpf_func_state *func,
1682 			      int off)
1683 {
1684 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
1685 
1686 	if (stack >= -off)
1687 		return 0;
1688 
1689 	/* update known max for given subprogram */
1690 	env->subprog_info[func->subprogno].stack_depth = -off;
1691 	return 0;
1692 }
1693 
1694 /* starting from main bpf function walk all instructions of the function
1695  * and recursively walk all callees that given function can call.
1696  * Ignore jump and exit insns.
1697  * Since recursion is prevented by check_cfg() this algorithm
1698  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1699  */
1700 static int check_max_stack_depth(struct bpf_verifier_env *env)
1701 {
1702 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1703 	struct bpf_subprog_info *subprog = env->subprog_info;
1704 	struct bpf_insn *insn = env->prog->insnsi;
1705 	int ret_insn[MAX_CALL_FRAMES];
1706 	int ret_prog[MAX_CALL_FRAMES];
1707 
1708 process_func:
1709 	/* round up to 32-bytes, since this is granularity
1710 	 * of interpreter stack size
1711 	 */
1712 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1713 	if (depth > MAX_BPF_STACK) {
1714 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
1715 			frame + 1, depth);
1716 		return -EACCES;
1717 	}
1718 continue_func:
1719 	subprog_end = subprog[idx + 1].start;
1720 	for (; i < subprog_end; i++) {
1721 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1722 			continue;
1723 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1724 			continue;
1725 		/* remember insn and function to return to */
1726 		ret_insn[frame] = i + 1;
1727 		ret_prog[frame] = idx;
1728 
1729 		/* find the callee */
1730 		i = i + insn[i].imm + 1;
1731 		idx = find_subprog(env, i);
1732 		if (idx < 0) {
1733 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1734 				  i);
1735 			return -EFAULT;
1736 		}
1737 		frame++;
1738 		if (frame >= MAX_CALL_FRAMES) {
1739 			WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1740 			return -EFAULT;
1741 		}
1742 		goto process_func;
1743 	}
1744 	/* end of for() loop means the last insn of the 'subprog'
1745 	 * was reached. Doesn't matter whether it was JA or EXIT
1746 	 */
1747 	if (frame == 0)
1748 		return 0;
1749 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1750 	frame--;
1751 	i = ret_insn[frame];
1752 	idx = ret_prog[frame];
1753 	goto continue_func;
1754 }
1755 
1756 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1757 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1758 				  const struct bpf_insn *insn, int idx)
1759 {
1760 	int start = idx + insn->imm + 1, subprog;
1761 
1762 	subprog = find_subprog(env, start);
1763 	if (subprog < 0) {
1764 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1765 			  start);
1766 		return -EFAULT;
1767 	}
1768 	return env->subprog_info[subprog].stack_depth;
1769 }
1770 #endif
1771 
1772 static int check_ctx_reg(struct bpf_verifier_env *env,
1773 			 const struct bpf_reg_state *reg, int regno)
1774 {
1775 	/* Access to ctx or passing it to a helper is only allowed in
1776 	 * its original, unmodified form.
1777 	 */
1778 
1779 	if (reg->off) {
1780 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1781 			regno, reg->off);
1782 		return -EACCES;
1783 	}
1784 
1785 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1786 		char tn_buf[48];
1787 
1788 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1789 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1790 		return -EACCES;
1791 	}
1792 
1793 	return 0;
1794 }
1795 
1796 /* truncate register to smaller size (in bytes)
1797  * must be called with size < BPF_REG_SIZE
1798  */
1799 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1800 {
1801 	u64 mask;
1802 
1803 	/* clear high bits in bit representation */
1804 	reg->var_off = tnum_cast(reg->var_off, size);
1805 
1806 	/* fix arithmetic bounds */
1807 	mask = ((u64)1 << (size * 8)) - 1;
1808 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1809 		reg->umin_value &= mask;
1810 		reg->umax_value &= mask;
1811 	} else {
1812 		reg->umin_value = 0;
1813 		reg->umax_value = mask;
1814 	}
1815 	reg->smin_value = reg->umin_value;
1816 	reg->smax_value = reg->umax_value;
1817 }
1818 
1819 /* check whether memory at (regno + off) is accessible for t = (read | write)
1820  * if t==write, value_regno is a register which value is stored into memory
1821  * if t==read, value_regno is a register which will receive the value from memory
1822  * if t==write && value_regno==-1, some unknown value is stored into memory
1823  * if t==read && value_regno==-1, don't care what we read from memory
1824  */
1825 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1826 			    int off, int bpf_size, enum bpf_access_type t,
1827 			    int value_regno, bool strict_alignment_once)
1828 {
1829 	struct bpf_reg_state *regs = cur_regs(env);
1830 	struct bpf_reg_state *reg = regs + regno;
1831 	struct bpf_func_state *state;
1832 	int size, err = 0;
1833 
1834 	size = bpf_size_to_bytes(bpf_size);
1835 	if (size < 0)
1836 		return size;
1837 
1838 	/* alignment checks will add in reg->off themselves */
1839 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1840 	if (err)
1841 		return err;
1842 
1843 	/* for access checks, reg->off is just part of off */
1844 	off += reg->off;
1845 
1846 	if (reg->type == PTR_TO_MAP_VALUE) {
1847 		if (t == BPF_WRITE && value_regno >= 0 &&
1848 		    is_pointer_value(env, value_regno)) {
1849 			verbose(env, "R%d leaks addr into map\n", value_regno);
1850 			return -EACCES;
1851 		}
1852 
1853 		err = check_map_access(env, regno, off, size, false);
1854 		if (!err && t == BPF_READ && value_regno >= 0)
1855 			mark_reg_unknown(env, regs, value_regno);
1856 
1857 	} else if (reg->type == PTR_TO_CTX) {
1858 		enum bpf_reg_type reg_type = SCALAR_VALUE;
1859 
1860 		if (t == BPF_WRITE && value_regno >= 0 &&
1861 		    is_pointer_value(env, value_regno)) {
1862 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
1863 			return -EACCES;
1864 		}
1865 
1866 		err = check_ctx_reg(env, reg, regno);
1867 		if (err < 0)
1868 			return err;
1869 
1870 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1871 		if (!err && t == BPF_READ && value_regno >= 0) {
1872 			/* ctx access returns either a scalar, or a
1873 			 * PTR_TO_PACKET[_META,_END]. In the latter
1874 			 * case, we know the offset is zero.
1875 			 */
1876 			if (reg_type == SCALAR_VALUE)
1877 				mark_reg_unknown(env, regs, value_regno);
1878 			else
1879 				mark_reg_known_zero(env, regs,
1880 						    value_regno);
1881 			regs[value_regno].type = reg_type;
1882 		}
1883 
1884 	} else if (reg->type == PTR_TO_STACK) {
1885 		/* stack accesses must be at a fixed offset, so that we can
1886 		 * determine what type of data were returned.
1887 		 * See check_stack_read().
1888 		 */
1889 		if (!tnum_is_const(reg->var_off)) {
1890 			char tn_buf[48];
1891 
1892 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1893 			verbose(env, "variable stack access var_off=%s off=%d size=%d",
1894 				tn_buf, off, size);
1895 			return -EACCES;
1896 		}
1897 		off += reg->var_off.value;
1898 		if (off >= 0 || off < -MAX_BPF_STACK) {
1899 			verbose(env, "invalid stack off=%d size=%d\n", off,
1900 				size);
1901 			return -EACCES;
1902 		}
1903 
1904 		state = func(env, reg);
1905 		err = update_stack_depth(env, state, off);
1906 		if (err)
1907 			return err;
1908 
1909 		if (t == BPF_WRITE)
1910 			err = check_stack_write(env, state, off, size,
1911 						value_regno, insn_idx);
1912 		else
1913 			err = check_stack_read(env, state, off, size,
1914 					       value_regno);
1915 	} else if (reg_is_pkt_pointer(reg)) {
1916 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1917 			verbose(env, "cannot write into packet\n");
1918 			return -EACCES;
1919 		}
1920 		if (t == BPF_WRITE && value_regno >= 0 &&
1921 		    is_pointer_value(env, value_regno)) {
1922 			verbose(env, "R%d leaks addr into packet\n",
1923 				value_regno);
1924 			return -EACCES;
1925 		}
1926 		err = check_packet_access(env, regno, off, size, false);
1927 		if (!err && t == BPF_READ && value_regno >= 0)
1928 			mark_reg_unknown(env, regs, value_regno);
1929 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
1930 		if (t == BPF_WRITE && value_regno >= 0 &&
1931 		    is_pointer_value(env, value_regno)) {
1932 			verbose(env, "R%d leaks addr into flow keys\n",
1933 				value_regno);
1934 			return -EACCES;
1935 		}
1936 
1937 		err = check_flow_keys_access(env, off, size);
1938 		if (!err && t == BPF_READ && value_regno >= 0)
1939 			mark_reg_unknown(env, regs, value_regno);
1940 	} else if (reg->type == PTR_TO_SOCKET) {
1941 		if (t == BPF_WRITE) {
1942 			verbose(env, "cannot write into socket\n");
1943 			return -EACCES;
1944 		}
1945 		err = check_sock_access(env, regno, off, size, t);
1946 		if (!err && value_regno >= 0)
1947 			mark_reg_unknown(env, regs, value_regno);
1948 	} else {
1949 		verbose(env, "R%d invalid mem access '%s'\n", regno,
1950 			reg_type_str[reg->type]);
1951 		return -EACCES;
1952 	}
1953 
1954 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1955 	    regs[value_regno].type == SCALAR_VALUE) {
1956 		/* b/h/w load zero-extends, mark upper bits as known 0 */
1957 		coerce_reg_to_size(&regs[value_regno], size);
1958 	}
1959 	return err;
1960 }
1961 
1962 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1963 {
1964 	int err;
1965 
1966 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1967 	    insn->imm != 0) {
1968 		verbose(env, "BPF_XADD uses reserved fields\n");
1969 		return -EINVAL;
1970 	}
1971 
1972 	/* check src1 operand */
1973 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
1974 	if (err)
1975 		return err;
1976 
1977 	/* check src2 operand */
1978 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1979 	if (err)
1980 		return err;
1981 
1982 	if (is_pointer_value(env, insn->src_reg)) {
1983 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1984 		return -EACCES;
1985 	}
1986 
1987 	if (is_ctx_reg(env, insn->dst_reg) ||
1988 	    is_pkt_reg(env, insn->dst_reg) ||
1989 	    is_flow_key_reg(env, insn->dst_reg)) {
1990 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1991 			insn->dst_reg,
1992 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
1993 		return -EACCES;
1994 	}
1995 
1996 	/* check whether atomic_add can read the memory */
1997 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1998 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
1999 	if (err)
2000 		return err;
2001 
2002 	/* check whether atomic_add can write into the same memory */
2003 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
2004 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
2005 }
2006 
2007 /* when register 'regno' is passed into function that will read 'access_size'
2008  * bytes from that pointer, make sure that it's within stack boundary
2009  * and all elements of stack are initialized.
2010  * Unlike most pointer bounds-checking functions, this one doesn't take an
2011  * 'off' argument, so it has to add in reg->off itself.
2012  */
2013 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
2014 				int access_size, bool zero_size_allowed,
2015 				struct bpf_call_arg_meta *meta)
2016 {
2017 	struct bpf_reg_state *reg = reg_state(env, regno);
2018 	struct bpf_func_state *state = func(env, reg);
2019 	int off, i, slot, spi;
2020 
2021 	if (reg->type != PTR_TO_STACK) {
2022 		/* Allow zero-byte read from NULL, regardless of pointer type */
2023 		if (zero_size_allowed && access_size == 0 &&
2024 		    register_is_null(reg))
2025 			return 0;
2026 
2027 		verbose(env, "R%d type=%s expected=%s\n", regno,
2028 			reg_type_str[reg->type],
2029 			reg_type_str[PTR_TO_STACK]);
2030 		return -EACCES;
2031 	}
2032 
2033 	/* Only allow fixed-offset stack reads */
2034 	if (!tnum_is_const(reg->var_off)) {
2035 		char tn_buf[48];
2036 
2037 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2038 		verbose(env, "invalid variable stack read R%d var_off=%s\n",
2039 			regno, tn_buf);
2040 		return -EACCES;
2041 	}
2042 	off = reg->off + reg->var_off.value;
2043 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
2044 	    access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
2045 		verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
2046 			regno, off, access_size);
2047 		return -EACCES;
2048 	}
2049 
2050 	if (meta && meta->raw_mode) {
2051 		meta->access_size = access_size;
2052 		meta->regno = regno;
2053 		return 0;
2054 	}
2055 
2056 	for (i = 0; i < access_size; i++) {
2057 		u8 *stype;
2058 
2059 		slot = -(off + i) - 1;
2060 		spi = slot / BPF_REG_SIZE;
2061 		if (state->allocated_stack <= slot)
2062 			goto err;
2063 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2064 		if (*stype == STACK_MISC)
2065 			goto mark;
2066 		if (*stype == STACK_ZERO) {
2067 			/* helper can write anything into the stack */
2068 			*stype = STACK_MISC;
2069 			goto mark;
2070 		}
2071 err:
2072 		verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
2073 			off, i, access_size);
2074 		return -EACCES;
2075 mark:
2076 		/* reading any byte out of 8-byte 'spill_slot' will cause
2077 		 * the whole slot to be marked as 'read'
2078 		 */
2079 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
2080 			      state->stack[spi].spilled_ptr.parent);
2081 	}
2082 	return update_stack_depth(env, state, off);
2083 }
2084 
2085 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
2086 				   int access_size, bool zero_size_allowed,
2087 				   struct bpf_call_arg_meta *meta)
2088 {
2089 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
2090 
2091 	switch (reg->type) {
2092 	case PTR_TO_PACKET:
2093 	case PTR_TO_PACKET_META:
2094 		return check_packet_access(env, regno, reg->off, access_size,
2095 					   zero_size_allowed);
2096 	case PTR_TO_MAP_VALUE:
2097 		return check_map_access(env, regno, reg->off, access_size,
2098 					zero_size_allowed);
2099 	default: /* scalar_value|ptr_to_stack or invalid ptr */
2100 		return check_stack_boundary(env, regno, access_size,
2101 					    zero_size_allowed, meta);
2102 	}
2103 }
2104 
2105 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
2106 {
2107 	return type == ARG_PTR_TO_MEM ||
2108 	       type == ARG_PTR_TO_MEM_OR_NULL ||
2109 	       type == ARG_PTR_TO_UNINIT_MEM;
2110 }
2111 
2112 static bool arg_type_is_mem_size(enum bpf_arg_type type)
2113 {
2114 	return type == ARG_CONST_SIZE ||
2115 	       type == ARG_CONST_SIZE_OR_ZERO;
2116 }
2117 
2118 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
2119 			  enum bpf_arg_type arg_type,
2120 			  struct bpf_call_arg_meta *meta)
2121 {
2122 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
2123 	enum bpf_reg_type expected_type, type = reg->type;
2124 	int err = 0;
2125 
2126 	if (arg_type == ARG_DONTCARE)
2127 		return 0;
2128 
2129 	err = check_reg_arg(env, regno, SRC_OP);
2130 	if (err)
2131 		return err;
2132 
2133 	if (arg_type == ARG_ANYTHING) {
2134 		if (is_pointer_value(env, regno)) {
2135 			verbose(env, "R%d leaks addr into helper function\n",
2136 				regno);
2137 			return -EACCES;
2138 		}
2139 		return 0;
2140 	}
2141 
2142 	if (type_is_pkt_pointer(type) &&
2143 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
2144 		verbose(env, "helper access to the packet is not allowed\n");
2145 		return -EACCES;
2146 	}
2147 
2148 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
2149 	    arg_type == ARG_PTR_TO_MAP_VALUE ||
2150 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
2151 		expected_type = PTR_TO_STACK;
2152 		if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
2153 		    type != expected_type)
2154 			goto err_type;
2155 	} else if (arg_type == ARG_CONST_SIZE ||
2156 		   arg_type == ARG_CONST_SIZE_OR_ZERO) {
2157 		expected_type = SCALAR_VALUE;
2158 		if (type != expected_type)
2159 			goto err_type;
2160 	} else if (arg_type == ARG_CONST_MAP_PTR) {
2161 		expected_type = CONST_PTR_TO_MAP;
2162 		if (type != expected_type)
2163 			goto err_type;
2164 	} else if (arg_type == ARG_PTR_TO_CTX) {
2165 		expected_type = PTR_TO_CTX;
2166 		if (type != expected_type)
2167 			goto err_type;
2168 		err = check_ctx_reg(env, reg, regno);
2169 		if (err < 0)
2170 			return err;
2171 	} else if (arg_type == ARG_PTR_TO_SOCKET) {
2172 		expected_type = PTR_TO_SOCKET;
2173 		if (type != expected_type)
2174 			goto err_type;
2175 		if (meta->ptr_id || !reg->id) {
2176 			verbose(env, "verifier internal error: mismatched references meta=%d, reg=%d\n",
2177 				meta->ptr_id, reg->id);
2178 			return -EFAULT;
2179 		}
2180 		meta->ptr_id = reg->id;
2181 	} else if (arg_type_is_mem_ptr(arg_type)) {
2182 		expected_type = PTR_TO_STACK;
2183 		/* One exception here. In case function allows for NULL to be
2184 		 * passed in as argument, it's a SCALAR_VALUE type. Final test
2185 		 * happens during stack boundary checking.
2186 		 */
2187 		if (register_is_null(reg) &&
2188 		    arg_type == ARG_PTR_TO_MEM_OR_NULL)
2189 			/* final test in check_stack_boundary() */;
2190 		else if (!type_is_pkt_pointer(type) &&
2191 			 type != PTR_TO_MAP_VALUE &&
2192 			 type != expected_type)
2193 			goto err_type;
2194 		meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2195 	} else {
2196 		verbose(env, "unsupported arg_type %d\n", arg_type);
2197 		return -EFAULT;
2198 	}
2199 
2200 	if (arg_type == ARG_CONST_MAP_PTR) {
2201 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2202 		meta->map_ptr = reg->map_ptr;
2203 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2204 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
2205 		 * check that [key, key + map->key_size) are within
2206 		 * stack limits and initialized
2207 		 */
2208 		if (!meta->map_ptr) {
2209 			/* in function declaration map_ptr must come before
2210 			 * map_key, so that it's verified and known before
2211 			 * we have to check map_key here. Otherwise it means
2212 			 * that kernel subsystem misconfigured verifier
2213 			 */
2214 			verbose(env, "invalid map_ptr to access map->key\n");
2215 			return -EACCES;
2216 		}
2217 		err = check_helper_mem_access(env, regno,
2218 					      meta->map_ptr->key_size, false,
2219 					      NULL);
2220 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
2221 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
2222 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
2223 		 * check [value, value + map->value_size) validity
2224 		 */
2225 		if (!meta->map_ptr) {
2226 			/* kernel subsystem misconfigured verifier */
2227 			verbose(env, "invalid map_ptr to access map->value\n");
2228 			return -EACCES;
2229 		}
2230 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
2231 		err = check_helper_mem_access(env, regno,
2232 					      meta->map_ptr->value_size, false,
2233 					      meta);
2234 	} else if (arg_type_is_mem_size(arg_type)) {
2235 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2236 
2237 		/* remember the mem_size which may be used later
2238 		 * to refine return values.
2239 		 */
2240 		meta->msize_smax_value = reg->smax_value;
2241 		meta->msize_umax_value = reg->umax_value;
2242 
2243 		/* The register is SCALAR_VALUE; the access check
2244 		 * happens using its boundaries.
2245 		 */
2246 		if (!tnum_is_const(reg->var_off))
2247 			/* For unprivileged variable accesses, disable raw
2248 			 * mode so that the program is required to
2249 			 * initialize all the memory that the helper could
2250 			 * just partially fill up.
2251 			 */
2252 			meta = NULL;
2253 
2254 		if (reg->smin_value < 0) {
2255 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2256 				regno);
2257 			return -EACCES;
2258 		}
2259 
2260 		if (reg->umin_value == 0) {
2261 			err = check_helper_mem_access(env, regno - 1, 0,
2262 						      zero_size_allowed,
2263 						      meta);
2264 			if (err)
2265 				return err;
2266 		}
2267 
2268 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2269 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2270 				regno);
2271 			return -EACCES;
2272 		}
2273 		err = check_helper_mem_access(env, regno - 1,
2274 					      reg->umax_value,
2275 					      zero_size_allowed, meta);
2276 	}
2277 
2278 	return err;
2279 err_type:
2280 	verbose(env, "R%d type=%s expected=%s\n", regno,
2281 		reg_type_str[type], reg_type_str[expected_type]);
2282 	return -EACCES;
2283 }
2284 
2285 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2286 					struct bpf_map *map, int func_id)
2287 {
2288 	if (!map)
2289 		return 0;
2290 
2291 	/* We need a two way check, first is from map perspective ... */
2292 	switch (map->map_type) {
2293 	case BPF_MAP_TYPE_PROG_ARRAY:
2294 		if (func_id != BPF_FUNC_tail_call)
2295 			goto error;
2296 		break;
2297 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2298 		if (func_id != BPF_FUNC_perf_event_read &&
2299 		    func_id != BPF_FUNC_perf_event_output &&
2300 		    func_id != BPF_FUNC_perf_event_read_value)
2301 			goto error;
2302 		break;
2303 	case BPF_MAP_TYPE_STACK_TRACE:
2304 		if (func_id != BPF_FUNC_get_stackid)
2305 			goto error;
2306 		break;
2307 	case BPF_MAP_TYPE_CGROUP_ARRAY:
2308 		if (func_id != BPF_FUNC_skb_under_cgroup &&
2309 		    func_id != BPF_FUNC_current_task_under_cgroup)
2310 			goto error;
2311 		break;
2312 	case BPF_MAP_TYPE_CGROUP_STORAGE:
2313 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
2314 		if (func_id != BPF_FUNC_get_local_storage)
2315 			goto error;
2316 		break;
2317 	/* devmap returns a pointer to a live net_device ifindex that we cannot
2318 	 * allow to be modified from bpf side. So do not allow lookup elements
2319 	 * for now.
2320 	 */
2321 	case BPF_MAP_TYPE_DEVMAP:
2322 		if (func_id != BPF_FUNC_redirect_map)
2323 			goto error;
2324 		break;
2325 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
2326 	 * appear.
2327 	 */
2328 	case BPF_MAP_TYPE_CPUMAP:
2329 	case BPF_MAP_TYPE_XSKMAP:
2330 		if (func_id != BPF_FUNC_redirect_map)
2331 			goto error;
2332 		break;
2333 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2334 	case BPF_MAP_TYPE_HASH_OF_MAPS:
2335 		if (func_id != BPF_FUNC_map_lookup_elem)
2336 			goto error;
2337 		break;
2338 	case BPF_MAP_TYPE_SOCKMAP:
2339 		if (func_id != BPF_FUNC_sk_redirect_map &&
2340 		    func_id != BPF_FUNC_sock_map_update &&
2341 		    func_id != BPF_FUNC_map_delete_elem &&
2342 		    func_id != BPF_FUNC_msg_redirect_map)
2343 			goto error;
2344 		break;
2345 	case BPF_MAP_TYPE_SOCKHASH:
2346 		if (func_id != BPF_FUNC_sk_redirect_hash &&
2347 		    func_id != BPF_FUNC_sock_hash_update &&
2348 		    func_id != BPF_FUNC_map_delete_elem &&
2349 		    func_id != BPF_FUNC_msg_redirect_hash)
2350 			goto error;
2351 		break;
2352 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2353 		if (func_id != BPF_FUNC_sk_select_reuseport)
2354 			goto error;
2355 		break;
2356 	case BPF_MAP_TYPE_QUEUE:
2357 	case BPF_MAP_TYPE_STACK:
2358 		if (func_id != BPF_FUNC_map_peek_elem &&
2359 		    func_id != BPF_FUNC_map_pop_elem &&
2360 		    func_id != BPF_FUNC_map_push_elem)
2361 			goto error;
2362 		break;
2363 	default:
2364 		break;
2365 	}
2366 
2367 	/* ... and second from the function itself. */
2368 	switch (func_id) {
2369 	case BPF_FUNC_tail_call:
2370 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2371 			goto error;
2372 		if (env->subprog_cnt > 1) {
2373 			verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2374 			return -EINVAL;
2375 		}
2376 		break;
2377 	case BPF_FUNC_perf_event_read:
2378 	case BPF_FUNC_perf_event_output:
2379 	case BPF_FUNC_perf_event_read_value:
2380 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2381 			goto error;
2382 		break;
2383 	case BPF_FUNC_get_stackid:
2384 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2385 			goto error;
2386 		break;
2387 	case BPF_FUNC_current_task_under_cgroup:
2388 	case BPF_FUNC_skb_under_cgroup:
2389 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2390 			goto error;
2391 		break;
2392 	case BPF_FUNC_redirect_map:
2393 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2394 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
2395 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
2396 			goto error;
2397 		break;
2398 	case BPF_FUNC_sk_redirect_map:
2399 	case BPF_FUNC_msg_redirect_map:
2400 	case BPF_FUNC_sock_map_update:
2401 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2402 			goto error;
2403 		break;
2404 	case BPF_FUNC_sk_redirect_hash:
2405 	case BPF_FUNC_msg_redirect_hash:
2406 	case BPF_FUNC_sock_hash_update:
2407 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2408 			goto error;
2409 		break;
2410 	case BPF_FUNC_get_local_storage:
2411 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
2412 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
2413 			goto error;
2414 		break;
2415 	case BPF_FUNC_sk_select_reuseport:
2416 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2417 			goto error;
2418 		break;
2419 	case BPF_FUNC_map_peek_elem:
2420 	case BPF_FUNC_map_pop_elem:
2421 	case BPF_FUNC_map_push_elem:
2422 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
2423 		    map->map_type != BPF_MAP_TYPE_STACK)
2424 			goto error;
2425 		break;
2426 	default:
2427 		break;
2428 	}
2429 
2430 	return 0;
2431 error:
2432 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
2433 		map->map_type, func_id_name(func_id), func_id);
2434 	return -EINVAL;
2435 }
2436 
2437 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2438 {
2439 	int count = 0;
2440 
2441 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2442 		count++;
2443 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2444 		count++;
2445 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2446 		count++;
2447 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2448 		count++;
2449 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2450 		count++;
2451 
2452 	/* We only support one arg being in raw mode at the moment,
2453 	 * which is sufficient for the helper functions we have
2454 	 * right now.
2455 	 */
2456 	return count <= 1;
2457 }
2458 
2459 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2460 				    enum bpf_arg_type arg_next)
2461 {
2462 	return (arg_type_is_mem_ptr(arg_curr) &&
2463 	        !arg_type_is_mem_size(arg_next)) ||
2464 	       (!arg_type_is_mem_ptr(arg_curr) &&
2465 		arg_type_is_mem_size(arg_next));
2466 }
2467 
2468 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2469 {
2470 	/* bpf_xxx(..., buf, len) call will access 'len'
2471 	 * bytes from memory 'buf'. Both arg types need
2472 	 * to be paired, so make sure there's no buggy
2473 	 * helper function specification.
2474 	 */
2475 	if (arg_type_is_mem_size(fn->arg1_type) ||
2476 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
2477 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2478 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2479 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2480 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2481 		return false;
2482 
2483 	return true;
2484 }
2485 
2486 static bool check_refcount_ok(const struct bpf_func_proto *fn)
2487 {
2488 	int count = 0;
2489 
2490 	if (arg_type_is_refcounted(fn->arg1_type))
2491 		count++;
2492 	if (arg_type_is_refcounted(fn->arg2_type))
2493 		count++;
2494 	if (arg_type_is_refcounted(fn->arg3_type))
2495 		count++;
2496 	if (arg_type_is_refcounted(fn->arg4_type))
2497 		count++;
2498 	if (arg_type_is_refcounted(fn->arg5_type))
2499 		count++;
2500 
2501 	/* We only support one arg being unreferenced at the moment,
2502 	 * which is sufficient for the helper functions we have right now.
2503 	 */
2504 	return count <= 1;
2505 }
2506 
2507 static int check_func_proto(const struct bpf_func_proto *fn)
2508 {
2509 	return check_raw_mode_ok(fn) &&
2510 	       check_arg_pair_ok(fn) &&
2511 	       check_refcount_ok(fn) ? 0 : -EINVAL;
2512 }
2513 
2514 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2515  * are now invalid, so turn them into unknown SCALAR_VALUE.
2516  */
2517 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2518 				     struct bpf_func_state *state)
2519 {
2520 	struct bpf_reg_state *regs = state->regs, *reg;
2521 	int i;
2522 
2523 	for (i = 0; i < MAX_BPF_REG; i++)
2524 		if (reg_is_pkt_pointer_any(&regs[i]))
2525 			mark_reg_unknown(env, regs, i);
2526 
2527 	bpf_for_each_spilled_reg(i, state, reg) {
2528 		if (!reg)
2529 			continue;
2530 		if (reg_is_pkt_pointer_any(reg))
2531 			__mark_reg_unknown(reg);
2532 	}
2533 }
2534 
2535 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2536 {
2537 	struct bpf_verifier_state *vstate = env->cur_state;
2538 	int i;
2539 
2540 	for (i = 0; i <= vstate->curframe; i++)
2541 		__clear_all_pkt_pointers(env, vstate->frame[i]);
2542 }
2543 
2544 static void release_reg_references(struct bpf_verifier_env *env,
2545 				   struct bpf_func_state *state, int id)
2546 {
2547 	struct bpf_reg_state *regs = state->regs, *reg;
2548 	int i;
2549 
2550 	for (i = 0; i < MAX_BPF_REG; i++)
2551 		if (regs[i].id == id)
2552 			mark_reg_unknown(env, regs, i);
2553 
2554 	bpf_for_each_spilled_reg(i, state, reg) {
2555 		if (!reg)
2556 			continue;
2557 		if (reg_is_refcounted(reg) && reg->id == id)
2558 			__mark_reg_unknown(reg);
2559 	}
2560 }
2561 
2562 /* The pointer with the specified id has released its reference to kernel
2563  * resources. Identify all copies of the same pointer and clear the reference.
2564  */
2565 static int release_reference(struct bpf_verifier_env *env,
2566 			     struct bpf_call_arg_meta *meta)
2567 {
2568 	struct bpf_verifier_state *vstate = env->cur_state;
2569 	int i;
2570 
2571 	for (i = 0; i <= vstate->curframe; i++)
2572 		release_reg_references(env, vstate->frame[i], meta->ptr_id);
2573 
2574 	return release_reference_state(env, meta->ptr_id);
2575 }
2576 
2577 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2578 			   int *insn_idx)
2579 {
2580 	struct bpf_verifier_state *state = env->cur_state;
2581 	struct bpf_func_state *caller, *callee;
2582 	int i, err, subprog, target_insn;
2583 
2584 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2585 		verbose(env, "the call stack of %d frames is too deep\n",
2586 			state->curframe + 2);
2587 		return -E2BIG;
2588 	}
2589 
2590 	target_insn = *insn_idx + insn->imm;
2591 	subprog = find_subprog(env, target_insn + 1);
2592 	if (subprog < 0) {
2593 		verbose(env, "verifier bug. No program starts at insn %d\n",
2594 			target_insn + 1);
2595 		return -EFAULT;
2596 	}
2597 
2598 	caller = state->frame[state->curframe];
2599 	if (state->frame[state->curframe + 1]) {
2600 		verbose(env, "verifier bug. Frame %d already allocated\n",
2601 			state->curframe + 1);
2602 		return -EFAULT;
2603 	}
2604 
2605 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2606 	if (!callee)
2607 		return -ENOMEM;
2608 	state->frame[state->curframe + 1] = callee;
2609 
2610 	/* callee cannot access r0, r6 - r9 for reading and has to write
2611 	 * into its own stack before reading from it.
2612 	 * callee can read/write into caller's stack
2613 	 */
2614 	init_func_state(env, callee,
2615 			/* remember the callsite, it will be used by bpf_exit */
2616 			*insn_idx /* callsite */,
2617 			state->curframe + 1 /* frameno within this callchain */,
2618 			subprog /* subprog number within this prog */);
2619 
2620 	/* Transfer references to the callee */
2621 	err = transfer_reference_state(callee, caller);
2622 	if (err)
2623 		return err;
2624 
2625 	/* copy r1 - r5 args that callee can access.  The copy includes parent
2626 	 * pointers, which connects us up to the liveness chain
2627 	 */
2628 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2629 		callee->regs[i] = caller->regs[i];
2630 
2631 	/* after the call registers r0 - r5 were scratched */
2632 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2633 		mark_reg_not_init(env, caller->regs, caller_saved[i]);
2634 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2635 	}
2636 
2637 	/* only increment it after check_reg_arg() finished */
2638 	state->curframe++;
2639 
2640 	/* and go analyze first insn of the callee */
2641 	*insn_idx = target_insn;
2642 
2643 	if (env->log.level) {
2644 		verbose(env, "caller:\n");
2645 		print_verifier_state(env, caller);
2646 		verbose(env, "callee:\n");
2647 		print_verifier_state(env, callee);
2648 	}
2649 	return 0;
2650 }
2651 
2652 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2653 {
2654 	struct bpf_verifier_state *state = env->cur_state;
2655 	struct bpf_func_state *caller, *callee;
2656 	struct bpf_reg_state *r0;
2657 	int err;
2658 
2659 	callee = state->frame[state->curframe];
2660 	r0 = &callee->regs[BPF_REG_0];
2661 	if (r0->type == PTR_TO_STACK) {
2662 		/* technically it's ok to return caller's stack pointer
2663 		 * (or caller's caller's pointer) back to the caller,
2664 		 * since these pointers are valid. Only current stack
2665 		 * pointer will be invalid as soon as function exits,
2666 		 * but let's be conservative
2667 		 */
2668 		verbose(env, "cannot return stack pointer to the caller\n");
2669 		return -EINVAL;
2670 	}
2671 
2672 	state->curframe--;
2673 	caller = state->frame[state->curframe];
2674 	/* return to the caller whatever r0 had in the callee */
2675 	caller->regs[BPF_REG_0] = *r0;
2676 
2677 	/* Transfer references to the caller */
2678 	err = transfer_reference_state(caller, callee);
2679 	if (err)
2680 		return err;
2681 
2682 	*insn_idx = callee->callsite + 1;
2683 	if (env->log.level) {
2684 		verbose(env, "returning from callee:\n");
2685 		print_verifier_state(env, callee);
2686 		verbose(env, "to caller at %d:\n", *insn_idx);
2687 		print_verifier_state(env, caller);
2688 	}
2689 	/* clear everything in the callee */
2690 	free_func_state(callee);
2691 	state->frame[state->curframe + 1] = NULL;
2692 	return 0;
2693 }
2694 
2695 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
2696 				   int func_id,
2697 				   struct bpf_call_arg_meta *meta)
2698 {
2699 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
2700 
2701 	if (ret_type != RET_INTEGER ||
2702 	    (func_id != BPF_FUNC_get_stack &&
2703 	     func_id != BPF_FUNC_probe_read_str))
2704 		return;
2705 
2706 	ret_reg->smax_value = meta->msize_smax_value;
2707 	ret_reg->umax_value = meta->msize_umax_value;
2708 	__reg_deduce_bounds(ret_reg);
2709 	__reg_bound_offset(ret_reg);
2710 }
2711 
2712 static int
2713 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2714 		int func_id, int insn_idx)
2715 {
2716 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2717 
2718 	if (func_id != BPF_FUNC_tail_call &&
2719 	    func_id != BPF_FUNC_map_lookup_elem &&
2720 	    func_id != BPF_FUNC_map_update_elem &&
2721 	    func_id != BPF_FUNC_map_delete_elem &&
2722 	    func_id != BPF_FUNC_map_push_elem &&
2723 	    func_id != BPF_FUNC_map_pop_elem &&
2724 	    func_id != BPF_FUNC_map_peek_elem)
2725 		return 0;
2726 
2727 	if (meta->map_ptr == NULL) {
2728 		verbose(env, "kernel subsystem misconfigured verifier\n");
2729 		return -EINVAL;
2730 	}
2731 
2732 	if (!BPF_MAP_PTR(aux->map_state))
2733 		bpf_map_ptr_store(aux, meta->map_ptr,
2734 				  meta->map_ptr->unpriv_array);
2735 	else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2736 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2737 				  meta->map_ptr->unpriv_array);
2738 	return 0;
2739 }
2740 
2741 static int check_reference_leak(struct bpf_verifier_env *env)
2742 {
2743 	struct bpf_func_state *state = cur_func(env);
2744 	int i;
2745 
2746 	for (i = 0; i < state->acquired_refs; i++) {
2747 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
2748 			state->refs[i].id, state->refs[i].insn_idx);
2749 	}
2750 	return state->acquired_refs ? -EINVAL : 0;
2751 }
2752 
2753 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2754 {
2755 	const struct bpf_func_proto *fn = NULL;
2756 	struct bpf_reg_state *regs;
2757 	struct bpf_call_arg_meta meta;
2758 	bool changes_data;
2759 	int i, err;
2760 
2761 	/* find function prototype */
2762 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2763 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2764 			func_id);
2765 		return -EINVAL;
2766 	}
2767 
2768 	if (env->ops->get_func_proto)
2769 		fn = env->ops->get_func_proto(func_id, env->prog);
2770 	if (!fn) {
2771 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2772 			func_id);
2773 		return -EINVAL;
2774 	}
2775 
2776 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
2777 	if (!env->prog->gpl_compatible && fn->gpl_only) {
2778 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2779 		return -EINVAL;
2780 	}
2781 
2782 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
2783 	changes_data = bpf_helper_changes_pkt_data(fn->func);
2784 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2785 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2786 			func_id_name(func_id), func_id);
2787 		return -EINVAL;
2788 	}
2789 
2790 	memset(&meta, 0, sizeof(meta));
2791 	meta.pkt_access = fn->pkt_access;
2792 
2793 	err = check_func_proto(fn);
2794 	if (err) {
2795 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2796 			func_id_name(func_id), func_id);
2797 		return err;
2798 	}
2799 
2800 	/* check args */
2801 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2802 	if (err)
2803 		return err;
2804 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2805 	if (err)
2806 		return err;
2807 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2808 	if (err)
2809 		return err;
2810 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2811 	if (err)
2812 		return err;
2813 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2814 	if (err)
2815 		return err;
2816 
2817 	err = record_func_map(env, &meta, func_id, insn_idx);
2818 	if (err)
2819 		return err;
2820 
2821 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
2822 	 * is inferred from register state.
2823 	 */
2824 	for (i = 0; i < meta.access_size; i++) {
2825 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2826 				       BPF_WRITE, -1, false);
2827 		if (err)
2828 			return err;
2829 	}
2830 
2831 	if (func_id == BPF_FUNC_tail_call) {
2832 		err = check_reference_leak(env);
2833 		if (err) {
2834 			verbose(env, "tail_call would lead to reference leak\n");
2835 			return err;
2836 		}
2837 	} else if (is_release_function(func_id)) {
2838 		err = release_reference(env, &meta);
2839 		if (err)
2840 			return err;
2841 	}
2842 
2843 	regs = cur_regs(env);
2844 
2845 	/* check that flags argument in get_local_storage(map, flags) is 0,
2846 	 * this is required because get_local_storage() can't return an error.
2847 	 */
2848 	if (func_id == BPF_FUNC_get_local_storage &&
2849 	    !register_is_null(&regs[BPF_REG_2])) {
2850 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2851 		return -EINVAL;
2852 	}
2853 
2854 	/* reset caller saved regs */
2855 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2856 		mark_reg_not_init(env, regs, caller_saved[i]);
2857 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2858 	}
2859 
2860 	/* update return register (already marked as written above) */
2861 	if (fn->ret_type == RET_INTEGER) {
2862 		/* sets type to SCALAR_VALUE */
2863 		mark_reg_unknown(env, regs, BPF_REG_0);
2864 	} else if (fn->ret_type == RET_VOID) {
2865 		regs[BPF_REG_0].type = NOT_INIT;
2866 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2867 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2868 		/* There is no offset yet applied, variable or fixed */
2869 		mark_reg_known_zero(env, regs, BPF_REG_0);
2870 		/* remember map_ptr, so that check_map_access()
2871 		 * can check 'value_size' boundary of memory access
2872 		 * to map element returned from bpf_map_lookup_elem()
2873 		 */
2874 		if (meta.map_ptr == NULL) {
2875 			verbose(env,
2876 				"kernel subsystem misconfigured verifier\n");
2877 			return -EINVAL;
2878 		}
2879 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
2880 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2881 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2882 		} else {
2883 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2884 			regs[BPF_REG_0].id = ++env->id_gen;
2885 		}
2886 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
2887 		int id = acquire_reference_state(env, insn_idx);
2888 		if (id < 0)
2889 			return id;
2890 		mark_reg_known_zero(env, regs, BPF_REG_0);
2891 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
2892 		regs[BPF_REG_0].id = id;
2893 	} else {
2894 		verbose(env, "unknown return type %d of func %s#%d\n",
2895 			fn->ret_type, func_id_name(func_id), func_id);
2896 		return -EINVAL;
2897 	}
2898 
2899 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
2900 
2901 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2902 	if (err)
2903 		return err;
2904 
2905 	if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2906 		const char *err_str;
2907 
2908 #ifdef CONFIG_PERF_EVENTS
2909 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
2910 		err_str = "cannot get callchain buffer for func %s#%d\n";
2911 #else
2912 		err = -ENOTSUPP;
2913 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2914 #endif
2915 		if (err) {
2916 			verbose(env, err_str, func_id_name(func_id), func_id);
2917 			return err;
2918 		}
2919 
2920 		env->prog->has_callchain_buf = true;
2921 	}
2922 
2923 	if (changes_data)
2924 		clear_all_pkt_pointers(env);
2925 	return 0;
2926 }
2927 
2928 static bool signed_add_overflows(s64 a, s64 b)
2929 {
2930 	/* Do the add in u64, where overflow is well-defined */
2931 	s64 res = (s64)((u64)a + (u64)b);
2932 
2933 	if (b < 0)
2934 		return res > a;
2935 	return res < a;
2936 }
2937 
2938 static bool signed_sub_overflows(s64 a, s64 b)
2939 {
2940 	/* Do the sub in u64, where overflow is well-defined */
2941 	s64 res = (s64)((u64)a - (u64)b);
2942 
2943 	if (b < 0)
2944 		return res < a;
2945 	return res > a;
2946 }
2947 
2948 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2949 				  const struct bpf_reg_state *reg,
2950 				  enum bpf_reg_type type)
2951 {
2952 	bool known = tnum_is_const(reg->var_off);
2953 	s64 val = reg->var_off.value;
2954 	s64 smin = reg->smin_value;
2955 
2956 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2957 		verbose(env, "math between %s pointer and %lld is not allowed\n",
2958 			reg_type_str[type], val);
2959 		return false;
2960 	}
2961 
2962 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2963 		verbose(env, "%s pointer offset %d is not allowed\n",
2964 			reg_type_str[type], reg->off);
2965 		return false;
2966 	}
2967 
2968 	if (smin == S64_MIN) {
2969 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2970 			reg_type_str[type]);
2971 		return false;
2972 	}
2973 
2974 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2975 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
2976 			smin, reg_type_str[type]);
2977 		return false;
2978 	}
2979 
2980 	return true;
2981 }
2982 
2983 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2984  * Caller should also handle BPF_MOV case separately.
2985  * If we return -EACCES, caller may want to try again treating pointer as a
2986  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
2987  */
2988 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2989 				   struct bpf_insn *insn,
2990 				   const struct bpf_reg_state *ptr_reg,
2991 				   const struct bpf_reg_state *off_reg)
2992 {
2993 	struct bpf_verifier_state *vstate = env->cur_state;
2994 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2995 	struct bpf_reg_state *regs = state->regs, *dst_reg;
2996 	bool known = tnum_is_const(off_reg->var_off);
2997 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2998 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2999 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3000 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3001 	u8 opcode = BPF_OP(insn->code);
3002 	u32 dst = insn->dst_reg;
3003 
3004 	dst_reg = &regs[dst];
3005 
3006 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3007 	    smin_val > smax_val || umin_val > umax_val) {
3008 		/* Taint dst register if offset had invalid bounds derived from
3009 		 * e.g. dead branches.
3010 		 */
3011 		__mark_reg_unknown(dst_reg);
3012 		return 0;
3013 	}
3014 
3015 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
3016 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
3017 		verbose(env,
3018 			"R%d 32-bit pointer arithmetic prohibited\n",
3019 			dst);
3020 		return -EACCES;
3021 	}
3022 
3023 	switch (ptr_reg->type) {
3024 	case PTR_TO_MAP_VALUE_OR_NULL:
3025 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
3026 			dst, reg_type_str[ptr_reg->type]);
3027 		return -EACCES;
3028 	case CONST_PTR_TO_MAP:
3029 	case PTR_TO_PACKET_END:
3030 	case PTR_TO_SOCKET:
3031 	case PTR_TO_SOCKET_OR_NULL:
3032 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
3033 			dst, reg_type_str[ptr_reg->type]);
3034 		return -EACCES;
3035 	default:
3036 		break;
3037 	}
3038 
3039 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3040 	 * The id may be overwritten later if we create a new variable offset.
3041 	 */
3042 	dst_reg->type = ptr_reg->type;
3043 	dst_reg->id = ptr_reg->id;
3044 
3045 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3046 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3047 		return -EINVAL;
3048 
3049 	switch (opcode) {
3050 	case BPF_ADD:
3051 		/* We can take a fixed offset as long as it doesn't overflow
3052 		 * the s32 'off' field
3053 		 */
3054 		if (known && (ptr_reg->off + smin_val ==
3055 			      (s64)(s32)(ptr_reg->off + smin_val))) {
3056 			/* pointer += K.  Accumulate it into fixed offset */
3057 			dst_reg->smin_value = smin_ptr;
3058 			dst_reg->smax_value = smax_ptr;
3059 			dst_reg->umin_value = umin_ptr;
3060 			dst_reg->umax_value = umax_ptr;
3061 			dst_reg->var_off = ptr_reg->var_off;
3062 			dst_reg->off = ptr_reg->off + smin_val;
3063 			dst_reg->raw = ptr_reg->raw;
3064 			break;
3065 		}
3066 		/* A new variable offset is created.  Note that off_reg->off
3067 		 * == 0, since it's a scalar.
3068 		 * dst_reg gets the pointer type and since some positive
3069 		 * integer value was added to the pointer, give it a new 'id'
3070 		 * if it's a PTR_TO_PACKET.
3071 		 * this creates a new 'base' pointer, off_reg (variable) gets
3072 		 * added into the variable offset, and we copy the fixed offset
3073 		 * from ptr_reg.
3074 		 */
3075 		if (signed_add_overflows(smin_ptr, smin_val) ||
3076 		    signed_add_overflows(smax_ptr, smax_val)) {
3077 			dst_reg->smin_value = S64_MIN;
3078 			dst_reg->smax_value = S64_MAX;
3079 		} else {
3080 			dst_reg->smin_value = smin_ptr + smin_val;
3081 			dst_reg->smax_value = smax_ptr + smax_val;
3082 		}
3083 		if (umin_ptr + umin_val < umin_ptr ||
3084 		    umax_ptr + umax_val < umax_ptr) {
3085 			dst_reg->umin_value = 0;
3086 			dst_reg->umax_value = U64_MAX;
3087 		} else {
3088 			dst_reg->umin_value = umin_ptr + umin_val;
3089 			dst_reg->umax_value = umax_ptr + umax_val;
3090 		}
3091 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3092 		dst_reg->off = ptr_reg->off;
3093 		dst_reg->raw = ptr_reg->raw;
3094 		if (reg_is_pkt_pointer(ptr_reg)) {
3095 			dst_reg->id = ++env->id_gen;
3096 			/* something was added to pkt_ptr, set range to zero */
3097 			dst_reg->raw = 0;
3098 		}
3099 		break;
3100 	case BPF_SUB:
3101 		if (dst_reg == off_reg) {
3102 			/* scalar -= pointer.  Creates an unknown scalar */
3103 			verbose(env, "R%d tried to subtract pointer from scalar\n",
3104 				dst);
3105 			return -EACCES;
3106 		}
3107 		/* We don't allow subtraction from FP, because (according to
3108 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
3109 		 * be able to deal with it.
3110 		 */
3111 		if (ptr_reg->type == PTR_TO_STACK) {
3112 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
3113 				dst);
3114 			return -EACCES;
3115 		}
3116 		if (known && (ptr_reg->off - smin_val ==
3117 			      (s64)(s32)(ptr_reg->off - smin_val))) {
3118 			/* pointer -= K.  Subtract it from fixed offset */
3119 			dst_reg->smin_value = smin_ptr;
3120 			dst_reg->smax_value = smax_ptr;
3121 			dst_reg->umin_value = umin_ptr;
3122 			dst_reg->umax_value = umax_ptr;
3123 			dst_reg->var_off = ptr_reg->var_off;
3124 			dst_reg->id = ptr_reg->id;
3125 			dst_reg->off = ptr_reg->off - smin_val;
3126 			dst_reg->raw = ptr_reg->raw;
3127 			break;
3128 		}
3129 		/* A new variable offset is created.  If the subtrahend is known
3130 		 * nonnegative, then any reg->range we had before is still good.
3131 		 */
3132 		if (signed_sub_overflows(smin_ptr, smax_val) ||
3133 		    signed_sub_overflows(smax_ptr, smin_val)) {
3134 			/* Overflow possible, we know nothing */
3135 			dst_reg->smin_value = S64_MIN;
3136 			dst_reg->smax_value = S64_MAX;
3137 		} else {
3138 			dst_reg->smin_value = smin_ptr - smax_val;
3139 			dst_reg->smax_value = smax_ptr - smin_val;
3140 		}
3141 		if (umin_ptr < umax_val) {
3142 			/* Overflow possible, we know nothing */
3143 			dst_reg->umin_value = 0;
3144 			dst_reg->umax_value = U64_MAX;
3145 		} else {
3146 			/* Cannot overflow (as long as bounds are consistent) */
3147 			dst_reg->umin_value = umin_ptr - umax_val;
3148 			dst_reg->umax_value = umax_ptr - umin_val;
3149 		}
3150 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3151 		dst_reg->off = ptr_reg->off;
3152 		dst_reg->raw = ptr_reg->raw;
3153 		if (reg_is_pkt_pointer(ptr_reg)) {
3154 			dst_reg->id = ++env->id_gen;
3155 			/* something was added to pkt_ptr, set range to zero */
3156 			if (smin_val < 0)
3157 				dst_reg->raw = 0;
3158 		}
3159 		break;
3160 	case BPF_AND:
3161 	case BPF_OR:
3162 	case BPF_XOR:
3163 		/* bitwise ops on pointers are troublesome, prohibit. */
3164 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3165 			dst, bpf_alu_string[opcode >> 4]);
3166 		return -EACCES;
3167 	default:
3168 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
3169 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3170 			dst, bpf_alu_string[opcode >> 4]);
3171 		return -EACCES;
3172 	}
3173 
3174 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3175 		return -EINVAL;
3176 
3177 	__update_reg_bounds(dst_reg);
3178 	__reg_deduce_bounds(dst_reg);
3179 	__reg_bound_offset(dst_reg);
3180 	return 0;
3181 }
3182 
3183 /* WARNING: This function does calculations on 64-bit values, but the actual
3184  * execution may occur on 32-bit values. Therefore, things like bitshifts
3185  * need extra checks in the 32-bit case.
3186  */
3187 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3188 				      struct bpf_insn *insn,
3189 				      struct bpf_reg_state *dst_reg,
3190 				      struct bpf_reg_state src_reg)
3191 {
3192 	struct bpf_reg_state *regs = cur_regs(env);
3193 	u8 opcode = BPF_OP(insn->code);
3194 	bool src_known, dst_known;
3195 	s64 smin_val, smax_val;
3196 	u64 umin_val, umax_val;
3197 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3198 
3199 	if (insn_bitness == 32) {
3200 		/* Relevant for 32-bit RSH: Information can propagate towards
3201 		 * LSB, so it isn't sufficient to only truncate the output to
3202 		 * 32 bits.
3203 		 */
3204 		coerce_reg_to_size(dst_reg, 4);
3205 		coerce_reg_to_size(&src_reg, 4);
3206 	}
3207 
3208 	smin_val = src_reg.smin_value;
3209 	smax_val = src_reg.smax_value;
3210 	umin_val = src_reg.umin_value;
3211 	umax_val = src_reg.umax_value;
3212 	src_known = tnum_is_const(src_reg.var_off);
3213 	dst_known = tnum_is_const(dst_reg->var_off);
3214 
3215 	if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3216 	    smin_val > smax_val || umin_val > umax_val) {
3217 		/* Taint dst register if offset had invalid bounds derived from
3218 		 * e.g. dead branches.
3219 		 */
3220 		__mark_reg_unknown(dst_reg);
3221 		return 0;
3222 	}
3223 
3224 	if (!src_known &&
3225 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3226 		__mark_reg_unknown(dst_reg);
3227 		return 0;
3228 	}
3229 
3230 	switch (opcode) {
3231 	case BPF_ADD:
3232 		if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3233 		    signed_add_overflows(dst_reg->smax_value, smax_val)) {
3234 			dst_reg->smin_value = S64_MIN;
3235 			dst_reg->smax_value = S64_MAX;
3236 		} else {
3237 			dst_reg->smin_value += smin_val;
3238 			dst_reg->smax_value += smax_val;
3239 		}
3240 		if (dst_reg->umin_value + umin_val < umin_val ||
3241 		    dst_reg->umax_value + umax_val < umax_val) {
3242 			dst_reg->umin_value = 0;
3243 			dst_reg->umax_value = U64_MAX;
3244 		} else {
3245 			dst_reg->umin_value += umin_val;
3246 			dst_reg->umax_value += umax_val;
3247 		}
3248 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3249 		break;
3250 	case BPF_SUB:
3251 		if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3252 		    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3253 			/* Overflow possible, we know nothing */
3254 			dst_reg->smin_value = S64_MIN;
3255 			dst_reg->smax_value = S64_MAX;
3256 		} else {
3257 			dst_reg->smin_value -= smax_val;
3258 			dst_reg->smax_value -= smin_val;
3259 		}
3260 		if (dst_reg->umin_value < umax_val) {
3261 			/* Overflow possible, we know nothing */
3262 			dst_reg->umin_value = 0;
3263 			dst_reg->umax_value = U64_MAX;
3264 		} else {
3265 			/* Cannot overflow (as long as bounds are consistent) */
3266 			dst_reg->umin_value -= umax_val;
3267 			dst_reg->umax_value -= umin_val;
3268 		}
3269 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3270 		break;
3271 	case BPF_MUL:
3272 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3273 		if (smin_val < 0 || dst_reg->smin_value < 0) {
3274 			/* Ain't nobody got time to multiply that sign */
3275 			__mark_reg_unbounded(dst_reg);
3276 			__update_reg_bounds(dst_reg);
3277 			break;
3278 		}
3279 		/* Both values are positive, so we can work with unsigned and
3280 		 * copy the result to signed (unless it exceeds S64_MAX).
3281 		 */
3282 		if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3283 			/* Potential overflow, we know nothing */
3284 			__mark_reg_unbounded(dst_reg);
3285 			/* (except what we can learn from the var_off) */
3286 			__update_reg_bounds(dst_reg);
3287 			break;
3288 		}
3289 		dst_reg->umin_value *= umin_val;
3290 		dst_reg->umax_value *= umax_val;
3291 		if (dst_reg->umax_value > S64_MAX) {
3292 			/* Overflow possible, we know nothing */
3293 			dst_reg->smin_value = S64_MIN;
3294 			dst_reg->smax_value = S64_MAX;
3295 		} else {
3296 			dst_reg->smin_value = dst_reg->umin_value;
3297 			dst_reg->smax_value = dst_reg->umax_value;
3298 		}
3299 		break;
3300 	case BPF_AND:
3301 		if (src_known && dst_known) {
3302 			__mark_reg_known(dst_reg, dst_reg->var_off.value &
3303 						  src_reg.var_off.value);
3304 			break;
3305 		}
3306 		/* We get our minimum from the var_off, since that's inherently
3307 		 * bitwise.  Our maximum is the minimum of the operands' maxima.
3308 		 */
3309 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3310 		dst_reg->umin_value = dst_reg->var_off.value;
3311 		dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3312 		if (dst_reg->smin_value < 0 || smin_val < 0) {
3313 			/* Lose signed bounds when ANDing negative numbers,
3314 			 * ain't nobody got time for that.
3315 			 */
3316 			dst_reg->smin_value = S64_MIN;
3317 			dst_reg->smax_value = S64_MAX;
3318 		} else {
3319 			/* ANDing two positives gives a positive, so safe to
3320 			 * cast result into s64.
3321 			 */
3322 			dst_reg->smin_value = dst_reg->umin_value;
3323 			dst_reg->smax_value = dst_reg->umax_value;
3324 		}
3325 		/* We may learn something more from the var_off */
3326 		__update_reg_bounds(dst_reg);
3327 		break;
3328 	case BPF_OR:
3329 		if (src_known && dst_known) {
3330 			__mark_reg_known(dst_reg, dst_reg->var_off.value |
3331 						  src_reg.var_off.value);
3332 			break;
3333 		}
3334 		/* We get our maximum from the var_off, and our minimum is the
3335 		 * maximum of the operands' minima
3336 		 */
3337 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3338 		dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3339 		dst_reg->umax_value = dst_reg->var_off.value |
3340 				      dst_reg->var_off.mask;
3341 		if (dst_reg->smin_value < 0 || smin_val < 0) {
3342 			/* Lose signed bounds when ORing negative numbers,
3343 			 * ain't nobody got time for that.
3344 			 */
3345 			dst_reg->smin_value = S64_MIN;
3346 			dst_reg->smax_value = S64_MAX;
3347 		} else {
3348 			/* ORing two positives gives a positive, so safe to
3349 			 * cast result into s64.
3350 			 */
3351 			dst_reg->smin_value = dst_reg->umin_value;
3352 			dst_reg->smax_value = dst_reg->umax_value;
3353 		}
3354 		/* We may learn something more from the var_off */
3355 		__update_reg_bounds(dst_reg);
3356 		break;
3357 	case BPF_LSH:
3358 		if (umax_val >= insn_bitness) {
3359 			/* Shifts greater than 31 or 63 are undefined.
3360 			 * This includes shifts by a negative number.
3361 			 */
3362 			mark_reg_unknown(env, regs, insn->dst_reg);
3363 			break;
3364 		}
3365 		/* We lose all sign bit information (except what we can pick
3366 		 * up from var_off)
3367 		 */
3368 		dst_reg->smin_value = S64_MIN;
3369 		dst_reg->smax_value = S64_MAX;
3370 		/* If we might shift our top bit out, then we know nothing */
3371 		if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3372 			dst_reg->umin_value = 0;
3373 			dst_reg->umax_value = U64_MAX;
3374 		} else {
3375 			dst_reg->umin_value <<= umin_val;
3376 			dst_reg->umax_value <<= umax_val;
3377 		}
3378 		dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3379 		/* We may learn something more from the var_off */
3380 		__update_reg_bounds(dst_reg);
3381 		break;
3382 	case BPF_RSH:
3383 		if (umax_val >= insn_bitness) {
3384 			/* Shifts greater than 31 or 63 are undefined.
3385 			 * This includes shifts by a negative number.
3386 			 */
3387 			mark_reg_unknown(env, regs, insn->dst_reg);
3388 			break;
3389 		}
3390 		/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
3391 		 * be negative, then either:
3392 		 * 1) src_reg might be zero, so the sign bit of the result is
3393 		 *    unknown, so we lose our signed bounds
3394 		 * 2) it's known negative, thus the unsigned bounds capture the
3395 		 *    signed bounds
3396 		 * 3) the signed bounds cross zero, so they tell us nothing
3397 		 *    about the result
3398 		 * If the value in dst_reg is known nonnegative, then again the
3399 		 * unsigned bounts capture the signed bounds.
3400 		 * Thus, in all cases it suffices to blow away our signed bounds
3401 		 * and rely on inferring new ones from the unsigned bounds and
3402 		 * var_off of the result.
3403 		 */
3404 		dst_reg->smin_value = S64_MIN;
3405 		dst_reg->smax_value = S64_MAX;
3406 		dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3407 		dst_reg->umin_value >>= umax_val;
3408 		dst_reg->umax_value >>= umin_val;
3409 		/* We may learn something more from the var_off */
3410 		__update_reg_bounds(dst_reg);
3411 		break;
3412 	case BPF_ARSH:
3413 		if (umax_val >= insn_bitness) {
3414 			/* Shifts greater than 31 or 63 are undefined.
3415 			 * This includes shifts by a negative number.
3416 			 */
3417 			mark_reg_unknown(env, regs, insn->dst_reg);
3418 			break;
3419 		}
3420 
3421 		/* Upon reaching here, src_known is true and
3422 		 * umax_val is equal to umin_val.
3423 		 */
3424 		dst_reg->smin_value >>= umin_val;
3425 		dst_reg->smax_value >>= umin_val;
3426 		dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
3427 
3428 		/* blow away the dst_reg umin_value/umax_value and rely on
3429 		 * dst_reg var_off to refine the result.
3430 		 */
3431 		dst_reg->umin_value = 0;
3432 		dst_reg->umax_value = U64_MAX;
3433 		__update_reg_bounds(dst_reg);
3434 		break;
3435 	default:
3436 		mark_reg_unknown(env, regs, insn->dst_reg);
3437 		break;
3438 	}
3439 
3440 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
3441 		/* 32-bit ALU ops are (32,32)->32 */
3442 		coerce_reg_to_size(dst_reg, 4);
3443 	}
3444 
3445 	__reg_deduce_bounds(dst_reg);
3446 	__reg_bound_offset(dst_reg);
3447 	return 0;
3448 }
3449 
3450 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3451  * and var_off.
3452  */
3453 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3454 				   struct bpf_insn *insn)
3455 {
3456 	struct bpf_verifier_state *vstate = env->cur_state;
3457 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3458 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3459 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3460 	u8 opcode = BPF_OP(insn->code);
3461 
3462 	dst_reg = &regs[insn->dst_reg];
3463 	src_reg = NULL;
3464 	if (dst_reg->type != SCALAR_VALUE)
3465 		ptr_reg = dst_reg;
3466 	if (BPF_SRC(insn->code) == BPF_X) {
3467 		src_reg = &regs[insn->src_reg];
3468 		if (src_reg->type != SCALAR_VALUE) {
3469 			if (dst_reg->type != SCALAR_VALUE) {
3470 				/* Combining two pointers by any ALU op yields
3471 				 * an arbitrary scalar. Disallow all math except
3472 				 * pointer subtraction
3473 				 */
3474 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3475 					mark_reg_unknown(env, regs, insn->dst_reg);
3476 					return 0;
3477 				}
3478 				verbose(env, "R%d pointer %s pointer prohibited\n",
3479 					insn->dst_reg,
3480 					bpf_alu_string[opcode >> 4]);
3481 				return -EACCES;
3482 			} else {
3483 				/* scalar += pointer
3484 				 * This is legal, but we have to reverse our
3485 				 * src/dest handling in computing the range
3486 				 */
3487 				return adjust_ptr_min_max_vals(env, insn,
3488 							       src_reg, dst_reg);
3489 			}
3490 		} else if (ptr_reg) {
3491 			/* pointer += scalar */
3492 			return adjust_ptr_min_max_vals(env, insn,
3493 						       dst_reg, src_reg);
3494 		}
3495 	} else {
3496 		/* Pretend the src is a reg with a known value, since we only
3497 		 * need to be able to read from this state.
3498 		 */
3499 		off_reg.type = SCALAR_VALUE;
3500 		__mark_reg_known(&off_reg, insn->imm);
3501 		src_reg = &off_reg;
3502 		if (ptr_reg) /* pointer += K */
3503 			return adjust_ptr_min_max_vals(env, insn,
3504 						       ptr_reg, src_reg);
3505 	}
3506 
3507 	/* Got here implies adding two SCALAR_VALUEs */
3508 	if (WARN_ON_ONCE(ptr_reg)) {
3509 		print_verifier_state(env, state);
3510 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
3511 		return -EINVAL;
3512 	}
3513 	if (WARN_ON(!src_reg)) {
3514 		print_verifier_state(env, state);
3515 		verbose(env, "verifier internal error: no src_reg\n");
3516 		return -EINVAL;
3517 	}
3518 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3519 }
3520 
3521 /* check validity of 32-bit and 64-bit arithmetic operations */
3522 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3523 {
3524 	struct bpf_reg_state *regs = cur_regs(env);
3525 	u8 opcode = BPF_OP(insn->code);
3526 	int err;
3527 
3528 	if (opcode == BPF_END || opcode == BPF_NEG) {
3529 		if (opcode == BPF_NEG) {
3530 			if (BPF_SRC(insn->code) != 0 ||
3531 			    insn->src_reg != BPF_REG_0 ||
3532 			    insn->off != 0 || insn->imm != 0) {
3533 				verbose(env, "BPF_NEG uses reserved fields\n");
3534 				return -EINVAL;
3535 			}
3536 		} else {
3537 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3538 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3539 			    BPF_CLASS(insn->code) == BPF_ALU64) {
3540 				verbose(env, "BPF_END uses reserved fields\n");
3541 				return -EINVAL;
3542 			}
3543 		}
3544 
3545 		/* check src operand */
3546 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3547 		if (err)
3548 			return err;
3549 
3550 		if (is_pointer_value(env, insn->dst_reg)) {
3551 			verbose(env, "R%d pointer arithmetic prohibited\n",
3552 				insn->dst_reg);
3553 			return -EACCES;
3554 		}
3555 
3556 		/* check dest operand */
3557 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
3558 		if (err)
3559 			return err;
3560 
3561 	} else if (opcode == BPF_MOV) {
3562 
3563 		if (BPF_SRC(insn->code) == BPF_X) {
3564 			if (insn->imm != 0 || insn->off != 0) {
3565 				verbose(env, "BPF_MOV uses reserved fields\n");
3566 				return -EINVAL;
3567 			}
3568 
3569 			/* check src operand */
3570 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
3571 			if (err)
3572 				return err;
3573 		} else {
3574 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3575 				verbose(env, "BPF_MOV uses reserved fields\n");
3576 				return -EINVAL;
3577 			}
3578 		}
3579 
3580 		/* check dest operand, mark as required later */
3581 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3582 		if (err)
3583 			return err;
3584 
3585 		if (BPF_SRC(insn->code) == BPF_X) {
3586 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
3587 				/* case: R1 = R2
3588 				 * copy register state to dest reg
3589 				 */
3590 				regs[insn->dst_reg] = regs[insn->src_reg];
3591 				regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3592 			} else {
3593 				/* R1 = (u32) R2 */
3594 				if (is_pointer_value(env, insn->src_reg)) {
3595 					verbose(env,
3596 						"R%d partial copy of pointer\n",
3597 						insn->src_reg);
3598 					return -EACCES;
3599 				}
3600 				mark_reg_unknown(env, regs, insn->dst_reg);
3601 				coerce_reg_to_size(&regs[insn->dst_reg], 4);
3602 			}
3603 		} else {
3604 			/* case: R = imm
3605 			 * remember the value we stored into this reg
3606 			 */
3607 			/* clear any state __mark_reg_known doesn't set */
3608 			mark_reg_unknown(env, regs, insn->dst_reg);
3609 			regs[insn->dst_reg].type = SCALAR_VALUE;
3610 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
3611 				__mark_reg_known(regs + insn->dst_reg,
3612 						 insn->imm);
3613 			} else {
3614 				__mark_reg_known(regs + insn->dst_reg,
3615 						 (u32)insn->imm);
3616 			}
3617 		}
3618 
3619 	} else if (opcode > BPF_END) {
3620 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3621 		return -EINVAL;
3622 
3623 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
3624 
3625 		if (BPF_SRC(insn->code) == BPF_X) {
3626 			if (insn->imm != 0 || insn->off != 0) {
3627 				verbose(env, "BPF_ALU uses reserved fields\n");
3628 				return -EINVAL;
3629 			}
3630 			/* check src1 operand */
3631 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
3632 			if (err)
3633 				return err;
3634 		} else {
3635 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3636 				verbose(env, "BPF_ALU uses reserved fields\n");
3637 				return -EINVAL;
3638 			}
3639 		}
3640 
3641 		/* check src2 operand */
3642 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3643 		if (err)
3644 			return err;
3645 
3646 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3647 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3648 			verbose(env, "div by zero\n");
3649 			return -EINVAL;
3650 		}
3651 
3652 		if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3653 			verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3654 			return -EINVAL;
3655 		}
3656 
3657 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3658 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3659 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3660 
3661 			if (insn->imm < 0 || insn->imm >= size) {
3662 				verbose(env, "invalid shift %d\n", insn->imm);
3663 				return -EINVAL;
3664 			}
3665 		}
3666 
3667 		/* check dest operand */
3668 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3669 		if (err)
3670 			return err;
3671 
3672 		return adjust_reg_min_max_vals(env, insn);
3673 	}
3674 
3675 	return 0;
3676 }
3677 
3678 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3679 				   struct bpf_reg_state *dst_reg,
3680 				   enum bpf_reg_type type,
3681 				   bool range_right_open)
3682 {
3683 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3684 	struct bpf_reg_state *regs = state->regs, *reg;
3685 	u16 new_range;
3686 	int i, j;
3687 
3688 	if (dst_reg->off < 0 ||
3689 	    (dst_reg->off == 0 && range_right_open))
3690 		/* This doesn't give us any range */
3691 		return;
3692 
3693 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
3694 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3695 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
3696 		 * than pkt_end, but that's because it's also less than pkt.
3697 		 */
3698 		return;
3699 
3700 	new_range = dst_reg->off;
3701 	if (range_right_open)
3702 		new_range--;
3703 
3704 	/* Examples for register markings:
3705 	 *
3706 	 * pkt_data in dst register:
3707 	 *
3708 	 *   r2 = r3;
3709 	 *   r2 += 8;
3710 	 *   if (r2 > pkt_end) goto <handle exception>
3711 	 *   <access okay>
3712 	 *
3713 	 *   r2 = r3;
3714 	 *   r2 += 8;
3715 	 *   if (r2 < pkt_end) goto <access okay>
3716 	 *   <handle exception>
3717 	 *
3718 	 *   Where:
3719 	 *     r2 == dst_reg, pkt_end == src_reg
3720 	 *     r2=pkt(id=n,off=8,r=0)
3721 	 *     r3=pkt(id=n,off=0,r=0)
3722 	 *
3723 	 * pkt_data in src register:
3724 	 *
3725 	 *   r2 = r3;
3726 	 *   r2 += 8;
3727 	 *   if (pkt_end >= r2) goto <access okay>
3728 	 *   <handle exception>
3729 	 *
3730 	 *   r2 = r3;
3731 	 *   r2 += 8;
3732 	 *   if (pkt_end <= r2) goto <handle exception>
3733 	 *   <access okay>
3734 	 *
3735 	 *   Where:
3736 	 *     pkt_end == dst_reg, r2 == src_reg
3737 	 *     r2=pkt(id=n,off=8,r=0)
3738 	 *     r3=pkt(id=n,off=0,r=0)
3739 	 *
3740 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3741 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3742 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
3743 	 * the check.
3744 	 */
3745 
3746 	/* If our ids match, then we must have the same max_value.  And we
3747 	 * don't care about the other reg's fixed offset, since if it's too big
3748 	 * the range won't allow anything.
3749 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3750 	 */
3751 	for (i = 0; i < MAX_BPF_REG; i++)
3752 		if (regs[i].type == type && regs[i].id == dst_reg->id)
3753 			/* keep the maximum range already checked */
3754 			regs[i].range = max(regs[i].range, new_range);
3755 
3756 	for (j = 0; j <= vstate->curframe; j++) {
3757 		state = vstate->frame[j];
3758 		bpf_for_each_spilled_reg(i, state, reg) {
3759 			if (!reg)
3760 				continue;
3761 			if (reg->type == type && reg->id == dst_reg->id)
3762 				reg->range = max(reg->range, new_range);
3763 		}
3764 	}
3765 }
3766 
3767 /* Adjusts the register min/max values in the case that the dst_reg is the
3768  * variable register that we are working on, and src_reg is a constant or we're
3769  * simply doing a BPF_K check.
3770  * In JEQ/JNE cases we also adjust the var_off values.
3771  */
3772 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3773 			    struct bpf_reg_state *false_reg, u64 val,
3774 			    u8 opcode)
3775 {
3776 	/* If the dst_reg is a pointer, we can't learn anything about its
3777 	 * variable offset from the compare (unless src_reg were a pointer into
3778 	 * the same object, but we don't bother with that.
3779 	 * Since false_reg and true_reg have the same type by construction, we
3780 	 * only need to check one of them for pointerness.
3781 	 */
3782 	if (__is_pointer_value(false, false_reg))
3783 		return;
3784 
3785 	switch (opcode) {
3786 	case BPF_JEQ:
3787 		/* If this is false then we know nothing Jon Snow, but if it is
3788 		 * true then we know for sure.
3789 		 */
3790 		__mark_reg_known(true_reg, val);
3791 		break;
3792 	case BPF_JNE:
3793 		/* If this is true we know nothing Jon Snow, but if it is false
3794 		 * we know the value for sure;
3795 		 */
3796 		__mark_reg_known(false_reg, val);
3797 		break;
3798 	case BPF_JGT:
3799 		false_reg->umax_value = min(false_reg->umax_value, val);
3800 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3801 		break;
3802 	case BPF_JSGT:
3803 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3804 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3805 		break;
3806 	case BPF_JLT:
3807 		false_reg->umin_value = max(false_reg->umin_value, val);
3808 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3809 		break;
3810 	case BPF_JSLT:
3811 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3812 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3813 		break;
3814 	case BPF_JGE:
3815 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3816 		true_reg->umin_value = max(true_reg->umin_value, val);
3817 		break;
3818 	case BPF_JSGE:
3819 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3820 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3821 		break;
3822 	case BPF_JLE:
3823 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3824 		true_reg->umax_value = min(true_reg->umax_value, val);
3825 		break;
3826 	case BPF_JSLE:
3827 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3828 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3829 		break;
3830 	default:
3831 		break;
3832 	}
3833 
3834 	__reg_deduce_bounds(false_reg);
3835 	__reg_deduce_bounds(true_reg);
3836 	/* We might have learned some bits from the bounds. */
3837 	__reg_bound_offset(false_reg);
3838 	__reg_bound_offset(true_reg);
3839 	/* Intersecting with the old var_off might have improved our bounds
3840 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3841 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3842 	 */
3843 	__update_reg_bounds(false_reg);
3844 	__update_reg_bounds(true_reg);
3845 }
3846 
3847 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3848  * the variable reg.
3849  */
3850 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3851 				struct bpf_reg_state *false_reg, u64 val,
3852 				u8 opcode)
3853 {
3854 	if (__is_pointer_value(false, false_reg))
3855 		return;
3856 
3857 	switch (opcode) {
3858 	case BPF_JEQ:
3859 		/* If this is false then we know nothing Jon Snow, but if it is
3860 		 * true then we know for sure.
3861 		 */
3862 		__mark_reg_known(true_reg, val);
3863 		break;
3864 	case BPF_JNE:
3865 		/* If this is true we know nothing Jon Snow, but if it is false
3866 		 * we know the value for sure;
3867 		 */
3868 		__mark_reg_known(false_reg, val);
3869 		break;
3870 	case BPF_JGT:
3871 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3872 		false_reg->umin_value = max(false_reg->umin_value, val);
3873 		break;
3874 	case BPF_JSGT:
3875 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3876 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3877 		break;
3878 	case BPF_JLT:
3879 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3880 		false_reg->umax_value = min(false_reg->umax_value, val);
3881 		break;
3882 	case BPF_JSLT:
3883 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3884 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3885 		break;
3886 	case BPF_JGE:
3887 		true_reg->umax_value = min(true_reg->umax_value, val);
3888 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3889 		break;
3890 	case BPF_JSGE:
3891 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3892 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3893 		break;
3894 	case BPF_JLE:
3895 		true_reg->umin_value = max(true_reg->umin_value, val);
3896 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3897 		break;
3898 	case BPF_JSLE:
3899 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3900 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3901 		break;
3902 	default:
3903 		break;
3904 	}
3905 
3906 	__reg_deduce_bounds(false_reg);
3907 	__reg_deduce_bounds(true_reg);
3908 	/* We might have learned some bits from the bounds. */
3909 	__reg_bound_offset(false_reg);
3910 	__reg_bound_offset(true_reg);
3911 	/* Intersecting with the old var_off might have improved our bounds
3912 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3913 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3914 	 */
3915 	__update_reg_bounds(false_reg);
3916 	__update_reg_bounds(true_reg);
3917 }
3918 
3919 /* Regs are known to be equal, so intersect their min/max/var_off */
3920 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3921 				  struct bpf_reg_state *dst_reg)
3922 {
3923 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3924 							dst_reg->umin_value);
3925 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3926 							dst_reg->umax_value);
3927 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3928 							dst_reg->smin_value);
3929 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3930 							dst_reg->smax_value);
3931 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3932 							     dst_reg->var_off);
3933 	/* We might have learned new bounds from the var_off. */
3934 	__update_reg_bounds(src_reg);
3935 	__update_reg_bounds(dst_reg);
3936 	/* We might have learned something about the sign bit. */
3937 	__reg_deduce_bounds(src_reg);
3938 	__reg_deduce_bounds(dst_reg);
3939 	/* We might have learned some bits from the bounds. */
3940 	__reg_bound_offset(src_reg);
3941 	__reg_bound_offset(dst_reg);
3942 	/* Intersecting with the old var_off might have improved our bounds
3943 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3944 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3945 	 */
3946 	__update_reg_bounds(src_reg);
3947 	__update_reg_bounds(dst_reg);
3948 }
3949 
3950 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3951 				struct bpf_reg_state *true_dst,
3952 				struct bpf_reg_state *false_src,
3953 				struct bpf_reg_state *false_dst,
3954 				u8 opcode)
3955 {
3956 	switch (opcode) {
3957 	case BPF_JEQ:
3958 		__reg_combine_min_max(true_src, true_dst);
3959 		break;
3960 	case BPF_JNE:
3961 		__reg_combine_min_max(false_src, false_dst);
3962 		break;
3963 	}
3964 }
3965 
3966 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
3967 				 struct bpf_reg_state *reg, u32 id,
3968 				 bool is_null)
3969 {
3970 	if (reg_type_may_be_null(reg->type) && reg->id == id) {
3971 		/* Old offset (both fixed and variable parts) should
3972 		 * have been known-zero, because we don't allow pointer
3973 		 * arithmetic on pointers that might be NULL.
3974 		 */
3975 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3976 				 !tnum_equals_const(reg->var_off, 0) ||
3977 				 reg->off)) {
3978 			__mark_reg_known_zero(reg);
3979 			reg->off = 0;
3980 		}
3981 		if (is_null) {
3982 			reg->type = SCALAR_VALUE;
3983 		} else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3984 			if (reg->map_ptr->inner_map_meta) {
3985 				reg->type = CONST_PTR_TO_MAP;
3986 				reg->map_ptr = reg->map_ptr->inner_map_meta;
3987 			} else {
3988 				reg->type = PTR_TO_MAP_VALUE;
3989 			}
3990 		} else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
3991 			reg->type = PTR_TO_SOCKET;
3992 		}
3993 		if (is_null || !reg_is_refcounted(reg)) {
3994 			/* We don't need id from this point onwards anymore,
3995 			 * thus we should better reset it, so that state
3996 			 * pruning has chances to take effect.
3997 			 */
3998 			reg->id = 0;
3999 		}
4000 	}
4001 }
4002 
4003 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4004  * be folded together at some point.
4005  */
4006 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
4007 				  bool is_null)
4008 {
4009 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4010 	struct bpf_reg_state *reg, *regs = state->regs;
4011 	u32 id = regs[regno].id;
4012 	int i, j;
4013 
4014 	if (reg_is_refcounted_or_null(&regs[regno]) && is_null)
4015 		__release_reference_state(state, id);
4016 
4017 	for (i = 0; i < MAX_BPF_REG; i++)
4018 		mark_ptr_or_null_reg(state, &regs[i], id, is_null);
4019 
4020 	for (j = 0; j <= vstate->curframe; j++) {
4021 		state = vstate->frame[j];
4022 		bpf_for_each_spilled_reg(i, state, reg) {
4023 			if (!reg)
4024 				continue;
4025 			mark_ptr_or_null_reg(state, reg, id, is_null);
4026 		}
4027 	}
4028 }
4029 
4030 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4031 				   struct bpf_reg_state *dst_reg,
4032 				   struct bpf_reg_state *src_reg,
4033 				   struct bpf_verifier_state *this_branch,
4034 				   struct bpf_verifier_state *other_branch)
4035 {
4036 	if (BPF_SRC(insn->code) != BPF_X)
4037 		return false;
4038 
4039 	switch (BPF_OP(insn->code)) {
4040 	case BPF_JGT:
4041 		if ((dst_reg->type == PTR_TO_PACKET &&
4042 		     src_reg->type == PTR_TO_PACKET_END) ||
4043 		    (dst_reg->type == PTR_TO_PACKET_META &&
4044 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4045 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4046 			find_good_pkt_pointers(this_branch, dst_reg,
4047 					       dst_reg->type, false);
4048 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
4049 			    src_reg->type == PTR_TO_PACKET) ||
4050 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4051 			    src_reg->type == PTR_TO_PACKET_META)) {
4052 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
4053 			find_good_pkt_pointers(other_branch, src_reg,
4054 					       src_reg->type, true);
4055 		} else {
4056 			return false;
4057 		}
4058 		break;
4059 	case BPF_JLT:
4060 		if ((dst_reg->type == PTR_TO_PACKET &&
4061 		     src_reg->type == PTR_TO_PACKET_END) ||
4062 		    (dst_reg->type == PTR_TO_PACKET_META &&
4063 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4064 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4065 			find_good_pkt_pointers(other_branch, dst_reg,
4066 					       dst_reg->type, true);
4067 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
4068 			    src_reg->type == PTR_TO_PACKET) ||
4069 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4070 			    src_reg->type == PTR_TO_PACKET_META)) {
4071 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
4072 			find_good_pkt_pointers(this_branch, src_reg,
4073 					       src_reg->type, false);
4074 		} else {
4075 			return false;
4076 		}
4077 		break;
4078 	case BPF_JGE:
4079 		if ((dst_reg->type == PTR_TO_PACKET &&
4080 		     src_reg->type == PTR_TO_PACKET_END) ||
4081 		    (dst_reg->type == PTR_TO_PACKET_META &&
4082 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4083 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4084 			find_good_pkt_pointers(this_branch, dst_reg,
4085 					       dst_reg->type, true);
4086 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
4087 			    src_reg->type == PTR_TO_PACKET) ||
4088 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4089 			    src_reg->type == PTR_TO_PACKET_META)) {
4090 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4091 			find_good_pkt_pointers(other_branch, src_reg,
4092 					       src_reg->type, false);
4093 		} else {
4094 			return false;
4095 		}
4096 		break;
4097 	case BPF_JLE:
4098 		if ((dst_reg->type == PTR_TO_PACKET &&
4099 		     src_reg->type == PTR_TO_PACKET_END) ||
4100 		    (dst_reg->type == PTR_TO_PACKET_META &&
4101 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4102 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4103 			find_good_pkt_pointers(other_branch, dst_reg,
4104 					       dst_reg->type, false);
4105 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
4106 			    src_reg->type == PTR_TO_PACKET) ||
4107 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4108 			    src_reg->type == PTR_TO_PACKET_META)) {
4109 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4110 			find_good_pkt_pointers(this_branch, src_reg,
4111 					       src_reg->type, true);
4112 		} else {
4113 			return false;
4114 		}
4115 		break;
4116 	default:
4117 		return false;
4118 	}
4119 
4120 	return true;
4121 }
4122 
4123 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4124 			     struct bpf_insn *insn, int *insn_idx)
4125 {
4126 	struct bpf_verifier_state *this_branch = env->cur_state;
4127 	struct bpf_verifier_state *other_branch;
4128 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4129 	struct bpf_reg_state *dst_reg, *other_branch_regs;
4130 	u8 opcode = BPF_OP(insn->code);
4131 	int err;
4132 
4133 	if (opcode > BPF_JSLE) {
4134 		verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
4135 		return -EINVAL;
4136 	}
4137 
4138 	if (BPF_SRC(insn->code) == BPF_X) {
4139 		if (insn->imm != 0) {
4140 			verbose(env, "BPF_JMP uses reserved fields\n");
4141 			return -EINVAL;
4142 		}
4143 
4144 		/* check src1 operand */
4145 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
4146 		if (err)
4147 			return err;
4148 
4149 		if (is_pointer_value(env, insn->src_reg)) {
4150 			verbose(env, "R%d pointer comparison prohibited\n",
4151 				insn->src_reg);
4152 			return -EACCES;
4153 		}
4154 	} else {
4155 		if (insn->src_reg != BPF_REG_0) {
4156 			verbose(env, "BPF_JMP uses reserved fields\n");
4157 			return -EINVAL;
4158 		}
4159 	}
4160 
4161 	/* check src2 operand */
4162 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4163 	if (err)
4164 		return err;
4165 
4166 	dst_reg = &regs[insn->dst_reg];
4167 
4168 	/* detect if R == 0 where R was initialized to zero earlier */
4169 	if (BPF_SRC(insn->code) == BPF_K &&
4170 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4171 	    dst_reg->type == SCALAR_VALUE &&
4172 	    tnum_is_const(dst_reg->var_off)) {
4173 		if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
4174 		    (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
4175 			/* if (imm == imm) goto pc+off;
4176 			 * only follow the goto, ignore fall-through
4177 			 */
4178 			*insn_idx += insn->off;
4179 			return 0;
4180 		} else {
4181 			/* if (imm != imm) goto pc+off;
4182 			 * only follow fall-through branch, since
4183 			 * that's where the program will go
4184 			 */
4185 			return 0;
4186 		}
4187 	}
4188 
4189 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
4190 	if (!other_branch)
4191 		return -EFAULT;
4192 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4193 
4194 	/* detect if we are comparing against a constant value so we can adjust
4195 	 * our min/max values for our dst register.
4196 	 * this is only legit if both are scalars (or pointers to the same
4197 	 * object, I suppose, but we don't support that right now), because
4198 	 * otherwise the different base pointers mean the offsets aren't
4199 	 * comparable.
4200 	 */
4201 	if (BPF_SRC(insn->code) == BPF_X) {
4202 		if (dst_reg->type == SCALAR_VALUE &&
4203 		    regs[insn->src_reg].type == SCALAR_VALUE) {
4204 			if (tnum_is_const(regs[insn->src_reg].var_off))
4205 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
4206 						dst_reg, regs[insn->src_reg].var_off.value,
4207 						opcode);
4208 			else if (tnum_is_const(dst_reg->var_off))
4209 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4210 						    &regs[insn->src_reg],
4211 						    dst_reg->var_off.value, opcode);
4212 			else if (opcode == BPF_JEQ || opcode == BPF_JNE)
4213 				/* Comparing for equality, we can combine knowledge */
4214 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
4215 						    &other_branch_regs[insn->dst_reg],
4216 						    &regs[insn->src_reg],
4217 						    &regs[insn->dst_reg], opcode);
4218 		}
4219 	} else if (dst_reg->type == SCALAR_VALUE) {
4220 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
4221 					dst_reg, insn->imm, opcode);
4222 	}
4223 
4224 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
4225 	if (BPF_SRC(insn->code) == BPF_K &&
4226 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4227 	    reg_type_may_be_null(dst_reg->type)) {
4228 		/* Mark all identical registers in each branch as either
4229 		 * safe or unknown depending R == 0 or R != 0 conditional.
4230 		 */
4231 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
4232 				      opcode == BPF_JNE);
4233 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
4234 				      opcode == BPF_JEQ);
4235 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
4236 					   this_branch, other_branch) &&
4237 		   is_pointer_value(env, insn->dst_reg)) {
4238 		verbose(env, "R%d pointer comparison prohibited\n",
4239 			insn->dst_reg);
4240 		return -EACCES;
4241 	}
4242 	if (env->log.level)
4243 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4244 	return 0;
4245 }
4246 
4247 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
4248 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4249 {
4250 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4251 
4252 	return (struct bpf_map *) (unsigned long) imm64;
4253 }
4254 
4255 /* verify BPF_LD_IMM64 instruction */
4256 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4257 {
4258 	struct bpf_reg_state *regs = cur_regs(env);
4259 	int err;
4260 
4261 	if (BPF_SIZE(insn->code) != BPF_DW) {
4262 		verbose(env, "invalid BPF_LD_IMM insn\n");
4263 		return -EINVAL;
4264 	}
4265 	if (insn->off != 0) {
4266 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4267 		return -EINVAL;
4268 	}
4269 
4270 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
4271 	if (err)
4272 		return err;
4273 
4274 	if (insn->src_reg == 0) {
4275 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4276 
4277 		regs[insn->dst_reg].type = SCALAR_VALUE;
4278 		__mark_reg_known(&regs[insn->dst_reg], imm);
4279 		return 0;
4280 	}
4281 
4282 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4283 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4284 
4285 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4286 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4287 	return 0;
4288 }
4289 
4290 static bool may_access_skb(enum bpf_prog_type type)
4291 {
4292 	switch (type) {
4293 	case BPF_PROG_TYPE_SOCKET_FILTER:
4294 	case BPF_PROG_TYPE_SCHED_CLS:
4295 	case BPF_PROG_TYPE_SCHED_ACT:
4296 		return true;
4297 	default:
4298 		return false;
4299 	}
4300 }
4301 
4302 /* verify safety of LD_ABS|LD_IND instructions:
4303  * - they can only appear in the programs where ctx == skb
4304  * - since they are wrappers of function calls, they scratch R1-R5 registers,
4305  *   preserve R6-R9, and store return value into R0
4306  *
4307  * Implicit input:
4308  *   ctx == skb == R6 == CTX
4309  *
4310  * Explicit input:
4311  *   SRC == any register
4312  *   IMM == 32-bit immediate
4313  *
4314  * Output:
4315  *   R0 - 8/16/32-bit skb data converted to cpu endianness
4316  */
4317 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4318 {
4319 	struct bpf_reg_state *regs = cur_regs(env);
4320 	u8 mode = BPF_MODE(insn->code);
4321 	int i, err;
4322 
4323 	if (!may_access_skb(env->prog->type)) {
4324 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4325 		return -EINVAL;
4326 	}
4327 
4328 	if (!env->ops->gen_ld_abs) {
4329 		verbose(env, "bpf verifier is misconfigured\n");
4330 		return -EINVAL;
4331 	}
4332 
4333 	if (env->subprog_cnt > 1) {
4334 		/* when program has LD_ABS insn JITs and interpreter assume
4335 		 * that r1 == ctx == skb which is not the case for callees
4336 		 * that can have arbitrary arguments. It's problematic
4337 		 * for main prog as well since JITs would need to analyze
4338 		 * all functions in order to make proper register save/restore
4339 		 * decisions in the main prog. Hence disallow LD_ABS with calls
4340 		 */
4341 		verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4342 		return -EINVAL;
4343 	}
4344 
4345 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4346 	    BPF_SIZE(insn->code) == BPF_DW ||
4347 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4348 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4349 		return -EINVAL;
4350 	}
4351 
4352 	/* check whether implicit source operand (register R6) is readable */
4353 	err = check_reg_arg(env, BPF_REG_6, SRC_OP);
4354 	if (err)
4355 		return err;
4356 
4357 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
4358 	 * gen_ld_abs() may terminate the program at runtime, leading to
4359 	 * reference leak.
4360 	 */
4361 	err = check_reference_leak(env);
4362 	if (err) {
4363 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
4364 		return err;
4365 	}
4366 
4367 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
4368 		verbose(env,
4369 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
4370 		return -EINVAL;
4371 	}
4372 
4373 	if (mode == BPF_IND) {
4374 		/* check explicit source operand */
4375 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
4376 		if (err)
4377 			return err;
4378 	}
4379 
4380 	/* reset caller saved regs to unreadable */
4381 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
4382 		mark_reg_not_init(env, regs, caller_saved[i]);
4383 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4384 	}
4385 
4386 	/* mark destination R0 register as readable, since it contains
4387 	 * the value fetched from the packet.
4388 	 * Already marked as written above.
4389 	 */
4390 	mark_reg_unknown(env, regs, BPF_REG_0);
4391 	return 0;
4392 }
4393 
4394 static int check_return_code(struct bpf_verifier_env *env)
4395 {
4396 	struct bpf_reg_state *reg;
4397 	struct tnum range = tnum_range(0, 1);
4398 
4399 	switch (env->prog->type) {
4400 	case BPF_PROG_TYPE_CGROUP_SKB:
4401 	case BPF_PROG_TYPE_CGROUP_SOCK:
4402 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4403 	case BPF_PROG_TYPE_SOCK_OPS:
4404 	case BPF_PROG_TYPE_CGROUP_DEVICE:
4405 		break;
4406 	default:
4407 		return 0;
4408 	}
4409 
4410 	reg = cur_regs(env) + BPF_REG_0;
4411 	if (reg->type != SCALAR_VALUE) {
4412 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4413 			reg_type_str[reg->type]);
4414 		return -EINVAL;
4415 	}
4416 
4417 	if (!tnum_in(range, reg->var_off)) {
4418 		verbose(env, "At program exit the register R0 ");
4419 		if (!tnum_is_unknown(reg->var_off)) {
4420 			char tn_buf[48];
4421 
4422 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4423 			verbose(env, "has value %s", tn_buf);
4424 		} else {
4425 			verbose(env, "has unknown scalar value");
4426 		}
4427 		verbose(env, " should have been 0 or 1\n");
4428 		return -EINVAL;
4429 	}
4430 	return 0;
4431 }
4432 
4433 /* non-recursive DFS pseudo code
4434  * 1  procedure DFS-iterative(G,v):
4435  * 2      label v as discovered
4436  * 3      let S be a stack
4437  * 4      S.push(v)
4438  * 5      while S is not empty
4439  * 6            t <- S.pop()
4440  * 7            if t is what we're looking for:
4441  * 8                return t
4442  * 9            for all edges e in G.adjacentEdges(t) do
4443  * 10               if edge e is already labelled
4444  * 11                   continue with the next edge
4445  * 12               w <- G.adjacentVertex(t,e)
4446  * 13               if vertex w is not discovered and not explored
4447  * 14                   label e as tree-edge
4448  * 15                   label w as discovered
4449  * 16                   S.push(w)
4450  * 17                   continue at 5
4451  * 18               else if vertex w is discovered
4452  * 19                   label e as back-edge
4453  * 20               else
4454  * 21                   // vertex w is explored
4455  * 22                   label e as forward- or cross-edge
4456  * 23           label t as explored
4457  * 24           S.pop()
4458  *
4459  * convention:
4460  * 0x10 - discovered
4461  * 0x11 - discovered and fall-through edge labelled
4462  * 0x12 - discovered and fall-through and branch edges labelled
4463  * 0x20 - explored
4464  */
4465 
4466 enum {
4467 	DISCOVERED = 0x10,
4468 	EXPLORED = 0x20,
4469 	FALLTHROUGH = 1,
4470 	BRANCH = 2,
4471 };
4472 
4473 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4474 
4475 static int *insn_stack;	/* stack of insns to process */
4476 static int cur_stack;	/* current stack index */
4477 static int *insn_state;
4478 
4479 /* t, w, e - match pseudo-code above:
4480  * t - index of current instruction
4481  * w - next instruction
4482  * e - edge
4483  */
4484 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4485 {
4486 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4487 		return 0;
4488 
4489 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4490 		return 0;
4491 
4492 	if (w < 0 || w >= env->prog->len) {
4493 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
4494 		return -EINVAL;
4495 	}
4496 
4497 	if (e == BRANCH)
4498 		/* mark branch target for state pruning */
4499 		env->explored_states[w] = STATE_LIST_MARK;
4500 
4501 	if (insn_state[w] == 0) {
4502 		/* tree-edge */
4503 		insn_state[t] = DISCOVERED | e;
4504 		insn_state[w] = DISCOVERED;
4505 		if (cur_stack >= env->prog->len)
4506 			return -E2BIG;
4507 		insn_stack[cur_stack++] = w;
4508 		return 1;
4509 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4510 		verbose(env, "back-edge from insn %d to %d\n", t, w);
4511 		return -EINVAL;
4512 	} else if (insn_state[w] == EXPLORED) {
4513 		/* forward- or cross-edge */
4514 		insn_state[t] = DISCOVERED | e;
4515 	} else {
4516 		verbose(env, "insn state internal bug\n");
4517 		return -EFAULT;
4518 	}
4519 	return 0;
4520 }
4521 
4522 /* non-recursive depth-first-search to detect loops in BPF program
4523  * loop == back-edge in directed graph
4524  */
4525 static int check_cfg(struct bpf_verifier_env *env)
4526 {
4527 	struct bpf_insn *insns = env->prog->insnsi;
4528 	int insn_cnt = env->prog->len;
4529 	int ret = 0;
4530 	int i, t;
4531 
4532 	ret = check_subprogs(env);
4533 	if (ret < 0)
4534 		return ret;
4535 
4536 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4537 	if (!insn_state)
4538 		return -ENOMEM;
4539 
4540 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4541 	if (!insn_stack) {
4542 		kfree(insn_state);
4543 		return -ENOMEM;
4544 	}
4545 
4546 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4547 	insn_stack[0] = 0; /* 0 is the first instruction */
4548 	cur_stack = 1;
4549 
4550 peek_stack:
4551 	if (cur_stack == 0)
4552 		goto check_state;
4553 	t = insn_stack[cur_stack - 1];
4554 
4555 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4556 		u8 opcode = BPF_OP(insns[t].code);
4557 
4558 		if (opcode == BPF_EXIT) {
4559 			goto mark_explored;
4560 		} else if (opcode == BPF_CALL) {
4561 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
4562 			if (ret == 1)
4563 				goto peek_stack;
4564 			else if (ret < 0)
4565 				goto err_free;
4566 			if (t + 1 < insn_cnt)
4567 				env->explored_states[t + 1] = STATE_LIST_MARK;
4568 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4569 				env->explored_states[t] = STATE_LIST_MARK;
4570 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4571 				if (ret == 1)
4572 					goto peek_stack;
4573 				else if (ret < 0)
4574 					goto err_free;
4575 			}
4576 		} else if (opcode == BPF_JA) {
4577 			if (BPF_SRC(insns[t].code) != BPF_K) {
4578 				ret = -EINVAL;
4579 				goto err_free;
4580 			}
4581 			/* unconditional jump with single edge */
4582 			ret = push_insn(t, t + insns[t].off + 1,
4583 					FALLTHROUGH, env);
4584 			if (ret == 1)
4585 				goto peek_stack;
4586 			else if (ret < 0)
4587 				goto err_free;
4588 			/* tell verifier to check for equivalent states
4589 			 * after every call and jump
4590 			 */
4591 			if (t + 1 < insn_cnt)
4592 				env->explored_states[t + 1] = STATE_LIST_MARK;
4593 		} else {
4594 			/* conditional jump with two edges */
4595 			env->explored_states[t] = STATE_LIST_MARK;
4596 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
4597 			if (ret == 1)
4598 				goto peek_stack;
4599 			else if (ret < 0)
4600 				goto err_free;
4601 
4602 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4603 			if (ret == 1)
4604 				goto peek_stack;
4605 			else if (ret < 0)
4606 				goto err_free;
4607 		}
4608 	} else {
4609 		/* all other non-branch instructions with single
4610 		 * fall-through edge
4611 		 */
4612 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
4613 		if (ret == 1)
4614 			goto peek_stack;
4615 		else if (ret < 0)
4616 			goto err_free;
4617 	}
4618 
4619 mark_explored:
4620 	insn_state[t] = EXPLORED;
4621 	if (cur_stack-- <= 0) {
4622 		verbose(env, "pop stack internal bug\n");
4623 		ret = -EFAULT;
4624 		goto err_free;
4625 	}
4626 	goto peek_stack;
4627 
4628 check_state:
4629 	for (i = 0; i < insn_cnt; i++) {
4630 		if (insn_state[i] != EXPLORED) {
4631 			verbose(env, "unreachable insn %d\n", i);
4632 			ret = -EINVAL;
4633 			goto err_free;
4634 		}
4635 	}
4636 	ret = 0; /* cfg looks good */
4637 
4638 err_free:
4639 	kfree(insn_state);
4640 	kfree(insn_stack);
4641 	return ret;
4642 }
4643 
4644 /* The minimum supported BTF func info size */
4645 #define MIN_BPF_FUNCINFO_SIZE	8
4646 #define MAX_FUNCINFO_REC_SIZE	252
4647 
4648 static int check_btf_func(struct bpf_prog *prog, struct bpf_verifier_env *env,
4649 			  union bpf_attr *attr, union bpf_attr __user *uattr)
4650 {
4651 	u32 i, nfuncs, urec_size, min_size, prev_offset;
4652 	u32 krec_size = sizeof(struct bpf_func_info);
4653 	struct bpf_func_info *krecord = NULL;
4654 	const struct btf_type *type;
4655 	void __user *urecord;
4656 	struct btf *btf;
4657 	int ret = 0;
4658 
4659 	nfuncs = attr->func_info_cnt;
4660 	if (!nfuncs)
4661 		return 0;
4662 
4663 	if (nfuncs != env->subprog_cnt) {
4664 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
4665 		return -EINVAL;
4666 	}
4667 
4668 	urec_size = attr->func_info_rec_size;
4669 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
4670 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
4671 	    urec_size % sizeof(u32)) {
4672 		verbose(env, "invalid func info rec size %u\n", urec_size);
4673 		return -EINVAL;
4674 	}
4675 
4676 	btf = btf_get_by_fd(attr->prog_btf_fd);
4677 	if (IS_ERR(btf)) {
4678 		verbose(env, "unable to get btf from fd\n");
4679 		return PTR_ERR(btf);
4680 	}
4681 
4682 	urecord = u64_to_user_ptr(attr->func_info);
4683 	min_size = min_t(u32, krec_size, urec_size);
4684 
4685 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
4686 	if (!krecord) {
4687 		ret = -ENOMEM;
4688 		goto free_btf;
4689 	}
4690 
4691 	for (i = 0; i < nfuncs; i++) {
4692 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
4693 		if (ret) {
4694 			if (ret == -E2BIG) {
4695 				verbose(env, "nonzero tailing record in func info");
4696 				/* set the size kernel expects so loader can zero
4697 				 * out the rest of the record.
4698 				 */
4699 				if (put_user(min_size, &uattr->func_info_rec_size))
4700 					ret = -EFAULT;
4701 			}
4702 			goto free_btf;
4703 		}
4704 
4705 		if (copy_from_user(&krecord[i], urecord, min_size)) {
4706 			ret = -EFAULT;
4707 			goto free_btf;
4708 		}
4709 
4710 		/* check insn_offset */
4711 		if (i == 0) {
4712 			if (krecord[i].insn_offset) {
4713 				verbose(env,
4714 					"nonzero insn_offset %u for the first func info record",
4715 					krecord[i].insn_offset);
4716 				ret = -EINVAL;
4717 				goto free_btf;
4718 			}
4719 		} else if (krecord[i].insn_offset <= prev_offset) {
4720 			verbose(env,
4721 				"same or smaller insn offset (%u) than previous func info record (%u)",
4722 				krecord[i].insn_offset, prev_offset);
4723 			ret = -EINVAL;
4724 			goto free_btf;
4725 		}
4726 
4727 		if (env->subprog_info[i].start != krecord[i].insn_offset) {
4728 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
4729 			ret = -EINVAL;
4730 			goto free_btf;
4731 		}
4732 
4733 		/* check type_id */
4734 		type = btf_type_by_id(btf, krecord[i].type_id);
4735 		if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
4736 			verbose(env, "invalid type id %d in func info",
4737 				krecord[i].type_id);
4738 			ret = -EINVAL;
4739 			goto free_btf;
4740 		}
4741 
4742 		prev_offset = krecord[i].insn_offset;
4743 		urecord += urec_size;
4744 	}
4745 
4746 	prog->aux->btf = btf;
4747 	prog->aux->func_info = krecord;
4748 	prog->aux->func_info_cnt = nfuncs;
4749 	return 0;
4750 
4751 free_btf:
4752 	btf_put(btf);
4753 	kvfree(krecord);
4754 	return ret;
4755 }
4756 
4757 static void adjust_btf_func(struct bpf_verifier_env *env)
4758 {
4759 	int i;
4760 
4761 	if (!env->prog->aux->func_info)
4762 		return;
4763 
4764 	for (i = 0; i < env->subprog_cnt; i++)
4765 		env->prog->aux->func_info[i].insn_offset = env->subprog_info[i].start;
4766 }
4767 
4768 /* check %cur's range satisfies %old's */
4769 static bool range_within(struct bpf_reg_state *old,
4770 			 struct bpf_reg_state *cur)
4771 {
4772 	return old->umin_value <= cur->umin_value &&
4773 	       old->umax_value >= cur->umax_value &&
4774 	       old->smin_value <= cur->smin_value &&
4775 	       old->smax_value >= cur->smax_value;
4776 }
4777 
4778 /* Maximum number of register states that can exist at once */
4779 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4780 struct idpair {
4781 	u32 old;
4782 	u32 cur;
4783 };
4784 
4785 /* If in the old state two registers had the same id, then they need to have
4786  * the same id in the new state as well.  But that id could be different from
4787  * the old state, so we need to track the mapping from old to new ids.
4788  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4789  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
4790  * regs with a different old id could still have new id 9, we don't care about
4791  * that.
4792  * So we look through our idmap to see if this old id has been seen before.  If
4793  * so, we require the new id to match; otherwise, we add the id pair to the map.
4794  */
4795 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4796 {
4797 	unsigned int i;
4798 
4799 	for (i = 0; i < ID_MAP_SIZE; i++) {
4800 		if (!idmap[i].old) {
4801 			/* Reached an empty slot; haven't seen this id before */
4802 			idmap[i].old = old_id;
4803 			idmap[i].cur = cur_id;
4804 			return true;
4805 		}
4806 		if (idmap[i].old == old_id)
4807 			return idmap[i].cur == cur_id;
4808 	}
4809 	/* We ran out of idmap slots, which should be impossible */
4810 	WARN_ON_ONCE(1);
4811 	return false;
4812 }
4813 
4814 /* Returns true if (rold safe implies rcur safe) */
4815 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4816 		    struct idpair *idmap)
4817 {
4818 	bool equal;
4819 
4820 	if (!(rold->live & REG_LIVE_READ))
4821 		/* explored state didn't use this */
4822 		return true;
4823 
4824 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
4825 
4826 	if (rold->type == PTR_TO_STACK)
4827 		/* two stack pointers are equal only if they're pointing to
4828 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
4829 		 */
4830 		return equal && rold->frameno == rcur->frameno;
4831 
4832 	if (equal)
4833 		return true;
4834 
4835 	if (rold->type == NOT_INIT)
4836 		/* explored state can't have used this */
4837 		return true;
4838 	if (rcur->type == NOT_INIT)
4839 		return false;
4840 	switch (rold->type) {
4841 	case SCALAR_VALUE:
4842 		if (rcur->type == SCALAR_VALUE) {
4843 			/* new val must satisfy old val knowledge */
4844 			return range_within(rold, rcur) &&
4845 			       tnum_in(rold->var_off, rcur->var_off);
4846 		} else {
4847 			/* We're trying to use a pointer in place of a scalar.
4848 			 * Even if the scalar was unbounded, this could lead to
4849 			 * pointer leaks because scalars are allowed to leak
4850 			 * while pointers are not. We could make this safe in
4851 			 * special cases if root is calling us, but it's
4852 			 * probably not worth the hassle.
4853 			 */
4854 			return false;
4855 		}
4856 	case PTR_TO_MAP_VALUE:
4857 		/* If the new min/max/var_off satisfy the old ones and
4858 		 * everything else matches, we are OK.
4859 		 * We don't care about the 'id' value, because nothing
4860 		 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4861 		 */
4862 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4863 		       range_within(rold, rcur) &&
4864 		       tnum_in(rold->var_off, rcur->var_off);
4865 	case PTR_TO_MAP_VALUE_OR_NULL:
4866 		/* a PTR_TO_MAP_VALUE could be safe to use as a
4867 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4868 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4869 		 * checked, doing so could have affected others with the same
4870 		 * id, and we can't check for that because we lost the id when
4871 		 * we converted to a PTR_TO_MAP_VALUE.
4872 		 */
4873 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4874 			return false;
4875 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4876 			return false;
4877 		/* Check our ids match any regs they're supposed to */
4878 		return check_ids(rold->id, rcur->id, idmap);
4879 	case PTR_TO_PACKET_META:
4880 	case PTR_TO_PACKET:
4881 		if (rcur->type != rold->type)
4882 			return false;
4883 		/* We must have at least as much range as the old ptr
4884 		 * did, so that any accesses which were safe before are
4885 		 * still safe.  This is true even if old range < old off,
4886 		 * since someone could have accessed through (ptr - k), or
4887 		 * even done ptr -= k in a register, to get a safe access.
4888 		 */
4889 		if (rold->range > rcur->range)
4890 			return false;
4891 		/* If the offsets don't match, we can't trust our alignment;
4892 		 * nor can we be sure that we won't fall out of range.
4893 		 */
4894 		if (rold->off != rcur->off)
4895 			return false;
4896 		/* id relations must be preserved */
4897 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4898 			return false;
4899 		/* new val must satisfy old val knowledge */
4900 		return range_within(rold, rcur) &&
4901 		       tnum_in(rold->var_off, rcur->var_off);
4902 	case PTR_TO_CTX:
4903 	case CONST_PTR_TO_MAP:
4904 	case PTR_TO_PACKET_END:
4905 	case PTR_TO_FLOW_KEYS:
4906 	case PTR_TO_SOCKET:
4907 	case PTR_TO_SOCKET_OR_NULL:
4908 		/* Only valid matches are exact, which memcmp() above
4909 		 * would have accepted
4910 		 */
4911 	default:
4912 		/* Don't know what's going on, just say it's not safe */
4913 		return false;
4914 	}
4915 
4916 	/* Shouldn't get here; if we do, say it's not safe */
4917 	WARN_ON_ONCE(1);
4918 	return false;
4919 }
4920 
4921 static bool stacksafe(struct bpf_func_state *old,
4922 		      struct bpf_func_state *cur,
4923 		      struct idpair *idmap)
4924 {
4925 	int i, spi;
4926 
4927 	/* if explored stack has more populated slots than current stack
4928 	 * such stacks are not equivalent
4929 	 */
4930 	if (old->allocated_stack > cur->allocated_stack)
4931 		return false;
4932 
4933 	/* walk slots of the explored stack and ignore any additional
4934 	 * slots in the current stack, since explored(safe) state
4935 	 * didn't use them
4936 	 */
4937 	for (i = 0; i < old->allocated_stack; i++) {
4938 		spi = i / BPF_REG_SIZE;
4939 
4940 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4941 			/* explored state didn't use this */
4942 			continue;
4943 
4944 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4945 			continue;
4946 		/* if old state was safe with misc data in the stack
4947 		 * it will be safe with zero-initialized stack.
4948 		 * The opposite is not true
4949 		 */
4950 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4951 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4952 			continue;
4953 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4954 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4955 			/* Ex: old explored (safe) state has STACK_SPILL in
4956 			 * this stack slot, but current has has STACK_MISC ->
4957 			 * this verifier states are not equivalent,
4958 			 * return false to continue verification of this path
4959 			 */
4960 			return false;
4961 		if (i % BPF_REG_SIZE)
4962 			continue;
4963 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
4964 			continue;
4965 		if (!regsafe(&old->stack[spi].spilled_ptr,
4966 			     &cur->stack[spi].spilled_ptr,
4967 			     idmap))
4968 			/* when explored and current stack slot are both storing
4969 			 * spilled registers, check that stored pointers types
4970 			 * are the same as well.
4971 			 * Ex: explored safe path could have stored
4972 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4973 			 * but current path has stored:
4974 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4975 			 * such verifier states are not equivalent.
4976 			 * return false to continue verification of this path
4977 			 */
4978 			return false;
4979 	}
4980 	return true;
4981 }
4982 
4983 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
4984 {
4985 	if (old->acquired_refs != cur->acquired_refs)
4986 		return false;
4987 	return !memcmp(old->refs, cur->refs,
4988 		       sizeof(*old->refs) * old->acquired_refs);
4989 }
4990 
4991 /* compare two verifier states
4992  *
4993  * all states stored in state_list are known to be valid, since
4994  * verifier reached 'bpf_exit' instruction through them
4995  *
4996  * this function is called when verifier exploring different branches of
4997  * execution popped from the state stack. If it sees an old state that has
4998  * more strict register state and more strict stack state then this execution
4999  * branch doesn't need to be explored further, since verifier already
5000  * concluded that more strict state leads to valid finish.
5001  *
5002  * Therefore two states are equivalent if register state is more conservative
5003  * and explored stack state is more conservative than the current one.
5004  * Example:
5005  *       explored                   current
5006  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
5007  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
5008  *
5009  * In other words if current stack state (one being explored) has more
5010  * valid slots than old one that already passed validation, it means
5011  * the verifier can stop exploring and conclude that current state is valid too
5012  *
5013  * Similarly with registers. If explored state has register type as invalid
5014  * whereas register type in current state is meaningful, it means that
5015  * the current state will reach 'bpf_exit' instruction safely
5016  */
5017 static bool func_states_equal(struct bpf_func_state *old,
5018 			      struct bpf_func_state *cur)
5019 {
5020 	struct idpair *idmap;
5021 	bool ret = false;
5022 	int i;
5023 
5024 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
5025 	/* If we failed to allocate the idmap, just say it's not safe */
5026 	if (!idmap)
5027 		return false;
5028 
5029 	for (i = 0; i < MAX_BPF_REG; i++) {
5030 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
5031 			goto out_free;
5032 	}
5033 
5034 	if (!stacksafe(old, cur, idmap))
5035 		goto out_free;
5036 
5037 	if (!refsafe(old, cur))
5038 		goto out_free;
5039 	ret = true;
5040 out_free:
5041 	kfree(idmap);
5042 	return ret;
5043 }
5044 
5045 static bool states_equal(struct bpf_verifier_env *env,
5046 			 struct bpf_verifier_state *old,
5047 			 struct bpf_verifier_state *cur)
5048 {
5049 	int i;
5050 
5051 	if (old->curframe != cur->curframe)
5052 		return false;
5053 
5054 	/* for states to be equal callsites have to be the same
5055 	 * and all frame states need to be equivalent
5056 	 */
5057 	for (i = 0; i <= old->curframe; i++) {
5058 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
5059 			return false;
5060 		if (!func_states_equal(old->frame[i], cur->frame[i]))
5061 			return false;
5062 	}
5063 	return true;
5064 }
5065 
5066 /* A write screens off any subsequent reads; but write marks come from the
5067  * straight-line code between a state and its parent.  When we arrive at an
5068  * equivalent state (jump target or such) we didn't arrive by the straight-line
5069  * code, so read marks in the state must propagate to the parent regardless
5070  * of the state's write marks. That's what 'parent == state->parent' comparison
5071  * in mark_reg_read() is for.
5072  */
5073 static int propagate_liveness(struct bpf_verifier_env *env,
5074 			      const struct bpf_verifier_state *vstate,
5075 			      struct bpf_verifier_state *vparent)
5076 {
5077 	int i, frame, err = 0;
5078 	struct bpf_func_state *state, *parent;
5079 
5080 	if (vparent->curframe != vstate->curframe) {
5081 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
5082 		     vparent->curframe, vstate->curframe);
5083 		return -EFAULT;
5084 	}
5085 	/* Propagate read liveness of registers... */
5086 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
5087 	/* We don't need to worry about FP liveness because it's read-only */
5088 	for (i = 0; i < BPF_REG_FP; i++) {
5089 		if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
5090 			continue;
5091 		if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
5092 			err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
5093 					    &vparent->frame[vstate->curframe]->regs[i]);
5094 			if (err)
5095 				return err;
5096 		}
5097 	}
5098 
5099 	/* ... and stack slots */
5100 	for (frame = 0; frame <= vstate->curframe; frame++) {
5101 		state = vstate->frame[frame];
5102 		parent = vparent->frame[frame];
5103 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
5104 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
5105 			if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
5106 				continue;
5107 			if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
5108 				mark_reg_read(env, &state->stack[i].spilled_ptr,
5109 					      &parent->stack[i].spilled_ptr);
5110 		}
5111 	}
5112 	return err;
5113 }
5114 
5115 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
5116 {
5117 	struct bpf_verifier_state_list *new_sl;
5118 	struct bpf_verifier_state_list *sl;
5119 	struct bpf_verifier_state *cur = env->cur_state, *new;
5120 	int i, j, err;
5121 
5122 	sl = env->explored_states[insn_idx];
5123 	if (!sl)
5124 		/* this 'insn_idx' instruction wasn't marked, so we will not
5125 		 * be doing state search here
5126 		 */
5127 		return 0;
5128 
5129 	while (sl != STATE_LIST_MARK) {
5130 		if (states_equal(env, &sl->state, cur)) {
5131 			/* reached equivalent register/stack state,
5132 			 * prune the search.
5133 			 * Registers read by the continuation are read by us.
5134 			 * If we have any write marks in env->cur_state, they
5135 			 * will prevent corresponding reads in the continuation
5136 			 * from reaching our parent (an explored_state).  Our
5137 			 * own state will get the read marks recorded, but
5138 			 * they'll be immediately forgotten as we're pruning
5139 			 * this state and will pop a new one.
5140 			 */
5141 			err = propagate_liveness(env, &sl->state, cur);
5142 			if (err)
5143 				return err;
5144 			return 1;
5145 		}
5146 		sl = sl->next;
5147 	}
5148 
5149 	/* there were no equivalent states, remember current one.
5150 	 * technically the current state is not proven to be safe yet,
5151 	 * but it will either reach outer most bpf_exit (which means it's safe)
5152 	 * or it will be rejected. Since there are no loops, we won't be
5153 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
5154 	 * again on the way to bpf_exit
5155 	 */
5156 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
5157 	if (!new_sl)
5158 		return -ENOMEM;
5159 
5160 	/* add new state to the head of linked list */
5161 	new = &new_sl->state;
5162 	err = copy_verifier_state(new, cur);
5163 	if (err) {
5164 		free_verifier_state(new, false);
5165 		kfree(new_sl);
5166 		return err;
5167 	}
5168 	new_sl->next = env->explored_states[insn_idx];
5169 	env->explored_states[insn_idx] = new_sl;
5170 	/* connect new state to parentage chain */
5171 	for (i = 0; i < BPF_REG_FP; i++)
5172 		cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i];
5173 	/* clear write marks in current state: the writes we did are not writes
5174 	 * our child did, so they don't screen off its reads from us.
5175 	 * (There are no read marks in current state, because reads always mark
5176 	 * their parent and current state never has children yet.  Only
5177 	 * explored_states can get read marks.)
5178 	 */
5179 	for (i = 0; i < BPF_REG_FP; i++)
5180 		cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
5181 
5182 	/* all stack frames are accessible from callee, clear them all */
5183 	for (j = 0; j <= cur->curframe; j++) {
5184 		struct bpf_func_state *frame = cur->frame[j];
5185 		struct bpf_func_state *newframe = new->frame[j];
5186 
5187 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
5188 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
5189 			frame->stack[i].spilled_ptr.parent =
5190 						&newframe->stack[i].spilled_ptr;
5191 		}
5192 	}
5193 	return 0;
5194 }
5195 
5196 /* Return true if it's OK to have the same insn return a different type. */
5197 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
5198 {
5199 	switch (type) {
5200 	case PTR_TO_CTX:
5201 	case PTR_TO_SOCKET:
5202 	case PTR_TO_SOCKET_OR_NULL:
5203 		return false;
5204 	default:
5205 		return true;
5206 	}
5207 }
5208 
5209 /* If an instruction was previously used with particular pointer types, then we
5210  * need to be careful to avoid cases such as the below, where it may be ok
5211  * for one branch accessing the pointer, but not ok for the other branch:
5212  *
5213  * R1 = sock_ptr
5214  * goto X;
5215  * ...
5216  * R1 = some_other_valid_ptr;
5217  * goto X;
5218  * ...
5219  * R2 = *(u32 *)(R1 + 0);
5220  */
5221 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
5222 {
5223 	return src != prev && (!reg_type_mismatch_ok(src) ||
5224 			       !reg_type_mismatch_ok(prev));
5225 }
5226 
5227 static int do_check(struct bpf_verifier_env *env)
5228 {
5229 	struct bpf_verifier_state *state;
5230 	struct bpf_insn *insns = env->prog->insnsi;
5231 	struct bpf_reg_state *regs;
5232 	int insn_cnt = env->prog->len, i;
5233 	int insn_idx, prev_insn_idx = 0;
5234 	int insn_processed = 0;
5235 	bool do_print_state = false;
5236 
5237 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
5238 	if (!state)
5239 		return -ENOMEM;
5240 	state->curframe = 0;
5241 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
5242 	if (!state->frame[0]) {
5243 		kfree(state);
5244 		return -ENOMEM;
5245 	}
5246 	env->cur_state = state;
5247 	init_func_state(env, state->frame[0],
5248 			BPF_MAIN_FUNC /* callsite */,
5249 			0 /* frameno */,
5250 			0 /* subprogno, zero == main subprog */);
5251 	insn_idx = 0;
5252 	for (;;) {
5253 		struct bpf_insn *insn;
5254 		u8 class;
5255 		int err;
5256 
5257 		if (insn_idx >= insn_cnt) {
5258 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
5259 				insn_idx, insn_cnt);
5260 			return -EFAULT;
5261 		}
5262 
5263 		insn = &insns[insn_idx];
5264 		class = BPF_CLASS(insn->code);
5265 
5266 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
5267 			verbose(env,
5268 				"BPF program is too large. Processed %d insn\n",
5269 				insn_processed);
5270 			return -E2BIG;
5271 		}
5272 
5273 		err = is_state_visited(env, insn_idx);
5274 		if (err < 0)
5275 			return err;
5276 		if (err == 1) {
5277 			/* found equivalent state, can prune the search */
5278 			if (env->log.level) {
5279 				if (do_print_state)
5280 					verbose(env, "\nfrom %d to %d: safe\n",
5281 						prev_insn_idx, insn_idx);
5282 				else
5283 					verbose(env, "%d: safe\n", insn_idx);
5284 			}
5285 			goto process_bpf_exit;
5286 		}
5287 
5288 		if (need_resched())
5289 			cond_resched();
5290 
5291 		if (env->log.level > 1 || (env->log.level && do_print_state)) {
5292 			if (env->log.level > 1)
5293 				verbose(env, "%d:", insn_idx);
5294 			else
5295 				verbose(env, "\nfrom %d to %d:",
5296 					prev_insn_idx, insn_idx);
5297 			print_verifier_state(env, state->frame[state->curframe]);
5298 			do_print_state = false;
5299 		}
5300 
5301 		if (env->log.level) {
5302 			const struct bpf_insn_cbs cbs = {
5303 				.cb_print	= verbose,
5304 				.private_data	= env,
5305 			};
5306 
5307 			verbose(env, "%d: ", insn_idx);
5308 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
5309 		}
5310 
5311 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
5312 			err = bpf_prog_offload_verify_insn(env, insn_idx,
5313 							   prev_insn_idx);
5314 			if (err)
5315 				return err;
5316 		}
5317 
5318 		regs = cur_regs(env);
5319 		env->insn_aux_data[insn_idx].seen = true;
5320 
5321 		if (class == BPF_ALU || class == BPF_ALU64) {
5322 			err = check_alu_op(env, insn);
5323 			if (err)
5324 				return err;
5325 
5326 		} else if (class == BPF_LDX) {
5327 			enum bpf_reg_type *prev_src_type, src_reg_type;
5328 
5329 			/* check for reserved fields is already done */
5330 
5331 			/* check src operand */
5332 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
5333 			if (err)
5334 				return err;
5335 
5336 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5337 			if (err)
5338 				return err;
5339 
5340 			src_reg_type = regs[insn->src_reg].type;
5341 
5342 			/* check that memory (src_reg + off) is readable,
5343 			 * the state of dst_reg will be updated by this func
5344 			 */
5345 			err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
5346 					       BPF_SIZE(insn->code), BPF_READ,
5347 					       insn->dst_reg, false);
5348 			if (err)
5349 				return err;
5350 
5351 			prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
5352 
5353 			if (*prev_src_type == NOT_INIT) {
5354 				/* saw a valid insn
5355 				 * dst_reg = *(u32 *)(src_reg + off)
5356 				 * save type to validate intersecting paths
5357 				 */
5358 				*prev_src_type = src_reg_type;
5359 
5360 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
5361 				/* ABuser program is trying to use the same insn
5362 				 * dst_reg = *(u32*) (src_reg + off)
5363 				 * with different pointer types:
5364 				 * src_reg == ctx in one branch and
5365 				 * src_reg == stack|map in some other branch.
5366 				 * Reject it.
5367 				 */
5368 				verbose(env, "same insn cannot be used with different pointers\n");
5369 				return -EINVAL;
5370 			}
5371 
5372 		} else if (class == BPF_STX) {
5373 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
5374 
5375 			if (BPF_MODE(insn->code) == BPF_XADD) {
5376 				err = check_xadd(env, insn_idx, insn);
5377 				if (err)
5378 					return err;
5379 				insn_idx++;
5380 				continue;
5381 			}
5382 
5383 			/* check src1 operand */
5384 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
5385 			if (err)
5386 				return err;
5387 			/* check src2 operand */
5388 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5389 			if (err)
5390 				return err;
5391 
5392 			dst_reg_type = regs[insn->dst_reg].type;
5393 
5394 			/* check that memory (dst_reg + off) is writeable */
5395 			err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5396 					       BPF_SIZE(insn->code), BPF_WRITE,
5397 					       insn->src_reg, false);
5398 			if (err)
5399 				return err;
5400 
5401 			prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
5402 
5403 			if (*prev_dst_type == NOT_INIT) {
5404 				*prev_dst_type = dst_reg_type;
5405 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
5406 				verbose(env, "same insn cannot be used with different pointers\n");
5407 				return -EINVAL;
5408 			}
5409 
5410 		} else if (class == BPF_ST) {
5411 			if (BPF_MODE(insn->code) != BPF_MEM ||
5412 			    insn->src_reg != BPF_REG_0) {
5413 				verbose(env, "BPF_ST uses reserved fields\n");
5414 				return -EINVAL;
5415 			}
5416 			/* check src operand */
5417 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5418 			if (err)
5419 				return err;
5420 
5421 			if (is_ctx_reg(env, insn->dst_reg)) {
5422 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
5423 					insn->dst_reg,
5424 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
5425 				return -EACCES;
5426 			}
5427 
5428 			/* check that memory (dst_reg + off) is writeable */
5429 			err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5430 					       BPF_SIZE(insn->code), BPF_WRITE,
5431 					       -1, false);
5432 			if (err)
5433 				return err;
5434 
5435 		} else if (class == BPF_JMP) {
5436 			u8 opcode = BPF_OP(insn->code);
5437 
5438 			if (opcode == BPF_CALL) {
5439 				if (BPF_SRC(insn->code) != BPF_K ||
5440 				    insn->off != 0 ||
5441 				    (insn->src_reg != BPF_REG_0 &&
5442 				     insn->src_reg != BPF_PSEUDO_CALL) ||
5443 				    insn->dst_reg != BPF_REG_0) {
5444 					verbose(env, "BPF_CALL uses reserved fields\n");
5445 					return -EINVAL;
5446 				}
5447 
5448 				if (insn->src_reg == BPF_PSEUDO_CALL)
5449 					err = check_func_call(env, insn, &insn_idx);
5450 				else
5451 					err = check_helper_call(env, insn->imm, insn_idx);
5452 				if (err)
5453 					return err;
5454 
5455 			} else if (opcode == BPF_JA) {
5456 				if (BPF_SRC(insn->code) != BPF_K ||
5457 				    insn->imm != 0 ||
5458 				    insn->src_reg != BPF_REG_0 ||
5459 				    insn->dst_reg != BPF_REG_0) {
5460 					verbose(env, "BPF_JA uses reserved fields\n");
5461 					return -EINVAL;
5462 				}
5463 
5464 				insn_idx += insn->off + 1;
5465 				continue;
5466 
5467 			} else if (opcode == BPF_EXIT) {
5468 				if (BPF_SRC(insn->code) != BPF_K ||
5469 				    insn->imm != 0 ||
5470 				    insn->src_reg != BPF_REG_0 ||
5471 				    insn->dst_reg != BPF_REG_0) {
5472 					verbose(env, "BPF_EXIT uses reserved fields\n");
5473 					return -EINVAL;
5474 				}
5475 
5476 				if (state->curframe) {
5477 					/* exit from nested function */
5478 					prev_insn_idx = insn_idx;
5479 					err = prepare_func_exit(env, &insn_idx);
5480 					if (err)
5481 						return err;
5482 					do_print_state = true;
5483 					continue;
5484 				}
5485 
5486 				err = check_reference_leak(env);
5487 				if (err)
5488 					return err;
5489 
5490 				/* eBPF calling convetion is such that R0 is used
5491 				 * to return the value from eBPF program.
5492 				 * Make sure that it's readable at this time
5493 				 * of bpf_exit, which means that program wrote
5494 				 * something into it earlier
5495 				 */
5496 				err = check_reg_arg(env, BPF_REG_0, SRC_OP);
5497 				if (err)
5498 					return err;
5499 
5500 				if (is_pointer_value(env, BPF_REG_0)) {
5501 					verbose(env, "R0 leaks addr as return value\n");
5502 					return -EACCES;
5503 				}
5504 
5505 				err = check_return_code(env);
5506 				if (err)
5507 					return err;
5508 process_bpf_exit:
5509 				err = pop_stack(env, &prev_insn_idx, &insn_idx);
5510 				if (err < 0) {
5511 					if (err != -ENOENT)
5512 						return err;
5513 					break;
5514 				} else {
5515 					do_print_state = true;
5516 					continue;
5517 				}
5518 			} else {
5519 				err = check_cond_jmp_op(env, insn, &insn_idx);
5520 				if (err)
5521 					return err;
5522 			}
5523 		} else if (class == BPF_LD) {
5524 			u8 mode = BPF_MODE(insn->code);
5525 
5526 			if (mode == BPF_ABS || mode == BPF_IND) {
5527 				err = check_ld_abs(env, insn);
5528 				if (err)
5529 					return err;
5530 
5531 			} else if (mode == BPF_IMM) {
5532 				err = check_ld_imm(env, insn);
5533 				if (err)
5534 					return err;
5535 
5536 				insn_idx++;
5537 				env->insn_aux_data[insn_idx].seen = true;
5538 			} else {
5539 				verbose(env, "invalid BPF_LD mode\n");
5540 				return -EINVAL;
5541 			}
5542 		} else {
5543 			verbose(env, "unknown insn class %d\n", class);
5544 			return -EINVAL;
5545 		}
5546 
5547 		insn_idx++;
5548 	}
5549 
5550 	verbose(env, "processed %d insns (limit %d), stack depth ",
5551 		insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
5552 	for (i = 0; i < env->subprog_cnt; i++) {
5553 		u32 depth = env->subprog_info[i].stack_depth;
5554 
5555 		verbose(env, "%d", depth);
5556 		if (i + 1 < env->subprog_cnt)
5557 			verbose(env, "+");
5558 	}
5559 	verbose(env, "\n");
5560 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
5561 	return 0;
5562 }
5563 
5564 static int check_map_prealloc(struct bpf_map *map)
5565 {
5566 	return (map->map_type != BPF_MAP_TYPE_HASH &&
5567 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
5568 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
5569 		!(map->map_flags & BPF_F_NO_PREALLOC);
5570 }
5571 
5572 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
5573 					struct bpf_map *map,
5574 					struct bpf_prog *prog)
5575 
5576 {
5577 	/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
5578 	 * preallocated hash maps, since doing memory allocation
5579 	 * in overflow_handler can crash depending on where nmi got
5580 	 * triggered.
5581 	 */
5582 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5583 		if (!check_map_prealloc(map)) {
5584 			verbose(env, "perf_event programs can only use preallocated hash map\n");
5585 			return -EINVAL;
5586 		}
5587 		if (map->inner_map_meta &&
5588 		    !check_map_prealloc(map->inner_map_meta)) {
5589 			verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5590 			return -EINVAL;
5591 		}
5592 	}
5593 
5594 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5595 	    !bpf_offload_prog_map_match(prog, map)) {
5596 		verbose(env, "offload device mismatch between prog and map\n");
5597 		return -EINVAL;
5598 	}
5599 
5600 	return 0;
5601 }
5602 
5603 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
5604 {
5605 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
5606 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
5607 }
5608 
5609 /* look for pseudo eBPF instructions that access map FDs and
5610  * replace them with actual map pointers
5611  */
5612 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5613 {
5614 	struct bpf_insn *insn = env->prog->insnsi;
5615 	int insn_cnt = env->prog->len;
5616 	int i, j, err;
5617 
5618 	err = bpf_prog_calc_tag(env->prog);
5619 	if (err)
5620 		return err;
5621 
5622 	for (i = 0; i < insn_cnt; i++, insn++) {
5623 		if (BPF_CLASS(insn->code) == BPF_LDX &&
5624 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5625 			verbose(env, "BPF_LDX uses reserved fields\n");
5626 			return -EINVAL;
5627 		}
5628 
5629 		if (BPF_CLASS(insn->code) == BPF_STX &&
5630 		    ((BPF_MODE(insn->code) != BPF_MEM &&
5631 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5632 			verbose(env, "BPF_STX uses reserved fields\n");
5633 			return -EINVAL;
5634 		}
5635 
5636 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5637 			struct bpf_map *map;
5638 			struct fd f;
5639 
5640 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
5641 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5642 			    insn[1].off != 0) {
5643 				verbose(env, "invalid bpf_ld_imm64 insn\n");
5644 				return -EINVAL;
5645 			}
5646 
5647 			if (insn->src_reg == 0)
5648 				/* valid generic load 64-bit imm */
5649 				goto next_insn;
5650 
5651 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5652 				verbose(env,
5653 					"unrecognized bpf_ld_imm64 insn\n");
5654 				return -EINVAL;
5655 			}
5656 
5657 			f = fdget(insn->imm);
5658 			map = __bpf_map_get(f);
5659 			if (IS_ERR(map)) {
5660 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
5661 					insn->imm);
5662 				return PTR_ERR(map);
5663 			}
5664 
5665 			err = check_map_prog_compatibility(env, map, env->prog);
5666 			if (err) {
5667 				fdput(f);
5668 				return err;
5669 			}
5670 
5671 			/* store map pointer inside BPF_LD_IMM64 instruction */
5672 			insn[0].imm = (u32) (unsigned long) map;
5673 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
5674 
5675 			/* check whether we recorded this map already */
5676 			for (j = 0; j < env->used_map_cnt; j++)
5677 				if (env->used_maps[j] == map) {
5678 					fdput(f);
5679 					goto next_insn;
5680 				}
5681 
5682 			if (env->used_map_cnt >= MAX_USED_MAPS) {
5683 				fdput(f);
5684 				return -E2BIG;
5685 			}
5686 
5687 			/* hold the map. If the program is rejected by verifier,
5688 			 * the map will be released by release_maps() or it
5689 			 * will be used by the valid program until it's unloaded
5690 			 * and all maps are released in free_used_maps()
5691 			 */
5692 			map = bpf_map_inc(map, false);
5693 			if (IS_ERR(map)) {
5694 				fdput(f);
5695 				return PTR_ERR(map);
5696 			}
5697 			env->used_maps[env->used_map_cnt++] = map;
5698 
5699 			if (bpf_map_is_cgroup_storage(map) &&
5700 			    bpf_cgroup_storage_assign(env->prog, map)) {
5701 				verbose(env, "only one cgroup storage of each type is allowed\n");
5702 				fdput(f);
5703 				return -EBUSY;
5704 			}
5705 
5706 			fdput(f);
5707 next_insn:
5708 			insn++;
5709 			i++;
5710 			continue;
5711 		}
5712 
5713 		/* Basic sanity check before we invest more work here. */
5714 		if (!bpf_opcode_in_insntable(insn->code)) {
5715 			verbose(env, "unknown opcode %02x\n", insn->code);
5716 			return -EINVAL;
5717 		}
5718 	}
5719 
5720 	/* now all pseudo BPF_LD_IMM64 instructions load valid
5721 	 * 'struct bpf_map *' into a register instead of user map_fd.
5722 	 * These pointers will be used later by verifier to validate map access.
5723 	 */
5724 	return 0;
5725 }
5726 
5727 /* drop refcnt of maps used by the rejected program */
5728 static void release_maps(struct bpf_verifier_env *env)
5729 {
5730 	enum bpf_cgroup_storage_type stype;
5731 	int i;
5732 
5733 	for_each_cgroup_storage_type(stype) {
5734 		if (!env->prog->aux->cgroup_storage[stype])
5735 			continue;
5736 		bpf_cgroup_storage_release(env->prog,
5737 			env->prog->aux->cgroup_storage[stype]);
5738 	}
5739 
5740 	for (i = 0; i < env->used_map_cnt; i++)
5741 		bpf_map_put(env->used_maps[i]);
5742 }
5743 
5744 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5745 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5746 {
5747 	struct bpf_insn *insn = env->prog->insnsi;
5748 	int insn_cnt = env->prog->len;
5749 	int i;
5750 
5751 	for (i = 0; i < insn_cnt; i++, insn++)
5752 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5753 			insn->src_reg = 0;
5754 }
5755 
5756 /* single env->prog->insni[off] instruction was replaced with the range
5757  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
5758  * [0, off) and [off, end) to new locations, so the patched range stays zero
5759  */
5760 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5761 				u32 off, u32 cnt)
5762 {
5763 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5764 	int i;
5765 
5766 	if (cnt == 1)
5767 		return 0;
5768 	new_data = vzalloc(array_size(prog_len,
5769 				      sizeof(struct bpf_insn_aux_data)));
5770 	if (!new_data)
5771 		return -ENOMEM;
5772 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5773 	memcpy(new_data + off + cnt - 1, old_data + off,
5774 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5775 	for (i = off; i < off + cnt - 1; i++)
5776 		new_data[i].seen = true;
5777 	env->insn_aux_data = new_data;
5778 	vfree(old_data);
5779 	return 0;
5780 }
5781 
5782 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5783 {
5784 	int i;
5785 
5786 	if (len == 1)
5787 		return;
5788 	/* NOTE: fake 'exit' subprog should be updated as well. */
5789 	for (i = 0; i <= env->subprog_cnt; i++) {
5790 		if (env->subprog_info[i].start <= off)
5791 			continue;
5792 		env->subprog_info[i].start += len - 1;
5793 	}
5794 }
5795 
5796 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5797 					    const struct bpf_insn *patch, u32 len)
5798 {
5799 	struct bpf_prog *new_prog;
5800 
5801 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5802 	if (!new_prog)
5803 		return NULL;
5804 	if (adjust_insn_aux_data(env, new_prog->len, off, len))
5805 		return NULL;
5806 	adjust_subprog_starts(env, off, len);
5807 	return new_prog;
5808 }
5809 
5810 /* The verifier does more data flow analysis than llvm and will not
5811  * explore branches that are dead at run time. Malicious programs can
5812  * have dead code too. Therefore replace all dead at-run-time code
5813  * with 'ja -1'.
5814  *
5815  * Just nops are not optimal, e.g. if they would sit at the end of the
5816  * program and through another bug we would manage to jump there, then
5817  * we'd execute beyond program memory otherwise. Returning exception
5818  * code also wouldn't work since we can have subprogs where the dead
5819  * code could be located.
5820  */
5821 static void sanitize_dead_code(struct bpf_verifier_env *env)
5822 {
5823 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5824 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5825 	struct bpf_insn *insn = env->prog->insnsi;
5826 	const int insn_cnt = env->prog->len;
5827 	int i;
5828 
5829 	for (i = 0; i < insn_cnt; i++) {
5830 		if (aux_data[i].seen)
5831 			continue;
5832 		memcpy(insn + i, &trap, sizeof(trap));
5833 	}
5834 }
5835 
5836 /* convert load instructions that access fields of a context type into a
5837  * sequence of instructions that access fields of the underlying structure:
5838  *     struct __sk_buff    -> struct sk_buff
5839  *     struct bpf_sock_ops -> struct sock
5840  */
5841 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5842 {
5843 	const struct bpf_verifier_ops *ops = env->ops;
5844 	int i, cnt, size, ctx_field_size, delta = 0;
5845 	const int insn_cnt = env->prog->len;
5846 	struct bpf_insn insn_buf[16], *insn;
5847 	u32 target_size, size_default, off;
5848 	struct bpf_prog *new_prog;
5849 	enum bpf_access_type type;
5850 	bool is_narrower_load;
5851 
5852 	if (ops->gen_prologue || env->seen_direct_write) {
5853 		if (!ops->gen_prologue) {
5854 			verbose(env, "bpf verifier is misconfigured\n");
5855 			return -EINVAL;
5856 		}
5857 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5858 					env->prog);
5859 		if (cnt >= ARRAY_SIZE(insn_buf)) {
5860 			verbose(env, "bpf verifier is misconfigured\n");
5861 			return -EINVAL;
5862 		} else if (cnt) {
5863 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5864 			if (!new_prog)
5865 				return -ENOMEM;
5866 
5867 			env->prog = new_prog;
5868 			delta += cnt - 1;
5869 		}
5870 	}
5871 
5872 	if (bpf_prog_is_dev_bound(env->prog->aux))
5873 		return 0;
5874 
5875 	insn = env->prog->insnsi + delta;
5876 
5877 	for (i = 0; i < insn_cnt; i++, insn++) {
5878 		bpf_convert_ctx_access_t convert_ctx_access;
5879 
5880 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5881 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5882 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5883 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5884 			type = BPF_READ;
5885 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5886 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5887 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5888 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5889 			type = BPF_WRITE;
5890 		else
5891 			continue;
5892 
5893 		if (type == BPF_WRITE &&
5894 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
5895 			struct bpf_insn patch[] = {
5896 				/* Sanitize suspicious stack slot with zero.
5897 				 * There are no memory dependencies for this store,
5898 				 * since it's only using frame pointer and immediate
5899 				 * constant of zero
5900 				 */
5901 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
5902 					   env->insn_aux_data[i + delta].sanitize_stack_off,
5903 					   0),
5904 				/* the original STX instruction will immediately
5905 				 * overwrite the same stack slot with appropriate value
5906 				 */
5907 				*insn,
5908 			};
5909 
5910 			cnt = ARRAY_SIZE(patch);
5911 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5912 			if (!new_prog)
5913 				return -ENOMEM;
5914 
5915 			delta    += cnt - 1;
5916 			env->prog = new_prog;
5917 			insn      = new_prog->insnsi + i + delta;
5918 			continue;
5919 		}
5920 
5921 		switch (env->insn_aux_data[i + delta].ptr_type) {
5922 		case PTR_TO_CTX:
5923 			if (!ops->convert_ctx_access)
5924 				continue;
5925 			convert_ctx_access = ops->convert_ctx_access;
5926 			break;
5927 		case PTR_TO_SOCKET:
5928 			convert_ctx_access = bpf_sock_convert_ctx_access;
5929 			break;
5930 		default:
5931 			continue;
5932 		}
5933 
5934 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5935 		size = BPF_LDST_BYTES(insn);
5936 
5937 		/* If the read access is a narrower load of the field,
5938 		 * convert to a 4/8-byte load, to minimum program type specific
5939 		 * convert_ctx_access changes. If conversion is successful,
5940 		 * we will apply proper mask to the result.
5941 		 */
5942 		is_narrower_load = size < ctx_field_size;
5943 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
5944 		off = insn->off;
5945 		if (is_narrower_load) {
5946 			u8 size_code;
5947 
5948 			if (type == BPF_WRITE) {
5949 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5950 				return -EINVAL;
5951 			}
5952 
5953 			size_code = BPF_H;
5954 			if (ctx_field_size == 4)
5955 				size_code = BPF_W;
5956 			else if (ctx_field_size == 8)
5957 				size_code = BPF_DW;
5958 
5959 			insn->off = off & ~(size_default - 1);
5960 			insn->code = BPF_LDX | BPF_MEM | size_code;
5961 		}
5962 
5963 		target_size = 0;
5964 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
5965 					 &target_size);
5966 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5967 		    (ctx_field_size && !target_size)) {
5968 			verbose(env, "bpf verifier is misconfigured\n");
5969 			return -EINVAL;
5970 		}
5971 
5972 		if (is_narrower_load && size < target_size) {
5973 			u8 shift = (off & (size_default - 1)) * 8;
5974 
5975 			if (ctx_field_size <= 4) {
5976 				if (shift)
5977 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
5978 									insn->dst_reg,
5979 									shift);
5980 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5981 								(1 << size * 8) - 1);
5982 			} else {
5983 				if (shift)
5984 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
5985 									insn->dst_reg,
5986 									shift);
5987 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5988 								(1 << size * 8) - 1);
5989 			}
5990 		}
5991 
5992 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5993 		if (!new_prog)
5994 			return -ENOMEM;
5995 
5996 		delta += cnt - 1;
5997 
5998 		/* keep walking new program and skip insns we just inserted */
5999 		env->prog = new_prog;
6000 		insn      = new_prog->insnsi + i + delta;
6001 	}
6002 
6003 	return 0;
6004 }
6005 
6006 static int jit_subprogs(struct bpf_verifier_env *env)
6007 {
6008 	struct bpf_prog *prog = env->prog, **func, *tmp;
6009 	int i, j, subprog_start, subprog_end = 0, len, subprog;
6010 	struct bpf_insn *insn;
6011 	void *old_bpf_func;
6012 	int err = -ENOMEM;
6013 
6014 	if (env->subprog_cnt <= 1)
6015 		return 0;
6016 
6017 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6018 		if (insn->code != (BPF_JMP | BPF_CALL) ||
6019 		    insn->src_reg != BPF_PSEUDO_CALL)
6020 			continue;
6021 		/* Upon error here we cannot fall back to interpreter but
6022 		 * need a hard reject of the program. Thus -EFAULT is
6023 		 * propagated in any case.
6024 		 */
6025 		subprog = find_subprog(env, i + insn->imm + 1);
6026 		if (subprog < 0) {
6027 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6028 				  i + insn->imm + 1);
6029 			return -EFAULT;
6030 		}
6031 		/* temporarily remember subprog id inside insn instead of
6032 		 * aux_data, since next loop will split up all insns into funcs
6033 		 */
6034 		insn->off = subprog;
6035 		/* remember original imm in case JIT fails and fallback
6036 		 * to interpreter will be needed
6037 		 */
6038 		env->insn_aux_data[i].call_imm = insn->imm;
6039 		/* point imm to __bpf_call_base+1 from JITs point of view */
6040 		insn->imm = 1;
6041 	}
6042 
6043 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
6044 	if (!func)
6045 		goto out_undo_insn;
6046 
6047 	for (i = 0; i < env->subprog_cnt; i++) {
6048 		subprog_start = subprog_end;
6049 		subprog_end = env->subprog_info[i + 1].start;
6050 
6051 		len = subprog_end - subprog_start;
6052 		func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
6053 		if (!func[i])
6054 			goto out_free;
6055 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
6056 		       len * sizeof(struct bpf_insn));
6057 		func[i]->type = prog->type;
6058 		func[i]->len = len;
6059 		if (bpf_prog_calc_tag(func[i]))
6060 			goto out_free;
6061 		func[i]->is_func = 1;
6062 		func[i]->aux->func_idx = i;
6063 		/* the btf and func_info will be freed only at prog->aux */
6064 		func[i]->aux->btf = prog->aux->btf;
6065 		func[i]->aux->func_info = prog->aux->func_info;
6066 
6067 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
6068 		 * Long term would need debug info to populate names
6069 		 */
6070 		func[i]->aux->name[0] = 'F';
6071 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
6072 		func[i]->jit_requested = 1;
6073 		func[i] = bpf_int_jit_compile(func[i]);
6074 		if (!func[i]->jited) {
6075 			err = -ENOTSUPP;
6076 			goto out_free;
6077 		}
6078 		cond_resched();
6079 	}
6080 	/* at this point all bpf functions were successfully JITed
6081 	 * now populate all bpf_calls with correct addresses and
6082 	 * run last pass of JIT
6083 	 */
6084 	for (i = 0; i < env->subprog_cnt; i++) {
6085 		insn = func[i]->insnsi;
6086 		for (j = 0; j < func[i]->len; j++, insn++) {
6087 			if (insn->code != (BPF_JMP | BPF_CALL) ||
6088 			    insn->src_reg != BPF_PSEUDO_CALL)
6089 				continue;
6090 			subprog = insn->off;
6091 			insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
6092 				func[subprog]->bpf_func -
6093 				__bpf_call_base;
6094 		}
6095 
6096 		/* we use the aux data to keep a list of the start addresses
6097 		 * of the JITed images for each function in the program
6098 		 *
6099 		 * for some architectures, such as powerpc64, the imm field
6100 		 * might not be large enough to hold the offset of the start
6101 		 * address of the callee's JITed image from __bpf_call_base
6102 		 *
6103 		 * in such cases, we can lookup the start address of a callee
6104 		 * by using its subprog id, available from the off field of
6105 		 * the call instruction, as an index for this list
6106 		 */
6107 		func[i]->aux->func = func;
6108 		func[i]->aux->func_cnt = env->subprog_cnt;
6109 	}
6110 	for (i = 0; i < env->subprog_cnt; i++) {
6111 		old_bpf_func = func[i]->bpf_func;
6112 		tmp = bpf_int_jit_compile(func[i]);
6113 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
6114 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
6115 			err = -ENOTSUPP;
6116 			goto out_free;
6117 		}
6118 		cond_resched();
6119 	}
6120 
6121 	/* finally lock prog and jit images for all functions and
6122 	 * populate kallsysm
6123 	 */
6124 	for (i = 0; i < env->subprog_cnt; i++) {
6125 		bpf_prog_lock_ro(func[i]);
6126 		bpf_prog_kallsyms_add(func[i]);
6127 	}
6128 
6129 	/* Last step: make now unused interpreter insns from main
6130 	 * prog consistent for later dump requests, so they can
6131 	 * later look the same as if they were interpreted only.
6132 	 */
6133 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6134 		if (insn->code != (BPF_JMP | BPF_CALL) ||
6135 		    insn->src_reg != BPF_PSEUDO_CALL)
6136 			continue;
6137 		insn->off = env->insn_aux_data[i].call_imm;
6138 		subprog = find_subprog(env, i + insn->off + 1);
6139 		insn->imm = subprog;
6140 	}
6141 
6142 	prog->jited = 1;
6143 	prog->bpf_func = func[0]->bpf_func;
6144 	prog->aux->func = func;
6145 	prog->aux->func_cnt = env->subprog_cnt;
6146 	return 0;
6147 out_free:
6148 	for (i = 0; i < env->subprog_cnt; i++)
6149 		if (func[i])
6150 			bpf_jit_free(func[i]);
6151 	kfree(func);
6152 out_undo_insn:
6153 	/* cleanup main prog to be interpreted */
6154 	prog->jit_requested = 0;
6155 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6156 		if (insn->code != (BPF_JMP | BPF_CALL) ||
6157 		    insn->src_reg != BPF_PSEUDO_CALL)
6158 			continue;
6159 		insn->off = 0;
6160 		insn->imm = env->insn_aux_data[i].call_imm;
6161 	}
6162 	return err;
6163 }
6164 
6165 static int fixup_call_args(struct bpf_verifier_env *env)
6166 {
6167 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6168 	struct bpf_prog *prog = env->prog;
6169 	struct bpf_insn *insn = prog->insnsi;
6170 	int i, depth;
6171 #endif
6172 	int err = 0;
6173 
6174 	if (env->prog->jit_requested &&
6175 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
6176 		err = jit_subprogs(env);
6177 		if (err == 0)
6178 			return 0;
6179 		if (err == -EFAULT)
6180 			return err;
6181 	}
6182 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6183 	for (i = 0; i < prog->len; i++, insn++) {
6184 		if (insn->code != (BPF_JMP | BPF_CALL) ||
6185 		    insn->src_reg != BPF_PSEUDO_CALL)
6186 			continue;
6187 		depth = get_callee_stack_depth(env, insn, i);
6188 		if (depth < 0)
6189 			return depth;
6190 		bpf_patch_call_args(insn, depth);
6191 	}
6192 	err = 0;
6193 #endif
6194 	return err;
6195 }
6196 
6197 /* fixup insn->imm field of bpf_call instructions
6198  * and inline eligible helpers as explicit sequence of BPF instructions
6199  *
6200  * this function is called after eBPF program passed verification
6201  */
6202 static int fixup_bpf_calls(struct bpf_verifier_env *env)
6203 {
6204 	struct bpf_prog *prog = env->prog;
6205 	struct bpf_insn *insn = prog->insnsi;
6206 	const struct bpf_func_proto *fn;
6207 	const int insn_cnt = prog->len;
6208 	const struct bpf_map_ops *ops;
6209 	struct bpf_insn_aux_data *aux;
6210 	struct bpf_insn insn_buf[16];
6211 	struct bpf_prog *new_prog;
6212 	struct bpf_map *map_ptr;
6213 	int i, cnt, delta = 0;
6214 
6215 	for (i = 0; i < insn_cnt; i++, insn++) {
6216 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
6217 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6218 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
6219 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6220 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
6221 			struct bpf_insn mask_and_div[] = {
6222 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
6223 				/* Rx div 0 -> 0 */
6224 				BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
6225 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
6226 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6227 				*insn,
6228 			};
6229 			struct bpf_insn mask_and_mod[] = {
6230 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
6231 				/* Rx mod 0 -> Rx */
6232 				BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
6233 				*insn,
6234 			};
6235 			struct bpf_insn *patchlet;
6236 
6237 			if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6238 			    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6239 				patchlet = mask_and_div + (is64 ? 1 : 0);
6240 				cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
6241 			} else {
6242 				patchlet = mask_and_mod + (is64 ? 1 : 0);
6243 				cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
6244 			}
6245 
6246 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
6247 			if (!new_prog)
6248 				return -ENOMEM;
6249 
6250 			delta    += cnt - 1;
6251 			env->prog = prog = new_prog;
6252 			insn      = new_prog->insnsi + i + delta;
6253 			continue;
6254 		}
6255 
6256 		if (BPF_CLASS(insn->code) == BPF_LD &&
6257 		    (BPF_MODE(insn->code) == BPF_ABS ||
6258 		     BPF_MODE(insn->code) == BPF_IND)) {
6259 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
6260 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6261 				verbose(env, "bpf verifier is misconfigured\n");
6262 				return -EINVAL;
6263 			}
6264 
6265 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6266 			if (!new_prog)
6267 				return -ENOMEM;
6268 
6269 			delta    += cnt - 1;
6270 			env->prog = prog = new_prog;
6271 			insn      = new_prog->insnsi + i + delta;
6272 			continue;
6273 		}
6274 
6275 		if (insn->code != (BPF_JMP | BPF_CALL))
6276 			continue;
6277 		if (insn->src_reg == BPF_PSEUDO_CALL)
6278 			continue;
6279 
6280 		if (insn->imm == BPF_FUNC_get_route_realm)
6281 			prog->dst_needed = 1;
6282 		if (insn->imm == BPF_FUNC_get_prandom_u32)
6283 			bpf_user_rnd_init_once();
6284 		if (insn->imm == BPF_FUNC_override_return)
6285 			prog->kprobe_override = 1;
6286 		if (insn->imm == BPF_FUNC_tail_call) {
6287 			/* If we tail call into other programs, we
6288 			 * cannot make any assumptions since they can
6289 			 * be replaced dynamically during runtime in
6290 			 * the program array.
6291 			 */
6292 			prog->cb_access = 1;
6293 			env->prog->aux->stack_depth = MAX_BPF_STACK;
6294 			env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
6295 
6296 			/* mark bpf_tail_call as different opcode to avoid
6297 			 * conditional branch in the interpeter for every normal
6298 			 * call and to prevent accidental JITing by JIT compiler
6299 			 * that doesn't support bpf_tail_call yet
6300 			 */
6301 			insn->imm = 0;
6302 			insn->code = BPF_JMP | BPF_TAIL_CALL;
6303 
6304 			aux = &env->insn_aux_data[i + delta];
6305 			if (!bpf_map_ptr_unpriv(aux))
6306 				continue;
6307 
6308 			/* instead of changing every JIT dealing with tail_call
6309 			 * emit two extra insns:
6310 			 * if (index >= max_entries) goto out;
6311 			 * index &= array->index_mask;
6312 			 * to avoid out-of-bounds cpu speculation
6313 			 */
6314 			if (bpf_map_ptr_poisoned(aux)) {
6315 				verbose(env, "tail_call abusing map_ptr\n");
6316 				return -EINVAL;
6317 			}
6318 
6319 			map_ptr = BPF_MAP_PTR(aux->map_state);
6320 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
6321 						  map_ptr->max_entries, 2);
6322 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
6323 						    container_of(map_ptr,
6324 								 struct bpf_array,
6325 								 map)->index_mask);
6326 			insn_buf[2] = *insn;
6327 			cnt = 3;
6328 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6329 			if (!new_prog)
6330 				return -ENOMEM;
6331 
6332 			delta    += cnt - 1;
6333 			env->prog = prog = new_prog;
6334 			insn      = new_prog->insnsi + i + delta;
6335 			continue;
6336 		}
6337 
6338 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
6339 		 * and other inlining handlers are currently limited to 64 bit
6340 		 * only.
6341 		 */
6342 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
6343 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
6344 		     insn->imm == BPF_FUNC_map_update_elem ||
6345 		     insn->imm == BPF_FUNC_map_delete_elem ||
6346 		     insn->imm == BPF_FUNC_map_push_elem   ||
6347 		     insn->imm == BPF_FUNC_map_pop_elem    ||
6348 		     insn->imm == BPF_FUNC_map_peek_elem)) {
6349 			aux = &env->insn_aux_data[i + delta];
6350 			if (bpf_map_ptr_poisoned(aux))
6351 				goto patch_call_imm;
6352 
6353 			map_ptr = BPF_MAP_PTR(aux->map_state);
6354 			ops = map_ptr->ops;
6355 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
6356 			    ops->map_gen_lookup) {
6357 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
6358 				if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6359 					verbose(env, "bpf verifier is misconfigured\n");
6360 					return -EINVAL;
6361 				}
6362 
6363 				new_prog = bpf_patch_insn_data(env, i + delta,
6364 							       insn_buf, cnt);
6365 				if (!new_prog)
6366 					return -ENOMEM;
6367 
6368 				delta    += cnt - 1;
6369 				env->prog = prog = new_prog;
6370 				insn      = new_prog->insnsi + i + delta;
6371 				continue;
6372 			}
6373 
6374 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
6375 				     (void *(*)(struct bpf_map *map, void *key))NULL));
6376 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
6377 				     (int (*)(struct bpf_map *map, void *key))NULL));
6378 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
6379 				     (int (*)(struct bpf_map *map, void *key, void *value,
6380 					      u64 flags))NULL));
6381 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
6382 				     (int (*)(struct bpf_map *map, void *value,
6383 					      u64 flags))NULL));
6384 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
6385 				     (int (*)(struct bpf_map *map, void *value))NULL));
6386 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
6387 				     (int (*)(struct bpf_map *map, void *value))NULL));
6388 
6389 			switch (insn->imm) {
6390 			case BPF_FUNC_map_lookup_elem:
6391 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
6392 					    __bpf_call_base;
6393 				continue;
6394 			case BPF_FUNC_map_update_elem:
6395 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
6396 					    __bpf_call_base;
6397 				continue;
6398 			case BPF_FUNC_map_delete_elem:
6399 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
6400 					    __bpf_call_base;
6401 				continue;
6402 			case BPF_FUNC_map_push_elem:
6403 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
6404 					    __bpf_call_base;
6405 				continue;
6406 			case BPF_FUNC_map_pop_elem:
6407 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
6408 					    __bpf_call_base;
6409 				continue;
6410 			case BPF_FUNC_map_peek_elem:
6411 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
6412 					    __bpf_call_base;
6413 				continue;
6414 			}
6415 
6416 			goto patch_call_imm;
6417 		}
6418 
6419 patch_call_imm:
6420 		fn = env->ops->get_func_proto(insn->imm, env->prog);
6421 		/* all functions that have prototype and verifier allowed
6422 		 * programs to call them, must be real in-kernel functions
6423 		 */
6424 		if (!fn->func) {
6425 			verbose(env,
6426 				"kernel subsystem misconfigured func %s#%d\n",
6427 				func_id_name(insn->imm), insn->imm);
6428 			return -EFAULT;
6429 		}
6430 		insn->imm = fn->func - __bpf_call_base;
6431 	}
6432 
6433 	return 0;
6434 }
6435 
6436 static void free_states(struct bpf_verifier_env *env)
6437 {
6438 	struct bpf_verifier_state_list *sl, *sln;
6439 	int i;
6440 
6441 	if (!env->explored_states)
6442 		return;
6443 
6444 	for (i = 0; i < env->prog->len; i++) {
6445 		sl = env->explored_states[i];
6446 
6447 		if (sl)
6448 			while (sl != STATE_LIST_MARK) {
6449 				sln = sl->next;
6450 				free_verifier_state(&sl->state, false);
6451 				kfree(sl);
6452 				sl = sln;
6453 			}
6454 	}
6455 
6456 	kfree(env->explored_states);
6457 }
6458 
6459 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
6460 	      union bpf_attr __user *uattr)
6461 {
6462 	struct bpf_verifier_env *env;
6463 	struct bpf_verifier_log *log;
6464 	int ret = -EINVAL;
6465 
6466 	/* no program is valid */
6467 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
6468 		return -EINVAL;
6469 
6470 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
6471 	 * allocate/free it every time bpf_check() is called
6472 	 */
6473 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
6474 	if (!env)
6475 		return -ENOMEM;
6476 	log = &env->log;
6477 
6478 	env->insn_aux_data =
6479 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
6480 				   (*prog)->len));
6481 	ret = -ENOMEM;
6482 	if (!env->insn_aux_data)
6483 		goto err_free_env;
6484 	env->prog = *prog;
6485 	env->ops = bpf_verifier_ops[env->prog->type];
6486 
6487 	/* grab the mutex to protect few globals used by verifier */
6488 	mutex_lock(&bpf_verifier_lock);
6489 
6490 	if (attr->log_level || attr->log_buf || attr->log_size) {
6491 		/* user requested verbose verifier output
6492 		 * and supplied buffer to store the verification trace
6493 		 */
6494 		log->level = attr->log_level;
6495 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
6496 		log->len_total = attr->log_size;
6497 
6498 		ret = -EINVAL;
6499 		/* log attributes have to be sane */
6500 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
6501 		    !log->level || !log->ubuf)
6502 			goto err_unlock;
6503 	}
6504 
6505 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
6506 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
6507 		env->strict_alignment = true;
6508 
6509 	ret = replace_map_fd_with_map_ptr(env);
6510 	if (ret < 0)
6511 		goto skip_full_check;
6512 
6513 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
6514 		ret = bpf_prog_offload_verifier_prep(env->prog);
6515 		if (ret)
6516 			goto skip_full_check;
6517 	}
6518 
6519 	env->explored_states = kcalloc(env->prog->len,
6520 				       sizeof(struct bpf_verifier_state_list *),
6521 				       GFP_USER);
6522 	ret = -ENOMEM;
6523 	if (!env->explored_states)
6524 		goto skip_full_check;
6525 
6526 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
6527 
6528 	ret = check_cfg(env);
6529 	if (ret < 0)
6530 		goto skip_full_check;
6531 
6532 	ret = check_btf_func(env->prog, env, attr, uattr);
6533 	if (ret < 0)
6534 		goto skip_full_check;
6535 
6536 	ret = do_check(env);
6537 	if (env->cur_state) {
6538 		free_verifier_state(env->cur_state, true);
6539 		env->cur_state = NULL;
6540 	}
6541 
6542 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
6543 		ret = bpf_prog_offload_finalize(env);
6544 
6545 skip_full_check:
6546 	while (!pop_stack(env, NULL, NULL));
6547 	free_states(env);
6548 
6549 	if (ret == 0)
6550 		sanitize_dead_code(env);
6551 
6552 	if (ret == 0)
6553 		ret = check_max_stack_depth(env);
6554 
6555 	if (ret == 0)
6556 		/* program is valid, convert *(u32*)(ctx + off) accesses */
6557 		ret = convert_ctx_accesses(env);
6558 
6559 	if (ret == 0)
6560 		ret = fixup_bpf_calls(env);
6561 
6562 	if (ret == 0)
6563 		ret = fixup_call_args(env);
6564 
6565 	if (log->level && bpf_verifier_log_full(log))
6566 		ret = -ENOSPC;
6567 	if (log->level && !log->ubuf) {
6568 		ret = -EFAULT;
6569 		goto err_release_maps;
6570 	}
6571 
6572 	if (ret == 0 && env->used_map_cnt) {
6573 		/* if program passed verifier, update used_maps in bpf_prog_info */
6574 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
6575 							  sizeof(env->used_maps[0]),
6576 							  GFP_KERNEL);
6577 
6578 		if (!env->prog->aux->used_maps) {
6579 			ret = -ENOMEM;
6580 			goto err_release_maps;
6581 		}
6582 
6583 		memcpy(env->prog->aux->used_maps, env->used_maps,
6584 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
6585 		env->prog->aux->used_map_cnt = env->used_map_cnt;
6586 
6587 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
6588 		 * bpf_ld_imm64 instructions
6589 		 */
6590 		convert_pseudo_ld_imm64(env);
6591 	}
6592 
6593 	if (ret == 0)
6594 		adjust_btf_func(env);
6595 
6596 err_release_maps:
6597 	if (!env->prog->aux->used_maps)
6598 		/* if we didn't copy map pointers into bpf_prog_info, release
6599 		 * them now. Otherwise free_used_maps() will release them.
6600 		 */
6601 		release_maps(env);
6602 	*prog = env->prog;
6603 err_unlock:
6604 	mutex_unlock(&bpf_verifier_lock);
6605 	vfree(env->insn_aux_data);
6606 err_free_env:
6607 	kfree(env);
6608 	return ret;
6609 }
6610