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