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