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