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