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