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