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