xref: /openbmc/linux/kernel/bpf/verifier.c (revision 917edfb98c480fec1dce95ece6707779905ca0b5)
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/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 
27 #include "disasm.h"
28 
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
31 	[_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #define BPF_LINK_TYPE(_id, _name)
34 #include <linux/bpf_types.h>
35 #undef BPF_PROG_TYPE
36 #undef BPF_MAP_TYPE
37 #undef BPF_LINK_TYPE
38 };
39 
40 /* bpf_check() is a static code analyzer that walks eBPF program
41  * instruction by instruction and updates register/stack state.
42  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43  *
44  * The first pass is depth-first-search to check that the program is a DAG.
45  * It rejects the following programs:
46  * - larger than BPF_MAXINSNS insns
47  * - if loop is present (detected via back-edge)
48  * - unreachable insns exist (shouldn't be a forest. program = one function)
49  * - out of bounds or malformed jumps
50  * The second pass is all possible path descent from the 1st insn.
51  * Since it's analyzing all paths through the program, the length of the
52  * analysis is limited to 64k insn, which may be hit even if total number of
53  * insn is less then 4K, but there are too many branches that change stack/regs.
54  * Number of 'branches to be analyzed' is limited to 1k
55  *
56  * On entry to each instruction, each register has a type, and the instruction
57  * changes the types of the registers depending on instruction semantics.
58  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59  * copied to R1.
60  *
61  * All registers are 64-bit.
62  * R0 - return register
63  * R1-R5 argument passing registers
64  * R6-R9 callee saved registers
65  * R10 - frame pointer read-only
66  *
67  * At the start of BPF program the register R1 contains a pointer to bpf_context
68  * and has type PTR_TO_CTX.
69  *
70  * Verifier tracks arithmetic operations on pointers in case:
71  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73  * 1st insn copies R10 (which has FRAME_PTR) type into R1
74  * and 2nd arithmetic instruction is pattern matched to recognize
75  * that it wants to construct a pointer to some element within stack.
76  * So after 2nd insn, the register R1 has type PTR_TO_STACK
77  * (and -20 constant is saved for further stack bounds checking).
78  * Meaning that this reg is a pointer to stack plus known immediate constant.
79  *
80  * Most of the time the registers have SCALAR_VALUE type, which
81  * means the register has some value, but it's not a valid pointer.
82  * (like pointer plus pointer becomes SCALAR_VALUE type)
83  *
84  * When verifier sees load or store instructions the type of base register
85  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86  * four pointer types recognized by check_mem_access() function.
87  *
88  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89  * and the range of [ptr, ptr + map's value_size) is accessible.
90  *
91  * registers used to pass values to function calls are checked against
92  * function argument constraints.
93  *
94  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95  * It means that the register type passed to this function must be
96  * PTR_TO_STACK and it will be used inside the function as
97  * 'pointer to map element key'
98  *
99  * For example the argument constraints for bpf_map_lookup_elem():
100  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101  *   .arg1_type = ARG_CONST_MAP_PTR,
102  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
103  *
104  * ret_type says that this function returns 'pointer to map elem value or null'
105  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106  * 2nd argument should be a pointer to stack, which will be used inside
107  * the helper function as a pointer to map element key.
108  *
109  * On the kernel side the helper function looks like:
110  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111  * {
112  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113  *    void *key = (void *) (unsigned long) r2;
114  *    void *value;
115  *
116  *    here kernel can access 'key' and 'map' pointers safely, knowing that
117  *    [key, key + map->key_size) bytes are valid and were initialized on
118  *    the stack of eBPF program.
119  * }
120  *
121  * Corresponding eBPF program may look like:
122  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
123  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
125  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126  * here verifier looks at prototype of map_lookup_elem() and sees:
127  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129  *
130  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132  * and were initialized prior to this call.
133  * If it's ok, then verifier allows this BPF_CALL insn and looks at
134  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
136  * returns either pointer to map value or NULL.
137  *
138  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139  * insn, the register holding that pointer in the true branch changes state to
140  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141  * branch. See check_cond_jmp_op().
142  *
143  * After the call R0 is set to return type of the function and registers R1-R5
144  * are set to NOT_INIT to indicate that they are no longer readable.
145  *
146  * The following reference types represent a potential reference to a kernel
147  * resource which, after first being allocated, must be checked and freed by
148  * the BPF program:
149  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150  *
151  * When the verifier sees a helper call return a reference type, it allocates a
152  * pointer id for the reference and stores it in the current function state.
153  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155  * passes through a NULL-check conditional. For the branch wherein the state is
156  * changed to CONST_IMM, the verifier releases the reference.
157  *
158  * For each helper function that allocates a reference, such as
159  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160  * bpf_sk_release(). When a reference type passes into the release function,
161  * the verifier also releases the reference. If any unchecked or unreleased
162  * reference remains at the end of the program, the verifier rejects it.
163  */
164 
165 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
166 struct bpf_verifier_stack_elem {
167 	/* verifer state is 'st'
168 	 * before processing instruction 'insn_idx'
169 	 * and after processing instruction 'prev_insn_idx'
170 	 */
171 	struct bpf_verifier_state st;
172 	int insn_idx;
173 	int prev_insn_idx;
174 	struct bpf_verifier_stack_elem *next;
175 	/* length of verifier log at the time this state was pushed on stack */
176 	u32 log_pos;
177 };
178 
179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
180 #define BPF_COMPLEXITY_LIMIT_STATES	64
181 
182 #define BPF_MAP_KEY_POISON	(1ULL << 63)
183 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
184 
185 #define BPF_MAP_PTR_UNPRIV	1UL
186 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
187 					  POISON_POINTER_DELTA))
188 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 
190 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
191 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
192 
193 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
194 {
195 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
196 }
197 
198 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
199 {
200 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
201 }
202 
203 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
204 			      const struct bpf_map *map, bool unpriv)
205 {
206 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
207 	unpriv |= bpf_map_ptr_unpriv(aux);
208 	aux->map_ptr_state = (unsigned long)map |
209 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
210 }
211 
212 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
213 {
214 	return aux->map_key_state & BPF_MAP_KEY_POISON;
215 }
216 
217 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
218 {
219 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
220 }
221 
222 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
223 {
224 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
225 }
226 
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
228 {
229 	bool poisoned = bpf_map_key_poisoned(aux);
230 
231 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
233 }
234 
235 static bool bpf_pseudo_call(const struct bpf_insn *insn)
236 {
237 	return insn->code == (BPF_JMP | BPF_CALL) &&
238 	       insn->src_reg == BPF_PSEUDO_CALL;
239 }
240 
241 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
242 {
243 	return insn->code == (BPF_JMP | BPF_CALL) &&
244 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
245 }
246 
247 struct bpf_call_arg_meta {
248 	struct bpf_map *map_ptr;
249 	bool raw_mode;
250 	bool pkt_access;
251 	u8 release_regno;
252 	int regno;
253 	int access_size;
254 	int mem_size;
255 	u64 msize_max_value;
256 	int ref_obj_id;
257 	int map_uid;
258 	int func_id;
259 	struct btf *btf;
260 	u32 btf_id;
261 	struct btf *ret_btf;
262 	u32 ret_btf_id;
263 	u32 subprogno;
264 	struct bpf_map_value_off_desc *kptr_off_desc;
265 	u8 uninit_dynptr_regno;
266 };
267 
268 struct btf *btf_vmlinux;
269 
270 static DEFINE_MUTEX(bpf_verifier_lock);
271 
272 static const struct bpf_line_info *
273 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
274 {
275 	const struct bpf_line_info *linfo;
276 	const struct bpf_prog *prog;
277 	u32 i, nr_linfo;
278 
279 	prog = env->prog;
280 	nr_linfo = prog->aux->nr_linfo;
281 
282 	if (!nr_linfo || insn_off >= prog->len)
283 		return NULL;
284 
285 	linfo = prog->aux->linfo;
286 	for (i = 1; i < nr_linfo; i++)
287 		if (insn_off < linfo[i].insn_off)
288 			break;
289 
290 	return &linfo[i - 1];
291 }
292 
293 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
294 		       va_list args)
295 {
296 	unsigned int n;
297 
298 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
299 
300 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
301 		  "verifier log line truncated - local buffer too short\n");
302 
303 	if (log->level == BPF_LOG_KERNEL) {
304 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
305 
306 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
307 		return;
308 	}
309 
310 	n = min(log->len_total - log->len_used - 1, n);
311 	log->kbuf[n] = '\0';
312 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
313 		log->len_used += n;
314 	else
315 		log->ubuf = NULL;
316 }
317 
318 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
319 {
320 	char zero = 0;
321 
322 	if (!bpf_verifier_log_needed(log))
323 		return;
324 
325 	log->len_used = new_pos;
326 	if (put_user(zero, log->ubuf + new_pos))
327 		log->ubuf = NULL;
328 }
329 
330 /* log_level controls verbosity level of eBPF verifier.
331  * bpf_verifier_log_write() is used to dump the verification trace to the log,
332  * so the user can figure out what's wrong with the program
333  */
334 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
335 					   const char *fmt, ...)
336 {
337 	va_list args;
338 
339 	if (!bpf_verifier_log_needed(&env->log))
340 		return;
341 
342 	va_start(args, fmt);
343 	bpf_verifier_vlog(&env->log, fmt, args);
344 	va_end(args);
345 }
346 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
347 
348 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
349 {
350 	struct bpf_verifier_env *env = private_data;
351 	va_list args;
352 
353 	if (!bpf_verifier_log_needed(&env->log))
354 		return;
355 
356 	va_start(args, fmt);
357 	bpf_verifier_vlog(&env->log, fmt, args);
358 	va_end(args);
359 }
360 
361 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
362 			    const char *fmt, ...)
363 {
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool reg_type_not_null(enum bpf_reg_type type)
444 {
445 	return type == PTR_TO_SOCKET ||
446 		type == PTR_TO_TCP_SOCK ||
447 		type == PTR_TO_MAP_VALUE ||
448 		type == PTR_TO_MAP_KEY ||
449 		type == PTR_TO_SOCK_COMMON;
450 }
451 
452 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
453 {
454 	return reg->type == PTR_TO_MAP_VALUE &&
455 		map_value_has_spin_lock(reg->map_ptr);
456 }
457 
458 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
459 {
460 	type = base_type(type);
461 	return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
462 		type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
463 }
464 
465 static bool type_is_rdonly_mem(u32 type)
466 {
467 	return type & MEM_RDONLY;
468 }
469 
470 static bool type_may_be_null(u32 type)
471 {
472 	return type & PTR_MAYBE_NULL;
473 }
474 
475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
513 					const struct bpf_map *map)
514 {
515 	int ref_obj_uses = 0;
516 
517 	if (is_ptr_cast_function(func_id))
518 		ref_obj_uses++;
519 	if (is_acquire_function(func_id, map))
520 		ref_obj_uses++;
521 	if (is_dynptr_ref_function(func_id))
522 		ref_obj_uses++;
523 
524 	return ref_obj_uses > 1;
525 }
526 
527 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
528 {
529 	return BPF_CLASS(insn->code) == BPF_STX &&
530 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
531 	       insn->imm == BPF_CMPXCHG;
532 }
533 
534 /* string representation of 'enum bpf_reg_type'
535  *
536  * Note that reg_type_str() can not appear more than once in a single verbose()
537  * statement.
538  */
539 static const char *reg_type_str(struct bpf_verifier_env *env,
540 				enum bpf_reg_type type)
541 {
542 	char postfix[16] = {0}, prefix[32] = {0};
543 	static const char * const str[] = {
544 		[NOT_INIT]		= "?",
545 		[SCALAR_VALUE]		= "scalar",
546 		[PTR_TO_CTX]		= "ctx",
547 		[CONST_PTR_TO_MAP]	= "map_ptr",
548 		[PTR_TO_MAP_VALUE]	= "map_value",
549 		[PTR_TO_STACK]		= "fp",
550 		[PTR_TO_PACKET]		= "pkt",
551 		[PTR_TO_PACKET_META]	= "pkt_meta",
552 		[PTR_TO_PACKET_END]	= "pkt_end",
553 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
554 		[PTR_TO_SOCKET]		= "sock",
555 		[PTR_TO_SOCK_COMMON]	= "sock_common",
556 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
557 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
558 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
559 		[PTR_TO_BTF_ID]		= "ptr_",
560 		[PTR_TO_MEM]		= "mem",
561 		[PTR_TO_BUF]		= "buf",
562 		[PTR_TO_FUNC]		= "func",
563 		[PTR_TO_MAP_KEY]	= "map_key",
564 	};
565 
566 	if (type & PTR_MAYBE_NULL) {
567 		if (base_type(type) == PTR_TO_BTF_ID)
568 			strncpy(postfix, "or_null_", 16);
569 		else
570 			strncpy(postfix, "_or_null", 16);
571 	}
572 
573 	if (type & MEM_RDONLY)
574 		strncpy(prefix, "rdonly_", 32);
575 	if (type & MEM_ALLOC)
576 		strncpy(prefix, "alloc_", 32);
577 	if (type & MEM_USER)
578 		strncpy(prefix, "user_", 32);
579 	if (type & MEM_PERCPU)
580 		strncpy(prefix, "percpu_", 32);
581 	if (type & PTR_UNTRUSTED)
582 		strncpy(prefix, "untrusted_", 32);
583 
584 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
585 		 prefix, str[base_type(type)], postfix);
586 	return env->type_str_buf;
587 }
588 
589 static char slot_type_char[] = {
590 	[STACK_INVALID]	= '?',
591 	[STACK_SPILL]	= 'r',
592 	[STACK_MISC]	= 'm',
593 	[STACK_ZERO]	= '0',
594 	[STACK_DYNPTR]	= 'd',
595 };
596 
597 static void print_liveness(struct bpf_verifier_env *env,
598 			   enum bpf_reg_liveness live)
599 {
600 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
601 	    verbose(env, "_");
602 	if (live & REG_LIVE_READ)
603 		verbose(env, "r");
604 	if (live & REG_LIVE_WRITTEN)
605 		verbose(env, "w");
606 	if (live & REG_LIVE_DONE)
607 		verbose(env, "D");
608 }
609 
610 static int get_spi(s32 off)
611 {
612 	return (-off - 1) / BPF_REG_SIZE;
613 }
614 
615 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
616 {
617 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
618 
619 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
620 	 * within [0, allocated_stack).
621 	 *
622 	 * Please note that the spi grows downwards. For example, a dynptr
623 	 * takes the size of two stack slots; the first slot will be at
624 	 * spi and the second slot will be at spi - 1.
625 	 */
626 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
627 }
628 
629 static struct bpf_func_state *func(struct bpf_verifier_env *env,
630 				   const struct bpf_reg_state *reg)
631 {
632 	struct bpf_verifier_state *cur = env->cur_state;
633 
634 	return cur->frame[reg->frameno];
635 }
636 
637 static const char *kernel_type_name(const struct btf* btf, u32 id)
638 {
639 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
640 }
641 
642 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
643 {
644 	env->scratched_regs |= 1U << regno;
645 }
646 
647 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
648 {
649 	env->scratched_stack_slots |= 1ULL << spi;
650 }
651 
652 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
653 {
654 	return (env->scratched_regs >> regno) & 1;
655 }
656 
657 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
658 {
659 	return (env->scratched_stack_slots >> regno) & 1;
660 }
661 
662 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
663 {
664 	return env->scratched_regs || env->scratched_stack_slots;
665 }
666 
667 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
668 {
669 	env->scratched_regs = 0U;
670 	env->scratched_stack_slots = 0ULL;
671 }
672 
673 /* Used for printing the entire verifier state. */
674 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
675 {
676 	env->scratched_regs = ~0U;
677 	env->scratched_stack_slots = ~0ULL;
678 }
679 
680 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
681 {
682 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
683 	case DYNPTR_TYPE_LOCAL:
684 		return BPF_DYNPTR_TYPE_LOCAL;
685 	case DYNPTR_TYPE_RINGBUF:
686 		return BPF_DYNPTR_TYPE_RINGBUF;
687 	default:
688 		return BPF_DYNPTR_TYPE_INVALID;
689 	}
690 }
691 
692 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
693 {
694 	return type == BPF_DYNPTR_TYPE_RINGBUF;
695 }
696 
697 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
698 				   enum bpf_arg_type arg_type, int insn_idx)
699 {
700 	struct bpf_func_state *state = func(env, reg);
701 	enum bpf_dynptr_type type;
702 	int spi, i, id;
703 
704 	spi = get_spi(reg->off);
705 
706 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
707 		return -EINVAL;
708 
709 	for (i = 0; i < BPF_REG_SIZE; i++) {
710 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
711 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
712 	}
713 
714 	type = arg_to_dynptr_type(arg_type);
715 	if (type == BPF_DYNPTR_TYPE_INVALID)
716 		return -EINVAL;
717 
718 	state->stack[spi].spilled_ptr.dynptr.first_slot = true;
719 	state->stack[spi].spilled_ptr.dynptr.type = type;
720 	state->stack[spi - 1].spilled_ptr.dynptr.type = type;
721 
722 	if (dynptr_type_refcounted(type)) {
723 		/* The id is used to track proper releasing */
724 		id = acquire_reference_state(env, insn_idx);
725 		if (id < 0)
726 			return id;
727 
728 		state->stack[spi].spilled_ptr.id = id;
729 		state->stack[spi - 1].spilled_ptr.id = id;
730 	}
731 
732 	return 0;
733 }
734 
735 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
736 {
737 	struct bpf_func_state *state = func(env, reg);
738 	int spi, i;
739 
740 	spi = get_spi(reg->off);
741 
742 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
743 		return -EINVAL;
744 
745 	for (i = 0; i < BPF_REG_SIZE; i++) {
746 		state->stack[spi].slot_type[i] = STACK_INVALID;
747 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
748 	}
749 
750 	/* Invalidate any slices associated with this dynptr */
751 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
752 		release_reference(env, state->stack[spi].spilled_ptr.id);
753 		state->stack[spi].spilled_ptr.id = 0;
754 		state->stack[spi - 1].spilled_ptr.id = 0;
755 	}
756 
757 	state->stack[spi].spilled_ptr.dynptr.first_slot = false;
758 	state->stack[spi].spilled_ptr.dynptr.type = 0;
759 	state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
760 
761 	return 0;
762 }
763 
764 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
765 {
766 	struct bpf_func_state *state = func(env, reg);
767 	int spi = get_spi(reg->off);
768 	int i;
769 
770 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
771 		return true;
772 
773 	for (i = 0; i < BPF_REG_SIZE; i++) {
774 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
775 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
776 			return false;
777 	}
778 
779 	return true;
780 }
781 
782 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
783 				     enum bpf_arg_type arg_type)
784 {
785 	struct bpf_func_state *state = func(env, reg);
786 	int spi = get_spi(reg->off);
787 	int i;
788 
789 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
790 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
791 		return false;
792 
793 	for (i = 0; i < BPF_REG_SIZE; i++) {
794 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
795 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
796 			return false;
797 	}
798 
799 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
800 	if (arg_type == ARG_PTR_TO_DYNPTR)
801 		return true;
802 
803 	return state->stack[spi].spilled_ptr.dynptr.type == arg_to_dynptr_type(arg_type);
804 }
805 
806 /* The reg state of a pointer or a bounded scalar was saved when
807  * it was spilled to the stack.
808  */
809 static bool is_spilled_reg(const struct bpf_stack_state *stack)
810 {
811 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
812 }
813 
814 static void scrub_spilled_slot(u8 *stype)
815 {
816 	if (*stype != STACK_INVALID)
817 		*stype = STACK_MISC;
818 }
819 
820 static void print_verifier_state(struct bpf_verifier_env *env,
821 				 const struct bpf_func_state *state,
822 				 bool print_all)
823 {
824 	const struct bpf_reg_state *reg;
825 	enum bpf_reg_type t;
826 	int i;
827 
828 	if (state->frameno)
829 		verbose(env, " frame%d:", state->frameno);
830 	for (i = 0; i < MAX_BPF_REG; i++) {
831 		reg = &state->regs[i];
832 		t = reg->type;
833 		if (t == NOT_INIT)
834 			continue;
835 		if (!print_all && !reg_scratched(env, i))
836 			continue;
837 		verbose(env, " R%d", i);
838 		print_liveness(env, reg->live);
839 		verbose(env, "=");
840 		if (t == SCALAR_VALUE && reg->precise)
841 			verbose(env, "P");
842 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
843 		    tnum_is_const(reg->var_off)) {
844 			/* reg->off should be 0 for SCALAR_VALUE */
845 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
846 			verbose(env, "%lld", reg->var_off.value + reg->off);
847 		} else {
848 			const char *sep = "";
849 
850 			verbose(env, "%s", reg_type_str(env, t));
851 			if (base_type(t) == PTR_TO_BTF_ID)
852 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
853 			verbose(env, "(");
854 /*
855  * _a stands for append, was shortened to avoid multiline statements below.
856  * This macro is used to output a comma separated list of attributes.
857  */
858 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
859 
860 			if (reg->id)
861 				verbose_a("id=%d", reg->id);
862 			if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
863 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
864 			if (t != SCALAR_VALUE)
865 				verbose_a("off=%d", reg->off);
866 			if (type_is_pkt_pointer(t))
867 				verbose_a("r=%d", reg->range);
868 			else if (base_type(t) == CONST_PTR_TO_MAP ||
869 				 base_type(t) == PTR_TO_MAP_KEY ||
870 				 base_type(t) == PTR_TO_MAP_VALUE)
871 				verbose_a("ks=%d,vs=%d",
872 					  reg->map_ptr->key_size,
873 					  reg->map_ptr->value_size);
874 			if (tnum_is_const(reg->var_off)) {
875 				/* Typically an immediate SCALAR_VALUE, but
876 				 * could be a pointer whose offset is too big
877 				 * for reg->off
878 				 */
879 				verbose_a("imm=%llx", reg->var_off.value);
880 			} else {
881 				if (reg->smin_value != reg->umin_value &&
882 				    reg->smin_value != S64_MIN)
883 					verbose_a("smin=%lld", (long long)reg->smin_value);
884 				if (reg->smax_value != reg->umax_value &&
885 				    reg->smax_value != S64_MAX)
886 					verbose_a("smax=%lld", (long long)reg->smax_value);
887 				if (reg->umin_value != 0)
888 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
889 				if (reg->umax_value != U64_MAX)
890 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
891 				if (!tnum_is_unknown(reg->var_off)) {
892 					char tn_buf[48];
893 
894 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
895 					verbose_a("var_off=%s", tn_buf);
896 				}
897 				if (reg->s32_min_value != reg->smin_value &&
898 				    reg->s32_min_value != S32_MIN)
899 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
900 				if (reg->s32_max_value != reg->smax_value &&
901 				    reg->s32_max_value != S32_MAX)
902 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
903 				if (reg->u32_min_value != reg->umin_value &&
904 				    reg->u32_min_value != U32_MIN)
905 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
906 				if (reg->u32_max_value != reg->umax_value &&
907 				    reg->u32_max_value != U32_MAX)
908 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
909 			}
910 #undef verbose_a
911 
912 			verbose(env, ")");
913 		}
914 	}
915 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
916 		char types_buf[BPF_REG_SIZE + 1];
917 		bool valid = false;
918 		int j;
919 
920 		for (j = 0; j < BPF_REG_SIZE; j++) {
921 			if (state->stack[i].slot_type[j] != STACK_INVALID)
922 				valid = true;
923 			types_buf[j] = slot_type_char[
924 					state->stack[i].slot_type[j]];
925 		}
926 		types_buf[BPF_REG_SIZE] = 0;
927 		if (!valid)
928 			continue;
929 		if (!print_all && !stack_slot_scratched(env, i))
930 			continue;
931 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
932 		print_liveness(env, state->stack[i].spilled_ptr.live);
933 		if (is_spilled_reg(&state->stack[i])) {
934 			reg = &state->stack[i].spilled_ptr;
935 			t = reg->type;
936 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
937 			if (t == SCALAR_VALUE && reg->precise)
938 				verbose(env, "P");
939 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
940 				verbose(env, "%lld", reg->var_off.value + reg->off);
941 		} else {
942 			verbose(env, "=%s", types_buf);
943 		}
944 	}
945 	if (state->acquired_refs && state->refs[0].id) {
946 		verbose(env, " refs=%d", state->refs[0].id);
947 		for (i = 1; i < state->acquired_refs; i++)
948 			if (state->refs[i].id)
949 				verbose(env, ",%d", state->refs[i].id);
950 	}
951 	if (state->in_callback_fn)
952 		verbose(env, " cb");
953 	if (state->in_async_callback_fn)
954 		verbose(env, " async_cb");
955 	verbose(env, "\n");
956 	mark_verifier_state_clean(env);
957 }
958 
959 static inline u32 vlog_alignment(u32 pos)
960 {
961 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
962 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
963 }
964 
965 static void print_insn_state(struct bpf_verifier_env *env,
966 			     const struct bpf_func_state *state)
967 {
968 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
969 		/* remove new line character */
970 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
971 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
972 	} else {
973 		verbose(env, "%d:", env->insn_idx);
974 	}
975 	print_verifier_state(env, state, false);
976 }
977 
978 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
979  * small to hold src. This is different from krealloc since we don't want to preserve
980  * the contents of dst.
981  *
982  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
983  * not be allocated.
984  */
985 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
986 {
987 	size_t bytes;
988 
989 	if (ZERO_OR_NULL_PTR(src))
990 		goto out;
991 
992 	if (unlikely(check_mul_overflow(n, size, &bytes)))
993 		return NULL;
994 
995 	if (ksize(dst) < bytes) {
996 		kfree(dst);
997 		dst = kmalloc_track_caller(bytes, flags);
998 		if (!dst)
999 			return NULL;
1000 	}
1001 
1002 	memcpy(dst, src, bytes);
1003 out:
1004 	return dst ? dst : ZERO_SIZE_PTR;
1005 }
1006 
1007 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1008  * small to hold new_n items. new items are zeroed out if the array grows.
1009  *
1010  * Contrary to krealloc_array, does not free arr if new_n is zero.
1011  */
1012 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1013 {
1014 	if (!new_n || old_n == new_n)
1015 		goto out;
1016 
1017 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1018 	if (!arr)
1019 		return NULL;
1020 
1021 	if (new_n > old_n)
1022 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1023 
1024 out:
1025 	return arr ? arr : ZERO_SIZE_PTR;
1026 }
1027 
1028 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1029 {
1030 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1031 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1032 	if (!dst->refs)
1033 		return -ENOMEM;
1034 
1035 	dst->acquired_refs = src->acquired_refs;
1036 	return 0;
1037 }
1038 
1039 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1040 {
1041 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1042 
1043 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1044 				GFP_KERNEL);
1045 	if (!dst->stack)
1046 		return -ENOMEM;
1047 
1048 	dst->allocated_stack = src->allocated_stack;
1049 	return 0;
1050 }
1051 
1052 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1053 {
1054 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1055 				    sizeof(struct bpf_reference_state));
1056 	if (!state->refs)
1057 		return -ENOMEM;
1058 
1059 	state->acquired_refs = n;
1060 	return 0;
1061 }
1062 
1063 static int grow_stack_state(struct bpf_func_state *state, int size)
1064 {
1065 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1066 
1067 	if (old_n >= n)
1068 		return 0;
1069 
1070 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1071 	if (!state->stack)
1072 		return -ENOMEM;
1073 
1074 	state->allocated_stack = size;
1075 	return 0;
1076 }
1077 
1078 /* Acquire a pointer id from the env and update the state->refs to include
1079  * this new pointer reference.
1080  * On success, returns a valid pointer id to associate with the register
1081  * On failure, returns a negative errno.
1082  */
1083 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1084 {
1085 	struct bpf_func_state *state = cur_func(env);
1086 	int new_ofs = state->acquired_refs;
1087 	int id, err;
1088 
1089 	err = resize_reference_state(state, state->acquired_refs + 1);
1090 	if (err)
1091 		return err;
1092 	id = ++env->id_gen;
1093 	state->refs[new_ofs].id = id;
1094 	state->refs[new_ofs].insn_idx = insn_idx;
1095 
1096 	return id;
1097 }
1098 
1099 /* release function corresponding to acquire_reference_state(). Idempotent. */
1100 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1101 {
1102 	int i, last_idx;
1103 
1104 	last_idx = state->acquired_refs - 1;
1105 	for (i = 0; i < state->acquired_refs; i++) {
1106 		if (state->refs[i].id == ptr_id) {
1107 			if (last_idx && i != last_idx)
1108 				memcpy(&state->refs[i], &state->refs[last_idx],
1109 				       sizeof(*state->refs));
1110 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1111 			state->acquired_refs--;
1112 			return 0;
1113 		}
1114 	}
1115 	return -EINVAL;
1116 }
1117 
1118 static void free_func_state(struct bpf_func_state *state)
1119 {
1120 	if (!state)
1121 		return;
1122 	kfree(state->refs);
1123 	kfree(state->stack);
1124 	kfree(state);
1125 }
1126 
1127 static void clear_jmp_history(struct bpf_verifier_state *state)
1128 {
1129 	kfree(state->jmp_history);
1130 	state->jmp_history = NULL;
1131 	state->jmp_history_cnt = 0;
1132 }
1133 
1134 static void free_verifier_state(struct bpf_verifier_state *state,
1135 				bool free_self)
1136 {
1137 	int i;
1138 
1139 	for (i = 0; i <= state->curframe; i++) {
1140 		free_func_state(state->frame[i]);
1141 		state->frame[i] = NULL;
1142 	}
1143 	clear_jmp_history(state);
1144 	if (free_self)
1145 		kfree(state);
1146 }
1147 
1148 /* copy verifier state from src to dst growing dst stack space
1149  * when necessary to accommodate larger src stack
1150  */
1151 static int copy_func_state(struct bpf_func_state *dst,
1152 			   const struct bpf_func_state *src)
1153 {
1154 	int err;
1155 
1156 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1157 	err = copy_reference_state(dst, src);
1158 	if (err)
1159 		return err;
1160 	return copy_stack_state(dst, src);
1161 }
1162 
1163 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1164 			       const struct bpf_verifier_state *src)
1165 {
1166 	struct bpf_func_state *dst;
1167 	int i, err;
1168 
1169 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1170 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1171 					    GFP_USER);
1172 	if (!dst_state->jmp_history)
1173 		return -ENOMEM;
1174 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1175 
1176 	/* if dst has more stack frames then src frame, free them */
1177 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1178 		free_func_state(dst_state->frame[i]);
1179 		dst_state->frame[i] = NULL;
1180 	}
1181 	dst_state->speculative = src->speculative;
1182 	dst_state->curframe = src->curframe;
1183 	dst_state->active_spin_lock = src->active_spin_lock;
1184 	dst_state->branches = src->branches;
1185 	dst_state->parent = src->parent;
1186 	dst_state->first_insn_idx = src->first_insn_idx;
1187 	dst_state->last_insn_idx = src->last_insn_idx;
1188 	for (i = 0; i <= src->curframe; i++) {
1189 		dst = dst_state->frame[i];
1190 		if (!dst) {
1191 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1192 			if (!dst)
1193 				return -ENOMEM;
1194 			dst_state->frame[i] = dst;
1195 		}
1196 		err = copy_func_state(dst, src->frame[i]);
1197 		if (err)
1198 			return err;
1199 	}
1200 	return 0;
1201 }
1202 
1203 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1204 {
1205 	while (st) {
1206 		u32 br = --st->branches;
1207 
1208 		/* WARN_ON(br > 1) technically makes sense here,
1209 		 * but see comment in push_stack(), hence:
1210 		 */
1211 		WARN_ONCE((int)br < 0,
1212 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1213 			  br);
1214 		if (br)
1215 			break;
1216 		st = st->parent;
1217 	}
1218 }
1219 
1220 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1221 		     int *insn_idx, bool pop_log)
1222 {
1223 	struct bpf_verifier_state *cur = env->cur_state;
1224 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1225 	int err;
1226 
1227 	if (env->head == NULL)
1228 		return -ENOENT;
1229 
1230 	if (cur) {
1231 		err = copy_verifier_state(cur, &head->st);
1232 		if (err)
1233 			return err;
1234 	}
1235 	if (pop_log)
1236 		bpf_vlog_reset(&env->log, head->log_pos);
1237 	if (insn_idx)
1238 		*insn_idx = head->insn_idx;
1239 	if (prev_insn_idx)
1240 		*prev_insn_idx = head->prev_insn_idx;
1241 	elem = head->next;
1242 	free_verifier_state(&head->st, false);
1243 	kfree(head);
1244 	env->head = elem;
1245 	env->stack_size--;
1246 	return 0;
1247 }
1248 
1249 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1250 					     int insn_idx, int prev_insn_idx,
1251 					     bool speculative)
1252 {
1253 	struct bpf_verifier_state *cur = env->cur_state;
1254 	struct bpf_verifier_stack_elem *elem;
1255 	int err;
1256 
1257 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1258 	if (!elem)
1259 		goto err;
1260 
1261 	elem->insn_idx = insn_idx;
1262 	elem->prev_insn_idx = prev_insn_idx;
1263 	elem->next = env->head;
1264 	elem->log_pos = env->log.len_used;
1265 	env->head = elem;
1266 	env->stack_size++;
1267 	err = copy_verifier_state(&elem->st, cur);
1268 	if (err)
1269 		goto err;
1270 	elem->st.speculative |= speculative;
1271 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1272 		verbose(env, "The sequence of %d jumps is too complex.\n",
1273 			env->stack_size);
1274 		goto err;
1275 	}
1276 	if (elem->st.parent) {
1277 		++elem->st.parent->branches;
1278 		/* WARN_ON(branches > 2) technically makes sense here,
1279 		 * but
1280 		 * 1. speculative states will bump 'branches' for non-branch
1281 		 * instructions
1282 		 * 2. is_state_visited() heuristics may decide not to create
1283 		 * a new state for a sequence of branches and all such current
1284 		 * and cloned states will be pointing to a single parent state
1285 		 * which might have large 'branches' count.
1286 		 */
1287 	}
1288 	return &elem->st;
1289 err:
1290 	free_verifier_state(env->cur_state, true);
1291 	env->cur_state = NULL;
1292 	/* pop all elements and return */
1293 	while (!pop_stack(env, NULL, NULL, false));
1294 	return NULL;
1295 }
1296 
1297 #define CALLER_SAVED_REGS 6
1298 static const int caller_saved[CALLER_SAVED_REGS] = {
1299 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1300 };
1301 
1302 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1303 				struct bpf_reg_state *reg);
1304 
1305 /* This helper doesn't clear reg->id */
1306 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1307 {
1308 	reg->var_off = tnum_const(imm);
1309 	reg->smin_value = (s64)imm;
1310 	reg->smax_value = (s64)imm;
1311 	reg->umin_value = imm;
1312 	reg->umax_value = imm;
1313 
1314 	reg->s32_min_value = (s32)imm;
1315 	reg->s32_max_value = (s32)imm;
1316 	reg->u32_min_value = (u32)imm;
1317 	reg->u32_max_value = (u32)imm;
1318 }
1319 
1320 /* Mark the unknown part of a register (variable offset or scalar value) as
1321  * known to have the value @imm.
1322  */
1323 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1324 {
1325 	/* Clear id, off, and union(map_ptr, range) */
1326 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1327 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1328 	___mark_reg_known(reg, imm);
1329 }
1330 
1331 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1332 {
1333 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1334 	reg->s32_min_value = (s32)imm;
1335 	reg->s32_max_value = (s32)imm;
1336 	reg->u32_min_value = (u32)imm;
1337 	reg->u32_max_value = (u32)imm;
1338 }
1339 
1340 /* Mark the 'variable offset' part of a register as zero.  This should be
1341  * used only on registers holding a pointer type.
1342  */
1343 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1344 {
1345 	__mark_reg_known(reg, 0);
1346 }
1347 
1348 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1349 {
1350 	__mark_reg_known(reg, 0);
1351 	reg->type = SCALAR_VALUE;
1352 }
1353 
1354 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1355 				struct bpf_reg_state *regs, u32 regno)
1356 {
1357 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1358 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1359 		/* Something bad happened, let's kill all regs */
1360 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1361 			__mark_reg_not_init(env, regs + regno);
1362 		return;
1363 	}
1364 	__mark_reg_known_zero(regs + regno);
1365 }
1366 
1367 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1368 {
1369 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1370 		const struct bpf_map *map = reg->map_ptr;
1371 
1372 		if (map->inner_map_meta) {
1373 			reg->type = CONST_PTR_TO_MAP;
1374 			reg->map_ptr = map->inner_map_meta;
1375 			/* transfer reg's id which is unique for every map_lookup_elem
1376 			 * as UID of the inner map.
1377 			 */
1378 			if (map_value_has_timer(map->inner_map_meta))
1379 				reg->map_uid = reg->id;
1380 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1381 			reg->type = PTR_TO_XDP_SOCK;
1382 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1383 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1384 			reg->type = PTR_TO_SOCKET;
1385 		} else {
1386 			reg->type = PTR_TO_MAP_VALUE;
1387 		}
1388 		return;
1389 	}
1390 
1391 	reg->type &= ~PTR_MAYBE_NULL;
1392 }
1393 
1394 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1395 {
1396 	return type_is_pkt_pointer(reg->type);
1397 }
1398 
1399 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1400 {
1401 	return reg_is_pkt_pointer(reg) ||
1402 	       reg->type == PTR_TO_PACKET_END;
1403 }
1404 
1405 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1406 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1407 				    enum bpf_reg_type which)
1408 {
1409 	/* The register can already have a range from prior markings.
1410 	 * This is fine as long as it hasn't been advanced from its
1411 	 * origin.
1412 	 */
1413 	return reg->type == which &&
1414 	       reg->id == 0 &&
1415 	       reg->off == 0 &&
1416 	       tnum_equals_const(reg->var_off, 0);
1417 }
1418 
1419 /* Reset the min/max bounds of a register */
1420 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1421 {
1422 	reg->smin_value = S64_MIN;
1423 	reg->smax_value = S64_MAX;
1424 	reg->umin_value = 0;
1425 	reg->umax_value = U64_MAX;
1426 
1427 	reg->s32_min_value = S32_MIN;
1428 	reg->s32_max_value = S32_MAX;
1429 	reg->u32_min_value = 0;
1430 	reg->u32_max_value = U32_MAX;
1431 }
1432 
1433 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1434 {
1435 	reg->smin_value = S64_MIN;
1436 	reg->smax_value = S64_MAX;
1437 	reg->umin_value = 0;
1438 	reg->umax_value = U64_MAX;
1439 }
1440 
1441 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1442 {
1443 	reg->s32_min_value = S32_MIN;
1444 	reg->s32_max_value = S32_MAX;
1445 	reg->u32_min_value = 0;
1446 	reg->u32_max_value = U32_MAX;
1447 }
1448 
1449 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1450 {
1451 	struct tnum var32_off = tnum_subreg(reg->var_off);
1452 
1453 	/* min signed is max(sign bit) | min(other bits) */
1454 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1455 			var32_off.value | (var32_off.mask & S32_MIN));
1456 	/* max signed is min(sign bit) | max(other bits) */
1457 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1458 			var32_off.value | (var32_off.mask & S32_MAX));
1459 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1460 	reg->u32_max_value = min(reg->u32_max_value,
1461 				 (u32)(var32_off.value | var32_off.mask));
1462 }
1463 
1464 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1465 {
1466 	/* min signed is max(sign bit) | min(other bits) */
1467 	reg->smin_value = max_t(s64, reg->smin_value,
1468 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1469 	/* max signed is min(sign bit) | max(other bits) */
1470 	reg->smax_value = min_t(s64, reg->smax_value,
1471 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1472 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1473 	reg->umax_value = min(reg->umax_value,
1474 			      reg->var_off.value | reg->var_off.mask);
1475 }
1476 
1477 static void __update_reg_bounds(struct bpf_reg_state *reg)
1478 {
1479 	__update_reg32_bounds(reg);
1480 	__update_reg64_bounds(reg);
1481 }
1482 
1483 /* Uses signed min/max values to inform unsigned, and vice-versa */
1484 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1485 {
1486 	/* Learn sign from signed bounds.
1487 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1488 	 * are the same, so combine.  This works even in the negative case, e.g.
1489 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1490 	 */
1491 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1492 		reg->s32_min_value = reg->u32_min_value =
1493 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1494 		reg->s32_max_value = reg->u32_max_value =
1495 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1496 		return;
1497 	}
1498 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1499 	 * boundary, so we must be careful.
1500 	 */
1501 	if ((s32)reg->u32_max_value >= 0) {
1502 		/* Positive.  We can't learn anything from the smin, but smax
1503 		 * is positive, hence safe.
1504 		 */
1505 		reg->s32_min_value = reg->u32_min_value;
1506 		reg->s32_max_value = reg->u32_max_value =
1507 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1508 	} else if ((s32)reg->u32_min_value < 0) {
1509 		/* Negative.  We can't learn anything from the smax, but smin
1510 		 * is negative, hence safe.
1511 		 */
1512 		reg->s32_min_value = reg->u32_min_value =
1513 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1514 		reg->s32_max_value = reg->u32_max_value;
1515 	}
1516 }
1517 
1518 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1519 {
1520 	/* Learn sign from signed bounds.
1521 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1522 	 * are the same, so combine.  This works even in the negative case, e.g.
1523 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1524 	 */
1525 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1526 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1527 							  reg->umin_value);
1528 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1529 							  reg->umax_value);
1530 		return;
1531 	}
1532 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1533 	 * boundary, so we must be careful.
1534 	 */
1535 	if ((s64)reg->umax_value >= 0) {
1536 		/* Positive.  We can't learn anything from the smin, but smax
1537 		 * is positive, hence safe.
1538 		 */
1539 		reg->smin_value = reg->umin_value;
1540 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1541 							  reg->umax_value);
1542 	} else if ((s64)reg->umin_value < 0) {
1543 		/* Negative.  We can't learn anything from the smax, but smin
1544 		 * is negative, hence safe.
1545 		 */
1546 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1547 							  reg->umin_value);
1548 		reg->smax_value = reg->umax_value;
1549 	}
1550 }
1551 
1552 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1553 {
1554 	__reg32_deduce_bounds(reg);
1555 	__reg64_deduce_bounds(reg);
1556 }
1557 
1558 /* Attempts to improve var_off based on unsigned min/max information */
1559 static void __reg_bound_offset(struct bpf_reg_state *reg)
1560 {
1561 	struct tnum var64_off = tnum_intersect(reg->var_off,
1562 					       tnum_range(reg->umin_value,
1563 							  reg->umax_value));
1564 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1565 						tnum_range(reg->u32_min_value,
1566 							   reg->u32_max_value));
1567 
1568 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1569 }
1570 
1571 static void reg_bounds_sync(struct bpf_reg_state *reg)
1572 {
1573 	/* We might have learned new bounds from the var_off. */
1574 	__update_reg_bounds(reg);
1575 	/* We might have learned something about the sign bit. */
1576 	__reg_deduce_bounds(reg);
1577 	/* We might have learned some bits from the bounds. */
1578 	__reg_bound_offset(reg);
1579 	/* Intersecting with the old var_off might have improved our bounds
1580 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1581 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1582 	 */
1583 	__update_reg_bounds(reg);
1584 }
1585 
1586 static bool __reg32_bound_s64(s32 a)
1587 {
1588 	return a >= 0 && a <= S32_MAX;
1589 }
1590 
1591 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1592 {
1593 	reg->umin_value = reg->u32_min_value;
1594 	reg->umax_value = reg->u32_max_value;
1595 
1596 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1597 	 * be positive otherwise set to worse case bounds and refine later
1598 	 * from tnum.
1599 	 */
1600 	if (__reg32_bound_s64(reg->s32_min_value) &&
1601 	    __reg32_bound_s64(reg->s32_max_value)) {
1602 		reg->smin_value = reg->s32_min_value;
1603 		reg->smax_value = reg->s32_max_value;
1604 	} else {
1605 		reg->smin_value = 0;
1606 		reg->smax_value = U32_MAX;
1607 	}
1608 }
1609 
1610 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1611 {
1612 	/* special case when 64-bit register has upper 32-bit register
1613 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1614 	 * allowing us to use 32-bit bounds directly,
1615 	 */
1616 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1617 		__reg_assign_32_into_64(reg);
1618 	} else {
1619 		/* Otherwise the best we can do is push lower 32bit known and
1620 		 * unknown bits into register (var_off set from jmp logic)
1621 		 * then learn as much as possible from the 64-bit tnum
1622 		 * known and unknown bits. The previous smin/smax bounds are
1623 		 * invalid here because of jmp32 compare so mark them unknown
1624 		 * so they do not impact tnum bounds calculation.
1625 		 */
1626 		__mark_reg64_unbounded(reg);
1627 	}
1628 	reg_bounds_sync(reg);
1629 }
1630 
1631 static bool __reg64_bound_s32(s64 a)
1632 {
1633 	return a >= S32_MIN && a <= S32_MAX;
1634 }
1635 
1636 static bool __reg64_bound_u32(u64 a)
1637 {
1638 	return a >= U32_MIN && a <= U32_MAX;
1639 }
1640 
1641 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1642 {
1643 	__mark_reg32_unbounded(reg);
1644 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1645 		reg->s32_min_value = (s32)reg->smin_value;
1646 		reg->s32_max_value = (s32)reg->smax_value;
1647 	}
1648 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1649 		reg->u32_min_value = (u32)reg->umin_value;
1650 		reg->u32_max_value = (u32)reg->umax_value;
1651 	}
1652 	reg_bounds_sync(reg);
1653 }
1654 
1655 /* Mark a register as having a completely unknown (scalar) value. */
1656 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1657 			       struct bpf_reg_state *reg)
1658 {
1659 	/*
1660 	 * Clear type, id, off, and union(map_ptr, range) and
1661 	 * padding between 'type' and union
1662 	 */
1663 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1664 	reg->type = SCALAR_VALUE;
1665 	reg->var_off = tnum_unknown;
1666 	reg->frameno = 0;
1667 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1668 	__mark_reg_unbounded(reg);
1669 }
1670 
1671 static void mark_reg_unknown(struct bpf_verifier_env *env,
1672 			     struct bpf_reg_state *regs, u32 regno)
1673 {
1674 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1675 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1676 		/* Something bad happened, let's kill all regs except FP */
1677 		for (regno = 0; regno < BPF_REG_FP; regno++)
1678 			__mark_reg_not_init(env, regs + regno);
1679 		return;
1680 	}
1681 	__mark_reg_unknown(env, regs + regno);
1682 }
1683 
1684 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1685 				struct bpf_reg_state *reg)
1686 {
1687 	__mark_reg_unknown(env, reg);
1688 	reg->type = NOT_INIT;
1689 }
1690 
1691 static void mark_reg_not_init(struct bpf_verifier_env *env,
1692 			      struct bpf_reg_state *regs, u32 regno)
1693 {
1694 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1695 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1696 		/* Something bad happened, let's kill all regs except FP */
1697 		for (regno = 0; regno < BPF_REG_FP; regno++)
1698 			__mark_reg_not_init(env, regs + regno);
1699 		return;
1700 	}
1701 	__mark_reg_not_init(env, regs + regno);
1702 }
1703 
1704 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1705 			    struct bpf_reg_state *regs, u32 regno,
1706 			    enum bpf_reg_type reg_type,
1707 			    struct btf *btf, u32 btf_id,
1708 			    enum bpf_type_flag flag)
1709 {
1710 	if (reg_type == SCALAR_VALUE) {
1711 		mark_reg_unknown(env, regs, regno);
1712 		return;
1713 	}
1714 	mark_reg_known_zero(env, regs, regno);
1715 	regs[regno].type = PTR_TO_BTF_ID | flag;
1716 	regs[regno].btf = btf;
1717 	regs[regno].btf_id = btf_id;
1718 }
1719 
1720 #define DEF_NOT_SUBREG	(0)
1721 static void init_reg_state(struct bpf_verifier_env *env,
1722 			   struct bpf_func_state *state)
1723 {
1724 	struct bpf_reg_state *regs = state->regs;
1725 	int i;
1726 
1727 	for (i = 0; i < MAX_BPF_REG; i++) {
1728 		mark_reg_not_init(env, regs, i);
1729 		regs[i].live = REG_LIVE_NONE;
1730 		regs[i].parent = NULL;
1731 		regs[i].subreg_def = DEF_NOT_SUBREG;
1732 	}
1733 
1734 	/* frame pointer */
1735 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1736 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1737 	regs[BPF_REG_FP].frameno = state->frameno;
1738 }
1739 
1740 #define BPF_MAIN_FUNC (-1)
1741 static void init_func_state(struct bpf_verifier_env *env,
1742 			    struct bpf_func_state *state,
1743 			    int callsite, int frameno, int subprogno)
1744 {
1745 	state->callsite = callsite;
1746 	state->frameno = frameno;
1747 	state->subprogno = subprogno;
1748 	init_reg_state(env, state);
1749 	mark_verifier_state_scratched(env);
1750 }
1751 
1752 /* Similar to push_stack(), but for async callbacks */
1753 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1754 						int insn_idx, int prev_insn_idx,
1755 						int subprog)
1756 {
1757 	struct bpf_verifier_stack_elem *elem;
1758 	struct bpf_func_state *frame;
1759 
1760 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1761 	if (!elem)
1762 		goto err;
1763 
1764 	elem->insn_idx = insn_idx;
1765 	elem->prev_insn_idx = prev_insn_idx;
1766 	elem->next = env->head;
1767 	elem->log_pos = env->log.len_used;
1768 	env->head = elem;
1769 	env->stack_size++;
1770 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1771 		verbose(env,
1772 			"The sequence of %d jumps is too complex for async cb.\n",
1773 			env->stack_size);
1774 		goto err;
1775 	}
1776 	/* Unlike push_stack() do not copy_verifier_state().
1777 	 * The caller state doesn't matter.
1778 	 * This is async callback. It starts in a fresh stack.
1779 	 * Initialize it similar to do_check_common().
1780 	 */
1781 	elem->st.branches = 1;
1782 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1783 	if (!frame)
1784 		goto err;
1785 	init_func_state(env, frame,
1786 			BPF_MAIN_FUNC /* callsite */,
1787 			0 /* frameno within this callchain */,
1788 			subprog /* subprog number within this prog */);
1789 	elem->st.frame[0] = frame;
1790 	return &elem->st;
1791 err:
1792 	free_verifier_state(env->cur_state, true);
1793 	env->cur_state = NULL;
1794 	/* pop all elements and return */
1795 	while (!pop_stack(env, NULL, NULL, false));
1796 	return NULL;
1797 }
1798 
1799 
1800 enum reg_arg_type {
1801 	SRC_OP,		/* register is used as source operand */
1802 	DST_OP,		/* register is used as destination operand */
1803 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1804 };
1805 
1806 static int cmp_subprogs(const void *a, const void *b)
1807 {
1808 	return ((struct bpf_subprog_info *)a)->start -
1809 	       ((struct bpf_subprog_info *)b)->start;
1810 }
1811 
1812 static int find_subprog(struct bpf_verifier_env *env, int off)
1813 {
1814 	struct bpf_subprog_info *p;
1815 
1816 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1817 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1818 	if (!p)
1819 		return -ENOENT;
1820 	return p - env->subprog_info;
1821 
1822 }
1823 
1824 static int add_subprog(struct bpf_verifier_env *env, int off)
1825 {
1826 	int insn_cnt = env->prog->len;
1827 	int ret;
1828 
1829 	if (off >= insn_cnt || off < 0) {
1830 		verbose(env, "call to invalid destination\n");
1831 		return -EINVAL;
1832 	}
1833 	ret = find_subprog(env, off);
1834 	if (ret >= 0)
1835 		return ret;
1836 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1837 		verbose(env, "too many subprograms\n");
1838 		return -E2BIG;
1839 	}
1840 	/* determine subprog starts. The end is one before the next starts */
1841 	env->subprog_info[env->subprog_cnt++].start = off;
1842 	sort(env->subprog_info, env->subprog_cnt,
1843 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1844 	return env->subprog_cnt - 1;
1845 }
1846 
1847 #define MAX_KFUNC_DESCS 256
1848 #define MAX_KFUNC_BTFS	256
1849 
1850 struct bpf_kfunc_desc {
1851 	struct btf_func_model func_model;
1852 	u32 func_id;
1853 	s32 imm;
1854 	u16 offset;
1855 };
1856 
1857 struct bpf_kfunc_btf {
1858 	struct btf *btf;
1859 	struct module *module;
1860 	u16 offset;
1861 };
1862 
1863 struct bpf_kfunc_desc_tab {
1864 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1865 	u32 nr_descs;
1866 };
1867 
1868 struct bpf_kfunc_btf_tab {
1869 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1870 	u32 nr_descs;
1871 };
1872 
1873 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1874 {
1875 	const struct bpf_kfunc_desc *d0 = a;
1876 	const struct bpf_kfunc_desc *d1 = b;
1877 
1878 	/* func_id is not greater than BTF_MAX_TYPE */
1879 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1880 }
1881 
1882 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1883 {
1884 	const struct bpf_kfunc_btf *d0 = a;
1885 	const struct bpf_kfunc_btf *d1 = b;
1886 
1887 	return d0->offset - d1->offset;
1888 }
1889 
1890 static const struct bpf_kfunc_desc *
1891 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1892 {
1893 	struct bpf_kfunc_desc desc = {
1894 		.func_id = func_id,
1895 		.offset = offset,
1896 	};
1897 	struct bpf_kfunc_desc_tab *tab;
1898 
1899 	tab = prog->aux->kfunc_tab;
1900 	return bsearch(&desc, tab->descs, tab->nr_descs,
1901 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1902 }
1903 
1904 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1905 					 s16 offset)
1906 {
1907 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1908 	struct bpf_kfunc_btf_tab *tab;
1909 	struct bpf_kfunc_btf *b;
1910 	struct module *mod;
1911 	struct btf *btf;
1912 	int btf_fd;
1913 
1914 	tab = env->prog->aux->kfunc_btf_tab;
1915 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1916 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1917 	if (!b) {
1918 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1919 			verbose(env, "too many different module BTFs\n");
1920 			return ERR_PTR(-E2BIG);
1921 		}
1922 
1923 		if (bpfptr_is_null(env->fd_array)) {
1924 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1925 			return ERR_PTR(-EPROTO);
1926 		}
1927 
1928 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1929 					    offset * sizeof(btf_fd),
1930 					    sizeof(btf_fd)))
1931 			return ERR_PTR(-EFAULT);
1932 
1933 		btf = btf_get_by_fd(btf_fd);
1934 		if (IS_ERR(btf)) {
1935 			verbose(env, "invalid module BTF fd specified\n");
1936 			return btf;
1937 		}
1938 
1939 		if (!btf_is_module(btf)) {
1940 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1941 			btf_put(btf);
1942 			return ERR_PTR(-EINVAL);
1943 		}
1944 
1945 		mod = btf_try_get_module(btf);
1946 		if (!mod) {
1947 			btf_put(btf);
1948 			return ERR_PTR(-ENXIO);
1949 		}
1950 
1951 		b = &tab->descs[tab->nr_descs++];
1952 		b->btf = btf;
1953 		b->module = mod;
1954 		b->offset = offset;
1955 
1956 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1957 		     kfunc_btf_cmp_by_off, NULL);
1958 	}
1959 	return b->btf;
1960 }
1961 
1962 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1963 {
1964 	if (!tab)
1965 		return;
1966 
1967 	while (tab->nr_descs--) {
1968 		module_put(tab->descs[tab->nr_descs].module);
1969 		btf_put(tab->descs[tab->nr_descs].btf);
1970 	}
1971 	kfree(tab);
1972 }
1973 
1974 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1975 {
1976 	if (offset) {
1977 		if (offset < 0) {
1978 			/* In the future, this can be allowed to increase limit
1979 			 * of fd index into fd_array, interpreted as u16.
1980 			 */
1981 			verbose(env, "negative offset disallowed for kernel module function call\n");
1982 			return ERR_PTR(-EINVAL);
1983 		}
1984 
1985 		return __find_kfunc_desc_btf(env, offset);
1986 	}
1987 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1988 }
1989 
1990 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1991 {
1992 	const struct btf_type *func, *func_proto;
1993 	struct bpf_kfunc_btf_tab *btf_tab;
1994 	struct bpf_kfunc_desc_tab *tab;
1995 	struct bpf_prog_aux *prog_aux;
1996 	struct bpf_kfunc_desc *desc;
1997 	const char *func_name;
1998 	struct btf *desc_btf;
1999 	unsigned long call_imm;
2000 	unsigned long addr;
2001 	int err;
2002 
2003 	prog_aux = env->prog->aux;
2004 	tab = prog_aux->kfunc_tab;
2005 	btf_tab = prog_aux->kfunc_btf_tab;
2006 	if (!tab) {
2007 		if (!btf_vmlinux) {
2008 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2009 			return -ENOTSUPP;
2010 		}
2011 
2012 		if (!env->prog->jit_requested) {
2013 			verbose(env, "JIT is required for calling kernel function\n");
2014 			return -ENOTSUPP;
2015 		}
2016 
2017 		if (!bpf_jit_supports_kfunc_call()) {
2018 			verbose(env, "JIT does not support calling kernel function\n");
2019 			return -ENOTSUPP;
2020 		}
2021 
2022 		if (!env->prog->gpl_compatible) {
2023 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2024 			return -EINVAL;
2025 		}
2026 
2027 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2028 		if (!tab)
2029 			return -ENOMEM;
2030 		prog_aux->kfunc_tab = tab;
2031 	}
2032 
2033 	/* func_id == 0 is always invalid, but instead of returning an error, be
2034 	 * conservative and wait until the code elimination pass before returning
2035 	 * error, so that invalid calls that get pruned out can be in BPF programs
2036 	 * loaded from userspace.  It is also required that offset be untouched
2037 	 * for such calls.
2038 	 */
2039 	if (!func_id && !offset)
2040 		return 0;
2041 
2042 	if (!btf_tab && offset) {
2043 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2044 		if (!btf_tab)
2045 			return -ENOMEM;
2046 		prog_aux->kfunc_btf_tab = btf_tab;
2047 	}
2048 
2049 	desc_btf = find_kfunc_desc_btf(env, offset);
2050 	if (IS_ERR(desc_btf)) {
2051 		verbose(env, "failed to find BTF for kernel function\n");
2052 		return PTR_ERR(desc_btf);
2053 	}
2054 
2055 	if (find_kfunc_desc(env->prog, func_id, offset))
2056 		return 0;
2057 
2058 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2059 		verbose(env, "too many different kernel function calls\n");
2060 		return -E2BIG;
2061 	}
2062 
2063 	func = btf_type_by_id(desc_btf, func_id);
2064 	if (!func || !btf_type_is_func(func)) {
2065 		verbose(env, "kernel btf_id %u is not a function\n",
2066 			func_id);
2067 		return -EINVAL;
2068 	}
2069 	func_proto = btf_type_by_id(desc_btf, func->type);
2070 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2071 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2072 			func_id);
2073 		return -EINVAL;
2074 	}
2075 
2076 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2077 	addr = kallsyms_lookup_name(func_name);
2078 	if (!addr) {
2079 		verbose(env, "cannot find address for kernel function %s\n",
2080 			func_name);
2081 		return -EINVAL;
2082 	}
2083 
2084 	call_imm = BPF_CALL_IMM(addr);
2085 	/* Check whether or not the relative offset overflows desc->imm */
2086 	if ((unsigned long)(s32)call_imm != call_imm) {
2087 		verbose(env, "address of kernel function %s is out of range\n",
2088 			func_name);
2089 		return -EINVAL;
2090 	}
2091 
2092 	desc = &tab->descs[tab->nr_descs++];
2093 	desc->func_id = func_id;
2094 	desc->imm = call_imm;
2095 	desc->offset = offset;
2096 	err = btf_distill_func_proto(&env->log, desc_btf,
2097 				     func_proto, func_name,
2098 				     &desc->func_model);
2099 	if (!err)
2100 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2101 		     kfunc_desc_cmp_by_id_off, NULL);
2102 	return err;
2103 }
2104 
2105 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2106 {
2107 	const struct bpf_kfunc_desc *d0 = a;
2108 	const struct bpf_kfunc_desc *d1 = b;
2109 
2110 	if (d0->imm > d1->imm)
2111 		return 1;
2112 	else if (d0->imm < d1->imm)
2113 		return -1;
2114 	return 0;
2115 }
2116 
2117 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2118 {
2119 	struct bpf_kfunc_desc_tab *tab;
2120 
2121 	tab = prog->aux->kfunc_tab;
2122 	if (!tab)
2123 		return;
2124 
2125 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2126 	     kfunc_desc_cmp_by_imm, NULL);
2127 }
2128 
2129 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2130 {
2131 	return !!prog->aux->kfunc_tab;
2132 }
2133 
2134 const struct btf_func_model *
2135 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2136 			 const struct bpf_insn *insn)
2137 {
2138 	const struct bpf_kfunc_desc desc = {
2139 		.imm = insn->imm,
2140 	};
2141 	const struct bpf_kfunc_desc *res;
2142 	struct bpf_kfunc_desc_tab *tab;
2143 
2144 	tab = prog->aux->kfunc_tab;
2145 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2146 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2147 
2148 	return res ? &res->func_model : NULL;
2149 }
2150 
2151 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2152 {
2153 	struct bpf_subprog_info *subprog = env->subprog_info;
2154 	struct bpf_insn *insn = env->prog->insnsi;
2155 	int i, ret, insn_cnt = env->prog->len;
2156 
2157 	/* Add entry function. */
2158 	ret = add_subprog(env, 0);
2159 	if (ret)
2160 		return ret;
2161 
2162 	for (i = 0; i < insn_cnt; i++, insn++) {
2163 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2164 		    !bpf_pseudo_kfunc_call(insn))
2165 			continue;
2166 
2167 		if (!env->bpf_capable) {
2168 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2169 			return -EPERM;
2170 		}
2171 
2172 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2173 			ret = add_subprog(env, i + insn->imm + 1);
2174 		else
2175 			ret = add_kfunc_call(env, insn->imm, insn->off);
2176 
2177 		if (ret < 0)
2178 			return ret;
2179 	}
2180 
2181 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2182 	 * logic. 'subprog_cnt' should not be increased.
2183 	 */
2184 	subprog[env->subprog_cnt].start = insn_cnt;
2185 
2186 	if (env->log.level & BPF_LOG_LEVEL2)
2187 		for (i = 0; i < env->subprog_cnt; i++)
2188 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2189 
2190 	return 0;
2191 }
2192 
2193 static int check_subprogs(struct bpf_verifier_env *env)
2194 {
2195 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2196 	struct bpf_subprog_info *subprog = env->subprog_info;
2197 	struct bpf_insn *insn = env->prog->insnsi;
2198 	int insn_cnt = env->prog->len;
2199 
2200 	/* now check that all jumps are within the same subprog */
2201 	subprog_start = subprog[cur_subprog].start;
2202 	subprog_end = subprog[cur_subprog + 1].start;
2203 	for (i = 0; i < insn_cnt; i++) {
2204 		u8 code = insn[i].code;
2205 
2206 		if (code == (BPF_JMP | BPF_CALL) &&
2207 		    insn[i].imm == BPF_FUNC_tail_call &&
2208 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2209 			subprog[cur_subprog].has_tail_call = true;
2210 		if (BPF_CLASS(code) == BPF_LD &&
2211 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2212 			subprog[cur_subprog].has_ld_abs = true;
2213 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2214 			goto next;
2215 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2216 			goto next;
2217 		off = i + insn[i].off + 1;
2218 		if (off < subprog_start || off >= subprog_end) {
2219 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2220 			return -EINVAL;
2221 		}
2222 next:
2223 		if (i == subprog_end - 1) {
2224 			/* to avoid fall-through from one subprog into another
2225 			 * the last insn of the subprog should be either exit
2226 			 * or unconditional jump back
2227 			 */
2228 			if (code != (BPF_JMP | BPF_EXIT) &&
2229 			    code != (BPF_JMP | BPF_JA)) {
2230 				verbose(env, "last insn is not an exit or jmp\n");
2231 				return -EINVAL;
2232 			}
2233 			subprog_start = subprog_end;
2234 			cur_subprog++;
2235 			if (cur_subprog < env->subprog_cnt)
2236 				subprog_end = subprog[cur_subprog + 1].start;
2237 		}
2238 	}
2239 	return 0;
2240 }
2241 
2242 /* Parentage chain of this register (or stack slot) should take care of all
2243  * issues like callee-saved registers, stack slot allocation time, etc.
2244  */
2245 static int mark_reg_read(struct bpf_verifier_env *env,
2246 			 const struct bpf_reg_state *state,
2247 			 struct bpf_reg_state *parent, u8 flag)
2248 {
2249 	bool writes = parent == state->parent; /* Observe write marks */
2250 	int cnt = 0;
2251 
2252 	while (parent) {
2253 		/* if read wasn't screened by an earlier write ... */
2254 		if (writes && state->live & REG_LIVE_WRITTEN)
2255 			break;
2256 		if (parent->live & REG_LIVE_DONE) {
2257 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2258 				reg_type_str(env, parent->type),
2259 				parent->var_off.value, parent->off);
2260 			return -EFAULT;
2261 		}
2262 		/* The first condition is more likely to be true than the
2263 		 * second, checked it first.
2264 		 */
2265 		if ((parent->live & REG_LIVE_READ) == flag ||
2266 		    parent->live & REG_LIVE_READ64)
2267 			/* The parentage chain never changes and
2268 			 * this parent was already marked as LIVE_READ.
2269 			 * There is no need to keep walking the chain again and
2270 			 * keep re-marking all parents as LIVE_READ.
2271 			 * This case happens when the same register is read
2272 			 * multiple times without writes into it in-between.
2273 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2274 			 * then no need to set the weak REG_LIVE_READ32.
2275 			 */
2276 			break;
2277 		/* ... then we depend on parent's value */
2278 		parent->live |= flag;
2279 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2280 		if (flag == REG_LIVE_READ64)
2281 			parent->live &= ~REG_LIVE_READ32;
2282 		state = parent;
2283 		parent = state->parent;
2284 		writes = true;
2285 		cnt++;
2286 	}
2287 
2288 	if (env->longest_mark_read_walk < cnt)
2289 		env->longest_mark_read_walk = cnt;
2290 	return 0;
2291 }
2292 
2293 /* This function is supposed to be used by the following 32-bit optimization
2294  * code only. It returns TRUE if the source or destination register operates
2295  * on 64-bit, otherwise return FALSE.
2296  */
2297 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2298 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2299 {
2300 	u8 code, class, op;
2301 
2302 	code = insn->code;
2303 	class = BPF_CLASS(code);
2304 	op = BPF_OP(code);
2305 	if (class == BPF_JMP) {
2306 		/* BPF_EXIT for "main" will reach here. Return TRUE
2307 		 * conservatively.
2308 		 */
2309 		if (op == BPF_EXIT)
2310 			return true;
2311 		if (op == BPF_CALL) {
2312 			/* BPF to BPF call will reach here because of marking
2313 			 * caller saved clobber with DST_OP_NO_MARK for which we
2314 			 * don't care the register def because they are anyway
2315 			 * marked as NOT_INIT already.
2316 			 */
2317 			if (insn->src_reg == BPF_PSEUDO_CALL)
2318 				return false;
2319 			/* Helper call will reach here because of arg type
2320 			 * check, conservatively return TRUE.
2321 			 */
2322 			if (t == SRC_OP)
2323 				return true;
2324 
2325 			return false;
2326 		}
2327 	}
2328 
2329 	if (class == BPF_ALU64 || class == BPF_JMP ||
2330 	    /* BPF_END always use BPF_ALU class. */
2331 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2332 		return true;
2333 
2334 	if (class == BPF_ALU || class == BPF_JMP32)
2335 		return false;
2336 
2337 	if (class == BPF_LDX) {
2338 		if (t != SRC_OP)
2339 			return BPF_SIZE(code) == BPF_DW;
2340 		/* LDX source must be ptr. */
2341 		return true;
2342 	}
2343 
2344 	if (class == BPF_STX) {
2345 		/* BPF_STX (including atomic variants) has multiple source
2346 		 * operands, one of which is a ptr. Check whether the caller is
2347 		 * asking about it.
2348 		 */
2349 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2350 			return true;
2351 		return BPF_SIZE(code) == BPF_DW;
2352 	}
2353 
2354 	if (class == BPF_LD) {
2355 		u8 mode = BPF_MODE(code);
2356 
2357 		/* LD_IMM64 */
2358 		if (mode == BPF_IMM)
2359 			return true;
2360 
2361 		/* Both LD_IND and LD_ABS return 32-bit data. */
2362 		if (t != SRC_OP)
2363 			return  false;
2364 
2365 		/* Implicit ctx ptr. */
2366 		if (regno == BPF_REG_6)
2367 			return true;
2368 
2369 		/* Explicit source could be any width. */
2370 		return true;
2371 	}
2372 
2373 	if (class == BPF_ST)
2374 		/* The only source register for BPF_ST is a ptr. */
2375 		return true;
2376 
2377 	/* Conservatively return true at default. */
2378 	return true;
2379 }
2380 
2381 /* Return the regno defined by the insn, or -1. */
2382 static int insn_def_regno(const struct bpf_insn *insn)
2383 {
2384 	switch (BPF_CLASS(insn->code)) {
2385 	case BPF_JMP:
2386 	case BPF_JMP32:
2387 	case BPF_ST:
2388 		return -1;
2389 	case BPF_STX:
2390 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2391 		    (insn->imm & BPF_FETCH)) {
2392 			if (insn->imm == BPF_CMPXCHG)
2393 				return BPF_REG_0;
2394 			else
2395 				return insn->src_reg;
2396 		} else {
2397 			return -1;
2398 		}
2399 	default:
2400 		return insn->dst_reg;
2401 	}
2402 }
2403 
2404 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2405 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2406 {
2407 	int dst_reg = insn_def_regno(insn);
2408 
2409 	if (dst_reg == -1)
2410 		return false;
2411 
2412 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2413 }
2414 
2415 static void mark_insn_zext(struct bpf_verifier_env *env,
2416 			   struct bpf_reg_state *reg)
2417 {
2418 	s32 def_idx = reg->subreg_def;
2419 
2420 	if (def_idx == DEF_NOT_SUBREG)
2421 		return;
2422 
2423 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2424 	/* The dst will be zero extended, so won't be sub-register anymore. */
2425 	reg->subreg_def = DEF_NOT_SUBREG;
2426 }
2427 
2428 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2429 			 enum reg_arg_type t)
2430 {
2431 	struct bpf_verifier_state *vstate = env->cur_state;
2432 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2433 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2434 	struct bpf_reg_state *reg, *regs = state->regs;
2435 	bool rw64;
2436 
2437 	if (regno >= MAX_BPF_REG) {
2438 		verbose(env, "R%d is invalid\n", regno);
2439 		return -EINVAL;
2440 	}
2441 
2442 	mark_reg_scratched(env, regno);
2443 
2444 	reg = &regs[regno];
2445 	rw64 = is_reg64(env, insn, regno, reg, t);
2446 	if (t == SRC_OP) {
2447 		/* check whether register used as source operand can be read */
2448 		if (reg->type == NOT_INIT) {
2449 			verbose(env, "R%d !read_ok\n", regno);
2450 			return -EACCES;
2451 		}
2452 		/* We don't need to worry about FP liveness because it's read-only */
2453 		if (regno == BPF_REG_FP)
2454 			return 0;
2455 
2456 		if (rw64)
2457 			mark_insn_zext(env, reg);
2458 
2459 		return mark_reg_read(env, reg, reg->parent,
2460 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2461 	} else {
2462 		/* check whether register used as dest operand can be written to */
2463 		if (regno == BPF_REG_FP) {
2464 			verbose(env, "frame pointer is read only\n");
2465 			return -EACCES;
2466 		}
2467 		reg->live |= REG_LIVE_WRITTEN;
2468 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2469 		if (t == DST_OP)
2470 			mark_reg_unknown(env, regs, regno);
2471 	}
2472 	return 0;
2473 }
2474 
2475 /* for any branch, call, exit record the history of jmps in the given state */
2476 static int push_jmp_history(struct bpf_verifier_env *env,
2477 			    struct bpf_verifier_state *cur)
2478 {
2479 	u32 cnt = cur->jmp_history_cnt;
2480 	struct bpf_idx_pair *p;
2481 
2482 	cnt++;
2483 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2484 	if (!p)
2485 		return -ENOMEM;
2486 	p[cnt - 1].idx = env->insn_idx;
2487 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2488 	cur->jmp_history = p;
2489 	cur->jmp_history_cnt = cnt;
2490 	return 0;
2491 }
2492 
2493 /* Backtrack one insn at a time. If idx is not at the top of recorded
2494  * history then previous instruction came from straight line execution.
2495  */
2496 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2497 			     u32 *history)
2498 {
2499 	u32 cnt = *history;
2500 
2501 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2502 		i = st->jmp_history[cnt - 1].prev_idx;
2503 		(*history)--;
2504 	} else {
2505 		i--;
2506 	}
2507 	return i;
2508 }
2509 
2510 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2511 {
2512 	const struct btf_type *func;
2513 	struct btf *desc_btf;
2514 
2515 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2516 		return NULL;
2517 
2518 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2519 	if (IS_ERR(desc_btf))
2520 		return "<error>";
2521 
2522 	func = btf_type_by_id(desc_btf, insn->imm);
2523 	return btf_name_by_offset(desc_btf, func->name_off);
2524 }
2525 
2526 /* For given verifier state backtrack_insn() is called from the last insn to
2527  * the first insn. Its purpose is to compute a bitmask of registers and
2528  * stack slots that needs precision in the parent verifier state.
2529  */
2530 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2531 			  u32 *reg_mask, u64 *stack_mask)
2532 {
2533 	const struct bpf_insn_cbs cbs = {
2534 		.cb_call	= disasm_kfunc_name,
2535 		.cb_print	= verbose,
2536 		.private_data	= env,
2537 	};
2538 	struct bpf_insn *insn = env->prog->insnsi + idx;
2539 	u8 class = BPF_CLASS(insn->code);
2540 	u8 opcode = BPF_OP(insn->code);
2541 	u8 mode = BPF_MODE(insn->code);
2542 	u32 dreg = 1u << insn->dst_reg;
2543 	u32 sreg = 1u << insn->src_reg;
2544 	u32 spi;
2545 
2546 	if (insn->code == 0)
2547 		return 0;
2548 	if (env->log.level & BPF_LOG_LEVEL2) {
2549 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2550 		verbose(env, "%d: ", idx);
2551 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2552 	}
2553 
2554 	if (class == BPF_ALU || class == BPF_ALU64) {
2555 		if (!(*reg_mask & dreg))
2556 			return 0;
2557 		if (opcode == BPF_MOV) {
2558 			if (BPF_SRC(insn->code) == BPF_X) {
2559 				/* dreg = sreg
2560 				 * dreg needs precision after this insn
2561 				 * sreg needs precision before this insn
2562 				 */
2563 				*reg_mask &= ~dreg;
2564 				*reg_mask |= sreg;
2565 			} else {
2566 				/* dreg = K
2567 				 * dreg needs precision after this insn.
2568 				 * Corresponding register is already marked
2569 				 * as precise=true in this verifier state.
2570 				 * No further markings in parent are necessary
2571 				 */
2572 				*reg_mask &= ~dreg;
2573 			}
2574 		} else {
2575 			if (BPF_SRC(insn->code) == BPF_X) {
2576 				/* dreg += sreg
2577 				 * both dreg and sreg need precision
2578 				 * before this insn
2579 				 */
2580 				*reg_mask |= sreg;
2581 			} /* else dreg += K
2582 			   * dreg still needs precision before this insn
2583 			   */
2584 		}
2585 	} else if (class == BPF_LDX) {
2586 		if (!(*reg_mask & dreg))
2587 			return 0;
2588 		*reg_mask &= ~dreg;
2589 
2590 		/* scalars can only be spilled into stack w/o losing precision.
2591 		 * Load from any other memory can be zero extended.
2592 		 * The desire to keep that precision is already indicated
2593 		 * by 'precise' mark in corresponding register of this state.
2594 		 * No further tracking necessary.
2595 		 */
2596 		if (insn->src_reg != BPF_REG_FP)
2597 			return 0;
2598 
2599 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2600 		 * that [fp - off] slot contains scalar that needs to be
2601 		 * tracked with precision
2602 		 */
2603 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2604 		if (spi >= 64) {
2605 			verbose(env, "BUG spi %d\n", spi);
2606 			WARN_ONCE(1, "verifier backtracking bug");
2607 			return -EFAULT;
2608 		}
2609 		*stack_mask |= 1ull << spi;
2610 	} else if (class == BPF_STX || class == BPF_ST) {
2611 		if (*reg_mask & dreg)
2612 			/* stx & st shouldn't be using _scalar_ dst_reg
2613 			 * to access memory. It means backtracking
2614 			 * encountered a case of pointer subtraction.
2615 			 */
2616 			return -ENOTSUPP;
2617 		/* scalars can only be spilled into stack */
2618 		if (insn->dst_reg != BPF_REG_FP)
2619 			return 0;
2620 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2621 		if (spi >= 64) {
2622 			verbose(env, "BUG spi %d\n", spi);
2623 			WARN_ONCE(1, "verifier backtracking bug");
2624 			return -EFAULT;
2625 		}
2626 		if (!(*stack_mask & (1ull << spi)))
2627 			return 0;
2628 		*stack_mask &= ~(1ull << spi);
2629 		if (class == BPF_STX)
2630 			*reg_mask |= sreg;
2631 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2632 		if (opcode == BPF_CALL) {
2633 			if (insn->src_reg == BPF_PSEUDO_CALL)
2634 				return -ENOTSUPP;
2635 			/* regular helper call sets R0 */
2636 			*reg_mask &= ~1;
2637 			if (*reg_mask & 0x3f) {
2638 				/* if backtracing was looking for registers R1-R5
2639 				 * they should have been found already.
2640 				 */
2641 				verbose(env, "BUG regs %x\n", *reg_mask);
2642 				WARN_ONCE(1, "verifier backtracking bug");
2643 				return -EFAULT;
2644 			}
2645 		} else if (opcode == BPF_EXIT) {
2646 			return -ENOTSUPP;
2647 		}
2648 	} else if (class == BPF_LD) {
2649 		if (!(*reg_mask & dreg))
2650 			return 0;
2651 		*reg_mask &= ~dreg;
2652 		/* It's ld_imm64 or ld_abs or ld_ind.
2653 		 * For ld_imm64 no further tracking of precision
2654 		 * into parent is necessary
2655 		 */
2656 		if (mode == BPF_IND || mode == BPF_ABS)
2657 			/* to be analyzed */
2658 			return -ENOTSUPP;
2659 	}
2660 	return 0;
2661 }
2662 
2663 /* the scalar precision tracking algorithm:
2664  * . at the start all registers have precise=false.
2665  * . scalar ranges are tracked as normal through alu and jmp insns.
2666  * . once precise value of the scalar register is used in:
2667  *   .  ptr + scalar alu
2668  *   . if (scalar cond K|scalar)
2669  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2670  *   backtrack through the verifier states and mark all registers and
2671  *   stack slots with spilled constants that these scalar regisers
2672  *   should be precise.
2673  * . during state pruning two registers (or spilled stack slots)
2674  *   are equivalent if both are not precise.
2675  *
2676  * Note the verifier cannot simply walk register parentage chain,
2677  * since many different registers and stack slots could have been
2678  * used to compute single precise scalar.
2679  *
2680  * The approach of starting with precise=true for all registers and then
2681  * backtrack to mark a register as not precise when the verifier detects
2682  * that program doesn't care about specific value (e.g., when helper
2683  * takes register as ARG_ANYTHING parameter) is not safe.
2684  *
2685  * It's ok to walk single parentage chain of the verifier states.
2686  * It's possible that this backtracking will go all the way till 1st insn.
2687  * All other branches will be explored for needing precision later.
2688  *
2689  * The backtracking needs to deal with cases like:
2690  *   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)
2691  * r9 -= r8
2692  * r5 = r9
2693  * if r5 > 0x79f goto pc+7
2694  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2695  * r5 += 1
2696  * ...
2697  * call bpf_perf_event_output#25
2698  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2699  *
2700  * and this case:
2701  * r6 = 1
2702  * call foo // uses callee's r6 inside to compute r0
2703  * r0 += r6
2704  * if r0 == 0 goto
2705  *
2706  * to track above reg_mask/stack_mask needs to be independent for each frame.
2707  *
2708  * Also if parent's curframe > frame where backtracking started,
2709  * the verifier need to mark registers in both frames, otherwise callees
2710  * may incorrectly prune callers. This is similar to
2711  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2712  *
2713  * For now backtracking falls back into conservative marking.
2714  */
2715 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2716 				     struct bpf_verifier_state *st)
2717 {
2718 	struct bpf_func_state *func;
2719 	struct bpf_reg_state *reg;
2720 	int i, j;
2721 
2722 	/* big hammer: mark all scalars precise in this path.
2723 	 * pop_stack may still get !precise scalars.
2724 	 */
2725 	for (; st; st = st->parent)
2726 		for (i = 0; i <= st->curframe; i++) {
2727 			func = st->frame[i];
2728 			for (j = 0; j < BPF_REG_FP; j++) {
2729 				reg = &func->regs[j];
2730 				if (reg->type != SCALAR_VALUE)
2731 					continue;
2732 				reg->precise = true;
2733 			}
2734 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2735 				if (!is_spilled_reg(&func->stack[j]))
2736 					continue;
2737 				reg = &func->stack[j].spilled_ptr;
2738 				if (reg->type != SCALAR_VALUE)
2739 					continue;
2740 				reg->precise = true;
2741 			}
2742 		}
2743 }
2744 
2745 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2746 				  int spi)
2747 {
2748 	struct bpf_verifier_state *st = env->cur_state;
2749 	int first_idx = st->first_insn_idx;
2750 	int last_idx = env->insn_idx;
2751 	struct bpf_func_state *func;
2752 	struct bpf_reg_state *reg;
2753 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2754 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2755 	bool skip_first = true;
2756 	bool new_marks = false;
2757 	int i, err;
2758 
2759 	if (!env->bpf_capable)
2760 		return 0;
2761 
2762 	func = st->frame[st->curframe];
2763 	if (regno >= 0) {
2764 		reg = &func->regs[regno];
2765 		if (reg->type != SCALAR_VALUE) {
2766 			WARN_ONCE(1, "backtracing misuse");
2767 			return -EFAULT;
2768 		}
2769 		if (!reg->precise)
2770 			new_marks = true;
2771 		else
2772 			reg_mask = 0;
2773 		reg->precise = true;
2774 	}
2775 
2776 	while (spi >= 0) {
2777 		if (!is_spilled_reg(&func->stack[spi])) {
2778 			stack_mask = 0;
2779 			break;
2780 		}
2781 		reg = &func->stack[spi].spilled_ptr;
2782 		if (reg->type != SCALAR_VALUE) {
2783 			stack_mask = 0;
2784 			break;
2785 		}
2786 		if (!reg->precise)
2787 			new_marks = true;
2788 		else
2789 			stack_mask = 0;
2790 		reg->precise = true;
2791 		break;
2792 	}
2793 
2794 	if (!new_marks)
2795 		return 0;
2796 	if (!reg_mask && !stack_mask)
2797 		return 0;
2798 	for (;;) {
2799 		DECLARE_BITMAP(mask, 64);
2800 		u32 history = st->jmp_history_cnt;
2801 
2802 		if (env->log.level & BPF_LOG_LEVEL2)
2803 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2804 		for (i = last_idx;;) {
2805 			if (skip_first) {
2806 				err = 0;
2807 				skip_first = false;
2808 			} else {
2809 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2810 			}
2811 			if (err == -ENOTSUPP) {
2812 				mark_all_scalars_precise(env, st);
2813 				return 0;
2814 			} else if (err) {
2815 				return err;
2816 			}
2817 			if (!reg_mask && !stack_mask)
2818 				/* Found assignment(s) into tracked register in this state.
2819 				 * Since this state is already marked, just return.
2820 				 * Nothing to be tracked further in the parent state.
2821 				 */
2822 				return 0;
2823 			if (i == first_idx)
2824 				break;
2825 			i = get_prev_insn_idx(st, i, &history);
2826 			if (i >= env->prog->len) {
2827 				/* This can happen if backtracking reached insn 0
2828 				 * and there are still reg_mask or stack_mask
2829 				 * to backtrack.
2830 				 * It means the backtracking missed the spot where
2831 				 * particular register was initialized with a constant.
2832 				 */
2833 				verbose(env, "BUG backtracking idx %d\n", i);
2834 				WARN_ONCE(1, "verifier backtracking bug");
2835 				return -EFAULT;
2836 			}
2837 		}
2838 		st = st->parent;
2839 		if (!st)
2840 			break;
2841 
2842 		new_marks = false;
2843 		func = st->frame[st->curframe];
2844 		bitmap_from_u64(mask, reg_mask);
2845 		for_each_set_bit(i, mask, 32) {
2846 			reg = &func->regs[i];
2847 			if (reg->type != SCALAR_VALUE) {
2848 				reg_mask &= ~(1u << i);
2849 				continue;
2850 			}
2851 			if (!reg->precise)
2852 				new_marks = true;
2853 			reg->precise = true;
2854 		}
2855 
2856 		bitmap_from_u64(mask, stack_mask);
2857 		for_each_set_bit(i, mask, 64) {
2858 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2859 				/* the sequence of instructions:
2860 				 * 2: (bf) r3 = r10
2861 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2862 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2863 				 * doesn't contain jmps. It's backtracked
2864 				 * as a single block.
2865 				 * During backtracking insn 3 is not recognized as
2866 				 * stack access, so at the end of backtracking
2867 				 * stack slot fp-8 is still marked in stack_mask.
2868 				 * However the parent state may not have accessed
2869 				 * fp-8 and it's "unallocated" stack space.
2870 				 * In such case fallback to conservative.
2871 				 */
2872 				mark_all_scalars_precise(env, st);
2873 				return 0;
2874 			}
2875 
2876 			if (!is_spilled_reg(&func->stack[i])) {
2877 				stack_mask &= ~(1ull << i);
2878 				continue;
2879 			}
2880 			reg = &func->stack[i].spilled_ptr;
2881 			if (reg->type != SCALAR_VALUE) {
2882 				stack_mask &= ~(1ull << i);
2883 				continue;
2884 			}
2885 			if (!reg->precise)
2886 				new_marks = true;
2887 			reg->precise = true;
2888 		}
2889 		if (env->log.level & BPF_LOG_LEVEL2) {
2890 			verbose(env, "parent %s regs=%x stack=%llx marks:",
2891 				new_marks ? "didn't have" : "already had",
2892 				reg_mask, stack_mask);
2893 			print_verifier_state(env, func, true);
2894 		}
2895 
2896 		if (!reg_mask && !stack_mask)
2897 			break;
2898 		if (!new_marks)
2899 			break;
2900 
2901 		last_idx = st->last_insn_idx;
2902 		first_idx = st->first_insn_idx;
2903 	}
2904 	return 0;
2905 }
2906 
2907 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2908 {
2909 	return __mark_chain_precision(env, regno, -1);
2910 }
2911 
2912 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2913 {
2914 	return __mark_chain_precision(env, -1, spi);
2915 }
2916 
2917 static bool is_spillable_regtype(enum bpf_reg_type type)
2918 {
2919 	switch (base_type(type)) {
2920 	case PTR_TO_MAP_VALUE:
2921 	case PTR_TO_STACK:
2922 	case PTR_TO_CTX:
2923 	case PTR_TO_PACKET:
2924 	case PTR_TO_PACKET_META:
2925 	case PTR_TO_PACKET_END:
2926 	case PTR_TO_FLOW_KEYS:
2927 	case CONST_PTR_TO_MAP:
2928 	case PTR_TO_SOCKET:
2929 	case PTR_TO_SOCK_COMMON:
2930 	case PTR_TO_TCP_SOCK:
2931 	case PTR_TO_XDP_SOCK:
2932 	case PTR_TO_BTF_ID:
2933 	case PTR_TO_BUF:
2934 	case PTR_TO_MEM:
2935 	case PTR_TO_FUNC:
2936 	case PTR_TO_MAP_KEY:
2937 		return true;
2938 	default:
2939 		return false;
2940 	}
2941 }
2942 
2943 /* Does this register contain a constant zero? */
2944 static bool register_is_null(struct bpf_reg_state *reg)
2945 {
2946 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2947 }
2948 
2949 static bool register_is_const(struct bpf_reg_state *reg)
2950 {
2951 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2952 }
2953 
2954 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2955 {
2956 	return tnum_is_unknown(reg->var_off) &&
2957 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2958 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2959 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2960 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2961 }
2962 
2963 static bool register_is_bounded(struct bpf_reg_state *reg)
2964 {
2965 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2966 }
2967 
2968 static bool __is_pointer_value(bool allow_ptr_leaks,
2969 			       const struct bpf_reg_state *reg)
2970 {
2971 	if (allow_ptr_leaks)
2972 		return false;
2973 
2974 	return reg->type != SCALAR_VALUE;
2975 }
2976 
2977 static void save_register_state(struct bpf_func_state *state,
2978 				int spi, struct bpf_reg_state *reg,
2979 				int size)
2980 {
2981 	int i;
2982 
2983 	state->stack[spi].spilled_ptr = *reg;
2984 	if (size == BPF_REG_SIZE)
2985 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2986 
2987 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2988 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2989 
2990 	/* size < 8 bytes spill */
2991 	for (; i; i--)
2992 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2993 }
2994 
2995 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2996  * stack boundary and alignment are checked in check_mem_access()
2997  */
2998 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2999 				       /* stack frame we're writing to */
3000 				       struct bpf_func_state *state,
3001 				       int off, int size, int value_regno,
3002 				       int insn_idx)
3003 {
3004 	struct bpf_func_state *cur; /* state of the current function */
3005 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3006 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3007 	struct bpf_reg_state *reg = NULL;
3008 
3009 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3010 	if (err)
3011 		return err;
3012 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3013 	 * so it's aligned access and [off, off + size) are within stack limits
3014 	 */
3015 	if (!env->allow_ptr_leaks &&
3016 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3017 	    size != BPF_REG_SIZE) {
3018 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3019 		return -EACCES;
3020 	}
3021 
3022 	cur = env->cur_state->frame[env->cur_state->curframe];
3023 	if (value_regno >= 0)
3024 		reg = &cur->regs[value_regno];
3025 	if (!env->bypass_spec_v4) {
3026 		bool sanitize = reg && is_spillable_regtype(reg->type);
3027 
3028 		for (i = 0; i < size; i++) {
3029 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3030 				sanitize = true;
3031 				break;
3032 			}
3033 		}
3034 
3035 		if (sanitize)
3036 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3037 	}
3038 
3039 	mark_stack_slot_scratched(env, spi);
3040 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3041 	    !register_is_null(reg) && env->bpf_capable) {
3042 		if (dst_reg != BPF_REG_FP) {
3043 			/* The backtracking logic can only recognize explicit
3044 			 * stack slot address like [fp - 8]. Other spill of
3045 			 * scalar via different register has to be conservative.
3046 			 * Backtrack from here and mark all registers as precise
3047 			 * that contributed into 'reg' being a constant.
3048 			 */
3049 			err = mark_chain_precision(env, value_regno);
3050 			if (err)
3051 				return err;
3052 		}
3053 		save_register_state(state, spi, reg, size);
3054 	} else if (reg && is_spillable_regtype(reg->type)) {
3055 		/* register containing pointer is being spilled into stack */
3056 		if (size != BPF_REG_SIZE) {
3057 			verbose_linfo(env, insn_idx, "; ");
3058 			verbose(env, "invalid size of register spill\n");
3059 			return -EACCES;
3060 		}
3061 		if (state != cur && reg->type == PTR_TO_STACK) {
3062 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3063 			return -EINVAL;
3064 		}
3065 		save_register_state(state, spi, reg, size);
3066 	} else {
3067 		u8 type = STACK_MISC;
3068 
3069 		/* regular write of data into stack destroys any spilled ptr */
3070 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3071 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3072 		if (is_spilled_reg(&state->stack[spi]))
3073 			for (i = 0; i < BPF_REG_SIZE; i++)
3074 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3075 
3076 		/* only mark the slot as written if all 8 bytes were written
3077 		 * otherwise read propagation may incorrectly stop too soon
3078 		 * when stack slots are partially written.
3079 		 * This heuristic means that read propagation will be
3080 		 * conservative, since it will add reg_live_read marks
3081 		 * to stack slots all the way to first state when programs
3082 		 * writes+reads less than 8 bytes
3083 		 */
3084 		if (size == BPF_REG_SIZE)
3085 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3086 
3087 		/* when we zero initialize stack slots mark them as such */
3088 		if (reg && register_is_null(reg)) {
3089 			/* backtracking doesn't work for STACK_ZERO yet. */
3090 			err = mark_chain_precision(env, value_regno);
3091 			if (err)
3092 				return err;
3093 			type = STACK_ZERO;
3094 		}
3095 
3096 		/* Mark slots affected by this stack write. */
3097 		for (i = 0; i < size; i++)
3098 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3099 				type;
3100 	}
3101 	return 0;
3102 }
3103 
3104 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3105  * known to contain a variable offset.
3106  * This function checks whether the write is permitted and conservatively
3107  * tracks the effects of the write, considering that each stack slot in the
3108  * dynamic range is potentially written to.
3109  *
3110  * 'off' includes 'regno->off'.
3111  * 'value_regno' can be -1, meaning that an unknown value is being written to
3112  * the stack.
3113  *
3114  * Spilled pointers in range are not marked as written because we don't know
3115  * what's going to be actually written. This means that read propagation for
3116  * future reads cannot be terminated by this write.
3117  *
3118  * For privileged programs, uninitialized stack slots are considered
3119  * initialized by this write (even though we don't know exactly what offsets
3120  * are going to be written to). The idea is that we don't want the verifier to
3121  * reject future reads that access slots written to through variable offsets.
3122  */
3123 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3124 				     /* func where register points to */
3125 				     struct bpf_func_state *state,
3126 				     int ptr_regno, int off, int size,
3127 				     int value_regno, int insn_idx)
3128 {
3129 	struct bpf_func_state *cur; /* state of the current function */
3130 	int min_off, max_off;
3131 	int i, err;
3132 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3133 	bool writing_zero = false;
3134 	/* set if the fact that we're writing a zero is used to let any
3135 	 * stack slots remain STACK_ZERO
3136 	 */
3137 	bool zero_used = false;
3138 
3139 	cur = env->cur_state->frame[env->cur_state->curframe];
3140 	ptr_reg = &cur->regs[ptr_regno];
3141 	min_off = ptr_reg->smin_value + off;
3142 	max_off = ptr_reg->smax_value + off + size;
3143 	if (value_regno >= 0)
3144 		value_reg = &cur->regs[value_regno];
3145 	if (value_reg && register_is_null(value_reg))
3146 		writing_zero = true;
3147 
3148 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3149 	if (err)
3150 		return err;
3151 
3152 
3153 	/* Variable offset writes destroy any spilled pointers in range. */
3154 	for (i = min_off; i < max_off; i++) {
3155 		u8 new_type, *stype;
3156 		int slot, spi;
3157 
3158 		slot = -i - 1;
3159 		spi = slot / BPF_REG_SIZE;
3160 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3161 		mark_stack_slot_scratched(env, spi);
3162 
3163 		if (!env->allow_ptr_leaks
3164 				&& *stype != NOT_INIT
3165 				&& *stype != SCALAR_VALUE) {
3166 			/* Reject the write if there's are spilled pointers in
3167 			 * range. If we didn't reject here, the ptr status
3168 			 * would be erased below (even though not all slots are
3169 			 * actually overwritten), possibly opening the door to
3170 			 * leaks.
3171 			 */
3172 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3173 				insn_idx, i);
3174 			return -EINVAL;
3175 		}
3176 
3177 		/* Erase all spilled pointers. */
3178 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3179 
3180 		/* Update the slot type. */
3181 		new_type = STACK_MISC;
3182 		if (writing_zero && *stype == STACK_ZERO) {
3183 			new_type = STACK_ZERO;
3184 			zero_used = true;
3185 		}
3186 		/* If the slot is STACK_INVALID, we check whether it's OK to
3187 		 * pretend that it will be initialized by this write. The slot
3188 		 * might not actually be written to, and so if we mark it as
3189 		 * initialized future reads might leak uninitialized memory.
3190 		 * For privileged programs, we will accept such reads to slots
3191 		 * that may or may not be written because, if we're reject
3192 		 * them, the error would be too confusing.
3193 		 */
3194 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3195 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3196 					insn_idx, i);
3197 			return -EINVAL;
3198 		}
3199 		*stype = new_type;
3200 	}
3201 	if (zero_used) {
3202 		/* backtracking doesn't work for STACK_ZERO yet. */
3203 		err = mark_chain_precision(env, value_regno);
3204 		if (err)
3205 			return err;
3206 	}
3207 	return 0;
3208 }
3209 
3210 /* When register 'dst_regno' is assigned some values from stack[min_off,
3211  * max_off), we set the register's type according to the types of the
3212  * respective stack slots. If all the stack values are known to be zeros, then
3213  * so is the destination reg. Otherwise, the register is considered to be
3214  * SCALAR. This function does not deal with register filling; the caller must
3215  * ensure that all spilled registers in the stack range have been marked as
3216  * read.
3217  */
3218 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3219 				/* func where src register points to */
3220 				struct bpf_func_state *ptr_state,
3221 				int min_off, int max_off, int dst_regno)
3222 {
3223 	struct bpf_verifier_state *vstate = env->cur_state;
3224 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3225 	int i, slot, spi;
3226 	u8 *stype;
3227 	int zeros = 0;
3228 
3229 	for (i = min_off; i < max_off; i++) {
3230 		slot = -i - 1;
3231 		spi = slot / BPF_REG_SIZE;
3232 		stype = ptr_state->stack[spi].slot_type;
3233 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3234 			break;
3235 		zeros++;
3236 	}
3237 	if (zeros == max_off - min_off) {
3238 		/* any access_size read into register is zero extended,
3239 		 * so the whole register == const_zero
3240 		 */
3241 		__mark_reg_const_zero(&state->regs[dst_regno]);
3242 		/* backtracking doesn't support STACK_ZERO yet,
3243 		 * so mark it precise here, so that later
3244 		 * backtracking can stop here.
3245 		 * Backtracking may not need this if this register
3246 		 * doesn't participate in pointer adjustment.
3247 		 * Forward propagation of precise flag is not
3248 		 * necessary either. This mark is only to stop
3249 		 * backtracking. Any register that contributed
3250 		 * to const 0 was marked precise before spill.
3251 		 */
3252 		state->regs[dst_regno].precise = true;
3253 	} else {
3254 		/* have read misc data from the stack */
3255 		mark_reg_unknown(env, state->regs, dst_regno);
3256 	}
3257 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3258 }
3259 
3260 /* Read the stack at 'off' and put the results into the register indicated by
3261  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3262  * spilled reg.
3263  *
3264  * 'dst_regno' can be -1, meaning that the read value is not going to a
3265  * register.
3266  *
3267  * The access is assumed to be within the current stack bounds.
3268  */
3269 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3270 				      /* func where src register points to */
3271 				      struct bpf_func_state *reg_state,
3272 				      int off, int size, int dst_regno)
3273 {
3274 	struct bpf_verifier_state *vstate = env->cur_state;
3275 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3276 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3277 	struct bpf_reg_state *reg;
3278 	u8 *stype, type;
3279 
3280 	stype = reg_state->stack[spi].slot_type;
3281 	reg = &reg_state->stack[spi].spilled_ptr;
3282 
3283 	if (is_spilled_reg(&reg_state->stack[spi])) {
3284 		u8 spill_size = 1;
3285 
3286 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3287 			spill_size++;
3288 
3289 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3290 			if (reg->type != SCALAR_VALUE) {
3291 				verbose_linfo(env, env->insn_idx, "; ");
3292 				verbose(env, "invalid size of register fill\n");
3293 				return -EACCES;
3294 			}
3295 
3296 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3297 			if (dst_regno < 0)
3298 				return 0;
3299 
3300 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3301 				/* The earlier check_reg_arg() has decided the
3302 				 * subreg_def for this insn.  Save it first.
3303 				 */
3304 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3305 
3306 				state->regs[dst_regno] = *reg;
3307 				state->regs[dst_regno].subreg_def = subreg_def;
3308 			} else {
3309 				for (i = 0; i < size; i++) {
3310 					type = stype[(slot - i) % BPF_REG_SIZE];
3311 					if (type == STACK_SPILL)
3312 						continue;
3313 					if (type == STACK_MISC)
3314 						continue;
3315 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3316 						off, i, size);
3317 					return -EACCES;
3318 				}
3319 				mark_reg_unknown(env, state->regs, dst_regno);
3320 			}
3321 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3322 			return 0;
3323 		}
3324 
3325 		if (dst_regno >= 0) {
3326 			/* restore register state from stack */
3327 			state->regs[dst_regno] = *reg;
3328 			/* mark reg as written since spilled pointer state likely
3329 			 * has its liveness marks cleared by is_state_visited()
3330 			 * which resets stack/reg liveness for state transitions
3331 			 */
3332 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3333 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3334 			/* If dst_regno==-1, the caller is asking us whether
3335 			 * it is acceptable to use this value as a SCALAR_VALUE
3336 			 * (e.g. for XADD).
3337 			 * We must not allow unprivileged callers to do that
3338 			 * with spilled pointers.
3339 			 */
3340 			verbose(env, "leaking pointer from stack off %d\n",
3341 				off);
3342 			return -EACCES;
3343 		}
3344 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3345 	} else {
3346 		for (i = 0; i < size; i++) {
3347 			type = stype[(slot - i) % BPF_REG_SIZE];
3348 			if (type == STACK_MISC)
3349 				continue;
3350 			if (type == STACK_ZERO)
3351 				continue;
3352 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3353 				off, i, size);
3354 			return -EACCES;
3355 		}
3356 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3357 		if (dst_regno >= 0)
3358 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3359 	}
3360 	return 0;
3361 }
3362 
3363 enum bpf_access_src {
3364 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3365 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3366 };
3367 
3368 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3369 					 int regno, int off, int access_size,
3370 					 bool zero_size_allowed,
3371 					 enum bpf_access_src type,
3372 					 struct bpf_call_arg_meta *meta);
3373 
3374 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3375 {
3376 	return cur_regs(env) + regno;
3377 }
3378 
3379 /* Read the stack at 'ptr_regno + off' and put the result into the register
3380  * 'dst_regno'.
3381  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3382  * but not its variable offset.
3383  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3384  *
3385  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3386  * filling registers (i.e. reads of spilled register cannot be detected when
3387  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3388  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3389  * offset; for a fixed offset check_stack_read_fixed_off should be used
3390  * instead.
3391  */
3392 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3393 				    int ptr_regno, int off, int size, int dst_regno)
3394 {
3395 	/* The state of the source register. */
3396 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3397 	struct bpf_func_state *ptr_state = func(env, reg);
3398 	int err;
3399 	int min_off, max_off;
3400 
3401 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3402 	 */
3403 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3404 					    false, ACCESS_DIRECT, NULL);
3405 	if (err)
3406 		return err;
3407 
3408 	min_off = reg->smin_value + off;
3409 	max_off = reg->smax_value + off;
3410 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3411 	return 0;
3412 }
3413 
3414 /* check_stack_read dispatches to check_stack_read_fixed_off or
3415  * check_stack_read_var_off.
3416  *
3417  * The caller must ensure that the offset falls within the allocated stack
3418  * bounds.
3419  *
3420  * 'dst_regno' is a register which will receive the value from the stack. It
3421  * can be -1, meaning that the read value is not going to a register.
3422  */
3423 static int check_stack_read(struct bpf_verifier_env *env,
3424 			    int ptr_regno, int off, int size,
3425 			    int dst_regno)
3426 {
3427 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3428 	struct bpf_func_state *state = func(env, reg);
3429 	int err;
3430 	/* Some accesses are only permitted with a static offset. */
3431 	bool var_off = !tnum_is_const(reg->var_off);
3432 
3433 	/* The offset is required to be static when reads don't go to a
3434 	 * register, in order to not leak pointers (see
3435 	 * check_stack_read_fixed_off).
3436 	 */
3437 	if (dst_regno < 0 && var_off) {
3438 		char tn_buf[48];
3439 
3440 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3441 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3442 			tn_buf, off, size);
3443 		return -EACCES;
3444 	}
3445 	/* Variable offset is prohibited for unprivileged mode for simplicity
3446 	 * since it requires corresponding support in Spectre masking for stack
3447 	 * ALU. See also retrieve_ptr_limit().
3448 	 */
3449 	if (!env->bypass_spec_v1 && var_off) {
3450 		char tn_buf[48];
3451 
3452 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3453 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3454 				ptr_regno, tn_buf);
3455 		return -EACCES;
3456 	}
3457 
3458 	if (!var_off) {
3459 		off += reg->var_off.value;
3460 		err = check_stack_read_fixed_off(env, state, off, size,
3461 						 dst_regno);
3462 	} else {
3463 		/* Variable offset stack reads need more conservative handling
3464 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3465 		 * branch.
3466 		 */
3467 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3468 					       dst_regno);
3469 	}
3470 	return err;
3471 }
3472 
3473 
3474 /* check_stack_write dispatches to check_stack_write_fixed_off or
3475  * check_stack_write_var_off.
3476  *
3477  * 'ptr_regno' is the register used as a pointer into the stack.
3478  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3479  * 'value_regno' is the register whose value we're writing to the stack. It can
3480  * be -1, meaning that we're not writing from a register.
3481  *
3482  * The caller must ensure that the offset falls within the maximum stack size.
3483  */
3484 static int check_stack_write(struct bpf_verifier_env *env,
3485 			     int ptr_regno, int off, int size,
3486 			     int value_regno, int insn_idx)
3487 {
3488 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3489 	struct bpf_func_state *state = func(env, reg);
3490 	int err;
3491 
3492 	if (tnum_is_const(reg->var_off)) {
3493 		off += reg->var_off.value;
3494 		err = check_stack_write_fixed_off(env, state, off, size,
3495 						  value_regno, insn_idx);
3496 	} else {
3497 		/* Variable offset stack reads need more conservative handling
3498 		 * than fixed offset ones.
3499 		 */
3500 		err = check_stack_write_var_off(env, state,
3501 						ptr_regno, off, size,
3502 						value_regno, insn_idx);
3503 	}
3504 	return err;
3505 }
3506 
3507 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3508 				 int off, int size, enum bpf_access_type type)
3509 {
3510 	struct bpf_reg_state *regs = cur_regs(env);
3511 	struct bpf_map *map = regs[regno].map_ptr;
3512 	u32 cap = bpf_map_flags_to_cap(map);
3513 
3514 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3515 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3516 			map->value_size, off, size);
3517 		return -EACCES;
3518 	}
3519 
3520 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3521 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3522 			map->value_size, off, size);
3523 		return -EACCES;
3524 	}
3525 
3526 	return 0;
3527 }
3528 
3529 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3530 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3531 			      int off, int size, u32 mem_size,
3532 			      bool zero_size_allowed)
3533 {
3534 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3535 	struct bpf_reg_state *reg;
3536 
3537 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3538 		return 0;
3539 
3540 	reg = &cur_regs(env)[regno];
3541 	switch (reg->type) {
3542 	case PTR_TO_MAP_KEY:
3543 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3544 			mem_size, off, size);
3545 		break;
3546 	case PTR_TO_MAP_VALUE:
3547 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3548 			mem_size, off, size);
3549 		break;
3550 	case PTR_TO_PACKET:
3551 	case PTR_TO_PACKET_META:
3552 	case PTR_TO_PACKET_END:
3553 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3554 			off, size, regno, reg->id, off, mem_size);
3555 		break;
3556 	case PTR_TO_MEM:
3557 	default:
3558 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3559 			mem_size, off, size);
3560 	}
3561 
3562 	return -EACCES;
3563 }
3564 
3565 /* check read/write into a memory region with possible variable offset */
3566 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3567 				   int off, int size, u32 mem_size,
3568 				   bool zero_size_allowed)
3569 {
3570 	struct bpf_verifier_state *vstate = env->cur_state;
3571 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3572 	struct bpf_reg_state *reg = &state->regs[regno];
3573 	int err;
3574 
3575 	/* We may have adjusted the register pointing to memory region, so we
3576 	 * need to try adding each of min_value and max_value to off
3577 	 * to make sure our theoretical access will be safe.
3578 	 *
3579 	 * The minimum value is only important with signed
3580 	 * comparisons where we can't assume the floor of a
3581 	 * value is 0.  If we are using signed variables for our
3582 	 * index'es we need to make sure that whatever we use
3583 	 * will have a set floor within our range.
3584 	 */
3585 	if (reg->smin_value < 0 &&
3586 	    (reg->smin_value == S64_MIN ||
3587 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3588 	      reg->smin_value + off < 0)) {
3589 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3590 			regno);
3591 		return -EACCES;
3592 	}
3593 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3594 				 mem_size, zero_size_allowed);
3595 	if (err) {
3596 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3597 			regno);
3598 		return err;
3599 	}
3600 
3601 	/* If we haven't set a max value then we need to bail since we can't be
3602 	 * sure we won't do bad things.
3603 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3604 	 */
3605 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3606 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3607 			regno);
3608 		return -EACCES;
3609 	}
3610 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3611 				 mem_size, zero_size_allowed);
3612 	if (err) {
3613 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3614 			regno);
3615 		return err;
3616 	}
3617 
3618 	return 0;
3619 }
3620 
3621 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3622 			       const struct bpf_reg_state *reg, int regno,
3623 			       bool fixed_off_ok)
3624 {
3625 	/* Access to this pointer-typed register or passing it to a helper
3626 	 * is only allowed in its original, unmodified form.
3627 	 */
3628 
3629 	if (reg->off < 0) {
3630 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3631 			reg_type_str(env, reg->type), regno, reg->off);
3632 		return -EACCES;
3633 	}
3634 
3635 	if (!fixed_off_ok && reg->off) {
3636 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3637 			reg_type_str(env, reg->type), regno, reg->off);
3638 		return -EACCES;
3639 	}
3640 
3641 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3642 		char tn_buf[48];
3643 
3644 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3645 		verbose(env, "variable %s access var_off=%s disallowed\n",
3646 			reg_type_str(env, reg->type), tn_buf);
3647 		return -EACCES;
3648 	}
3649 
3650 	return 0;
3651 }
3652 
3653 int check_ptr_off_reg(struct bpf_verifier_env *env,
3654 		      const struct bpf_reg_state *reg, int regno)
3655 {
3656 	return __check_ptr_off_reg(env, reg, regno, false);
3657 }
3658 
3659 static int map_kptr_match_type(struct bpf_verifier_env *env,
3660 			       struct bpf_map_value_off_desc *off_desc,
3661 			       struct bpf_reg_state *reg, u32 regno)
3662 {
3663 	const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3664 	int perm_flags = PTR_MAYBE_NULL;
3665 	const char *reg_name = "";
3666 
3667 	/* Only unreferenced case accepts untrusted pointers */
3668 	if (off_desc->type == BPF_KPTR_UNREF)
3669 		perm_flags |= PTR_UNTRUSTED;
3670 
3671 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3672 		goto bad_type;
3673 
3674 	if (!btf_is_kernel(reg->btf)) {
3675 		verbose(env, "R%d must point to kernel BTF\n", regno);
3676 		return -EINVAL;
3677 	}
3678 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3679 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3680 
3681 	/* For ref_ptr case, release function check should ensure we get one
3682 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3683 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3684 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3685 	 * reg->off and reg->ref_obj_id are not needed here.
3686 	 */
3687 	if (__check_ptr_off_reg(env, reg, regno, true))
3688 		return -EACCES;
3689 
3690 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3691 	 * we also need to take into account the reg->off.
3692 	 *
3693 	 * We want to support cases like:
3694 	 *
3695 	 * struct foo {
3696 	 *         struct bar br;
3697 	 *         struct baz bz;
3698 	 * };
3699 	 *
3700 	 * struct foo *v;
3701 	 * v = func();	      // PTR_TO_BTF_ID
3702 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3703 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3704 	 *                    // first member type of struct after comparison fails
3705 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3706 	 *                    // to match type
3707 	 *
3708 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3709 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3710 	 * the struct to match type against first member of struct, i.e. reject
3711 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3712 	 * strict mode to true for type match.
3713 	 */
3714 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3715 				  off_desc->kptr.btf, off_desc->kptr.btf_id,
3716 				  off_desc->type == BPF_KPTR_REF))
3717 		goto bad_type;
3718 	return 0;
3719 bad_type:
3720 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3721 		reg_type_str(env, reg->type), reg_name);
3722 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3723 	if (off_desc->type == BPF_KPTR_UNREF)
3724 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3725 			targ_name);
3726 	else
3727 		verbose(env, "\n");
3728 	return -EINVAL;
3729 }
3730 
3731 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3732 				 int value_regno, int insn_idx,
3733 				 struct bpf_map_value_off_desc *off_desc)
3734 {
3735 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3736 	int class = BPF_CLASS(insn->code);
3737 	struct bpf_reg_state *val_reg;
3738 
3739 	/* Things we already checked for in check_map_access and caller:
3740 	 *  - Reject cases where variable offset may touch kptr
3741 	 *  - size of access (must be BPF_DW)
3742 	 *  - tnum_is_const(reg->var_off)
3743 	 *  - off_desc->offset == off + reg->var_off.value
3744 	 */
3745 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3746 	if (BPF_MODE(insn->code) != BPF_MEM) {
3747 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3748 		return -EACCES;
3749 	}
3750 
3751 	/* We only allow loading referenced kptr, since it will be marked as
3752 	 * untrusted, similar to unreferenced kptr.
3753 	 */
3754 	if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3755 		verbose(env, "store to referenced kptr disallowed\n");
3756 		return -EACCES;
3757 	}
3758 
3759 	if (class == BPF_LDX) {
3760 		val_reg = reg_state(env, value_regno);
3761 		/* We can simply mark the value_regno receiving the pointer
3762 		 * value from map as PTR_TO_BTF_ID, with the correct type.
3763 		 */
3764 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3765 				off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3766 		/* For mark_ptr_or_null_reg */
3767 		val_reg->id = ++env->id_gen;
3768 	} else if (class == BPF_STX) {
3769 		val_reg = reg_state(env, value_regno);
3770 		if (!register_is_null(val_reg) &&
3771 		    map_kptr_match_type(env, off_desc, val_reg, value_regno))
3772 			return -EACCES;
3773 	} else if (class == BPF_ST) {
3774 		if (insn->imm) {
3775 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3776 				off_desc->offset);
3777 			return -EACCES;
3778 		}
3779 	} else {
3780 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3781 		return -EACCES;
3782 	}
3783 	return 0;
3784 }
3785 
3786 /* check read/write into a map element with possible variable offset */
3787 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3788 			    int off, int size, bool zero_size_allowed,
3789 			    enum bpf_access_src src)
3790 {
3791 	struct bpf_verifier_state *vstate = env->cur_state;
3792 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3793 	struct bpf_reg_state *reg = &state->regs[regno];
3794 	struct bpf_map *map = reg->map_ptr;
3795 	int err;
3796 
3797 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3798 				      zero_size_allowed);
3799 	if (err)
3800 		return err;
3801 
3802 	if (map_value_has_spin_lock(map)) {
3803 		u32 lock = map->spin_lock_off;
3804 
3805 		/* if any part of struct bpf_spin_lock can be touched by
3806 		 * load/store reject this program.
3807 		 * To check that [x1, x2) overlaps with [y1, y2)
3808 		 * it is sufficient to check x1 < y2 && y1 < x2.
3809 		 */
3810 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3811 		     lock < reg->umax_value + off + size) {
3812 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3813 			return -EACCES;
3814 		}
3815 	}
3816 	if (map_value_has_timer(map)) {
3817 		u32 t = map->timer_off;
3818 
3819 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3820 		     t < reg->umax_value + off + size) {
3821 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3822 			return -EACCES;
3823 		}
3824 	}
3825 	if (map_value_has_kptrs(map)) {
3826 		struct bpf_map_value_off *tab = map->kptr_off_tab;
3827 		int i;
3828 
3829 		for (i = 0; i < tab->nr_off; i++) {
3830 			u32 p = tab->off[i].offset;
3831 
3832 			if (reg->smin_value + off < p + sizeof(u64) &&
3833 			    p < reg->umax_value + off + size) {
3834 				if (src != ACCESS_DIRECT) {
3835 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
3836 					return -EACCES;
3837 				}
3838 				if (!tnum_is_const(reg->var_off)) {
3839 					verbose(env, "kptr access cannot have variable offset\n");
3840 					return -EACCES;
3841 				}
3842 				if (p != off + reg->var_off.value) {
3843 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3844 						p, off + reg->var_off.value);
3845 					return -EACCES;
3846 				}
3847 				if (size != bpf_size_to_bytes(BPF_DW)) {
3848 					verbose(env, "kptr access size must be BPF_DW\n");
3849 					return -EACCES;
3850 				}
3851 				break;
3852 			}
3853 		}
3854 	}
3855 	return err;
3856 }
3857 
3858 #define MAX_PACKET_OFF 0xffff
3859 
3860 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3861 				       const struct bpf_call_arg_meta *meta,
3862 				       enum bpf_access_type t)
3863 {
3864 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3865 
3866 	switch (prog_type) {
3867 	/* Program types only with direct read access go here! */
3868 	case BPF_PROG_TYPE_LWT_IN:
3869 	case BPF_PROG_TYPE_LWT_OUT:
3870 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3871 	case BPF_PROG_TYPE_SK_REUSEPORT:
3872 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3873 	case BPF_PROG_TYPE_CGROUP_SKB:
3874 		if (t == BPF_WRITE)
3875 			return false;
3876 		fallthrough;
3877 
3878 	/* Program types with direct read + write access go here! */
3879 	case BPF_PROG_TYPE_SCHED_CLS:
3880 	case BPF_PROG_TYPE_SCHED_ACT:
3881 	case BPF_PROG_TYPE_XDP:
3882 	case BPF_PROG_TYPE_LWT_XMIT:
3883 	case BPF_PROG_TYPE_SK_SKB:
3884 	case BPF_PROG_TYPE_SK_MSG:
3885 		if (meta)
3886 			return meta->pkt_access;
3887 
3888 		env->seen_direct_write = true;
3889 		return true;
3890 
3891 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3892 		if (t == BPF_WRITE)
3893 			env->seen_direct_write = true;
3894 
3895 		return true;
3896 
3897 	default:
3898 		return false;
3899 	}
3900 }
3901 
3902 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3903 			       int size, bool zero_size_allowed)
3904 {
3905 	struct bpf_reg_state *regs = cur_regs(env);
3906 	struct bpf_reg_state *reg = &regs[regno];
3907 	int err;
3908 
3909 	/* We may have added a variable offset to the packet pointer; but any
3910 	 * reg->range we have comes after that.  We are only checking the fixed
3911 	 * offset.
3912 	 */
3913 
3914 	/* We don't allow negative numbers, because we aren't tracking enough
3915 	 * detail to prove they're safe.
3916 	 */
3917 	if (reg->smin_value < 0) {
3918 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3919 			regno);
3920 		return -EACCES;
3921 	}
3922 
3923 	err = reg->range < 0 ? -EINVAL :
3924 	      __check_mem_access(env, regno, off, size, reg->range,
3925 				 zero_size_allowed);
3926 	if (err) {
3927 		verbose(env, "R%d offset is outside of the packet\n", regno);
3928 		return err;
3929 	}
3930 
3931 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3932 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3933 	 * otherwise find_good_pkt_pointers would have refused to set range info
3934 	 * that __check_mem_access would have rejected this pkt access.
3935 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3936 	 */
3937 	env->prog->aux->max_pkt_offset =
3938 		max_t(u32, env->prog->aux->max_pkt_offset,
3939 		      off + reg->umax_value + size - 1);
3940 
3941 	return err;
3942 }
3943 
3944 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3945 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3946 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3947 			    struct btf **btf, u32 *btf_id)
3948 {
3949 	struct bpf_insn_access_aux info = {
3950 		.reg_type = *reg_type,
3951 		.log = &env->log,
3952 	};
3953 
3954 	if (env->ops->is_valid_access &&
3955 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3956 		/* A non zero info.ctx_field_size indicates that this field is a
3957 		 * candidate for later verifier transformation to load the whole
3958 		 * field and then apply a mask when accessed with a narrower
3959 		 * access than actual ctx access size. A zero info.ctx_field_size
3960 		 * will only allow for whole field access and rejects any other
3961 		 * type of narrower access.
3962 		 */
3963 		*reg_type = info.reg_type;
3964 
3965 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3966 			*btf = info.btf;
3967 			*btf_id = info.btf_id;
3968 		} else {
3969 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3970 		}
3971 		/* remember the offset of last byte accessed in ctx */
3972 		if (env->prog->aux->max_ctx_offset < off + size)
3973 			env->prog->aux->max_ctx_offset = off + size;
3974 		return 0;
3975 	}
3976 
3977 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3978 	return -EACCES;
3979 }
3980 
3981 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3982 				  int size)
3983 {
3984 	if (size < 0 || off < 0 ||
3985 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3986 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3987 			off, size);
3988 		return -EACCES;
3989 	}
3990 	return 0;
3991 }
3992 
3993 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3994 			     u32 regno, int off, int size,
3995 			     enum bpf_access_type t)
3996 {
3997 	struct bpf_reg_state *regs = cur_regs(env);
3998 	struct bpf_reg_state *reg = &regs[regno];
3999 	struct bpf_insn_access_aux info = {};
4000 	bool valid;
4001 
4002 	if (reg->smin_value < 0) {
4003 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4004 			regno);
4005 		return -EACCES;
4006 	}
4007 
4008 	switch (reg->type) {
4009 	case PTR_TO_SOCK_COMMON:
4010 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4011 		break;
4012 	case PTR_TO_SOCKET:
4013 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4014 		break;
4015 	case PTR_TO_TCP_SOCK:
4016 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4017 		break;
4018 	case PTR_TO_XDP_SOCK:
4019 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4020 		break;
4021 	default:
4022 		valid = false;
4023 	}
4024 
4025 
4026 	if (valid) {
4027 		env->insn_aux_data[insn_idx].ctx_field_size =
4028 			info.ctx_field_size;
4029 		return 0;
4030 	}
4031 
4032 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4033 		regno, reg_type_str(env, reg->type), off, size);
4034 
4035 	return -EACCES;
4036 }
4037 
4038 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4039 {
4040 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4041 }
4042 
4043 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4044 {
4045 	const struct bpf_reg_state *reg = reg_state(env, regno);
4046 
4047 	return reg->type == PTR_TO_CTX;
4048 }
4049 
4050 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4051 {
4052 	const struct bpf_reg_state *reg = reg_state(env, regno);
4053 
4054 	return type_is_sk_pointer(reg->type);
4055 }
4056 
4057 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4058 {
4059 	const struct bpf_reg_state *reg = reg_state(env, regno);
4060 
4061 	return type_is_pkt_pointer(reg->type);
4062 }
4063 
4064 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4065 {
4066 	const struct bpf_reg_state *reg = reg_state(env, regno);
4067 
4068 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4069 	return reg->type == PTR_TO_FLOW_KEYS;
4070 }
4071 
4072 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4073 				   const struct bpf_reg_state *reg,
4074 				   int off, int size, bool strict)
4075 {
4076 	struct tnum reg_off;
4077 	int ip_align;
4078 
4079 	/* Byte size accesses are always allowed. */
4080 	if (!strict || size == 1)
4081 		return 0;
4082 
4083 	/* For platforms that do not have a Kconfig enabling
4084 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4085 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4086 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4087 	 * to this code only in strict mode where we want to emulate
4088 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4089 	 * unconditional IP align value of '2'.
4090 	 */
4091 	ip_align = 2;
4092 
4093 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4094 	if (!tnum_is_aligned(reg_off, size)) {
4095 		char tn_buf[48];
4096 
4097 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4098 		verbose(env,
4099 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4100 			ip_align, tn_buf, reg->off, off, size);
4101 		return -EACCES;
4102 	}
4103 
4104 	return 0;
4105 }
4106 
4107 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4108 				       const struct bpf_reg_state *reg,
4109 				       const char *pointer_desc,
4110 				       int off, int size, bool strict)
4111 {
4112 	struct tnum reg_off;
4113 
4114 	/* Byte size accesses are always allowed. */
4115 	if (!strict || size == 1)
4116 		return 0;
4117 
4118 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4119 	if (!tnum_is_aligned(reg_off, size)) {
4120 		char tn_buf[48];
4121 
4122 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4123 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4124 			pointer_desc, tn_buf, reg->off, off, size);
4125 		return -EACCES;
4126 	}
4127 
4128 	return 0;
4129 }
4130 
4131 static int check_ptr_alignment(struct bpf_verifier_env *env,
4132 			       const struct bpf_reg_state *reg, int off,
4133 			       int size, bool strict_alignment_once)
4134 {
4135 	bool strict = env->strict_alignment || strict_alignment_once;
4136 	const char *pointer_desc = "";
4137 
4138 	switch (reg->type) {
4139 	case PTR_TO_PACKET:
4140 	case PTR_TO_PACKET_META:
4141 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4142 		 * right in front, treat it the very same way.
4143 		 */
4144 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4145 	case PTR_TO_FLOW_KEYS:
4146 		pointer_desc = "flow keys ";
4147 		break;
4148 	case PTR_TO_MAP_KEY:
4149 		pointer_desc = "key ";
4150 		break;
4151 	case PTR_TO_MAP_VALUE:
4152 		pointer_desc = "value ";
4153 		break;
4154 	case PTR_TO_CTX:
4155 		pointer_desc = "context ";
4156 		break;
4157 	case PTR_TO_STACK:
4158 		pointer_desc = "stack ";
4159 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4160 		 * and check_stack_read_fixed_off() relies on stack accesses being
4161 		 * aligned.
4162 		 */
4163 		strict = true;
4164 		break;
4165 	case PTR_TO_SOCKET:
4166 		pointer_desc = "sock ";
4167 		break;
4168 	case PTR_TO_SOCK_COMMON:
4169 		pointer_desc = "sock_common ";
4170 		break;
4171 	case PTR_TO_TCP_SOCK:
4172 		pointer_desc = "tcp_sock ";
4173 		break;
4174 	case PTR_TO_XDP_SOCK:
4175 		pointer_desc = "xdp_sock ";
4176 		break;
4177 	default:
4178 		break;
4179 	}
4180 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4181 					   strict);
4182 }
4183 
4184 static int update_stack_depth(struct bpf_verifier_env *env,
4185 			      const struct bpf_func_state *func,
4186 			      int off)
4187 {
4188 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4189 
4190 	if (stack >= -off)
4191 		return 0;
4192 
4193 	/* update known max for given subprogram */
4194 	env->subprog_info[func->subprogno].stack_depth = -off;
4195 	return 0;
4196 }
4197 
4198 /* starting from main bpf function walk all instructions of the function
4199  * and recursively walk all callees that given function can call.
4200  * Ignore jump and exit insns.
4201  * Since recursion is prevented by check_cfg() this algorithm
4202  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4203  */
4204 static int check_max_stack_depth(struct bpf_verifier_env *env)
4205 {
4206 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4207 	struct bpf_subprog_info *subprog = env->subprog_info;
4208 	struct bpf_insn *insn = env->prog->insnsi;
4209 	bool tail_call_reachable = false;
4210 	int ret_insn[MAX_CALL_FRAMES];
4211 	int ret_prog[MAX_CALL_FRAMES];
4212 	int j;
4213 
4214 process_func:
4215 	/* protect against potential stack overflow that might happen when
4216 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4217 	 * depth for such case down to 256 so that the worst case scenario
4218 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4219 	 * 8k).
4220 	 *
4221 	 * To get the idea what might happen, see an example:
4222 	 * func1 -> sub rsp, 128
4223 	 *  subfunc1 -> sub rsp, 256
4224 	 *  tailcall1 -> add rsp, 256
4225 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4226 	 *   subfunc2 -> sub rsp, 64
4227 	 *   subfunc22 -> sub rsp, 128
4228 	 *   tailcall2 -> add rsp, 128
4229 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4230 	 *
4231 	 * tailcall will unwind the current stack frame but it will not get rid
4232 	 * of caller's stack as shown on the example above.
4233 	 */
4234 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4235 		verbose(env,
4236 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4237 			depth);
4238 		return -EACCES;
4239 	}
4240 	/* round up to 32-bytes, since this is granularity
4241 	 * of interpreter stack size
4242 	 */
4243 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4244 	if (depth > MAX_BPF_STACK) {
4245 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4246 			frame + 1, depth);
4247 		return -EACCES;
4248 	}
4249 continue_func:
4250 	subprog_end = subprog[idx + 1].start;
4251 	for (; i < subprog_end; i++) {
4252 		int next_insn;
4253 
4254 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4255 			continue;
4256 		/* remember insn and function to return to */
4257 		ret_insn[frame] = i + 1;
4258 		ret_prog[frame] = idx;
4259 
4260 		/* find the callee */
4261 		next_insn = i + insn[i].imm + 1;
4262 		idx = find_subprog(env, next_insn);
4263 		if (idx < 0) {
4264 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4265 				  next_insn);
4266 			return -EFAULT;
4267 		}
4268 		if (subprog[idx].is_async_cb) {
4269 			if (subprog[idx].has_tail_call) {
4270 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4271 				return -EFAULT;
4272 			}
4273 			 /* async callbacks don't increase bpf prog stack size */
4274 			continue;
4275 		}
4276 		i = next_insn;
4277 
4278 		if (subprog[idx].has_tail_call)
4279 			tail_call_reachable = true;
4280 
4281 		frame++;
4282 		if (frame >= MAX_CALL_FRAMES) {
4283 			verbose(env, "the call stack of %d frames is too deep !\n",
4284 				frame);
4285 			return -E2BIG;
4286 		}
4287 		goto process_func;
4288 	}
4289 	/* if tail call got detected across bpf2bpf calls then mark each of the
4290 	 * currently present subprog frames as tail call reachable subprogs;
4291 	 * this info will be utilized by JIT so that we will be preserving the
4292 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4293 	 */
4294 	if (tail_call_reachable)
4295 		for (j = 0; j < frame; j++)
4296 			subprog[ret_prog[j]].tail_call_reachable = true;
4297 	if (subprog[0].tail_call_reachable)
4298 		env->prog->aux->tail_call_reachable = true;
4299 
4300 	/* end of for() loop means the last insn of the 'subprog'
4301 	 * was reached. Doesn't matter whether it was JA or EXIT
4302 	 */
4303 	if (frame == 0)
4304 		return 0;
4305 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4306 	frame--;
4307 	i = ret_insn[frame];
4308 	idx = ret_prog[frame];
4309 	goto continue_func;
4310 }
4311 
4312 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4313 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4314 				  const struct bpf_insn *insn, int idx)
4315 {
4316 	int start = idx + insn->imm + 1, subprog;
4317 
4318 	subprog = find_subprog(env, start);
4319 	if (subprog < 0) {
4320 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4321 			  start);
4322 		return -EFAULT;
4323 	}
4324 	return env->subprog_info[subprog].stack_depth;
4325 }
4326 #endif
4327 
4328 static int __check_buffer_access(struct bpf_verifier_env *env,
4329 				 const char *buf_info,
4330 				 const struct bpf_reg_state *reg,
4331 				 int regno, int off, int size)
4332 {
4333 	if (off < 0) {
4334 		verbose(env,
4335 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4336 			regno, buf_info, off, size);
4337 		return -EACCES;
4338 	}
4339 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4340 		char tn_buf[48];
4341 
4342 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4343 		verbose(env,
4344 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4345 			regno, off, tn_buf);
4346 		return -EACCES;
4347 	}
4348 
4349 	return 0;
4350 }
4351 
4352 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4353 				  const struct bpf_reg_state *reg,
4354 				  int regno, int off, int size)
4355 {
4356 	int err;
4357 
4358 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4359 	if (err)
4360 		return err;
4361 
4362 	if (off + size > env->prog->aux->max_tp_access)
4363 		env->prog->aux->max_tp_access = off + size;
4364 
4365 	return 0;
4366 }
4367 
4368 static int check_buffer_access(struct bpf_verifier_env *env,
4369 			       const struct bpf_reg_state *reg,
4370 			       int regno, int off, int size,
4371 			       bool zero_size_allowed,
4372 			       u32 *max_access)
4373 {
4374 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4375 	int err;
4376 
4377 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4378 	if (err)
4379 		return err;
4380 
4381 	if (off + size > *max_access)
4382 		*max_access = off + size;
4383 
4384 	return 0;
4385 }
4386 
4387 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4388 static void zext_32_to_64(struct bpf_reg_state *reg)
4389 {
4390 	reg->var_off = tnum_subreg(reg->var_off);
4391 	__reg_assign_32_into_64(reg);
4392 }
4393 
4394 /* truncate register to smaller size (in bytes)
4395  * must be called with size < BPF_REG_SIZE
4396  */
4397 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4398 {
4399 	u64 mask;
4400 
4401 	/* clear high bits in bit representation */
4402 	reg->var_off = tnum_cast(reg->var_off, size);
4403 
4404 	/* fix arithmetic bounds */
4405 	mask = ((u64)1 << (size * 8)) - 1;
4406 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4407 		reg->umin_value &= mask;
4408 		reg->umax_value &= mask;
4409 	} else {
4410 		reg->umin_value = 0;
4411 		reg->umax_value = mask;
4412 	}
4413 	reg->smin_value = reg->umin_value;
4414 	reg->smax_value = reg->umax_value;
4415 
4416 	/* If size is smaller than 32bit register the 32bit register
4417 	 * values are also truncated so we push 64-bit bounds into
4418 	 * 32-bit bounds. Above were truncated < 32-bits already.
4419 	 */
4420 	if (size >= 4)
4421 		return;
4422 	__reg_combine_64_into_32(reg);
4423 }
4424 
4425 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4426 {
4427 	/* A map is considered read-only if the following condition are true:
4428 	 *
4429 	 * 1) BPF program side cannot change any of the map content. The
4430 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4431 	 *    and was set at map creation time.
4432 	 * 2) The map value(s) have been initialized from user space by a
4433 	 *    loader and then "frozen", such that no new map update/delete
4434 	 *    operations from syscall side are possible for the rest of
4435 	 *    the map's lifetime from that point onwards.
4436 	 * 3) Any parallel/pending map update/delete operations from syscall
4437 	 *    side have been completed. Only after that point, it's safe to
4438 	 *    assume that map value(s) are immutable.
4439 	 */
4440 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4441 	       READ_ONCE(map->frozen) &&
4442 	       !bpf_map_write_active(map);
4443 }
4444 
4445 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4446 {
4447 	void *ptr;
4448 	u64 addr;
4449 	int err;
4450 
4451 	err = map->ops->map_direct_value_addr(map, &addr, off);
4452 	if (err)
4453 		return err;
4454 	ptr = (void *)(long)addr + off;
4455 
4456 	switch (size) {
4457 	case sizeof(u8):
4458 		*val = (u64)*(u8 *)ptr;
4459 		break;
4460 	case sizeof(u16):
4461 		*val = (u64)*(u16 *)ptr;
4462 		break;
4463 	case sizeof(u32):
4464 		*val = (u64)*(u32 *)ptr;
4465 		break;
4466 	case sizeof(u64):
4467 		*val = *(u64 *)ptr;
4468 		break;
4469 	default:
4470 		return -EINVAL;
4471 	}
4472 	return 0;
4473 }
4474 
4475 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4476 				   struct bpf_reg_state *regs,
4477 				   int regno, int off, int size,
4478 				   enum bpf_access_type atype,
4479 				   int value_regno)
4480 {
4481 	struct bpf_reg_state *reg = regs + regno;
4482 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4483 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4484 	enum bpf_type_flag flag = 0;
4485 	u32 btf_id;
4486 	int ret;
4487 
4488 	if (off < 0) {
4489 		verbose(env,
4490 			"R%d is ptr_%s invalid negative access: off=%d\n",
4491 			regno, tname, off);
4492 		return -EACCES;
4493 	}
4494 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4495 		char tn_buf[48];
4496 
4497 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4498 		verbose(env,
4499 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4500 			regno, tname, off, tn_buf);
4501 		return -EACCES;
4502 	}
4503 
4504 	if (reg->type & MEM_USER) {
4505 		verbose(env,
4506 			"R%d is ptr_%s access user memory: off=%d\n",
4507 			regno, tname, off);
4508 		return -EACCES;
4509 	}
4510 
4511 	if (reg->type & MEM_PERCPU) {
4512 		verbose(env,
4513 			"R%d is ptr_%s access percpu memory: off=%d\n",
4514 			regno, tname, off);
4515 		return -EACCES;
4516 	}
4517 
4518 	if (env->ops->btf_struct_access) {
4519 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4520 						  off, size, atype, &btf_id, &flag);
4521 	} else {
4522 		if (atype != BPF_READ) {
4523 			verbose(env, "only read is supported\n");
4524 			return -EACCES;
4525 		}
4526 
4527 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4528 					atype, &btf_id, &flag);
4529 	}
4530 
4531 	if (ret < 0)
4532 		return ret;
4533 
4534 	/* If this is an untrusted pointer, all pointers formed by walking it
4535 	 * also inherit the untrusted flag.
4536 	 */
4537 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4538 		flag |= PTR_UNTRUSTED;
4539 
4540 	if (atype == BPF_READ && value_regno >= 0)
4541 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4542 
4543 	return 0;
4544 }
4545 
4546 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4547 				   struct bpf_reg_state *regs,
4548 				   int regno, int off, int size,
4549 				   enum bpf_access_type atype,
4550 				   int value_regno)
4551 {
4552 	struct bpf_reg_state *reg = regs + regno;
4553 	struct bpf_map *map = reg->map_ptr;
4554 	enum bpf_type_flag flag = 0;
4555 	const struct btf_type *t;
4556 	const char *tname;
4557 	u32 btf_id;
4558 	int ret;
4559 
4560 	if (!btf_vmlinux) {
4561 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4562 		return -ENOTSUPP;
4563 	}
4564 
4565 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4566 		verbose(env, "map_ptr access not supported for map type %d\n",
4567 			map->map_type);
4568 		return -ENOTSUPP;
4569 	}
4570 
4571 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4572 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4573 
4574 	if (!env->allow_ptr_to_map_access) {
4575 		verbose(env,
4576 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4577 			tname);
4578 		return -EPERM;
4579 	}
4580 
4581 	if (off < 0) {
4582 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4583 			regno, tname, off);
4584 		return -EACCES;
4585 	}
4586 
4587 	if (atype != BPF_READ) {
4588 		verbose(env, "only read from %s is supported\n", tname);
4589 		return -EACCES;
4590 	}
4591 
4592 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4593 	if (ret < 0)
4594 		return ret;
4595 
4596 	if (value_regno >= 0)
4597 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4598 
4599 	return 0;
4600 }
4601 
4602 /* Check that the stack access at the given offset is within bounds. The
4603  * maximum valid offset is -1.
4604  *
4605  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4606  * -state->allocated_stack for reads.
4607  */
4608 static int check_stack_slot_within_bounds(int off,
4609 					  struct bpf_func_state *state,
4610 					  enum bpf_access_type t)
4611 {
4612 	int min_valid_off;
4613 
4614 	if (t == BPF_WRITE)
4615 		min_valid_off = -MAX_BPF_STACK;
4616 	else
4617 		min_valid_off = -state->allocated_stack;
4618 
4619 	if (off < min_valid_off || off > -1)
4620 		return -EACCES;
4621 	return 0;
4622 }
4623 
4624 /* Check that the stack access at 'regno + off' falls within the maximum stack
4625  * bounds.
4626  *
4627  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4628  */
4629 static int check_stack_access_within_bounds(
4630 		struct bpf_verifier_env *env,
4631 		int regno, int off, int access_size,
4632 		enum bpf_access_src src, enum bpf_access_type type)
4633 {
4634 	struct bpf_reg_state *regs = cur_regs(env);
4635 	struct bpf_reg_state *reg = regs + regno;
4636 	struct bpf_func_state *state = func(env, reg);
4637 	int min_off, max_off;
4638 	int err;
4639 	char *err_extra;
4640 
4641 	if (src == ACCESS_HELPER)
4642 		/* We don't know if helpers are reading or writing (or both). */
4643 		err_extra = " indirect access to";
4644 	else if (type == BPF_READ)
4645 		err_extra = " read from";
4646 	else
4647 		err_extra = " write to";
4648 
4649 	if (tnum_is_const(reg->var_off)) {
4650 		min_off = reg->var_off.value + off;
4651 		if (access_size > 0)
4652 			max_off = min_off + access_size - 1;
4653 		else
4654 			max_off = min_off;
4655 	} else {
4656 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4657 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4658 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4659 				err_extra, regno);
4660 			return -EACCES;
4661 		}
4662 		min_off = reg->smin_value + off;
4663 		if (access_size > 0)
4664 			max_off = reg->smax_value + off + access_size - 1;
4665 		else
4666 			max_off = min_off;
4667 	}
4668 
4669 	err = check_stack_slot_within_bounds(min_off, state, type);
4670 	if (!err)
4671 		err = check_stack_slot_within_bounds(max_off, state, type);
4672 
4673 	if (err) {
4674 		if (tnum_is_const(reg->var_off)) {
4675 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4676 				err_extra, regno, off, access_size);
4677 		} else {
4678 			char tn_buf[48];
4679 
4680 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4681 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4682 				err_extra, regno, tn_buf, access_size);
4683 		}
4684 	}
4685 	return err;
4686 }
4687 
4688 /* check whether memory at (regno + off) is accessible for t = (read | write)
4689  * if t==write, value_regno is a register which value is stored into memory
4690  * if t==read, value_regno is a register which will receive the value from memory
4691  * if t==write && value_regno==-1, some unknown value is stored into memory
4692  * if t==read && value_regno==-1, don't care what we read from memory
4693  */
4694 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4695 			    int off, int bpf_size, enum bpf_access_type t,
4696 			    int value_regno, bool strict_alignment_once)
4697 {
4698 	struct bpf_reg_state *regs = cur_regs(env);
4699 	struct bpf_reg_state *reg = regs + regno;
4700 	struct bpf_func_state *state;
4701 	int size, err = 0;
4702 
4703 	size = bpf_size_to_bytes(bpf_size);
4704 	if (size < 0)
4705 		return size;
4706 
4707 	/* alignment checks will add in reg->off themselves */
4708 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4709 	if (err)
4710 		return err;
4711 
4712 	/* for access checks, reg->off is just part of off */
4713 	off += reg->off;
4714 
4715 	if (reg->type == PTR_TO_MAP_KEY) {
4716 		if (t == BPF_WRITE) {
4717 			verbose(env, "write to change key R%d not allowed\n", regno);
4718 			return -EACCES;
4719 		}
4720 
4721 		err = check_mem_region_access(env, regno, off, size,
4722 					      reg->map_ptr->key_size, false);
4723 		if (err)
4724 			return err;
4725 		if (value_regno >= 0)
4726 			mark_reg_unknown(env, regs, value_regno);
4727 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4728 		struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4729 
4730 		if (t == BPF_WRITE && value_regno >= 0 &&
4731 		    is_pointer_value(env, value_regno)) {
4732 			verbose(env, "R%d leaks addr into map\n", value_regno);
4733 			return -EACCES;
4734 		}
4735 		err = check_map_access_type(env, regno, off, size, t);
4736 		if (err)
4737 			return err;
4738 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4739 		if (err)
4740 			return err;
4741 		if (tnum_is_const(reg->var_off))
4742 			kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4743 								  off + reg->var_off.value);
4744 		if (kptr_off_desc) {
4745 			err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4746 						    kptr_off_desc);
4747 		} else if (t == BPF_READ && value_regno >= 0) {
4748 			struct bpf_map *map = reg->map_ptr;
4749 
4750 			/* if map is read-only, track its contents as scalars */
4751 			if (tnum_is_const(reg->var_off) &&
4752 			    bpf_map_is_rdonly(map) &&
4753 			    map->ops->map_direct_value_addr) {
4754 				int map_off = off + reg->var_off.value;
4755 				u64 val = 0;
4756 
4757 				err = bpf_map_direct_read(map, map_off, size,
4758 							  &val);
4759 				if (err)
4760 					return err;
4761 
4762 				regs[value_regno].type = SCALAR_VALUE;
4763 				__mark_reg_known(&regs[value_regno], val);
4764 			} else {
4765 				mark_reg_unknown(env, regs, value_regno);
4766 			}
4767 		}
4768 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4769 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4770 
4771 		if (type_may_be_null(reg->type)) {
4772 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4773 				reg_type_str(env, reg->type));
4774 			return -EACCES;
4775 		}
4776 
4777 		if (t == BPF_WRITE && rdonly_mem) {
4778 			verbose(env, "R%d cannot write into %s\n",
4779 				regno, reg_type_str(env, reg->type));
4780 			return -EACCES;
4781 		}
4782 
4783 		if (t == BPF_WRITE && value_regno >= 0 &&
4784 		    is_pointer_value(env, value_regno)) {
4785 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4786 			return -EACCES;
4787 		}
4788 
4789 		err = check_mem_region_access(env, regno, off, size,
4790 					      reg->mem_size, false);
4791 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4792 			mark_reg_unknown(env, regs, value_regno);
4793 	} else if (reg->type == PTR_TO_CTX) {
4794 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4795 		struct btf *btf = NULL;
4796 		u32 btf_id = 0;
4797 
4798 		if (t == BPF_WRITE && value_regno >= 0 &&
4799 		    is_pointer_value(env, value_regno)) {
4800 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4801 			return -EACCES;
4802 		}
4803 
4804 		err = check_ptr_off_reg(env, reg, regno);
4805 		if (err < 0)
4806 			return err;
4807 
4808 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4809 				       &btf_id);
4810 		if (err)
4811 			verbose_linfo(env, insn_idx, "; ");
4812 		if (!err && t == BPF_READ && value_regno >= 0) {
4813 			/* ctx access returns either a scalar, or a
4814 			 * PTR_TO_PACKET[_META,_END]. In the latter
4815 			 * case, we know the offset is zero.
4816 			 */
4817 			if (reg_type == SCALAR_VALUE) {
4818 				mark_reg_unknown(env, regs, value_regno);
4819 			} else {
4820 				mark_reg_known_zero(env, regs,
4821 						    value_regno);
4822 				if (type_may_be_null(reg_type))
4823 					regs[value_regno].id = ++env->id_gen;
4824 				/* A load of ctx field could have different
4825 				 * actual load size with the one encoded in the
4826 				 * insn. When the dst is PTR, it is for sure not
4827 				 * a sub-register.
4828 				 */
4829 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4830 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4831 					regs[value_regno].btf = btf;
4832 					regs[value_regno].btf_id = btf_id;
4833 				}
4834 			}
4835 			regs[value_regno].type = reg_type;
4836 		}
4837 
4838 	} else if (reg->type == PTR_TO_STACK) {
4839 		/* Basic bounds checks. */
4840 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4841 		if (err)
4842 			return err;
4843 
4844 		state = func(env, reg);
4845 		err = update_stack_depth(env, state, off);
4846 		if (err)
4847 			return err;
4848 
4849 		if (t == BPF_READ)
4850 			err = check_stack_read(env, regno, off, size,
4851 					       value_regno);
4852 		else
4853 			err = check_stack_write(env, regno, off, size,
4854 						value_regno, insn_idx);
4855 	} else if (reg_is_pkt_pointer(reg)) {
4856 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4857 			verbose(env, "cannot write into packet\n");
4858 			return -EACCES;
4859 		}
4860 		if (t == BPF_WRITE && value_regno >= 0 &&
4861 		    is_pointer_value(env, value_regno)) {
4862 			verbose(env, "R%d leaks addr into packet\n",
4863 				value_regno);
4864 			return -EACCES;
4865 		}
4866 		err = check_packet_access(env, regno, off, size, false);
4867 		if (!err && t == BPF_READ && value_regno >= 0)
4868 			mark_reg_unknown(env, regs, value_regno);
4869 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4870 		if (t == BPF_WRITE && value_regno >= 0 &&
4871 		    is_pointer_value(env, value_regno)) {
4872 			verbose(env, "R%d leaks addr into flow keys\n",
4873 				value_regno);
4874 			return -EACCES;
4875 		}
4876 
4877 		err = check_flow_keys_access(env, off, size);
4878 		if (!err && t == BPF_READ && value_regno >= 0)
4879 			mark_reg_unknown(env, regs, value_regno);
4880 	} else if (type_is_sk_pointer(reg->type)) {
4881 		if (t == BPF_WRITE) {
4882 			verbose(env, "R%d cannot write into %s\n",
4883 				regno, reg_type_str(env, reg->type));
4884 			return -EACCES;
4885 		}
4886 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4887 		if (!err && value_regno >= 0)
4888 			mark_reg_unknown(env, regs, value_regno);
4889 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4890 		err = check_tp_buffer_access(env, reg, regno, off, size);
4891 		if (!err && t == BPF_READ && value_regno >= 0)
4892 			mark_reg_unknown(env, regs, value_regno);
4893 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4894 		   !type_may_be_null(reg->type)) {
4895 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4896 					      value_regno);
4897 	} else if (reg->type == CONST_PTR_TO_MAP) {
4898 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4899 					      value_regno);
4900 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4901 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4902 		u32 *max_access;
4903 
4904 		if (rdonly_mem) {
4905 			if (t == BPF_WRITE) {
4906 				verbose(env, "R%d cannot write into %s\n",
4907 					regno, reg_type_str(env, reg->type));
4908 				return -EACCES;
4909 			}
4910 			max_access = &env->prog->aux->max_rdonly_access;
4911 		} else {
4912 			max_access = &env->prog->aux->max_rdwr_access;
4913 		}
4914 
4915 		err = check_buffer_access(env, reg, regno, off, size, false,
4916 					  max_access);
4917 
4918 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4919 			mark_reg_unknown(env, regs, value_regno);
4920 	} else {
4921 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4922 			reg_type_str(env, reg->type));
4923 		return -EACCES;
4924 	}
4925 
4926 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4927 	    regs[value_regno].type == SCALAR_VALUE) {
4928 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4929 		coerce_reg_to_size(&regs[value_regno], size);
4930 	}
4931 	return err;
4932 }
4933 
4934 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4935 {
4936 	int load_reg;
4937 	int err;
4938 
4939 	switch (insn->imm) {
4940 	case BPF_ADD:
4941 	case BPF_ADD | BPF_FETCH:
4942 	case BPF_AND:
4943 	case BPF_AND | BPF_FETCH:
4944 	case BPF_OR:
4945 	case BPF_OR | BPF_FETCH:
4946 	case BPF_XOR:
4947 	case BPF_XOR | BPF_FETCH:
4948 	case BPF_XCHG:
4949 	case BPF_CMPXCHG:
4950 		break;
4951 	default:
4952 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4953 		return -EINVAL;
4954 	}
4955 
4956 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4957 		verbose(env, "invalid atomic operand size\n");
4958 		return -EINVAL;
4959 	}
4960 
4961 	/* check src1 operand */
4962 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4963 	if (err)
4964 		return err;
4965 
4966 	/* check src2 operand */
4967 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4968 	if (err)
4969 		return err;
4970 
4971 	if (insn->imm == BPF_CMPXCHG) {
4972 		/* Check comparison of R0 with memory location */
4973 		const u32 aux_reg = BPF_REG_0;
4974 
4975 		err = check_reg_arg(env, aux_reg, SRC_OP);
4976 		if (err)
4977 			return err;
4978 
4979 		if (is_pointer_value(env, aux_reg)) {
4980 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4981 			return -EACCES;
4982 		}
4983 	}
4984 
4985 	if (is_pointer_value(env, insn->src_reg)) {
4986 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4987 		return -EACCES;
4988 	}
4989 
4990 	if (is_ctx_reg(env, insn->dst_reg) ||
4991 	    is_pkt_reg(env, insn->dst_reg) ||
4992 	    is_flow_key_reg(env, insn->dst_reg) ||
4993 	    is_sk_reg(env, insn->dst_reg)) {
4994 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4995 			insn->dst_reg,
4996 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4997 		return -EACCES;
4998 	}
4999 
5000 	if (insn->imm & BPF_FETCH) {
5001 		if (insn->imm == BPF_CMPXCHG)
5002 			load_reg = BPF_REG_0;
5003 		else
5004 			load_reg = insn->src_reg;
5005 
5006 		/* check and record load of old value */
5007 		err = check_reg_arg(env, load_reg, DST_OP);
5008 		if (err)
5009 			return err;
5010 	} else {
5011 		/* This instruction accesses a memory location but doesn't
5012 		 * actually load it into a register.
5013 		 */
5014 		load_reg = -1;
5015 	}
5016 
5017 	/* Check whether we can read the memory, with second call for fetch
5018 	 * case to simulate the register fill.
5019 	 */
5020 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5021 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5022 	if (!err && load_reg >= 0)
5023 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5024 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5025 				       true);
5026 	if (err)
5027 		return err;
5028 
5029 	/* Check whether we can write into the same memory. */
5030 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5031 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5032 	if (err)
5033 		return err;
5034 
5035 	return 0;
5036 }
5037 
5038 /* When register 'regno' is used to read the stack (either directly or through
5039  * a helper function) make sure that it's within stack boundary and, depending
5040  * on the access type, that all elements of the stack are initialized.
5041  *
5042  * 'off' includes 'regno->off', but not its dynamic part (if any).
5043  *
5044  * All registers that have been spilled on the stack in the slots within the
5045  * read offsets are marked as read.
5046  */
5047 static int check_stack_range_initialized(
5048 		struct bpf_verifier_env *env, int regno, int off,
5049 		int access_size, bool zero_size_allowed,
5050 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5051 {
5052 	struct bpf_reg_state *reg = reg_state(env, regno);
5053 	struct bpf_func_state *state = func(env, reg);
5054 	int err, min_off, max_off, i, j, slot, spi;
5055 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5056 	enum bpf_access_type bounds_check_type;
5057 	/* Some accesses can write anything into the stack, others are
5058 	 * read-only.
5059 	 */
5060 	bool clobber = false;
5061 
5062 	if (access_size == 0 && !zero_size_allowed) {
5063 		verbose(env, "invalid zero-sized read\n");
5064 		return -EACCES;
5065 	}
5066 
5067 	if (type == ACCESS_HELPER) {
5068 		/* The bounds checks for writes are more permissive than for
5069 		 * reads. However, if raw_mode is not set, we'll do extra
5070 		 * checks below.
5071 		 */
5072 		bounds_check_type = BPF_WRITE;
5073 		clobber = true;
5074 	} else {
5075 		bounds_check_type = BPF_READ;
5076 	}
5077 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5078 					       type, bounds_check_type);
5079 	if (err)
5080 		return err;
5081 
5082 
5083 	if (tnum_is_const(reg->var_off)) {
5084 		min_off = max_off = reg->var_off.value + off;
5085 	} else {
5086 		/* Variable offset is prohibited for unprivileged mode for
5087 		 * simplicity since it requires corresponding support in
5088 		 * Spectre masking for stack ALU.
5089 		 * See also retrieve_ptr_limit().
5090 		 */
5091 		if (!env->bypass_spec_v1) {
5092 			char tn_buf[48];
5093 
5094 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5095 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5096 				regno, err_extra, tn_buf);
5097 			return -EACCES;
5098 		}
5099 		/* Only initialized buffer on stack is allowed to be accessed
5100 		 * with variable offset. With uninitialized buffer it's hard to
5101 		 * guarantee that whole memory is marked as initialized on
5102 		 * helper return since specific bounds are unknown what may
5103 		 * cause uninitialized stack leaking.
5104 		 */
5105 		if (meta && meta->raw_mode)
5106 			meta = NULL;
5107 
5108 		min_off = reg->smin_value + off;
5109 		max_off = reg->smax_value + off;
5110 	}
5111 
5112 	if (meta && meta->raw_mode) {
5113 		meta->access_size = access_size;
5114 		meta->regno = regno;
5115 		return 0;
5116 	}
5117 
5118 	for (i = min_off; i < max_off + access_size; i++) {
5119 		u8 *stype;
5120 
5121 		slot = -i - 1;
5122 		spi = slot / BPF_REG_SIZE;
5123 		if (state->allocated_stack <= slot)
5124 			goto err;
5125 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5126 		if (*stype == STACK_MISC)
5127 			goto mark;
5128 		if (*stype == STACK_ZERO) {
5129 			if (clobber) {
5130 				/* helper can write anything into the stack */
5131 				*stype = STACK_MISC;
5132 			}
5133 			goto mark;
5134 		}
5135 
5136 		if (is_spilled_reg(&state->stack[spi]) &&
5137 		    base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5138 			goto mark;
5139 
5140 		if (is_spilled_reg(&state->stack[spi]) &&
5141 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5142 		     env->allow_ptr_leaks)) {
5143 			if (clobber) {
5144 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5145 				for (j = 0; j < BPF_REG_SIZE; j++)
5146 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5147 			}
5148 			goto mark;
5149 		}
5150 
5151 err:
5152 		if (tnum_is_const(reg->var_off)) {
5153 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5154 				err_extra, regno, min_off, i - min_off, access_size);
5155 		} else {
5156 			char tn_buf[48];
5157 
5158 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5159 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5160 				err_extra, regno, tn_buf, i - min_off, access_size);
5161 		}
5162 		return -EACCES;
5163 mark:
5164 		/* reading any byte out of 8-byte 'spill_slot' will cause
5165 		 * the whole slot to be marked as 'read'
5166 		 */
5167 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5168 			      state->stack[spi].spilled_ptr.parent,
5169 			      REG_LIVE_READ64);
5170 	}
5171 	return update_stack_depth(env, state, min_off);
5172 }
5173 
5174 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5175 				   int access_size, bool zero_size_allowed,
5176 				   struct bpf_call_arg_meta *meta)
5177 {
5178 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5179 	u32 *max_access;
5180 
5181 	switch (base_type(reg->type)) {
5182 	case PTR_TO_PACKET:
5183 	case PTR_TO_PACKET_META:
5184 		return check_packet_access(env, regno, reg->off, access_size,
5185 					   zero_size_allowed);
5186 	case PTR_TO_MAP_KEY:
5187 		if (meta && meta->raw_mode) {
5188 			verbose(env, "R%d cannot write into %s\n", regno,
5189 				reg_type_str(env, reg->type));
5190 			return -EACCES;
5191 		}
5192 		return check_mem_region_access(env, regno, reg->off, access_size,
5193 					       reg->map_ptr->key_size, false);
5194 	case PTR_TO_MAP_VALUE:
5195 		if (check_map_access_type(env, regno, reg->off, access_size,
5196 					  meta && meta->raw_mode ? BPF_WRITE :
5197 					  BPF_READ))
5198 			return -EACCES;
5199 		return check_map_access(env, regno, reg->off, access_size,
5200 					zero_size_allowed, ACCESS_HELPER);
5201 	case PTR_TO_MEM:
5202 		if (type_is_rdonly_mem(reg->type)) {
5203 			if (meta && meta->raw_mode) {
5204 				verbose(env, "R%d cannot write into %s\n", regno,
5205 					reg_type_str(env, reg->type));
5206 				return -EACCES;
5207 			}
5208 		}
5209 		return check_mem_region_access(env, regno, reg->off,
5210 					       access_size, reg->mem_size,
5211 					       zero_size_allowed);
5212 	case PTR_TO_BUF:
5213 		if (type_is_rdonly_mem(reg->type)) {
5214 			if (meta && meta->raw_mode) {
5215 				verbose(env, "R%d cannot write into %s\n", regno,
5216 					reg_type_str(env, reg->type));
5217 				return -EACCES;
5218 			}
5219 
5220 			max_access = &env->prog->aux->max_rdonly_access;
5221 		} else {
5222 			max_access = &env->prog->aux->max_rdwr_access;
5223 		}
5224 		return check_buffer_access(env, reg, regno, reg->off,
5225 					   access_size, zero_size_allowed,
5226 					   max_access);
5227 	case PTR_TO_STACK:
5228 		return check_stack_range_initialized(
5229 				env,
5230 				regno, reg->off, access_size,
5231 				zero_size_allowed, ACCESS_HELPER, meta);
5232 	default: /* scalar_value or invalid ptr */
5233 		/* Allow zero-byte read from NULL, regardless of pointer type */
5234 		if (zero_size_allowed && access_size == 0 &&
5235 		    register_is_null(reg))
5236 			return 0;
5237 
5238 		verbose(env, "R%d type=%s ", regno,
5239 			reg_type_str(env, reg->type));
5240 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5241 		return -EACCES;
5242 	}
5243 }
5244 
5245 static int check_mem_size_reg(struct bpf_verifier_env *env,
5246 			      struct bpf_reg_state *reg, u32 regno,
5247 			      bool zero_size_allowed,
5248 			      struct bpf_call_arg_meta *meta)
5249 {
5250 	int err;
5251 
5252 	/* This is used to refine r0 return value bounds for helpers
5253 	 * that enforce this value as an upper bound on return values.
5254 	 * See do_refine_retval_range() for helpers that can refine
5255 	 * the return value. C type of helper is u32 so we pull register
5256 	 * bound from umax_value however, if negative verifier errors
5257 	 * out. Only upper bounds can be learned because retval is an
5258 	 * int type and negative retvals are allowed.
5259 	 */
5260 	meta->msize_max_value = reg->umax_value;
5261 
5262 	/* The register is SCALAR_VALUE; the access check
5263 	 * happens using its boundaries.
5264 	 */
5265 	if (!tnum_is_const(reg->var_off))
5266 		/* For unprivileged variable accesses, disable raw
5267 		 * mode so that the program is required to
5268 		 * initialize all the memory that the helper could
5269 		 * just partially fill up.
5270 		 */
5271 		meta = NULL;
5272 
5273 	if (reg->smin_value < 0) {
5274 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5275 			regno);
5276 		return -EACCES;
5277 	}
5278 
5279 	if (reg->umin_value == 0) {
5280 		err = check_helper_mem_access(env, regno - 1, 0,
5281 					      zero_size_allowed,
5282 					      meta);
5283 		if (err)
5284 			return err;
5285 	}
5286 
5287 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5288 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5289 			regno);
5290 		return -EACCES;
5291 	}
5292 	err = check_helper_mem_access(env, regno - 1,
5293 				      reg->umax_value,
5294 				      zero_size_allowed, meta);
5295 	if (!err)
5296 		err = mark_chain_precision(env, regno);
5297 	return err;
5298 }
5299 
5300 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5301 		   u32 regno, u32 mem_size)
5302 {
5303 	bool may_be_null = type_may_be_null(reg->type);
5304 	struct bpf_reg_state saved_reg;
5305 	struct bpf_call_arg_meta meta;
5306 	int err;
5307 
5308 	if (register_is_null(reg))
5309 		return 0;
5310 
5311 	memset(&meta, 0, sizeof(meta));
5312 	/* Assuming that the register contains a value check if the memory
5313 	 * access is safe. Temporarily save and restore the register's state as
5314 	 * the conversion shouldn't be visible to a caller.
5315 	 */
5316 	if (may_be_null) {
5317 		saved_reg = *reg;
5318 		mark_ptr_not_null_reg(reg);
5319 	}
5320 
5321 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5322 	/* Check access for BPF_WRITE */
5323 	meta.raw_mode = true;
5324 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5325 
5326 	if (may_be_null)
5327 		*reg = saved_reg;
5328 
5329 	return err;
5330 }
5331 
5332 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5333 			     u32 regno)
5334 {
5335 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5336 	bool may_be_null = type_may_be_null(mem_reg->type);
5337 	struct bpf_reg_state saved_reg;
5338 	struct bpf_call_arg_meta meta;
5339 	int err;
5340 
5341 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5342 
5343 	memset(&meta, 0, sizeof(meta));
5344 
5345 	if (may_be_null) {
5346 		saved_reg = *mem_reg;
5347 		mark_ptr_not_null_reg(mem_reg);
5348 	}
5349 
5350 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5351 	/* Check access for BPF_WRITE */
5352 	meta.raw_mode = true;
5353 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5354 
5355 	if (may_be_null)
5356 		*mem_reg = saved_reg;
5357 	return err;
5358 }
5359 
5360 /* Implementation details:
5361  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5362  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5363  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5364  * value_or_null->value transition, since the verifier only cares about
5365  * the range of access to valid map value pointer and doesn't care about actual
5366  * address of the map element.
5367  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5368  * reg->id > 0 after value_or_null->value transition. By doing so
5369  * two bpf_map_lookups will be considered two different pointers that
5370  * point to different bpf_spin_locks.
5371  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5372  * dead-locks.
5373  * Since only one bpf_spin_lock is allowed the checks are simpler than
5374  * reg_is_refcounted() logic. The verifier needs to remember only
5375  * one spin_lock instead of array of acquired_refs.
5376  * cur_state->active_spin_lock remembers which map value element got locked
5377  * and clears it after bpf_spin_unlock.
5378  */
5379 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5380 			     bool is_lock)
5381 {
5382 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5383 	struct bpf_verifier_state *cur = env->cur_state;
5384 	bool is_const = tnum_is_const(reg->var_off);
5385 	struct bpf_map *map = reg->map_ptr;
5386 	u64 val = reg->var_off.value;
5387 
5388 	if (!is_const) {
5389 		verbose(env,
5390 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5391 			regno);
5392 		return -EINVAL;
5393 	}
5394 	if (!map->btf) {
5395 		verbose(env,
5396 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5397 			map->name);
5398 		return -EINVAL;
5399 	}
5400 	if (!map_value_has_spin_lock(map)) {
5401 		if (map->spin_lock_off == -E2BIG)
5402 			verbose(env,
5403 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
5404 				map->name);
5405 		else if (map->spin_lock_off == -ENOENT)
5406 			verbose(env,
5407 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
5408 				map->name);
5409 		else
5410 			verbose(env,
5411 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5412 				map->name);
5413 		return -EINVAL;
5414 	}
5415 	if (map->spin_lock_off != val + reg->off) {
5416 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5417 			val + reg->off);
5418 		return -EINVAL;
5419 	}
5420 	if (is_lock) {
5421 		if (cur->active_spin_lock) {
5422 			verbose(env,
5423 				"Locking two bpf_spin_locks are not allowed\n");
5424 			return -EINVAL;
5425 		}
5426 		cur->active_spin_lock = reg->id;
5427 	} else {
5428 		if (!cur->active_spin_lock) {
5429 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5430 			return -EINVAL;
5431 		}
5432 		if (cur->active_spin_lock != reg->id) {
5433 			verbose(env, "bpf_spin_unlock of different lock\n");
5434 			return -EINVAL;
5435 		}
5436 		cur->active_spin_lock = 0;
5437 	}
5438 	return 0;
5439 }
5440 
5441 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5442 			      struct bpf_call_arg_meta *meta)
5443 {
5444 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5445 	bool is_const = tnum_is_const(reg->var_off);
5446 	struct bpf_map *map = reg->map_ptr;
5447 	u64 val = reg->var_off.value;
5448 
5449 	if (!is_const) {
5450 		verbose(env,
5451 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5452 			regno);
5453 		return -EINVAL;
5454 	}
5455 	if (!map->btf) {
5456 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5457 			map->name);
5458 		return -EINVAL;
5459 	}
5460 	if (!map_value_has_timer(map)) {
5461 		if (map->timer_off == -E2BIG)
5462 			verbose(env,
5463 				"map '%s' has more than one 'struct bpf_timer'\n",
5464 				map->name);
5465 		else if (map->timer_off == -ENOENT)
5466 			verbose(env,
5467 				"map '%s' doesn't have 'struct bpf_timer'\n",
5468 				map->name);
5469 		else
5470 			verbose(env,
5471 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5472 				map->name);
5473 		return -EINVAL;
5474 	}
5475 	if (map->timer_off != val + reg->off) {
5476 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5477 			val + reg->off, map->timer_off);
5478 		return -EINVAL;
5479 	}
5480 	if (meta->map_ptr) {
5481 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5482 		return -EFAULT;
5483 	}
5484 	meta->map_uid = reg->map_uid;
5485 	meta->map_ptr = map;
5486 	return 0;
5487 }
5488 
5489 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5490 			     struct bpf_call_arg_meta *meta)
5491 {
5492 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5493 	struct bpf_map_value_off_desc *off_desc;
5494 	struct bpf_map *map_ptr = reg->map_ptr;
5495 	u32 kptr_off;
5496 	int ret;
5497 
5498 	if (!tnum_is_const(reg->var_off)) {
5499 		verbose(env,
5500 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5501 			regno);
5502 		return -EINVAL;
5503 	}
5504 	if (!map_ptr->btf) {
5505 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5506 			map_ptr->name);
5507 		return -EINVAL;
5508 	}
5509 	if (!map_value_has_kptrs(map_ptr)) {
5510 		ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5511 		if (ret == -E2BIG)
5512 			verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5513 				BPF_MAP_VALUE_OFF_MAX);
5514 		else if (ret == -EEXIST)
5515 			verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5516 		else
5517 			verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5518 		return -EINVAL;
5519 	}
5520 
5521 	meta->map_ptr = map_ptr;
5522 	kptr_off = reg->off + reg->var_off.value;
5523 	off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5524 	if (!off_desc) {
5525 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5526 		return -EACCES;
5527 	}
5528 	if (off_desc->type != BPF_KPTR_REF) {
5529 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5530 		return -EACCES;
5531 	}
5532 	meta->kptr_off_desc = off_desc;
5533 	return 0;
5534 }
5535 
5536 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5537 {
5538 	return type == ARG_CONST_SIZE ||
5539 	       type == ARG_CONST_SIZE_OR_ZERO;
5540 }
5541 
5542 static bool arg_type_is_release(enum bpf_arg_type type)
5543 {
5544 	return type & OBJ_RELEASE;
5545 }
5546 
5547 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5548 {
5549 	return base_type(type) == ARG_PTR_TO_DYNPTR;
5550 }
5551 
5552 static int int_ptr_type_to_size(enum bpf_arg_type type)
5553 {
5554 	if (type == ARG_PTR_TO_INT)
5555 		return sizeof(u32);
5556 	else if (type == ARG_PTR_TO_LONG)
5557 		return sizeof(u64);
5558 
5559 	return -EINVAL;
5560 }
5561 
5562 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5563 				 const struct bpf_call_arg_meta *meta,
5564 				 enum bpf_arg_type *arg_type)
5565 {
5566 	if (!meta->map_ptr) {
5567 		/* kernel subsystem misconfigured verifier */
5568 		verbose(env, "invalid map_ptr to access map->type\n");
5569 		return -EACCES;
5570 	}
5571 
5572 	switch (meta->map_ptr->map_type) {
5573 	case BPF_MAP_TYPE_SOCKMAP:
5574 	case BPF_MAP_TYPE_SOCKHASH:
5575 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5576 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5577 		} else {
5578 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5579 			return -EINVAL;
5580 		}
5581 		break;
5582 	case BPF_MAP_TYPE_BLOOM_FILTER:
5583 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5584 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5585 		break;
5586 	default:
5587 		break;
5588 	}
5589 	return 0;
5590 }
5591 
5592 struct bpf_reg_types {
5593 	const enum bpf_reg_type types[10];
5594 	u32 *btf_id;
5595 };
5596 
5597 static const struct bpf_reg_types map_key_value_types = {
5598 	.types = {
5599 		PTR_TO_STACK,
5600 		PTR_TO_PACKET,
5601 		PTR_TO_PACKET_META,
5602 		PTR_TO_MAP_KEY,
5603 		PTR_TO_MAP_VALUE,
5604 	},
5605 };
5606 
5607 static const struct bpf_reg_types sock_types = {
5608 	.types = {
5609 		PTR_TO_SOCK_COMMON,
5610 		PTR_TO_SOCKET,
5611 		PTR_TO_TCP_SOCK,
5612 		PTR_TO_XDP_SOCK,
5613 	},
5614 };
5615 
5616 #ifdef CONFIG_NET
5617 static const struct bpf_reg_types btf_id_sock_common_types = {
5618 	.types = {
5619 		PTR_TO_SOCK_COMMON,
5620 		PTR_TO_SOCKET,
5621 		PTR_TO_TCP_SOCK,
5622 		PTR_TO_XDP_SOCK,
5623 		PTR_TO_BTF_ID,
5624 	},
5625 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5626 };
5627 #endif
5628 
5629 static const struct bpf_reg_types mem_types = {
5630 	.types = {
5631 		PTR_TO_STACK,
5632 		PTR_TO_PACKET,
5633 		PTR_TO_PACKET_META,
5634 		PTR_TO_MAP_KEY,
5635 		PTR_TO_MAP_VALUE,
5636 		PTR_TO_MEM,
5637 		PTR_TO_MEM | MEM_ALLOC,
5638 		PTR_TO_BUF,
5639 	},
5640 };
5641 
5642 static const struct bpf_reg_types int_ptr_types = {
5643 	.types = {
5644 		PTR_TO_STACK,
5645 		PTR_TO_PACKET,
5646 		PTR_TO_PACKET_META,
5647 		PTR_TO_MAP_KEY,
5648 		PTR_TO_MAP_VALUE,
5649 	},
5650 };
5651 
5652 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5653 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5654 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5655 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5656 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5657 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5658 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5659 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5660 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5661 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5662 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5663 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5664 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5665 
5666 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5667 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5668 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5669 	[ARG_CONST_SIZE]		= &scalar_types,
5670 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5671 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5672 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5673 	[ARG_PTR_TO_CTX]		= &context_types,
5674 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5675 #ifdef CONFIG_NET
5676 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5677 #endif
5678 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5679 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5680 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5681 	[ARG_PTR_TO_MEM]		= &mem_types,
5682 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5683 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5684 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5685 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5686 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5687 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5688 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5689 	[ARG_PTR_TO_TIMER]		= &timer_types,
5690 	[ARG_PTR_TO_KPTR]		= &kptr_types,
5691 	[ARG_PTR_TO_DYNPTR]		= &stack_ptr_types,
5692 };
5693 
5694 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5695 			  enum bpf_arg_type arg_type,
5696 			  const u32 *arg_btf_id,
5697 			  struct bpf_call_arg_meta *meta)
5698 {
5699 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5700 	enum bpf_reg_type expected, type = reg->type;
5701 	const struct bpf_reg_types *compatible;
5702 	int i, j;
5703 
5704 	compatible = compatible_reg_types[base_type(arg_type)];
5705 	if (!compatible) {
5706 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5707 		return -EFAULT;
5708 	}
5709 
5710 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5711 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5712 	 *
5713 	 * Same for MAYBE_NULL:
5714 	 *
5715 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5716 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5717 	 *
5718 	 * Therefore we fold these flags depending on the arg_type before comparison.
5719 	 */
5720 	if (arg_type & MEM_RDONLY)
5721 		type &= ~MEM_RDONLY;
5722 	if (arg_type & PTR_MAYBE_NULL)
5723 		type &= ~PTR_MAYBE_NULL;
5724 
5725 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5726 		expected = compatible->types[i];
5727 		if (expected == NOT_INIT)
5728 			break;
5729 
5730 		if (type == expected)
5731 			goto found;
5732 	}
5733 
5734 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5735 	for (j = 0; j + 1 < i; j++)
5736 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5737 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5738 	return -EACCES;
5739 
5740 found:
5741 	if (reg->type == PTR_TO_BTF_ID) {
5742 		/* For bpf_sk_release, it needs to match against first member
5743 		 * 'struct sock_common', hence make an exception for it. This
5744 		 * allows bpf_sk_release to work for multiple socket types.
5745 		 */
5746 		bool strict_type_match = arg_type_is_release(arg_type) &&
5747 					 meta->func_id != BPF_FUNC_sk_release;
5748 
5749 		if (!arg_btf_id) {
5750 			if (!compatible->btf_id) {
5751 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5752 				return -EFAULT;
5753 			}
5754 			arg_btf_id = compatible->btf_id;
5755 		}
5756 
5757 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
5758 			if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5759 				return -EACCES;
5760 		} else if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5761 						 btf_vmlinux, *arg_btf_id,
5762 						 strict_type_match)) {
5763 			verbose(env, "R%d is of type %s but %s is expected\n",
5764 				regno, kernel_type_name(reg->btf, reg->btf_id),
5765 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5766 			return -EACCES;
5767 		}
5768 	}
5769 
5770 	return 0;
5771 }
5772 
5773 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5774 			   const struct bpf_reg_state *reg, int regno,
5775 			   enum bpf_arg_type arg_type)
5776 {
5777 	enum bpf_reg_type type = reg->type;
5778 	bool fixed_off_ok = false;
5779 
5780 	switch ((u32)type) {
5781 	/* Pointer types where reg offset is explicitly allowed: */
5782 	case PTR_TO_STACK:
5783 		if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5784 			verbose(env, "cannot pass in dynptr at an offset\n");
5785 			return -EINVAL;
5786 		}
5787 		fallthrough;
5788 	case PTR_TO_PACKET:
5789 	case PTR_TO_PACKET_META:
5790 	case PTR_TO_MAP_KEY:
5791 	case PTR_TO_MAP_VALUE:
5792 	case PTR_TO_MEM:
5793 	case PTR_TO_MEM | MEM_RDONLY:
5794 	case PTR_TO_MEM | MEM_ALLOC:
5795 	case PTR_TO_BUF:
5796 	case PTR_TO_BUF | MEM_RDONLY:
5797 	case SCALAR_VALUE:
5798 		/* Some of the argument types nevertheless require a
5799 		 * zero register offset.
5800 		 */
5801 		if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5802 			return 0;
5803 		break;
5804 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5805 	 * fixed offset.
5806 	 */
5807 	case PTR_TO_BTF_ID:
5808 		/* When referenced PTR_TO_BTF_ID is passed to release function,
5809 		 * it's fixed offset must be 0.	In the other cases, fixed offset
5810 		 * can be non-zero.
5811 		 */
5812 		if (arg_type_is_release(arg_type) && reg->off) {
5813 			verbose(env, "R%d must have zero offset when passed to release func\n",
5814 				regno);
5815 			return -EINVAL;
5816 		}
5817 		/* For arg is release pointer, fixed_off_ok must be false, but
5818 		 * we already checked and rejected reg->off != 0 above, so set
5819 		 * to true to allow fixed offset for all other cases.
5820 		 */
5821 		fixed_off_ok = true;
5822 		break;
5823 	default:
5824 		break;
5825 	}
5826 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5827 }
5828 
5829 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5830 {
5831 	struct bpf_func_state *state = func(env, reg);
5832 	int spi = get_spi(reg->off);
5833 
5834 	return state->stack[spi].spilled_ptr.id;
5835 }
5836 
5837 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5838 			  struct bpf_call_arg_meta *meta,
5839 			  const struct bpf_func_proto *fn)
5840 {
5841 	u32 regno = BPF_REG_1 + arg;
5842 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5843 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5844 	enum bpf_reg_type type = reg->type;
5845 	u32 *arg_btf_id = NULL;
5846 	int err = 0;
5847 
5848 	if (arg_type == ARG_DONTCARE)
5849 		return 0;
5850 
5851 	err = check_reg_arg(env, regno, SRC_OP);
5852 	if (err)
5853 		return err;
5854 
5855 	if (arg_type == ARG_ANYTHING) {
5856 		if (is_pointer_value(env, regno)) {
5857 			verbose(env, "R%d leaks addr into helper function\n",
5858 				regno);
5859 			return -EACCES;
5860 		}
5861 		return 0;
5862 	}
5863 
5864 	if (type_is_pkt_pointer(type) &&
5865 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5866 		verbose(env, "helper access to the packet is not allowed\n");
5867 		return -EACCES;
5868 	}
5869 
5870 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5871 		err = resolve_map_arg_type(env, meta, &arg_type);
5872 		if (err)
5873 			return err;
5874 	}
5875 
5876 	if (register_is_null(reg) && type_may_be_null(arg_type))
5877 		/* A NULL register has a SCALAR_VALUE type, so skip
5878 		 * type checking.
5879 		 */
5880 		goto skip_type_check;
5881 
5882 	/* arg_btf_id and arg_size are in a union. */
5883 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5884 		arg_btf_id = fn->arg_btf_id[arg];
5885 
5886 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5887 	if (err)
5888 		return err;
5889 
5890 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
5891 	if (err)
5892 		return err;
5893 
5894 skip_type_check:
5895 	if (arg_type_is_release(arg_type)) {
5896 		if (arg_type_is_dynptr(arg_type)) {
5897 			struct bpf_func_state *state = func(env, reg);
5898 			int spi = get_spi(reg->off);
5899 
5900 			if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5901 			    !state->stack[spi].spilled_ptr.id) {
5902 				verbose(env, "arg %d is an unacquired reference\n", regno);
5903 				return -EINVAL;
5904 			}
5905 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
5906 			verbose(env, "R%d must be referenced when passed to release function\n",
5907 				regno);
5908 			return -EINVAL;
5909 		}
5910 		if (meta->release_regno) {
5911 			verbose(env, "verifier internal error: more than one release argument\n");
5912 			return -EFAULT;
5913 		}
5914 		meta->release_regno = regno;
5915 	}
5916 
5917 	if (reg->ref_obj_id) {
5918 		if (meta->ref_obj_id) {
5919 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5920 				regno, reg->ref_obj_id,
5921 				meta->ref_obj_id);
5922 			return -EFAULT;
5923 		}
5924 		meta->ref_obj_id = reg->ref_obj_id;
5925 	}
5926 
5927 	switch (base_type(arg_type)) {
5928 	case ARG_CONST_MAP_PTR:
5929 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5930 		if (meta->map_ptr) {
5931 			/* Use map_uid (which is unique id of inner map) to reject:
5932 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5933 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5934 			 * if (inner_map1 && inner_map2) {
5935 			 *     timer = bpf_map_lookup_elem(inner_map1);
5936 			 *     if (timer)
5937 			 *         // mismatch would have been allowed
5938 			 *         bpf_timer_init(timer, inner_map2);
5939 			 * }
5940 			 *
5941 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5942 			 */
5943 			if (meta->map_ptr != reg->map_ptr ||
5944 			    meta->map_uid != reg->map_uid) {
5945 				verbose(env,
5946 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5947 					meta->map_uid, reg->map_uid);
5948 				return -EINVAL;
5949 			}
5950 		}
5951 		meta->map_ptr = reg->map_ptr;
5952 		meta->map_uid = reg->map_uid;
5953 		break;
5954 	case ARG_PTR_TO_MAP_KEY:
5955 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5956 		 * check that [key, key + map->key_size) are within
5957 		 * stack limits and initialized
5958 		 */
5959 		if (!meta->map_ptr) {
5960 			/* in function declaration map_ptr must come before
5961 			 * map_key, so that it's verified and known before
5962 			 * we have to check map_key here. Otherwise it means
5963 			 * that kernel subsystem misconfigured verifier
5964 			 */
5965 			verbose(env, "invalid map_ptr to access map->key\n");
5966 			return -EACCES;
5967 		}
5968 		err = check_helper_mem_access(env, regno,
5969 					      meta->map_ptr->key_size, false,
5970 					      NULL);
5971 		break;
5972 	case ARG_PTR_TO_MAP_VALUE:
5973 		if (type_may_be_null(arg_type) && register_is_null(reg))
5974 			return 0;
5975 
5976 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5977 		 * check [value, value + map->value_size) validity
5978 		 */
5979 		if (!meta->map_ptr) {
5980 			/* kernel subsystem misconfigured verifier */
5981 			verbose(env, "invalid map_ptr to access map->value\n");
5982 			return -EACCES;
5983 		}
5984 		meta->raw_mode = arg_type & MEM_UNINIT;
5985 		err = check_helper_mem_access(env, regno,
5986 					      meta->map_ptr->value_size, false,
5987 					      meta);
5988 		break;
5989 	case ARG_PTR_TO_PERCPU_BTF_ID:
5990 		if (!reg->btf_id) {
5991 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5992 			return -EACCES;
5993 		}
5994 		meta->ret_btf = reg->btf;
5995 		meta->ret_btf_id = reg->btf_id;
5996 		break;
5997 	case ARG_PTR_TO_SPIN_LOCK:
5998 		if (meta->func_id == BPF_FUNC_spin_lock) {
5999 			if (process_spin_lock(env, regno, true))
6000 				return -EACCES;
6001 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6002 			if (process_spin_lock(env, regno, false))
6003 				return -EACCES;
6004 		} else {
6005 			verbose(env, "verifier internal error\n");
6006 			return -EFAULT;
6007 		}
6008 		break;
6009 	case ARG_PTR_TO_TIMER:
6010 		if (process_timer_func(env, regno, meta))
6011 			return -EACCES;
6012 		break;
6013 	case ARG_PTR_TO_FUNC:
6014 		meta->subprogno = reg->subprogno;
6015 		break;
6016 	case ARG_PTR_TO_MEM:
6017 		/* The access to this pointer is only checked when we hit the
6018 		 * next is_mem_size argument below.
6019 		 */
6020 		meta->raw_mode = arg_type & MEM_UNINIT;
6021 		if (arg_type & MEM_FIXED_SIZE) {
6022 			err = check_helper_mem_access(env, regno,
6023 						      fn->arg_size[arg], false,
6024 						      meta);
6025 		}
6026 		break;
6027 	case ARG_CONST_SIZE:
6028 		err = check_mem_size_reg(env, reg, regno, false, meta);
6029 		break;
6030 	case ARG_CONST_SIZE_OR_ZERO:
6031 		err = check_mem_size_reg(env, reg, regno, true, meta);
6032 		break;
6033 	case ARG_PTR_TO_DYNPTR:
6034 		if (arg_type & MEM_UNINIT) {
6035 			if (!is_dynptr_reg_valid_uninit(env, reg)) {
6036 				verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6037 				return -EINVAL;
6038 			}
6039 
6040 			/* We only support one dynptr being uninitialized at the moment,
6041 			 * which is sufficient for the helper functions we have right now.
6042 			 */
6043 			if (meta->uninit_dynptr_regno) {
6044 				verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6045 				return -EFAULT;
6046 			}
6047 
6048 			meta->uninit_dynptr_regno = regno;
6049 		} else if (!is_dynptr_reg_valid_init(env, reg, arg_type)) {
6050 			const char *err_extra = "";
6051 
6052 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6053 			case DYNPTR_TYPE_LOCAL:
6054 				err_extra = "local ";
6055 				break;
6056 			case DYNPTR_TYPE_RINGBUF:
6057 				err_extra = "ringbuf ";
6058 				break;
6059 			default:
6060 				break;
6061 			}
6062 
6063 			verbose(env, "Expected an initialized %sdynptr as arg #%d\n",
6064 				err_extra, arg + 1);
6065 			return -EINVAL;
6066 		}
6067 		break;
6068 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6069 		if (!tnum_is_const(reg->var_off)) {
6070 			verbose(env, "R%d is not a known constant'\n",
6071 				regno);
6072 			return -EACCES;
6073 		}
6074 		meta->mem_size = reg->var_off.value;
6075 		break;
6076 	case ARG_PTR_TO_INT:
6077 	case ARG_PTR_TO_LONG:
6078 	{
6079 		int size = int_ptr_type_to_size(arg_type);
6080 
6081 		err = check_helper_mem_access(env, regno, size, false, meta);
6082 		if (err)
6083 			return err;
6084 		err = check_ptr_alignment(env, reg, 0, size, true);
6085 		break;
6086 	}
6087 	case ARG_PTR_TO_CONST_STR:
6088 	{
6089 		struct bpf_map *map = reg->map_ptr;
6090 		int map_off;
6091 		u64 map_addr;
6092 		char *str_ptr;
6093 
6094 		if (!bpf_map_is_rdonly(map)) {
6095 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6096 			return -EACCES;
6097 		}
6098 
6099 		if (!tnum_is_const(reg->var_off)) {
6100 			verbose(env, "R%d is not a constant address'\n", regno);
6101 			return -EACCES;
6102 		}
6103 
6104 		if (!map->ops->map_direct_value_addr) {
6105 			verbose(env, "no direct value access support for this map type\n");
6106 			return -EACCES;
6107 		}
6108 
6109 		err = check_map_access(env, regno, reg->off,
6110 				       map->value_size - reg->off, false,
6111 				       ACCESS_HELPER);
6112 		if (err)
6113 			return err;
6114 
6115 		map_off = reg->off + reg->var_off.value;
6116 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6117 		if (err) {
6118 			verbose(env, "direct value access on string failed\n");
6119 			return err;
6120 		}
6121 
6122 		str_ptr = (char *)(long)(map_addr);
6123 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6124 			verbose(env, "string is not zero-terminated\n");
6125 			return -EINVAL;
6126 		}
6127 		break;
6128 	}
6129 	case ARG_PTR_TO_KPTR:
6130 		if (process_kptr_func(env, regno, meta))
6131 			return -EACCES;
6132 		break;
6133 	}
6134 
6135 	return err;
6136 }
6137 
6138 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6139 {
6140 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6141 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6142 
6143 	if (func_id != BPF_FUNC_map_update_elem)
6144 		return false;
6145 
6146 	/* It's not possible to get access to a locked struct sock in these
6147 	 * contexts, so updating is safe.
6148 	 */
6149 	switch (type) {
6150 	case BPF_PROG_TYPE_TRACING:
6151 		if (eatype == BPF_TRACE_ITER)
6152 			return true;
6153 		break;
6154 	case BPF_PROG_TYPE_SOCKET_FILTER:
6155 	case BPF_PROG_TYPE_SCHED_CLS:
6156 	case BPF_PROG_TYPE_SCHED_ACT:
6157 	case BPF_PROG_TYPE_XDP:
6158 	case BPF_PROG_TYPE_SK_REUSEPORT:
6159 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6160 	case BPF_PROG_TYPE_SK_LOOKUP:
6161 		return true;
6162 	default:
6163 		break;
6164 	}
6165 
6166 	verbose(env, "cannot update sockmap in this context\n");
6167 	return false;
6168 }
6169 
6170 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6171 {
6172 	return env->prog->jit_requested &&
6173 	       bpf_jit_supports_subprog_tailcalls();
6174 }
6175 
6176 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6177 					struct bpf_map *map, int func_id)
6178 {
6179 	if (!map)
6180 		return 0;
6181 
6182 	/* We need a two way check, first is from map perspective ... */
6183 	switch (map->map_type) {
6184 	case BPF_MAP_TYPE_PROG_ARRAY:
6185 		if (func_id != BPF_FUNC_tail_call)
6186 			goto error;
6187 		break;
6188 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6189 		if (func_id != BPF_FUNC_perf_event_read &&
6190 		    func_id != BPF_FUNC_perf_event_output &&
6191 		    func_id != BPF_FUNC_skb_output &&
6192 		    func_id != BPF_FUNC_perf_event_read_value &&
6193 		    func_id != BPF_FUNC_xdp_output)
6194 			goto error;
6195 		break;
6196 	case BPF_MAP_TYPE_RINGBUF:
6197 		if (func_id != BPF_FUNC_ringbuf_output &&
6198 		    func_id != BPF_FUNC_ringbuf_reserve &&
6199 		    func_id != BPF_FUNC_ringbuf_query &&
6200 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6201 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6202 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6203 			goto error;
6204 		break;
6205 	case BPF_MAP_TYPE_STACK_TRACE:
6206 		if (func_id != BPF_FUNC_get_stackid)
6207 			goto error;
6208 		break;
6209 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6210 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6211 		    func_id != BPF_FUNC_current_task_under_cgroup)
6212 			goto error;
6213 		break;
6214 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6215 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6216 		if (func_id != BPF_FUNC_get_local_storage)
6217 			goto error;
6218 		break;
6219 	case BPF_MAP_TYPE_DEVMAP:
6220 	case BPF_MAP_TYPE_DEVMAP_HASH:
6221 		if (func_id != BPF_FUNC_redirect_map &&
6222 		    func_id != BPF_FUNC_map_lookup_elem)
6223 			goto error;
6224 		break;
6225 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6226 	 * appear.
6227 	 */
6228 	case BPF_MAP_TYPE_CPUMAP:
6229 		if (func_id != BPF_FUNC_redirect_map)
6230 			goto error;
6231 		break;
6232 	case BPF_MAP_TYPE_XSKMAP:
6233 		if (func_id != BPF_FUNC_redirect_map &&
6234 		    func_id != BPF_FUNC_map_lookup_elem)
6235 			goto error;
6236 		break;
6237 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6238 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6239 		if (func_id != BPF_FUNC_map_lookup_elem)
6240 			goto error;
6241 		break;
6242 	case BPF_MAP_TYPE_SOCKMAP:
6243 		if (func_id != BPF_FUNC_sk_redirect_map &&
6244 		    func_id != BPF_FUNC_sock_map_update &&
6245 		    func_id != BPF_FUNC_map_delete_elem &&
6246 		    func_id != BPF_FUNC_msg_redirect_map &&
6247 		    func_id != BPF_FUNC_sk_select_reuseport &&
6248 		    func_id != BPF_FUNC_map_lookup_elem &&
6249 		    !may_update_sockmap(env, func_id))
6250 			goto error;
6251 		break;
6252 	case BPF_MAP_TYPE_SOCKHASH:
6253 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6254 		    func_id != BPF_FUNC_sock_hash_update &&
6255 		    func_id != BPF_FUNC_map_delete_elem &&
6256 		    func_id != BPF_FUNC_msg_redirect_hash &&
6257 		    func_id != BPF_FUNC_sk_select_reuseport &&
6258 		    func_id != BPF_FUNC_map_lookup_elem &&
6259 		    !may_update_sockmap(env, func_id))
6260 			goto error;
6261 		break;
6262 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6263 		if (func_id != BPF_FUNC_sk_select_reuseport)
6264 			goto error;
6265 		break;
6266 	case BPF_MAP_TYPE_QUEUE:
6267 	case BPF_MAP_TYPE_STACK:
6268 		if (func_id != BPF_FUNC_map_peek_elem &&
6269 		    func_id != BPF_FUNC_map_pop_elem &&
6270 		    func_id != BPF_FUNC_map_push_elem)
6271 			goto error;
6272 		break;
6273 	case BPF_MAP_TYPE_SK_STORAGE:
6274 		if (func_id != BPF_FUNC_sk_storage_get &&
6275 		    func_id != BPF_FUNC_sk_storage_delete)
6276 			goto error;
6277 		break;
6278 	case BPF_MAP_TYPE_INODE_STORAGE:
6279 		if (func_id != BPF_FUNC_inode_storage_get &&
6280 		    func_id != BPF_FUNC_inode_storage_delete)
6281 			goto error;
6282 		break;
6283 	case BPF_MAP_TYPE_TASK_STORAGE:
6284 		if (func_id != BPF_FUNC_task_storage_get &&
6285 		    func_id != BPF_FUNC_task_storage_delete)
6286 			goto error;
6287 		break;
6288 	case BPF_MAP_TYPE_BLOOM_FILTER:
6289 		if (func_id != BPF_FUNC_map_peek_elem &&
6290 		    func_id != BPF_FUNC_map_push_elem)
6291 			goto error;
6292 		break;
6293 	default:
6294 		break;
6295 	}
6296 
6297 	/* ... and second from the function itself. */
6298 	switch (func_id) {
6299 	case BPF_FUNC_tail_call:
6300 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6301 			goto error;
6302 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6303 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6304 			return -EINVAL;
6305 		}
6306 		break;
6307 	case BPF_FUNC_perf_event_read:
6308 	case BPF_FUNC_perf_event_output:
6309 	case BPF_FUNC_perf_event_read_value:
6310 	case BPF_FUNC_skb_output:
6311 	case BPF_FUNC_xdp_output:
6312 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6313 			goto error;
6314 		break;
6315 	case BPF_FUNC_ringbuf_output:
6316 	case BPF_FUNC_ringbuf_reserve:
6317 	case BPF_FUNC_ringbuf_query:
6318 	case BPF_FUNC_ringbuf_reserve_dynptr:
6319 	case BPF_FUNC_ringbuf_submit_dynptr:
6320 	case BPF_FUNC_ringbuf_discard_dynptr:
6321 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6322 			goto error;
6323 		break;
6324 	case BPF_FUNC_get_stackid:
6325 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6326 			goto error;
6327 		break;
6328 	case BPF_FUNC_current_task_under_cgroup:
6329 	case BPF_FUNC_skb_under_cgroup:
6330 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6331 			goto error;
6332 		break;
6333 	case BPF_FUNC_redirect_map:
6334 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6335 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6336 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6337 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6338 			goto error;
6339 		break;
6340 	case BPF_FUNC_sk_redirect_map:
6341 	case BPF_FUNC_msg_redirect_map:
6342 	case BPF_FUNC_sock_map_update:
6343 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6344 			goto error;
6345 		break;
6346 	case BPF_FUNC_sk_redirect_hash:
6347 	case BPF_FUNC_msg_redirect_hash:
6348 	case BPF_FUNC_sock_hash_update:
6349 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6350 			goto error;
6351 		break;
6352 	case BPF_FUNC_get_local_storage:
6353 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6354 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6355 			goto error;
6356 		break;
6357 	case BPF_FUNC_sk_select_reuseport:
6358 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6359 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6360 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6361 			goto error;
6362 		break;
6363 	case BPF_FUNC_map_pop_elem:
6364 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6365 		    map->map_type != BPF_MAP_TYPE_STACK)
6366 			goto error;
6367 		break;
6368 	case BPF_FUNC_map_peek_elem:
6369 	case BPF_FUNC_map_push_elem:
6370 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6371 		    map->map_type != BPF_MAP_TYPE_STACK &&
6372 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6373 			goto error;
6374 		break;
6375 	case BPF_FUNC_map_lookup_percpu_elem:
6376 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6377 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6378 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6379 			goto error;
6380 		break;
6381 	case BPF_FUNC_sk_storage_get:
6382 	case BPF_FUNC_sk_storage_delete:
6383 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6384 			goto error;
6385 		break;
6386 	case BPF_FUNC_inode_storage_get:
6387 	case BPF_FUNC_inode_storage_delete:
6388 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6389 			goto error;
6390 		break;
6391 	case BPF_FUNC_task_storage_get:
6392 	case BPF_FUNC_task_storage_delete:
6393 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6394 			goto error;
6395 		break;
6396 	default:
6397 		break;
6398 	}
6399 
6400 	return 0;
6401 error:
6402 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6403 		map->map_type, func_id_name(func_id), func_id);
6404 	return -EINVAL;
6405 }
6406 
6407 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6408 {
6409 	int count = 0;
6410 
6411 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6412 		count++;
6413 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6414 		count++;
6415 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6416 		count++;
6417 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6418 		count++;
6419 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6420 		count++;
6421 
6422 	/* We only support one arg being in raw mode at the moment,
6423 	 * which is sufficient for the helper functions we have
6424 	 * right now.
6425 	 */
6426 	return count <= 1;
6427 }
6428 
6429 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6430 {
6431 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6432 	bool has_size = fn->arg_size[arg] != 0;
6433 	bool is_next_size = false;
6434 
6435 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6436 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6437 
6438 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6439 		return is_next_size;
6440 
6441 	return has_size == is_next_size || is_next_size == is_fixed;
6442 }
6443 
6444 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6445 {
6446 	/* bpf_xxx(..., buf, len) call will access 'len'
6447 	 * bytes from memory 'buf'. Both arg types need
6448 	 * to be paired, so make sure there's no buggy
6449 	 * helper function specification.
6450 	 */
6451 	if (arg_type_is_mem_size(fn->arg1_type) ||
6452 	    check_args_pair_invalid(fn, 0) ||
6453 	    check_args_pair_invalid(fn, 1) ||
6454 	    check_args_pair_invalid(fn, 2) ||
6455 	    check_args_pair_invalid(fn, 3) ||
6456 	    check_args_pair_invalid(fn, 4))
6457 		return false;
6458 
6459 	return true;
6460 }
6461 
6462 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6463 {
6464 	int i;
6465 
6466 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6467 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6468 			return false;
6469 
6470 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6471 		    /* arg_btf_id and arg_size are in a union. */
6472 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6473 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6474 			return false;
6475 	}
6476 
6477 	return true;
6478 }
6479 
6480 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6481 {
6482 	return check_raw_mode_ok(fn) &&
6483 	       check_arg_pair_ok(fn) &&
6484 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6485 }
6486 
6487 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6488  * are now invalid, so turn them into unknown SCALAR_VALUE.
6489  */
6490 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
6491 				     struct bpf_func_state *state)
6492 {
6493 	struct bpf_reg_state *regs = state->regs, *reg;
6494 	int i;
6495 
6496 	for (i = 0; i < MAX_BPF_REG; i++)
6497 		if (reg_is_pkt_pointer_any(&regs[i]))
6498 			mark_reg_unknown(env, regs, i);
6499 
6500 	bpf_for_each_spilled_reg(i, state, reg) {
6501 		if (!reg)
6502 			continue;
6503 		if (reg_is_pkt_pointer_any(reg))
6504 			__mark_reg_unknown(env, reg);
6505 	}
6506 }
6507 
6508 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6509 {
6510 	struct bpf_verifier_state *vstate = env->cur_state;
6511 	int i;
6512 
6513 	for (i = 0; i <= vstate->curframe; i++)
6514 		__clear_all_pkt_pointers(env, vstate->frame[i]);
6515 }
6516 
6517 enum {
6518 	AT_PKT_END = -1,
6519 	BEYOND_PKT_END = -2,
6520 };
6521 
6522 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6523 {
6524 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6525 	struct bpf_reg_state *reg = &state->regs[regn];
6526 
6527 	if (reg->type != PTR_TO_PACKET)
6528 		/* PTR_TO_PACKET_META is not supported yet */
6529 		return;
6530 
6531 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6532 	 * How far beyond pkt_end it goes is unknown.
6533 	 * if (!range_open) it's the case of pkt >= pkt_end
6534 	 * if (range_open) it's the case of pkt > pkt_end
6535 	 * hence this pointer is at least 1 byte bigger than pkt_end
6536 	 */
6537 	if (range_open)
6538 		reg->range = BEYOND_PKT_END;
6539 	else
6540 		reg->range = AT_PKT_END;
6541 }
6542 
6543 static void release_reg_references(struct bpf_verifier_env *env,
6544 				   struct bpf_func_state *state,
6545 				   int ref_obj_id)
6546 {
6547 	struct bpf_reg_state *regs = state->regs, *reg;
6548 	int i;
6549 
6550 	for (i = 0; i < MAX_BPF_REG; i++)
6551 		if (regs[i].ref_obj_id == ref_obj_id)
6552 			mark_reg_unknown(env, regs, i);
6553 
6554 	bpf_for_each_spilled_reg(i, state, reg) {
6555 		if (!reg)
6556 			continue;
6557 		if (reg->ref_obj_id == ref_obj_id)
6558 			__mark_reg_unknown(env, reg);
6559 	}
6560 }
6561 
6562 /* The pointer with the specified id has released its reference to kernel
6563  * resources. Identify all copies of the same pointer and clear the reference.
6564  */
6565 static int release_reference(struct bpf_verifier_env *env,
6566 			     int ref_obj_id)
6567 {
6568 	struct bpf_verifier_state *vstate = env->cur_state;
6569 	int err;
6570 	int i;
6571 
6572 	err = release_reference_state(cur_func(env), ref_obj_id);
6573 	if (err)
6574 		return err;
6575 
6576 	for (i = 0; i <= vstate->curframe; i++)
6577 		release_reg_references(env, vstate->frame[i], ref_obj_id);
6578 
6579 	return 0;
6580 }
6581 
6582 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6583 				    struct bpf_reg_state *regs)
6584 {
6585 	int i;
6586 
6587 	/* after the call registers r0 - r5 were scratched */
6588 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6589 		mark_reg_not_init(env, regs, caller_saved[i]);
6590 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6591 	}
6592 }
6593 
6594 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6595 				   struct bpf_func_state *caller,
6596 				   struct bpf_func_state *callee,
6597 				   int insn_idx);
6598 
6599 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6600 			     int *insn_idx, int subprog,
6601 			     set_callee_state_fn set_callee_state_cb)
6602 {
6603 	struct bpf_verifier_state *state = env->cur_state;
6604 	struct bpf_func_info_aux *func_info_aux;
6605 	struct bpf_func_state *caller, *callee;
6606 	int err;
6607 	bool is_global = false;
6608 
6609 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6610 		verbose(env, "the call stack of %d frames is too deep\n",
6611 			state->curframe + 2);
6612 		return -E2BIG;
6613 	}
6614 
6615 	caller = state->frame[state->curframe];
6616 	if (state->frame[state->curframe + 1]) {
6617 		verbose(env, "verifier bug. Frame %d already allocated\n",
6618 			state->curframe + 1);
6619 		return -EFAULT;
6620 	}
6621 
6622 	func_info_aux = env->prog->aux->func_info_aux;
6623 	if (func_info_aux)
6624 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6625 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6626 	if (err == -EFAULT)
6627 		return err;
6628 	if (is_global) {
6629 		if (err) {
6630 			verbose(env, "Caller passes invalid args into func#%d\n",
6631 				subprog);
6632 			return err;
6633 		} else {
6634 			if (env->log.level & BPF_LOG_LEVEL)
6635 				verbose(env,
6636 					"Func#%d is global and valid. Skipping.\n",
6637 					subprog);
6638 			clear_caller_saved_regs(env, caller->regs);
6639 
6640 			/* All global functions return a 64-bit SCALAR_VALUE */
6641 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6642 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6643 
6644 			/* continue with next insn after call */
6645 			return 0;
6646 		}
6647 	}
6648 
6649 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6650 	    insn->src_reg == 0 &&
6651 	    insn->imm == BPF_FUNC_timer_set_callback) {
6652 		struct bpf_verifier_state *async_cb;
6653 
6654 		/* there is no real recursion here. timer callbacks are async */
6655 		env->subprog_info[subprog].is_async_cb = true;
6656 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6657 					 *insn_idx, subprog);
6658 		if (!async_cb)
6659 			return -EFAULT;
6660 		callee = async_cb->frame[0];
6661 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6662 
6663 		/* Convert bpf_timer_set_callback() args into timer callback args */
6664 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6665 		if (err)
6666 			return err;
6667 
6668 		clear_caller_saved_regs(env, caller->regs);
6669 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6670 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6671 		/* continue with next insn after call */
6672 		return 0;
6673 	}
6674 
6675 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6676 	if (!callee)
6677 		return -ENOMEM;
6678 	state->frame[state->curframe + 1] = callee;
6679 
6680 	/* callee cannot access r0, r6 - r9 for reading and has to write
6681 	 * into its own stack before reading from it.
6682 	 * callee can read/write into caller's stack
6683 	 */
6684 	init_func_state(env, callee,
6685 			/* remember the callsite, it will be used by bpf_exit */
6686 			*insn_idx /* callsite */,
6687 			state->curframe + 1 /* frameno within this callchain */,
6688 			subprog /* subprog number within this prog */);
6689 
6690 	/* Transfer references to the callee */
6691 	err = copy_reference_state(callee, caller);
6692 	if (err)
6693 		return err;
6694 
6695 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6696 	if (err)
6697 		return err;
6698 
6699 	clear_caller_saved_regs(env, caller->regs);
6700 
6701 	/* only increment it after check_reg_arg() finished */
6702 	state->curframe++;
6703 
6704 	/* and go analyze first insn of the callee */
6705 	*insn_idx = env->subprog_info[subprog].start - 1;
6706 
6707 	if (env->log.level & BPF_LOG_LEVEL) {
6708 		verbose(env, "caller:\n");
6709 		print_verifier_state(env, caller, true);
6710 		verbose(env, "callee:\n");
6711 		print_verifier_state(env, callee, true);
6712 	}
6713 	return 0;
6714 }
6715 
6716 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6717 				   struct bpf_func_state *caller,
6718 				   struct bpf_func_state *callee)
6719 {
6720 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6721 	 *      void *callback_ctx, u64 flags);
6722 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6723 	 *      void *callback_ctx);
6724 	 */
6725 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6726 
6727 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6728 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6729 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6730 
6731 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6732 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6733 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6734 
6735 	/* pointer to stack or null */
6736 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6737 
6738 	/* unused */
6739 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6740 	return 0;
6741 }
6742 
6743 static int set_callee_state(struct bpf_verifier_env *env,
6744 			    struct bpf_func_state *caller,
6745 			    struct bpf_func_state *callee, int insn_idx)
6746 {
6747 	int i;
6748 
6749 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6750 	 * pointers, which connects us up to the liveness chain
6751 	 */
6752 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6753 		callee->regs[i] = caller->regs[i];
6754 	return 0;
6755 }
6756 
6757 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6758 			   int *insn_idx)
6759 {
6760 	int subprog, target_insn;
6761 
6762 	target_insn = *insn_idx + insn->imm + 1;
6763 	subprog = find_subprog(env, target_insn);
6764 	if (subprog < 0) {
6765 		verbose(env, "verifier bug. No program starts at insn %d\n",
6766 			target_insn);
6767 		return -EFAULT;
6768 	}
6769 
6770 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6771 }
6772 
6773 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6774 				       struct bpf_func_state *caller,
6775 				       struct bpf_func_state *callee,
6776 				       int insn_idx)
6777 {
6778 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6779 	struct bpf_map *map;
6780 	int err;
6781 
6782 	if (bpf_map_ptr_poisoned(insn_aux)) {
6783 		verbose(env, "tail_call abusing map_ptr\n");
6784 		return -EINVAL;
6785 	}
6786 
6787 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6788 	if (!map->ops->map_set_for_each_callback_args ||
6789 	    !map->ops->map_for_each_callback) {
6790 		verbose(env, "callback function not allowed for map\n");
6791 		return -ENOTSUPP;
6792 	}
6793 
6794 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6795 	if (err)
6796 		return err;
6797 
6798 	callee->in_callback_fn = true;
6799 	return 0;
6800 }
6801 
6802 static int set_loop_callback_state(struct bpf_verifier_env *env,
6803 				   struct bpf_func_state *caller,
6804 				   struct bpf_func_state *callee,
6805 				   int insn_idx)
6806 {
6807 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6808 	 *	    u64 flags);
6809 	 * callback_fn(u32 index, void *callback_ctx);
6810 	 */
6811 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6812 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6813 
6814 	/* unused */
6815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6817 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6818 
6819 	callee->in_callback_fn = true;
6820 	return 0;
6821 }
6822 
6823 static int set_timer_callback_state(struct bpf_verifier_env *env,
6824 				    struct bpf_func_state *caller,
6825 				    struct bpf_func_state *callee,
6826 				    int insn_idx)
6827 {
6828 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6829 
6830 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6831 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6832 	 */
6833 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6834 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6835 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6836 
6837 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6838 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6839 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6840 
6841 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6842 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6843 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6844 
6845 	/* unused */
6846 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6847 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6848 	callee->in_async_callback_fn = true;
6849 	return 0;
6850 }
6851 
6852 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6853 				       struct bpf_func_state *caller,
6854 				       struct bpf_func_state *callee,
6855 				       int insn_idx)
6856 {
6857 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6858 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6859 	 * (callback_fn)(struct task_struct *task,
6860 	 *               struct vm_area_struct *vma, void *callback_ctx);
6861 	 */
6862 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6863 
6864 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6865 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6866 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6867 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6868 
6869 	/* pointer to stack or null */
6870 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6871 
6872 	/* unused */
6873 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6874 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6875 	callee->in_callback_fn = true;
6876 	return 0;
6877 }
6878 
6879 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6880 {
6881 	struct bpf_verifier_state *state = env->cur_state;
6882 	struct bpf_func_state *caller, *callee;
6883 	struct bpf_reg_state *r0;
6884 	int err;
6885 
6886 	callee = state->frame[state->curframe];
6887 	r0 = &callee->regs[BPF_REG_0];
6888 	if (r0->type == PTR_TO_STACK) {
6889 		/* technically it's ok to return caller's stack pointer
6890 		 * (or caller's caller's pointer) back to the caller,
6891 		 * since these pointers are valid. Only current stack
6892 		 * pointer will be invalid as soon as function exits,
6893 		 * but let's be conservative
6894 		 */
6895 		verbose(env, "cannot return stack pointer to the caller\n");
6896 		return -EINVAL;
6897 	}
6898 
6899 	state->curframe--;
6900 	caller = state->frame[state->curframe];
6901 	if (callee->in_callback_fn) {
6902 		/* enforce R0 return value range [0, 1]. */
6903 		struct tnum range = tnum_range(0, 1);
6904 
6905 		if (r0->type != SCALAR_VALUE) {
6906 			verbose(env, "R0 not a scalar value\n");
6907 			return -EACCES;
6908 		}
6909 		if (!tnum_in(range, r0->var_off)) {
6910 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6911 			return -EINVAL;
6912 		}
6913 	} else {
6914 		/* return to the caller whatever r0 had in the callee */
6915 		caller->regs[BPF_REG_0] = *r0;
6916 	}
6917 
6918 	/* Transfer references to the caller */
6919 	err = copy_reference_state(caller, callee);
6920 	if (err)
6921 		return err;
6922 
6923 	*insn_idx = callee->callsite + 1;
6924 	if (env->log.level & BPF_LOG_LEVEL) {
6925 		verbose(env, "returning from callee:\n");
6926 		print_verifier_state(env, callee, true);
6927 		verbose(env, "to caller at %d:\n", *insn_idx);
6928 		print_verifier_state(env, caller, true);
6929 	}
6930 	/* clear everything in the callee */
6931 	free_func_state(callee);
6932 	state->frame[state->curframe + 1] = NULL;
6933 	return 0;
6934 }
6935 
6936 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6937 				   int func_id,
6938 				   struct bpf_call_arg_meta *meta)
6939 {
6940 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6941 
6942 	if (ret_type != RET_INTEGER ||
6943 	    (func_id != BPF_FUNC_get_stack &&
6944 	     func_id != BPF_FUNC_get_task_stack &&
6945 	     func_id != BPF_FUNC_probe_read_str &&
6946 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6947 	     func_id != BPF_FUNC_probe_read_user_str))
6948 		return;
6949 
6950 	ret_reg->smax_value = meta->msize_max_value;
6951 	ret_reg->s32_max_value = meta->msize_max_value;
6952 	ret_reg->smin_value = -MAX_ERRNO;
6953 	ret_reg->s32_min_value = -MAX_ERRNO;
6954 	reg_bounds_sync(ret_reg);
6955 }
6956 
6957 static int
6958 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6959 		int func_id, int insn_idx)
6960 {
6961 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6962 	struct bpf_map *map = meta->map_ptr;
6963 
6964 	if (func_id != BPF_FUNC_tail_call &&
6965 	    func_id != BPF_FUNC_map_lookup_elem &&
6966 	    func_id != BPF_FUNC_map_update_elem &&
6967 	    func_id != BPF_FUNC_map_delete_elem &&
6968 	    func_id != BPF_FUNC_map_push_elem &&
6969 	    func_id != BPF_FUNC_map_pop_elem &&
6970 	    func_id != BPF_FUNC_map_peek_elem &&
6971 	    func_id != BPF_FUNC_for_each_map_elem &&
6972 	    func_id != BPF_FUNC_redirect_map &&
6973 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
6974 		return 0;
6975 
6976 	if (map == NULL) {
6977 		verbose(env, "kernel subsystem misconfigured verifier\n");
6978 		return -EINVAL;
6979 	}
6980 
6981 	/* In case of read-only, some additional restrictions
6982 	 * need to be applied in order to prevent altering the
6983 	 * state of the map from program side.
6984 	 */
6985 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6986 	    (func_id == BPF_FUNC_map_delete_elem ||
6987 	     func_id == BPF_FUNC_map_update_elem ||
6988 	     func_id == BPF_FUNC_map_push_elem ||
6989 	     func_id == BPF_FUNC_map_pop_elem)) {
6990 		verbose(env, "write into map forbidden\n");
6991 		return -EACCES;
6992 	}
6993 
6994 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6995 		bpf_map_ptr_store(aux, meta->map_ptr,
6996 				  !meta->map_ptr->bypass_spec_v1);
6997 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6998 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6999 				  !meta->map_ptr->bypass_spec_v1);
7000 	return 0;
7001 }
7002 
7003 static int
7004 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7005 		int func_id, int insn_idx)
7006 {
7007 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7008 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7009 	struct bpf_map *map = meta->map_ptr;
7010 	struct tnum range;
7011 	u64 val;
7012 	int err;
7013 
7014 	if (func_id != BPF_FUNC_tail_call)
7015 		return 0;
7016 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7017 		verbose(env, "kernel subsystem misconfigured verifier\n");
7018 		return -EINVAL;
7019 	}
7020 
7021 	range = tnum_range(0, map->max_entries - 1);
7022 	reg = &regs[BPF_REG_3];
7023 
7024 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
7025 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7026 		return 0;
7027 	}
7028 
7029 	err = mark_chain_precision(env, BPF_REG_3);
7030 	if (err)
7031 		return err;
7032 
7033 	val = reg->var_off.value;
7034 	if (bpf_map_key_unseen(aux))
7035 		bpf_map_key_store(aux, val);
7036 	else if (!bpf_map_key_poisoned(aux) &&
7037 		  bpf_map_key_immediate(aux) != val)
7038 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7039 	return 0;
7040 }
7041 
7042 static int check_reference_leak(struct bpf_verifier_env *env)
7043 {
7044 	struct bpf_func_state *state = cur_func(env);
7045 	int i;
7046 
7047 	for (i = 0; i < state->acquired_refs; i++) {
7048 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7049 			state->refs[i].id, state->refs[i].insn_idx);
7050 	}
7051 	return state->acquired_refs ? -EINVAL : 0;
7052 }
7053 
7054 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7055 				   struct bpf_reg_state *regs)
7056 {
7057 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7058 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7059 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7060 	int err, fmt_map_off, num_args;
7061 	u64 fmt_addr;
7062 	char *fmt;
7063 
7064 	/* data must be an array of u64 */
7065 	if (data_len_reg->var_off.value % 8)
7066 		return -EINVAL;
7067 	num_args = data_len_reg->var_off.value / 8;
7068 
7069 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7070 	 * and map_direct_value_addr is set.
7071 	 */
7072 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7073 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7074 						  fmt_map_off);
7075 	if (err) {
7076 		verbose(env, "verifier bug\n");
7077 		return -EFAULT;
7078 	}
7079 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7080 
7081 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7082 	 * can focus on validating the format specifiers.
7083 	 */
7084 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7085 	if (err < 0)
7086 		verbose(env, "Invalid format string\n");
7087 
7088 	return err;
7089 }
7090 
7091 static int check_get_func_ip(struct bpf_verifier_env *env)
7092 {
7093 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7094 	int func_id = BPF_FUNC_get_func_ip;
7095 
7096 	if (type == BPF_PROG_TYPE_TRACING) {
7097 		if (!bpf_prog_has_trampoline(env->prog)) {
7098 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7099 				func_id_name(func_id), func_id);
7100 			return -ENOTSUPP;
7101 		}
7102 		return 0;
7103 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7104 		return 0;
7105 	}
7106 
7107 	verbose(env, "func %s#%d not supported for program type %d\n",
7108 		func_id_name(func_id), func_id, type);
7109 	return -ENOTSUPP;
7110 }
7111 
7112 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7113 {
7114 	return &env->insn_aux_data[env->insn_idx];
7115 }
7116 
7117 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7118 {
7119 	struct bpf_reg_state *regs = cur_regs(env);
7120 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7121 	bool reg_is_null = register_is_null(reg);
7122 
7123 	if (reg_is_null)
7124 		mark_chain_precision(env, BPF_REG_4);
7125 
7126 	return reg_is_null;
7127 }
7128 
7129 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7130 {
7131 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7132 
7133 	if (!state->initialized) {
7134 		state->initialized = 1;
7135 		state->fit_for_inline = loop_flag_is_zero(env);
7136 		state->callback_subprogno = subprogno;
7137 		return;
7138 	}
7139 
7140 	if (!state->fit_for_inline)
7141 		return;
7142 
7143 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7144 				 state->callback_subprogno == subprogno);
7145 }
7146 
7147 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7148 			     int *insn_idx_p)
7149 {
7150 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7151 	const struct bpf_func_proto *fn = NULL;
7152 	enum bpf_return_type ret_type;
7153 	enum bpf_type_flag ret_flag;
7154 	struct bpf_reg_state *regs;
7155 	struct bpf_call_arg_meta meta;
7156 	int insn_idx = *insn_idx_p;
7157 	bool changes_data;
7158 	int i, err, func_id;
7159 
7160 	/* find function prototype */
7161 	func_id = insn->imm;
7162 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7163 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7164 			func_id);
7165 		return -EINVAL;
7166 	}
7167 
7168 	if (env->ops->get_func_proto)
7169 		fn = env->ops->get_func_proto(func_id, env->prog);
7170 	if (!fn) {
7171 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7172 			func_id);
7173 		return -EINVAL;
7174 	}
7175 
7176 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7177 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7178 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7179 		return -EINVAL;
7180 	}
7181 
7182 	if (fn->allowed && !fn->allowed(env->prog)) {
7183 		verbose(env, "helper call is not allowed in probe\n");
7184 		return -EINVAL;
7185 	}
7186 
7187 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7188 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7189 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7190 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7191 			func_id_name(func_id), func_id);
7192 		return -EINVAL;
7193 	}
7194 
7195 	memset(&meta, 0, sizeof(meta));
7196 	meta.pkt_access = fn->pkt_access;
7197 
7198 	err = check_func_proto(fn, func_id);
7199 	if (err) {
7200 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7201 			func_id_name(func_id), func_id);
7202 		return err;
7203 	}
7204 
7205 	meta.func_id = func_id;
7206 	/* check args */
7207 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7208 		err = check_func_arg(env, i, &meta, fn);
7209 		if (err)
7210 			return err;
7211 	}
7212 
7213 	err = record_func_map(env, &meta, func_id, insn_idx);
7214 	if (err)
7215 		return err;
7216 
7217 	err = record_func_key(env, &meta, func_id, insn_idx);
7218 	if (err)
7219 		return err;
7220 
7221 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7222 	 * is inferred from register state.
7223 	 */
7224 	for (i = 0; i < meta.access_size; i++) {
7225 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7226 				       BPF_WRITE, -1, false);
7227 		if (err)
7228 			return err;
7229 	}
7230 
7231 	regs = cur_regs(env);
7232 
7233 	if (meta.uninit_dynptr_regno) {
7234 		/* we write BPF_DW bits (8 bytes) at a time */
7235 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7236 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7237 					       i, BPF_DW, BPF_WRITE, -1, false);
7238 			if (err)
7239 				return err;
7240 		}
7241 
7242 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7243 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7244 					      insn_idx);
7245 		if (err)
7246 			return err;
7247 	}
7248 
7249 	if (meta.release_regno) {
7250 		err = -EINVAL;
7251 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7252 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7253 		else if (meta.ref_obj_id)
7254 			err = release_reference(env, meta.ref_obj_id);
7255 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7256 		 * released is NULL, which must be > R0.
7257 		 */
7258 		else if (register_is_null(&regs[meta.release_regno]))
7259 			err = 0;
7260 		if (err) {
7261 			verbose(env, "func %s#%d reference has not been acquired before\n",
7262 				func_id_name(func_id), func_id);
7263 			return err;
7264 		}
7265 	}
7266 
7267 	switch (func_id) {
7268 	case BPF_FUNC_tail_call:
7269 		err = check_reference_leak(env);
7270 		if (err) {
7271 			verbose(env, "tail_call would lead to reference leak\n");
7272 			return err;
7273 		}
7274 		break;
7275 	case BPF_FUNC_get_local_storage:
7276 		/* check that flags argument in get_local_storage(map, flags) is 0,
7277 		 * this is required because get_local_storage() can't return an error.
7278 		 */
7279 		if (!register_is_null(&regs[BPF_REG_2])) {
7280 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7281 			return -EINVAL;
7282 		}
7283 		break;
7284 	case BPF_FUNC_for_each_map_elem:
7285 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7286 					set_map_elem_callback_state);
7287 		break;
7288 	case BPF_FUNC_timer_set_callback:
7289 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7290 					set_timer_callback_state);
7291 		break;
7292 	case BPF_FUNC_find_vma:
7293 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7294 					set_find_vma_callback_state);
7295 		break;
7296 	case BPF_FUNC_snprintf:
7297 		err = check_bpf_snprintf_call(env, regs);
7298 		break;
7299 	case BPF_FUNC_loop:
7300 		update_loop_inline_state(env, meta.subprogno);
7301 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7302 					set_loop_callback_state);
7303 		break;
7304 	case BPF_FUNC_dynptr_from_mem:
7305 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7306 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7307 				reg_type_str(env, regs[BPF_REG_1].type));
7308 			return -EACCES;
7309 		}
7310 		break;
7311 	case BPF_FUNC_set_retval:
7312 		if (prog_type == BPF_PROG_TYPE_LSM &&
7313 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7314 			if (!env->prog->aux->attach_func_proto->type) {
7315 				/* Make sure programs that attach to void
7316 				 * hooks don't try to modify return value.
7317 				 */
7318 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7319 				return -EINVAL;
7320 			}
7321 		}
7322 		break;
7323 	case BPF_FUNC_dynptr_data:
7324 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7325 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7326 				if (meta.ref_obj_id) {
7327 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7328 					return -EFAULT;
7329 				}
7330 				/* Find the id of the dynptr we're tracking the reference of */
7331 				meta.ref_obj_id = stack_slot_get_id(env, &regs[BPF_REG_1 + i]);
7332 				break;
7333 			}
7334 		}
7335 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7336 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7337 			return -EFAULT;
7338 		}
7339 		break;
7340 	}
7341 
7342 	if (err)
7343 		return err;
7344 
7345 	/* reset caller saved regs */
7346 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7347 		mark_reg_not_init(env, regs, caller_saved[i]);
7348 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7349 	}
7350 
7351 	/* helper call returns 64-bit value. */
7352 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7353 
7354 	/* update return register (already marked as written above) */
7355 	ret_type = fn->ret_type;
7356 	ret_flag = type_flag(ret_type);
7357 
7358 	switch (base_type(ret_type)) {
7359 	case RET_INTEGER:
7360 		/* sets type to SCALAR_VALUE */
7361 		mark_reg_unknown(env, regs, BPF_REG_0);
7362 		break;
7363 	case RET_VOID:
7364 		regs[BPF_REG_0].type = NOT_INIT;
7365 		break;
7366 	case RET_PTR_TO_MAP_VALUE:
7367 		/* There is no offset yet applied, variable or fixed */
7368 		mark_reg_known_zero(env, regs, BPF_REG_0);
7369 		/* remember map_ptr, so that check_map_access()
7370 		 * can check 'value_size' boundary of memory access
7371 		 * to map element returned from bpf_map_lookup_elem()
7372 		 */
7373 		if (meta.map_ptr == NULL) {
7374 			verbose(env,
7375 				"kernel subsystem misconfigured verifier\n");
7376 			return -EINVAL;
7377 		}
7378 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7379 		regs[BPF_REG_0].map_uid = meta.map_uid;
7380 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7381 		if (!type_may_be_null(ret_type) &&
7382 		    map_value_has_spin_lock(meta.map_ptr)) {
7383 			regs[BPF_REG_0].id = ++env->id_gen;
7384 		}
7385 		break;
7386 	case RET_PTR_TO_SOCKET:
7387 		mark_reg_known_zero(env, regs, BPF_REG_0);
7388 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7389 		break;
7390 	case RET_PTR_TO_SOCK_COMMON:
7391 		mark_reg_known_zero(env, regs, BPF_REG_0);
7392 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7393 		break;
7394 	case RET_PTR_TO_TCP_SOCK:
7395 		mark_reg_known_zero(env, regs, BPF_REG_0);
7396 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7397 		break;
7398 	case RET_PTR_TO_ALLOC_MEM:
7399 		mark_reg_known_zero(env, regs, BPF_REG_0);
7400 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7401 		regs[BPF_REG_0].mem_size = meta.mem_size;
7402 		break;
7403 	case RET_PTR_TO_MEM_OR_BTF_ID:
7404 	{
7405 		const struct btf_type *t;
7406 
7407 		mark_reg_known_zero(env, regs, BPF_REG_0);
7408 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7409 		if (!btf_type_is_struct(t)) {
7410 			u32 tsize;
7411 			const struct btf_type *ret;
7412 			const char *tname;
7413 
7414 			/* resolve the type size of ksym. */
7415 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7416 			if (IS_ERR(ret)) {
7417 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7418 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7419 					tname, PTR_ERR(ret));
7420 				return -EINVAL;
7421 			}
7422 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7423 			regs[BPF_REG_0].mem_size = tsize;
7424 		} else {
7425 			/* MEM_RDONLY may be carried from ret_flag, but it
7426 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7427 			 * it will confuse the check of PTR_TO_BTF_ID in
7428 			 * check_mem_access().
7429 			 */
7430 			ret_flag &= ~MEM_RDONLY;
7431 
7432 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7433 			regs[BPF_REG_0].btf = meta.ret_btf;
7434 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7435 		}
7436 		break;
7437 	}
7438 	case RET_PTR_TO_BTF_ID:
7439 	{
7440 		struct btf *ret_btf;
7441 		int ret_btf_id;
7442 
7443 		mark_reg_known_zero(env, regs, BPF_REG_0);
7444 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7445 		if (func_id == BPF_FUNC_kptr_xchg) {
7446 			ret_btf = meta.kptr_off_desc->kptr.btf;
7447 			ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7448 		} else {
7449 			ret_btf = btf_vmlinux;
7450 			ret_btf_id = *fn->ret_btf_id;
7451 		}
7452 		if (ret_btf_id == 0) {
7453 			verbose(env, "invalid return type %u of func %s#%d\n",
7454 				base_type(ret_type), func_id_name(func_id),
7455 				func_id);
7456 			return -EINVAL;
7457 		}
7458 		regs[BPF_REG_0].btf = ret_btf;
7459 		regs[BPF_REG_0].btf_id = ret_btf_id;
7460 		break;
7461 	}
7462 	default:
7463 		verbose(env, "unknown return type %u of func %s#%d\n",
7464 			base_type(ret_type), func_id_name(func_id), func_id);
7465 		return -EINVAL;
7466 	}
7467 
7468 	if (type_may_be_null(regs[BPF_REG_0].type))
7469 		regs[BPF_REG_0].id = ++env->id_gen;
7470 
7471 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7472 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7473 			func_id_name(func_id), func_id);
7474 		return -EFAULT;
7475 	}
7476 
7477 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7478 		/* For release_reference() */
7479 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7480 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7481 		int id = acquire_reference_state(env, insn_idx);
7482 
7483 		if (id < 0)
7484 			return id;
7485 		/* For mark_ptr_or_null_reg() */
7486 		regs[BPF_REG_0].id = id;
7487 		/* For release_reference() */
7488 		regs[BPF_REG_0].ref_obj_id = id;
7489 	}
7490 
7491 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7492 
7493 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7494 	if (err)
7495 		return err;
7496 
7497 	if ((func_id == BPF_FUNC_get_stack ||
7498 	     func_id == BPF_FUNC_get_task_stack) &&
7499 	    !env->prog->has_callchain_buf) {
7500 		const char *err_str;
7501 
7502 #ifdef CONFIG_PERF_EVENTS
7503 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7504 		err_str = "cannot get callchain buffer for func %s#%d\n";
7505 #else
7506 		err = -ENOTSUPP;
7507 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7508 #endif
7509 		if (err) {
7510 			verbose(env, err_str, func_id_name(func_id), func_id);
7511 			return err;
7512 		}
7513 
7514 		env->prog->has_callchain_buf = true;
7515 	}
7516 
7517 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7518 		env->prog->call_get_stack = true;
7519 
7520 	if (func_id == BPF_FUNC_get_func_ip) {
7521 		if (check_get_func_ip(env))
7522 			return -ENOTSUPP;
7523 		env->prog->call_get_func_ip = true;
7524 	}
7525 
7526 	if (changes_data)
7527 		clear_all_pkt_pointers(env);
7528 	return 0;
7529 }
7530 
7531 /* mark_btf_func_reg_size() is used when the reg size is determined by
7532  * the BTF func_proto's return value size and argument.
7533  */
7534 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7535 				   size_t reg_size)
7536 {
7537 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7538 
7539 	if (regno == BPF_REG_0) {
7540 		/* Function return value */
7541 		reg->live |= REG_LIVE_WRITTEN;
7542 		reg->subreg_def = reg_size == sizeof(u64) ?
7543 			DEF_NOT_SUBREG : env->insn_idx + 1;
7544 	} else {
7545 		/* Function argument */
7546 		if (reg_size == sizeof(u64)) {
7547 			mark_insn_zext(env, reg);
7548 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7549 		} else {
7550 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7551 		}
7552 	}
7553 }
7554 
7555 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7556 			    int *insn_idx_p)
7557 {
7558 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7559 	struct bpf_reg_state *regs = cur_regs(env);
7560 	const char *func_name, *ptr_type_name;
7561 	u32 i, nargs, func_id, ptr_type_id;
7562 	int err, insn_idx = *insn_idx_p;
7563 	const struct btf_param *args;
7564 	struct btf *desc_btf;
7565 	u32 *kfunc_flags;
7566 	bool acq;
7567 
7568 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7569 	if (!insn->imm)
7570 		return 0;
7571 
7572 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7573 	if (IS_ERR(desc_btf))
7574 		return PTR_ERR(desc_btf);
7575 
7576 	func_id = insn->imm;
7577 	func = btf_type_by_id(desc_btf, func_id);
7578 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7579 	func_proto = btf_type_by_id(desc_btf, func->type);
7580 
7581 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7582 	if (!kfunc_flags) {
7583 		verbose(env, "calling kernel function %s is not allowed\n",
7584 			func_name);
7585 		return -EACCES;
7586 	}
7587 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7588 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7589 		return -EACCES;
7590 	}
7591 
7592 	acq = *kfunc_flags & KF_ACQUIRE;
7593 
7594 	/* Check the arguments */
7595 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, *kfunc_flags);
7596 	if (err < 0)
7597 		return err;
7598 	/* In case of release function, we get register number of refcounted
7599 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7600 	 */
7601 	if (err) {
7602 		err = release_reference(env, regs[err].ref_obj_id);
7603 		if (err) {
7604 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7605 				func_name, func_id);
7606 			return err;
7607 		}
7608 	}
7609 
7610 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7611 		mark_reg_not_init(env, regs, caller_saved[i]);
7612 
7613 	/* Check return type */
7614 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7615 
7616 	if (acq && !btf_type_is_ptr(t)) {
7617 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7618 		return -EINVAL;
7619 	}
7620 
7621 	if (btf_type_is_scalar(t)) {
7622 		mark_reg_unknown(env, regs, BPF_REG_0);
7623 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7624 	} else if (btf_type_is_ptr(t)) {
7625 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7626 						   &ptr_type_id);
7627 		if (!btf_type_is_struct(ptr_type)) {
7628 			ptr_type_name = btf_name_by_offset(desc_btf,
7629 							   ptr_type->name_off);
7630 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7631 				func_name, btf_type_str(ptr_type),
7632 				ptr_type_name);
7633 			return -EINVAL;
7634 		}
7635 		mark_reg_known_zero(env, regs, BPF_REG_0);
7636 		regs[BPF_REG_0].btf = desc_btf;
7637 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7638 		regs[BPF_REG_0].btf_id = ptr_type_id;
7639 		if (*kfunc_flags & KF_RET_NULL) {
7640 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7641 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7642 			regs[BPF_REG_0].id = ++env->id_gen;
7643 		}
7644 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7645 		if (acq) {
7646 			int id = acquire_reference_state(env, insn_idx);
7647 
7648 			if (id < 0)
7649 				return id;
7650 			regs[BPF_REG_0].id = id;
7651 			regs[BPF_REG_0].ref_obj_id = id;
7652 		}
7653 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7654 
7655 	nargs = btf_type_vlen(func_proto);
7656 	args = (const struct btf_param *)(func_proto + 1);
7657 	for (i = 0; i < nargs; i++) {
7658 		u32 regno = i + 1;
7659 
7660 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7661 		if (btf_type_is_ptr(t))
7662 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7663 		else
7664 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7665 			mark_btf_func_reg_size(env, regno, t->size);
7666 	}
7667 
7668 	return 0;
7669 }
7670 
7671 static bool signed_add_overflows(s64 a, s64 b)
7672 {
7673 	/* Do the add in u64, where overflow is well-defined */
7674 	s64 res = (s64)((u64)a + (u64)b);
7675 
7676 	if (b < 0)
7677 		return res > a;
7678 	return res < a;
7679 }
7680 
7681 static bool signed_add32_overflows(s32 a, s32 b)
7682 {
7683 	/* Do the add in u32, where overflow is well-defined */
7684 	s32 res = (s32)((u32)a + (u32)b);
7685 
7686 	if (b < 0)
7687 		return res > a;
7688 	return res < a;
7689 }
7690 
7691 static bool signed_sub_overflows(s64 a, s64 b)
7692 {
7693 	/* Do the sub in u64, where overflow is well-defined */
7694 	s64 res = (s64)((u64)a - (u64)b);
7695 
7696 	if (b < 0)
7697 		return res < a;
7698 	return res > a;
7699 }
7700 
7701 static bool signed_sub32_overflows(s32 a, s32 b)
7702 {
7703 	/* Do the sub in u32, where overflow is well-defined */
7704 	s32 res = (s32)((u32)a - (u32)b);
7705 
7706 	if (b < 0)
7707 		return res < a;
7708 	return res > a;
7709 }
7710 
7711 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7712 				  const struct bpf_reg_state *reg,
7713 				  enum bpf_reg_type type)
7714 {
7715 	bool known = tnum_is_const(reg->var_off);
7716 	s64 val = reg->var_off.value;
7717 	s64 smin = reg->smin_value;
7718 
7719 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7720 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7721 			reg_type_str(env, type), val);
7722 		return false;
7723 	}
7724 
7725 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7726 		verbose(env, "%s pointer offset %d is not allowed\n",
7727 			reg_type_str(env, type), reg->off);
7728 		return false;
7729 	}
7730 
7731 	if (smin == S64_MIN) {
7732 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7733 			reg_type_str(env, type));
7734 		return false;
7735 	}
7736 
7737 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7738 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7739 			smin, reg_type_str(env, type));
7740 		return false;
7741 	}
7742 
7743 	return true;
7744 }
7745 
7746 enum {
7747 	REASON_BOUNDS	= -1,
7748 	REASON_TYPE	= -2,
7749 	REASON_PATHS	= -3,
7750 	REASON_LIMIT	= -4,
7751 	REASON_STACK	= -5,
7752 };
7753 
7754 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7755 			      u32 *alu_limit, bool mask_to_left)
7756 {
7757 	u32 max = 0, ptr_limit = 0;
7758 
7759 	switch (ptr_reg->type) {
7760 	case PTR_TO_STACK:
7761 		/* Offset 0 is out-of-bounds, but acceptable start for the
7762 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7763 		 * offset where we would need to deal with min/max bounds is
7764 		 * currently prohibited for unprivileged.
7765 		 */
7766 		max = MAX_BPF_STACK + mask_to_left;
7767 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7768 		break;
7769 	case PTR_TO_MAP_VALUE:
7770 		max = ptr_reg->map_ptr->value_size;
7771 		ptr_limit = (mask_to_left ?
7772 			     ptr_reg->smin_value :
7773 			     ptr_reg->umax_value) + ptr_reg->off;
7774 		break;
7775 	default:
7776 		return REASON_TYPE;
7777 	}
7778 
7779 	if (ptr_limit >= max)
7780 		return REASON_LIMIT;
7781 	*alu_limit = ptr_limit;
7782 	return 0;
7783 }
7784 
7785 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7786 				    const struct bpf_insn *insn)
7787 {
7788 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7789 }
7790 
7791 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7792 				       u32 alu_state, u32 alu_limit)
7793 {
7794 	/* If we arrived here from different branches with different
7795 	 * state or limits to sanitize, then this won't work.
7796 	 */
7797 	if (aux->alu_state &&
7798 	    (aux->alu_state != alu_state ||
7799 	     aux->alu_limit != alu_limit))
7800 		return REASON_PATHS;
7801 
7802 	/* Corresponding fixup done in do_misc_fixups(). */
7803 	aux->alu_state = alu_state;
7804 	aux->alu_limit = alu_limit;
7805 	return 0;
7806 }
7807 
7808 static int sanitize_val_alu(struct bpf_verifier_env *env,
7809 			    struct bpf_insn *insn)
7810 {
7811 	struct bpf_insn_aux_data *aux = cur_aux(env);
7812 
7813 	if (can_skip_alu_sanitation(env, insn))
7814 		return 0;
7815 
7816 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7817 }
7818 
7819 static bool sanitize_needed(u8 opcode)
7820 {
7821 	return opcode == BPF_ADD || opcode == BPF_SUB;
7822 }
7823 
7824 struct bpf_sanitize_info {
7825 	struct bpf_insn_aux_data aux;
7826 	bool mask_to_left;
7827 };
7828 
7829 static struct bpf_verifier_state *
7830 sanitize_speculative_path(struct bpf_verifier_env *env,
7831 			  const struct bpf_insn *insn,
7832 			  u32 next_idx, u32 curr_idx)
7833 {
7834 	struct bpf_verifier_state *branch;
7835 	struct bpf_reg_state *regs;
7836 
7837 	branch = push_stack(env, next_idx, curr_idx, true);
7838 	if (branch && insn) {
7839 		regs = branch->frame[branch->curframe]->regs;
7840 		if (BPF_SRC(insn->code) == BPF_K) {
7841 			mark_reg_unknown(env, regs, insn->dst_reg);
7842 		} else if (BPF_SRC(insn->code) == BPF_X) {
7843 			mark_reg_unknown(env, regs, insn->dst_reg);
7844 			mark_reg_unknown(env, regs, insn->src_reg);
7845 		}
7846 	}
7847 	return branch;
7848 }
7849 
7850 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7851 			    struct bpf_insn *insn,
7852 			    const struct bpf_reg_state *ptr_reg,
7853 			    const struct bpf_reg_state *off_reg,
7854 			    struct bpf_reg_state *dst_reg,
7855 			    struct bpf_sanitize_info *info,
7856 			    const bool commit_window)
7857 {
7858 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7859 	struct bpf_verifier_state *vstate = env->cur_state;
7860 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7861 	bool off_is_neg = off_reg->smin_value < 0;
7862 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7863 	u8 opcode = BPF_OP(insn->code);
7864 	u32 alu_state, alu_limit;
7865 	struct bpf_reg_state tmp;
7866 	bool ret;
7867 	int err;
7868 
7869 	if (can_skip_alu_sanitation(env, insn))
7870 		return 0;
7871 
7872 	/* We already marked aux for masking from non-speculative
7873 	 * paths, thus we got here in the first place. We only care
7874 	 * to explore bad access from here.
7875 	 */
7876 	if (vstate->speculative)
7877 		goto do_sim;
7878 
7879 	if (!commit_window) {
7880 		if (!tnum_is_const(off_reg->var_off) &&
7881 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7882 			return REASON_BOUNDS;
7883 
7884 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7885 				     (opcode == BPF_SUB && !off_is_neg);
7886 	}
7887 
7888 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7889 	if (err < 0)
7890 		return err;
7891 
7892 	if (commit_window) {
7893 		/* In commit phase we narrow the masking window based on
7894 		 * the observed pointer move after the simulated operation.
7895 		 */
7896 		alu_state = info->aux.alu_state;
7897 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7898 	} else {
7899 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7900 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7901 		alu_state |= ptr_is_dst_reg ?
7902 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7903 
7904 		/* Limit pruning on unknown scalars to enable deep search for
7905 		 * potential masking differences from other program paths.
7906 		 */
7907 		if (!off_is_imm)
7908 			env->explore_alu_limits = true;
7909 	}
7910 
7911 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7912 	if (err < 0)
7913 		return err;
7914 do_sim:
7915 	/* If we're in commit phase, we're done here given we already
7916 	 * pushed the truncated dst_reg into the speculative verification
7917 	 * stack.
7918 	 *
7919 	 * Also, when register is a known constant, we rewrite register-based
7920 	 * operation to immediate-based, and thus do not need masking (and as
7921 	 * a consequence, do not need to simulate the zero-truncation either).
7922 	 */
7923 	if (commit_window || off_is_imm)
7924 		return 0;
7925 
7926 	/* Simulate and find potential out-of-bounds access under
7927 	 * speculative execution from truncation as a result of
7928 	 * masking when off was not within expected range. If off
7929 	 * sits in dst, then we temporarily need to move ptr there
7930 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7931 	 * for cases where we use K-based arithmetic in one direction
7932 	 * and truncated reg-based in the other in order to explore
7933 	 * bad access.
7934 	 */
7935 	if (!ptr_is_dst_reg) {
7936 		tmp = *dst_reg;
7937 		*dst_reg = *ptr_reg;
7938 	}
7939 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7940 					env->insn_idx);
7941 	if (!ptr_is_dst_reg && ret)
7942 		*dst_reg = tmp;
7943 	return !ret ? REASON_STACK : 0;
7944 }
7945 
7946 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7947 {
7948 	struct bpf_verifier_state *vstate = env->cur_state;
7949 
7950 	/* If we simulate paths under speculation, we don't update the
7951 	 * insn as 'seen' such that when we verify unreachable paths in
7952 	 * the non-speculative domain, sanitize_dead_code() can still
7953 	 * rewrite/sanitize them.
7954 	 */
7955 	if (!vstate->speculative)
7956 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7957 }
7958 
7959 static int sanitize_err(struct bpf_verifier_env *env,
7960 			const struct bpf_insn *insn, int reason,
7961 			const struct bpf_reg_state *off_reg,
7962 			const struct bpf_reg_state *dst_reg)
7963 {
7964 	static const char *err = "pointer arithmetic with it prohibited for !root";
7965 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7966 	u32 dst = insn->dst_reg, src = insn->src_reg;
7967 
7968 	switch (reason) {
7969 	case REASON_BOUNDS:
7970 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7971 			off_reg == dst_reg ? dst : src, err);
7972 		break;
7973 	case REASON_TYPE:
7974 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7975 			off_reg == dst_reg ? src : dst, err);
7976 		break;
7977 	case REASON_PATHS:
7978 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7979 			dst, op, err);
7980 		break;
7981 	case REASON_LIMIT:
7982 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7983 			dst, op, err);
7984 		break;
7985 	case REASON_STACK:
7986 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7987 			dst, err);
7988 		break;
7989 	default:
7990 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7991 			reason);
7992 		break;
7993 	}
7994 
7995 	return -EACCES;
7996 }
7997 
7998 /* check that stack access falls within stack limits and that 'reg' doesn't
7999  * have a variable offset.
8000  *
8001  * Variable offset is prohibited for unprivileged mode for simplicity since it
8002  * requires corresponding support in Spectre masking for stack ALU.  See also
8003  * retrieve_ptr_limit().
8004  *
8005  *
8006  * 'off' includes 'reg->off'.
8007  */
8008 static int check_stack_access_for_ptr_arithmetic(
8009 				struct bpf_verifier_env *env,
8010 				int regno,
8011 				const struct bpf_reg_state *reg,
8012 				int off)
8013 {
8014 	if (!tnum_is_const(reg->var_off)) {
8015 		char tn_buf[48];
8016 
8017 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8018 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8019 			regno, tn_buf, off);
8020 		return -EACCES;
8021 	}
8022 
8023 	if (off >= 0 || off < -MAX_BPF_STACK) {
8024 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8025 			"prohibited for !root; off=%d\n", regno, off);
8026 		return -EACCES;
8027 	}
8028 
8029 	return 0;
8030 }
8031 
8032 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8033 				 const struct bpf_insn *insn,
8034 				 const struct bpf_reg_state *dst_reg)
8035 {
8036 	u32 dst = insn->dst_reg;
8037 
8038 	/* For unprivileged we require that resulting offset must be in bounds
8039 	 * in order to be able to sanitize access later on.
8040 	 */
8041 	if (env->bypass_spec_v1)
8042 		return 0;
8043 
8044 	switch (dst_reg->type) {
8045 	case PTR_TO_STACK:
8046 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8047 					dst_reg->off + dst_reg->var_off.value))
8048 			return -EACCES;
8049 		break;
8050 	case PTR_TO_MAP_VALUE:
8051 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8052 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8053 				"prohibited for !root\n", dst);
8054 			return -EACCES;
8055 		}
8056 		break;
8057 	default:
8058 		break;
8059 	}
8060 
8061 	return 0;
8062 }
8063 
8064 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8065  * Caller should also handle BPF_MOV case separately.
8066  * If we return -EACCES, caller may want to try again treating pointer as a
8067  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8068  */
8069 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8070 				   struct bpf_insn *insn,
8071 				   const struct bpf_reg_state *ptr_reg,
8072 				   const struct bpf_reg_state *off_reg)
8073 {
8074 	struct bpf_verifier_state *vstate = env->cur_state;
8075 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8076 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8077 	bool known = tnum_is_const(off_reg->var_off);
8078 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8079 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8080 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8081 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8082 	struct bpf_sanitize_info info = {};
8083 	u8 opcode = BPF_OP(insn->code);
8084 	u32 dst = insn->dst_reg;
8085 	int ret;
8086 
8087 	dst_reg = &regs[dst];
8088 
8089 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8090 	    smin_val > smax_val || umin_val > umax_val) {
8091 		/* Taint dst register if offset had invalid bounds derived from
8092 		 * e.g. dead branches.
8093 		 */
8094 		__mark_reg_unknown(env, dst_reg);
8095 		return 0;
8096 	}
8097 
8098 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8099 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8100 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8101 			__mark_reg_unknown(env, dst_reg);
8102 			return 0;
8103 		}
8104 
8105 		verbose(env,
8106 			"R%d 32-bit pointer arithmetic prohibited\n",
8107 			dst);
8108 		return -EACCES;
8109 	}
8110 
8111 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8112 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8113 			dst, reg_type_str(env, ptr_reg->type));
8114 		return -EACCES;
8115 	}
8116 
8117 	switch (base_type(ptr_reg->type)) {
8118 	case CONST_PTR_TO_MAP:
8119 		/* smin_val represents the known value */
8120 		if (known && smin_val == 0 && opcode == BPF_ADD)
8121 			break;
8122 		fallthrough;
8123 	case PTR_TO_PACKET_END:
8124 	case PTR_TO_SOCKET:
8125 	case PTR_TO_SOCK_COMMON:
8126 	case PTR_TO_TCP_SOCK:
8127 	case PTR_TO_XDP_SOCK:
8128 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8129 			dst, reg_type_str(env, ptr_reg->type));
8130 		return -EACCES;
8131 	default:
8132 		break;
8133 	}
8134 
8135 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8136 	 * The id may be overwritten later if we create a new variable offset.
8137 	 */
8138 	dst_reg->type = ptr_reg->type;
8139 	dst_reg->id = ptr_reg->id;
8140 
8141 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8142 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8143 		return -EINVAL;
8144 
8145 	/* pointer types do not carry 32-bit bounds at the moment. */
8146 	__mark_reg32_unbounded(dst_reg);
8147 
8148 	if (sanitize_needed(opcode)) {
8149 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8150 				       &info, false);
8151 		if (ret < 0)
8152 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8153 	}
8154 
8155 	switch (opcode) {
8156 	case BPF_ADD:
8157 		/* We can take a fixed offset as long as it doesn't overflow
8158 		 * the s32 'off' field
8159 		 */
8160 		if (known && (ptr_reg->off + smin_val ==
8161 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8162 			/* pointer += K.  Accumulate it into fixed offset */
8163 			dst_reg->smin_value = smin_ptr;
8164 			dst_reg->smax_value = smax_ptr;
8165 			dst_reg->umin_value = umin_ptr;
8166 			dst_reg->umax_value = umax_ptr;
8167 			dst_reg->var_off = ptr_reg->var_off;
8168 			dst_reg->off = ptr_reg->off + smin_val;
8169 			dst_reg->raw = ptr_reg->raw;
8170 			break;
8171 		}
8172 		/* A new variable offset is created.  Note that off_reg->off
8173 		 * == 0, since it's a scalar.
8174 		 * dst_reg gets the pointer type and since some positive
8175 		 * integer value was added to the pointer, give it a new 'id'
8176 		 * if it's a PTR_TO_PACKET.
8177 		 * this creates a new 'base' pointer, off_reg (variable) gets
8178 		 * added into the variable offset, and we copy the fixed offset
8179 		 * from ptr_reg.
8180 		 */
8181 		if (signed_add_overflows(smin_ptr, smin_val) ||
8182 		    signed_add_overflows(smax_ptr, smax_val)) {
8183 			dst_reg->smin_value = S64_MIN;
8184 			dst_reg->smax_value = S64_MAX;
8185 		} else {
8186 			dst_reg->smin_value = smin_ptr + smin_val;
8187 			dst_reg->smax_value = smax_ptr + smax_val;
8188 		}
8189 		if (umin_ptr + umin_val < umin_ptr ||
8190 		    umax_ptr + umax_val < umax_ptr) {
8191 			dst_reg->umin_value = 0;
8192 			dst_reg->umax_value = U64_MAX;
8193 		} else {
8194 			dst_reg->umin_value = umin_ptr + umin_val;
8195 			dst_reg->umax_value = umax_ptr + umax_val;
8196 		}
8197 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8198 		dst_reg->off = ptr_reg->off;
8199 		dst_reg->raw = ptr_reg->raw;
8200 		if (reg_is_pkt_pointer(ptr_reg)) {
8201 			dst_reg->id = ++env->id_gen;
8202 			/* something was added to pkt_ptr, set range to zero */
8203 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8204 		}
8205 		break;
8206 	case BPF_SUB:
8207 		if (dst_reg == off_reg) {
8208 			/* scalar -= pointer.  Creates an unknown scalar */
8209 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8210 				dst);
8211 			return -EACCES;
8212 		}
8213 		/* We don't allow subtraction from FP, because (according to
8214 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8215 		 * be able to deal with it.
8216 		 */
8217 		if (ptr_reg->type == PTR_TO_STACK) {
8218 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8219 				dst);
8220 			return -EACCES;
8221 		}
8222 		if (known && (ptr_reg->off - smin_val ==
8223 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8224 			/* pointer -= K.  Subtract it from fixed offset */
8225 			dst_reg->smin_value = smin_ptr;
8226 			dst_reg->smax_value = smax_ptr;
8227 			dst_reg->umin_value = umin_ptr;
8228 			dst_reg->umax_value = umax_ptr;
8229 			dst_reg->var_off = ptr_reg->var_off;
8230 			dst_reg->id = ptr_reg->id;
8231 			dst_reg->off = ptr_reg->off - smin_val;
8232 			dst_reg->raw = ptr_reg->raw;
8233 			break;
8234 		}
8235 		/* A new variable offset is created.  If the subtrahend is known
8236 		 * nonnegative, then any reg->range we had before is still good.
8237 		 */
8238 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8239 		    signed_sub_overflows(smax_ptr, smin_val)) {
8240 			/* Overflow possible, we know nothing */
8241 			dst_reg->smin_value = S64_MIN;
8242 			dst_reg->smax_value = S64_MAX;
8243 		} else {
8244 			dst_reg->smin_value = smin_ptr - smax_val;
8245 			dst_reg->smax_value = smax_ptr - smin_val;
8246 		}
8247 		if (umin_ptr < umax_val) {
8248 			/* Overflow possible, we know nothing */
8249 			dst_reg->umin_value = 0;
8250 			dst_reg->umax_value = U64_MAX;
8251 		} else {
8252 			/* Cannot overflow (as long as bounds are consistent) */
8253 			dst_reg->umin_value = umin_ptr - umax_val;
8254 			dst_reg->umax_value = umax_ptr - umin_val;
8255 		}
8256 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8257 		dst_reg->off = ptr_reg->off;
8258 		dst_reg->raw = ptr_reg->raw;
8259 		if (reg_is_pkt_pointer(ptr_reg)) {
8260 			dst_reg->id = ++env->id_gen;
8261 			/* something was added to pkt_ptr, set range to zero */
8262 			if (smin_val < 0)
8263 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8264 		}
8265 		break;
8266 	case BPF_AND:
8267 	case BPF_OR:
8268 	case BPF_XOR:
8269 		/* bitwise ops on pointers are troublesome, prohibit. */
8270 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8271 			dst, bpf_alu_string[opcode >> 4]);
8272 		return -EACCES;
8273 	default:
8274 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8275 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8276 			dst, bpf_alu_string[opcode >> 4]);
8277 		return -EACCES;
8278 	}
8279 
8280 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8281 		return -EINVAL;
8282 	reg_bounds_sync(dst_reg);
8283 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8284 		return -EACCES;
8285 	if (sanitize_needed(opcode)) {
8286 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8287 				       &info, true);
8288 		if (ret < 0)
8289 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8290 	}
8291 
8292 	return 0;
8293 }
8294 
8295 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8296 				 struct bpf_reg_state *src_reg)
8297 {
8298 	s32 smin_val = src_reg->s32_min_value;
8299 	s32 smax_val = src_reg->s32_max_value;
8300 	u32 umin_val = src_reg->u32_min_value;
8301 	u32 umax_val = src_reg->u32_max_value;
8302 
8303 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8304 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8305 		dst_reg->s32_min_value = S32_MIN;
8306 		dst_reg->s32_max_value = S32_MAX;
8307 	} else {
8308 		dst_reg->s32_min_value += smin_val;
8309 		dst_reg->s32_max_value += smax_val;
8310 	}
8311 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8312 	    dst_reg->u32_max_value + umax_val < umax_val) {
8313 		dst_reg->u32_min_value = 0;
8314 		dst_reg->u32_max_value = U32_MAX;
8315 	} else {
8316 		dst_reg->u32_min_value += umin_val;
8317 		dst_reg->u32_max_value += umax_val;
8318 	}
8319 }
8320 
8321 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8322 			       struct bpf_reg_state *src_reg)
8323 {
8324 	s64 smin_val = src_reg->smin_value;
8325 	s64 smax_val = src_reg->smax_value;
8326 	u64 umin_val = src_reg->umin_value;
8327 	u64 umax_val = src_reg->umax_value;
8328 
8329 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8330 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8331 		dst_reg->smin_value = S64_MIN;
8332 		dst_reg->smax_value = S64_MAX;
8333 	} else {
8334 		dst_reg->smin_value += smin_val;
8335 		dst_reg->smax_value += smax_val;
8336 	}
8337 	if (dst_reg->umin_value + umin_val < umin_val ||
8338 	    dst_reg->umax_value + umax_val < umax_val) {
8339 		dst_reg->umin_value = 0;
8340 		dst_reg->umax_value = U64_MAX;
8341 	} else {
8342 		dst_reg->umin_value += umin_val;
8343 		dst_reg->umax_value += umax_val;
8344 	}
8345 }
8346 
8347 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8348 				 struct bpf_reg_state *src_reg)
8349 {
8350 	s32 smin_val = src_reg->s32_min_value;
8351 	s32 smax_val = src_reg->s32_max_value;
8352 	u32 umin_val = src_reg->u32_min_value;
8353 	u32 umax_val = src_reg->u32_max_value;
8354 
8355 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8356 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8357 		/* Overflow possible, we know nothing */
8358 		dst_reg->s32_min_value = S32_MIN;
8359 		dst_reg->s32_max_value = S32_MAX;
8360 	} else {
8361 		dst_reg->s32_min_value -= smax_val;
8362 		dst_reg->s32_max_value -= smin_val;
8363 	}
8364 	if (dst_reg->u32_min_value < umax_val) {
8365 		/* Overflow possible, we know nothing */
8366 		dst_reg->u32_min_value = 0;
8367 		dst_reg->u32_max_value = U32_MAX;
8368 	} else {
8369 		/* Cannot overflow (as long as bounds are consistent) */
8370 		dst_reg->u32_min_value -= umax_val;
8371 		dst_reg->u32_max_value -= umin_val;
8372 	}
8373 }
8374 
8375 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8376 			       struct bpf_reg_state *src_reg)
8377 {
8378 	s64 smin_val = src_reg->smin_value;
8379 	s64 smax_val = src_reg->smax_value;
8380 	u64 umin_val = src_reg->umin_value;
8381 	u64 umax_val = src_reg->umax_value;
8382 
8383 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8384 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8385 		/* Overflow possible, we know nothing */
8386 		dst_reg->smin_value = S64_MIN;
8387 		dst_reg->smax_value = S64_MAX;
8388 	} else {
8389 		dst_reg->smin_value -= smax_val;
8390 		dst_reg->smax_value -= smin_val;
8391 	}
8392 	if (dst_reg->umin_value < umax_val) {
8393 		/* Overflow possible, we know nothing */
8394 		dst_reg->umin_value = 0;
8395 		dst_reg->umax_value = U64_MAX;
8396 	} else {
8397 		/* Cannot overflow (as long as bounds are consistent) */
8398 		dst_reg->umin_value -= umax_val;
8399 		dst_reg->umax_value -= umin_val;
8400 	}
8401 }
8402 
8403 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8404 				 struct bpf_reg_state *src_reg)
8405 {
8406 	s32 smin_val = src_reg->s32_min_value;
8407 	u32 umin_val = src_reg->u32_min_value;
8408 	u32 umax_val = src_reg->u32_max_value;
8409 
8410 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8411 		/* Ain't nobody got time to multiply that sign */
8412 		__mark_reg32_unbounded(dst_reg);
8413 		return;
8414 	}
8415 	/* Both values are positive, so we can work with unsigned and
8416 	 * copy the result to signed (unless it exceeds S32_MAX).
8417 	 */
8418 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8419 		/* Potential overflow, we know nothing */
8420 		__mark_reg32_unbounded(dst_reg);
8421 		return;
8422 	}
8423 	dst_reg->u32_min_value *= umin_val;
8424 	dst_reg->u32_max_value *= umax_val;
8425 	if (dst_reg->u32_max_value > S32_MAX) {
8426 		/* Overflow possible, we know nothing */
8427 		dst_reg->s32_min_value = S32_MIN;
8428 		dst_reg->s32_max_value = S32_MAX;
8429 	} else {
8430 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8431 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8432 	}
8433 }
8434 
8435 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8436 			       struct bpf_reg_state *src_reg)
8437 {
8438 	s64 smin_val = src_reg->smin_value;
8439 	u64 umin_val = src_reg->umin_value;
8440 	u64 umax_val = src_reg->umax_value;
8441 
8442 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8443 		/* Ain't nobody got time to multiply that sign */
8444 		__mark_reg64_unbounded(dst_reg);
8445 		return;
8446 	}
8447 	/* Both values are positive, so we can work with unsigned and
8448 	 * copy the result to signed (unless it exceeds S64_MAX).
8449 	 */
8450 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8451 		/* Potential overflow, we know nothing */
8452 		__mark_reg64_unbounded(dst_reg);
8453 		return;
8454 	}
8455 	dst_reg->umin_value *= umin_val;
8456 	dst_reg->umax_value *= umax_val;
8457 	if (dst_reg->umax_value > S64_MAX) {
8458 		/* Overflow possible, we know nothing */
8459 		dst_reg->smin_value = S64_MIN;
8460 		dst_reg->smax_value = S64_MAX;
8461 	} else {
8462 		dst_reg->smin_value = dst_reg->umin_value;
8463 		dst_reg->smax_value = dst_reg->umax_value;
8464 	}
8465 }
8466 
8467 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8468 				 struct bpf_reg_state *src_reg)
8469 {
8470 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8471 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8472 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8473 	s32 smin_val = src_reg->s32_min_value;
8474 	u32 umax_val = src_reg->u32_max_value;
8475 
8476 	if (src_known && dst_known) {
8477 		__mark_reg32_known(dst_reg, var32_off.value);
8478 		return;
8479 	}
8480 
8481 	/* We get our minimum from the var_off, since that's inherently
8482 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8483 	 */
8484 	dst_reg->u32_min_value = var32_off.value;
8485 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8486 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8487 		/* Lose signed bounds when ANDing negative numbers,
8488 		 * ain't nobody got time for that.
8489 		 */
8490 		dst_reg->s32_min_value = S32_MIN;
8491 		dst_reg->s32_max_value = S32_MAX;
8492 	} else {
8493 		/* ANDing two positives gives a positive, so safe to
8494 		 * cast result into s64.
8495 		 */
8496 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8497 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8498 	}
8499 }
8500 
8501 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8502 			       struct bpf_reg_state *src_reg)
8503 {
8504 	bool src_known = tnum_is_const(src_reg->var_off);
8505 	bool dst_known = tnum_is_const(dst_reg->var_off);
8506 	s64 smin_val = src_reg->smin_value;
8507 	u64 umax_val = src_reg->umax_value;
8508 
8509 	if (src_known && dst_known) {
8510 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8511 		return;
8512 	}
8513 
8514 	/* We get our minimum from the var_off, since that's inherently
8515 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8516 	 */
8517 	dst_reg->umin_value = dst_reg->var_off.value;
8518 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8519 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8520 		/* Lose signed bounds when ANDing negative numbers,
8521 		 * ain't nobody got time for that.
8522 		 */
8523 		dst_reg->smin_value = S64_MIN;
8524 		dst_reg->smax_value = S64_MAX;
8525 	} else {
8526 		/* ANDing two positives gives a positive, so safe to
8527 		 * cast result into s64.
8528 		 */
8529 		dst_reg->smin_value = dst_reg->umin_value;
8530 		dst_reg->smax_value = dst_reg->umax_value;
8531 	}
8532 	/* We may learn something more from the var_off */
8533 	__update_reg_bounds(dst_reg);
8534 }
8535 
8536 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8537 				struct bpf_reg_state *src_reg)
8538 {
8539 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8540 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8541 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8542 	s32 smin_val = src_reg->s32_min_value;
8543 	u32 umin_val = src_reg->u32_min_value;
8544 
8545 	if (src_known && dst_known) {
8546 		__mark_reg32_known(dst_reg, var32_off.value);
8547 		return;
8548 	}
8549 
8550 	/* We get our maximum from the var_off, and our minimum is the
8551 	 * maximum of the operands' minima
8552 	 */
8553 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8554 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8555 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8556 		/* Lose signed bounds when ORing negative numbers,
8557 		 * ain't nobody got time for that.
8558 		 */
8559 		dst_reg->s32_min_value = S32_MIN;
8560 		dst_reg->s32_max_value = S32_MAX;
8561 	} else {
8562 		/* ORing two positives gives a positive, so safe to
8563 		 * cast result into s64.
8564 		 */
8565 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8566 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8567 	}
8568 }
8569 
8570 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8571 			      struct bpf_reg_state *src_reg)
8572 {
8573 	bool src_known = tnum_is_const(src_reg->var_off);
8574 	bool dst_known = tnum_is_const(dst_reg->var_off);
8575 	s64 smin_val = src_reg->smin_value;
8576 	u64 umin_val = src_reg->umin_value;
8577 
8578 	if (src_known && dst_known) {
8579 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8580 		return;
8581 	}
8582 
8583 	/* We get our maximum from the var_off, and our minimum is the
8584 	 * maximum of the operands' minima
8585 	 */
8586 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8587 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8588 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8589 		/* Lose signed bounds when ORing negative numbers,
8590 		 * ain't nobody got time for that.
8591 		 */
8592 		dst_reg->smin_value = S64_MIN;
8593 		dst_reg->smax_value = S64_MAX;
8594 	} else {
8595 		/* ORing two positives gives a positive, so safe to
8596 		 * cast result into s64.
8597 		 */
8598 		dst_reg->smin_value = dst_reg->umin_value;
8599 		dst_reg->smax_value = dst_reg->umax_value;
8600 	}
8601 	/* We may learn something more from the var_off */
8602 	__update_reg_bounds(dst_reg);
8603 }
8604 
8605 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8606 				 struct bpf_reg_state *src_reg)
8607 {
8608 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8609 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8610 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8611 	s32 smin_val = src_reg->s32_min_value;
8612 
8613 	if (src_known && dst_known) {
8614 		__mark_reg32_known(dst_reg, var32_off.value);
8615 		return;
8616 	}
8617 
8618 	/* We get both minimum and maximum from the var32_off. */
8619 	dst_reg->u32_min_value = var32_off.value;
8620 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8621 
8622 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8623 		/* XORing two positive sign numbers gives a positive,
8624 		 * so safe to cast u32 result into s32.
8625 		 */
8626 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8627 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8628 	} else {
8629 		dst_reg->s32_min_value = S32_MIN;
8630 		dst_reg->s32_max_value = S32_MAX;
8631 	}
8632 }
8633 
8634 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8635 			       struct bpf_reg_state *src_reg)
8636 {
8637 	bool src_known = tnum_is_const(src_reg->var_off);
8638 	bool dst_known = tnum_is_const(dst_reg->var_off);
8639 	s64 smin_val = src_reg->smin_value;
8640 
8641 	if (src_known && dst_known) {
8642 		/* dst_reg->var_off.value has been updated earlier */
8643 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8644 		return;
8645 	}
8646 
8647 	/* We get both minimum and maximum from the var_off. */
8648 	dst_reg->umin_value = dst_reg->var_off.value;
8649 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8650 
8651 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8652 		/* XORing two positive sign numbers gives a positive,
8653 		 * so safe to cast u64 result into s64.
8654 		 */
8655 		dst_reg->smin_value = dst_reg->umin_value;
8656 		dst_reg->smax_value = dst_reg->umax_value;
8657 	} else {
8658 		dst_reg->smin_value = S64_MIN;
8659 		dst_reg->smax_value = S64_MAX;
8660 	}
8661 
8662 	__update_reg_bounds(dst_reg);
8663 }
8664 
8665 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8666 				   u64 umin_val, u64 umax_val)
8667 {
8668 	/* We lose all sign bit information (except what we can pick
8669 	 * up from var_off)
8670 	 */
8671 	dst_reg->s32_min_value = S32_MIN;
8672 	dst_reg->s32_max_value = S32_MAX;
8673 	/* If we might shift our top bit out, then we know nothing */
8674 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8675 		dst_reg->u32_min_value = 0;
8676 		dst_reg->u32_max_value = U32_MAX;
8677 	} else {
8678 		dst_reg->u32_min_value <<= umin_val;
8679 		dst_reg->u32_max_value <<= umax_val;
8680 	}
8681 }
8682 
8683 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8684 				 struct bpf_reg_state *src_reg)
8685 {
8686 	u32 umax_val = src_reg->u32_max_value;
8687 	u32 umin_val = src_reg->u32_min_value;
8688 	/* u32 alu operation will zext upper bits */
8689 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8690 
8691 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8692 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8693 	/* Not required but being careful mark reg64 bounds as unknown so
8694 	 * that we are forced to pick them up from tnum and zext later and
8695 	 * if some path skips this step we are still safe.
8696 	 */
8697 	__mark_reg64_unbounded(dst_reg);
8698 	__update_reg32_bounds(dst_reg);
8699 }
8700 
8701 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8702 				   u64 umin_val, u64 umax_val)
8703 {
8704 	/* Special case <<32 because it is a common compiler pattern to sign
8705 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8706 	 * positive we know this shift will also be positive so we can track
8707 	 * bounds correctly. Otherwise we lose all sign bit information except
8708 	 * what we can pick up from var_off. Perhaps we can generalize this
8709 	 * later to shifts of any length.
8710 	 */
8711 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8712 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8713 	else
8714 		dst_reg->smax_value = S64_MAX;
8715 
8716 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8717 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8718 	else
8719 		dst_reg->smin_value = S64_MIN;
8720 
8721 	/* If we might shift our top bit out, then we know nothing */
8722 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8723 		dst_reg->umin_value = 0;
8724 		dst_reg->umax_value = U64_MAX;
8725 	} else {
8726 		dst_reg->umin_value <<= umin_val;
8727 		dst_reg->umax_value <<= umax_val;
8728 	}
8729 }
8730 
8731 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8732 			       struct bpf_reg_state *src_reg)
8733 {
8734 	u64 umax_val = src_reg->umax_value;
8735 	u64 umin_val = src_reg->umin_value;
8736 
8737 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8738 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8739 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8740 
8741 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8742 	/* We may learn something more from the var_off */
8743 	__update_reg_bounds(dst_reg);
8744 }
8745 
8746 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8747 				 struct bpf_reg_state *src_reg)
8748 {
8749 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8750 	u32 umax_val = src_reg->u32_max_value;
8751 	u32 umin_val = src_reg->u32_min_value;
8752 
8753 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8754 	 * be negative, then either:
8755 	 * 1) src_reg might be zero, so the sign bit of the result is
8756 	 *    unknown, so we lose our signed bounds
8757 	 * 2) it's known negative, thus the unsigned bounds capture the
8758 	 *    signed bounds
8759 	 * 3) the signed bounds cross zero, so they tell us nothing
8760 	 *    about the result
8761 	 * If the value in dst_reg is known nonnegative, then again the
8762 	 * unsigned bounds capture the signed bounds.
8763 	 * Thus, in all cases it suffices to blow away our signed bounds
8764 	 * and rely on inferring new ones from the unsigned bounds and
8765 	 * var_off of the result.
8766 	 */
8767 	dst_reg->s32_min_value = S32_MIN;
8768 	dst_reg->s32_max_value = S32_MAX;
8769 
8770 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8771 	dst_reg->u32_min_value >>= umax_val;
8772 	dst_reg->u32_max_value >>= umin_val;
8773 
8774 	__mark_reg64_unbounded(dst_reg);
8775 	__update_reg32_bounds(dst_reg);
8776 }
8777 
8778 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8779 			       struct bpf_reg_state *src_reg)
8780 {
8781 	u64 umax_val = src_reg->umax_value;
8782 	u64 umin_val = src_reg->umin_value;
8783 
8784 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8785 	 * be negative, then either:
8786 	 * 1) src_reg might be zero, so the sign bit of the result is
8787 	 *    unknown, so we lose our signed bounds
8788 	 * 2) it's known negative, thus the unsigned bounds capture the
8789 	 *    signed bounds
8790 	 * 3) the signed bounds cross zero, so they tell us nothing
8791 	 *    about the result
8792 	 * If the value in dst_reg is known nonnegative, then again the
8793 	 * unsigned bounds capture the signed bounds.
8794 	 * Thus, in all cases it suffices to blow away our signed bounds
8795 	 * and rely on inferring new ones from the unsigned bounds and
8796 	 * var_off of the result.
8797 	 */
8798 	dst_reg->smin_value = S64_MIN;
8799 	dst_reg->smax_value = S64_MAX;
8800 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8801 	dst_reg->umin_value >>= umax_val;
8802 	dst_reg->umax_value >>= umin_val;
8803 
8804 	/* Its not easy to operate on alu32 bounds here because it depends
8805 	 * on bits being shifted in. Take easy way out and mark unbounded
8806 	 * so we can recalculate later from tnum.
8807 	 */
8808 	__mark_reg32_unbounded(dst_reg);
8809 	__update_reg_bounds(dst_reg);
8810 }
8811 
8812 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8813 				  struct bpf_reg_state *src_reg)
8814 {
8815 	u64 umin_val = src_reg->u32_min_value;
8816 
8817 	/* Upon reaching here, src_known is true and
8818 	 * umax_val is equal to umin_val.
8819 	 */
8820 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8821 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8822 
8823 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8824 
8825 	/* blow away the dst_reg umin_value/umax_value and rely on
8826 	 * dst_reg var_off to refine the result.
8827 	 */
8828 	dst_reg->u32_min_value = 0;
8829 	dst_reg->u32_max_value = U32_MAX;
8830 
8831 	__mark_reg64_unbounded(dst_reg);
8832 	__update_reg32_bounds(dst_reg);
8833 }
8834 
8835 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8836 				struct bpf_reg_state *src_reg)
8837 {
8838 	u64 umin_val = src_reg->umin_value;
8839 
8840 	/* Upon reaching here, src_known is true and umax_val is equal
8841 	 * to umin_val.
8842 	 */
8843 	dst_reg->smin_value >>= umin_val;
8844 	dst_reg->smax_value >>= umin_val;
8845 
8846 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8847 
8848 	/* blow away the dst_reg umin_value/umax_value and rely on
8849 	 * dst_reg var_off to refine the result.
8850 	 */
8851 	dst_reg->umin_value = 0;
8852 	dst_reg->umax_value = U64_MAX;
8853 
8854 	/* Its not easy to operate on alu32 bounds here because it depends
8855 	 * on bits being shifted in from upper 32-bits. Take easy way out
8856 	 * and mark unbounded so we can recalculate later from tnum.
8857 	 */
8858 	__mark_reg32_unbounded(dst_reg);
8859 	__update_reg_bounds(dst_reg);
8860 }
8861 
8862 /* WARNING: This function does calculations on 64-bit values, but the actual
8863  * execution may occur on 32-bit values. Therefore, things like bitshifts
8864  * need extra checks in the 32-bit case.
8865  */
8866 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8867 				      struct bpf_insn *insn,
8868 				      struct bpf_reg_state *dst_reg,
8869 				      struct bpf_reg_state src_reg)
8870 {
8871 	struct bpf_reg_state *regs = cur_regs(env);
8872 	u8 opcode = BPF_OP(insn->code);
8873 	bool src_known;
8874 	s64 smin_val, smax_val;
8875 	u64 umin_val, umax_val;
8876 	s32 s32_min_val, s32_max_val;
8877 	u32 u32_min_val, u32_max_val;
8878 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8879 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8880 	int ret;
8881 
8882 	smin_val = src_reg.smin_value;
8883 	smax_val = src_reg.smax_value;
8884 	umin_val = src_reg.umin_value;
8885 	umax_val = src_reg.umax_value;
8886 
8887 	s32_min_val = src_reg.s32_min_value;
8888 	s32_max_val = src_reg.s32_max_value;
8889 	u32_min_val = src_reg.u32_min_value;
8890 	u32_max_val = src_reg.u32_max_value;
8891 
8892 	if (alu32) {
8893 		src_known = tnum_subreg_is_const(src_reg.var_off);
8894 		if ((src_known &&
8895 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8896 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8897 			/* Taint dst register if offset had invalid bounds
8898 			 * derived from e.g. dead branches.
8899 			 */
8900 			__mark_reg_unknown(env, dst_reg);
8901 			return 0;
8902 		}
8903 	} else {
8904 		src_known = tnum_is_const(src_reg.var_off);
8905 		if ((src_known &&
8906 		     (smin_val != smax_val || umin_val != umax_val)) ||
8907 		    smin_val > smax_val || umin_val > umax_val) {
8908 			/* Taint dst register if offset had invalid bounds
8909 			 * derived from e.g. dead branches.
8910 			 */
8911 			__mark_reg_unknown(env, dst_reg);
8912 			return 0;
8913 		}
8914 	}
8915 
8916 	if (!src_known &&
8917 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8918 		__mark_reg_unknown(env, dst_reg);
8919 		return 0;
8920 	}
8921 
8922 	if (sanitize_needed(opcode)) {
8923 		ret = sanitize_val_alu(env, insn);
8924 		if (ret < 0)
8925 			return sanitize_err(env, insn, ret, NULL, NULL);
8926 	}
8927 
8928 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8929 	 * There are two classes of instructions: The first class we track both
8930 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8931 	 * greatest amount of precision when alu operations are mixed with jmp32
8932 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8933 	 * and BPF_OR. This is possible because these ops have fairly easy to
8934 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8935 	 * See alu32 verifier tests for examples. The second class of
8936 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8937 	 * with regards to tracking sign/unsigned bounds because the bits may
8938 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8939 	 * the reg unbounded in the subreg bound space and use the resulting
8940 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8941 	 */
8942 	switch (opcode) {
8943 	case BPF_ADD:
8944 		scalar32_min_max_add(dst_reg, &src_reg);
8945 		scalar_min_max_add(dst_reg, &src_reg);
8946 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8947 		break;
8948 	case BPF_SUB:
8949 		scalar32_min_max_sub(dst_reg, &src_reg);
8950 		scalar_min_max_sub(dst_reg, &src_reg);
8951 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8952 		break;
8953 	case BPF_MUL:
8954 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8955 		scalar32_min_max_mul(dst_reg, &src_reg);
8956 		scalar_min_max_mul(dst_reg, &src_reg);
8957 		break;
8958 	case BPF_AND:
8959 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8960 		scalar32_min_max_and(dst_reg, &src_reg);
8961 		scalar_min_max_and(dst_reg, &src_reg);
8962 		break;
8963 	case BPF_OR:
8964 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8965 		scalar32_min_max_or(dst_reg, &src_reg);
8966 		scalar_min_max_or(dst_reg, &src_reg);
8967 		break;
8968 	case BPF_XOR:
8969 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8970 		scalar32_min_max_xor(dst_reg, &src_reg);
8971 		scalar_min_max_xor(dst_reg, &src_reg);
8972 		break;
8973 	case BPF_LSH:
8974 		if (umax_val >= insn_bitness) {
8975 			/* Shifts greater than 31 or 63 are undefined.
8976 			 * This includes shifts by a negative number.
8977 			 */
8978 			mark_reg_unknown(env, regs, insn->dst_reg);
8979 			break;
8980 		}
8981 		if (alu32)
8982 			scalar32_min_max_lsh(dst_reg, &src_reg);
8983 		else
8984 			scalar_min_max_lsh(dst_reg, &src_reg);
8985 		break;
8986 	case BPF_RSH:
8987 		if (umax_val >= insn_bitness) {
8988 			/* Shifts greater than 31 or 63 are undefined.
8989 			 * This includes shifts by a negative number.
8990 			 */
8991 			mark_reg_unknown(env, regs, insn->dst_reg);
8992 			break;
8993 		}
8994 		if (alu32)
8995 			scalar32_min_max_rsh(dst_reg, &src_reg);
8996 		else
8997 			scalar_min_max_rsh(dst_reg, &src_reg);
8998 		break;
8999 	case BPF_ARSH:
9000 		if (umax_val >= insn_bitness) {
9001 			/* Shifts greater than 31 or 63 are undefined.
9002 			 * This includes shifts by a negative number.
9003 			 */
9004 			mark_reg_unknown(env, regs, insn->dst_reg);
9005 			break;
9006 		}
9007 		if (alu32)
9008 			scalar32_min_max_arsh(dst_reg, &src_reg);
9009 		else
9010 			scalar_min_max_arsh(dst_reg, &src_reg);
9011 		break;
9012 	default:
9013 		mark_reg_unknown(env, regs, insn->dst_reg);
9014 		break;
9015 	}
9016 
9017 	/* ALU32 ops are zero extended into 64bit register */
9018 	if (alu32)
9019 		zext_32_to_64(dst_reg);
9020 	reg_bounds_sync(dst_reg);
9021 	return 0;
9022 }
9023 
9024 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9025  * and var_off.
9026  */
9027 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9028 				   struct bpf_insn *insn)
9029 {
9030 	struct bpf_verifier_state *vstate = env->cur_state;
9031 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9032 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9033 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9034 	u8 opcode = BPF_OP(insn->code);
9035 	int err;
9036 
9037 	dst_reg = &regs[insn->dst_reg];
9038 	src_reg = NULL;
9039 	if (dst_reg->type != SCALAR_VALUE)
9040 		ptr_reg = dst_reg;
9041 	else
9042 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9043 		 * incorrectly propagated into other registers by find_equal_scalars()
9044 		 */
9045 		dst_reg->id = 0;
9046 	if (BPF_SRC(insn->code) == BPF_X) {
9047 		src_reg = &regs[insn->src_reg];
9048 		if (src_reg->type != SCALAR_VALUE) {
9049 			if (dst_reg->type != SCALAR_VALUE) {
9050 				/* Combining two pointers by any ALU op yields
9051 				 * an arbitrary scalar. Disallow all math except
9052 				 * pointer subtraction
9053 				 */
9054 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9055 					mark_reg_unknown(env, regs, insn->dst_reg);
9056 					return 0;
9057 				}
9058 				verbose(env, "R%d pointer %s pointer prohibited\n",
9059 					insn->dst_reg,
9060 					bpf_alu_string[opcode >> 4]);
9061 				return -EACCES;
9062 			} else {
9063 				/* scalar += pointer
9064 				 * This is legal, but we have to reverse our
9065 				 * src/dest handling in computing the range
9066 				 */
9067 				err = mark_chain_precision(env, insn->dst_reg);
9068 				if (err)
9069 					return err;
9070 				return adjust_ptr_min_max_vals(env, insn,
9071 							       src_reg, dst_reg);
9072 			}
9073 		} else if (ptr_reg) {
9074 			/* pointer += scalar */
9075 			err = mark_chain_precision(env, insn->src_reg);
9076 			if (err)
9077 				return err;
9078 			return adjust_ptr_min_max_vals(env, insn,
9079 						       dst_reg, src_reg);
9080 		}
9081 	} else {
9082 		/* Pretend the src is a reg with a known value, since we only
9083 		 * need to be able to read from this state.
9084 		 */
9085 		off_reg.type = SCALAR_VALUE;
9086 		__mark_reg_known(&off_reg, insn->imm);
9087 		src_reg = &off_reg;
9088 		if (ptr_reg) /* pointer += K */
9089 			return adjust_ptr_min_max_vals(env, insn,
9090 						       ptr_reg, src_reg);
9091 	}
9092 
9093 	/* Got here implies adding two SCALAR_VALUEs */
9094 	if (WARN_ON_ONCE(ptr_reg)) {
9095 		print_verifier_state(env, state, true);
9096 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9097 		return -EINVAL;
9098 	}
9099 	if (WARN_ON(!src_reg)) {
9100 		print_verifier_state(env, state, true);
9101 		verbose(env, "verifier internal error: no src_reg\n");
9102 		return -EINVAL;
9103 	}
9104 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9105 }
9106 
9107 /* check validity of 32-bit and 64-bit arithmetic operations */
9108 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9109 {
9110 	struct bpf_reg_state *regs = cur_regs(env);
9111 	u8 opcode = BPF_OP(insn->code);
9112 	int err;
9113 
9114 	if (opcode == BPF_END || opcode == BPF_NEG) {
9115 		if (opcode == BPF_NEG) {
9116 			if (BPF_SRC(insn->code) != BPF_K ||
9117 			    insn->src_reg != BPF_REG_0 ||
9118 			    insn->off != 0 || insn->imm != 0) {
9119 				verbose(env, "BPF_NEG uses reserved fields\n");
9120 				return -EINVAL;
9121 			}
9122 		} else {
9123 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9124 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9125 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9126 				verbose(env, "BPF_END uses reserved fields\n");
9127 				return -EINVAL;
9128 			}
9129 		}
9130 
9131 		/* check src operand */
9132 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9133 		if (err)
9134 			return err;
9135 
9136 		if (is_pointer_value(env, insn->dst_reg)) {
9137 			verbose(env, "R%d pointer arithmetic prohibited\n",
9138 				insn->dst_reg);
9139 			return -EACCES;
9140 		}
9141 
9142 		/* check dest operand */
9143 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9144 		if (err)
9145 			return err;
9146 
9147 	} else if (opcode == BPF_MOV) {
9148 
9149 		if (BPF_SRC(insn->code) == BPF_X) {
9150 			if (insn->imm != 0 || insn->off != 0) {
9151 				verbose(env, "BPF_MOV uses reserved fields\n");
9152 				return -EINVAL;
9153 			}
9154 
9155 			/* check src operand */
9156 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9157 			if (err)
9158 				return err;
9159 		} else {
9160 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9161 				verbose(env, "BPF_MOV uses reserved fields\n");
9162 				return -EINVAL;
9163 			}
9164 		}
9165 
9166 		/* check dest operand, mark as required later */
9167 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9168 		if (err)
9169 			return err;
9170 
9171 		if (BPF_SRC(insn->code) == BPF_X) {
9172 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9173 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9174 
9175 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9176 				/* case: R1 = R2
9177 				 * copy register state to dest reg
9178 				 */
9179 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9180 					/* Assign src and dst registers the same ID
9181 					 * that will be used by find_equal_scalars()
9182 					 * to propagate min/max range.
9183 					 */
9184 					src_reg->id = ++env->id_gen;
9185 				*dst_reg = *src_reg;
9186 				dst_reg->live |= REG_LIVE_WRITTEN;
9187 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9188 			} else {
9189 				/* R1 = (u32) R2 */
9190 				if (is_pointer_value(env, insn->src_reg)) {
9191 					verbose(env,
9192 						"R%d partial copy of pointer\n",
9193 						insn->src_reg);
9194 					return -EACCES;
9195 				} else if (src_reg->type == SCALAR_VALUE) {
9196 					*dst_reg = *src_reg;
9197 					/* Make sure ID is cleared otherwise
9198 					 * dst_reg min/max could be incorrectly
9199 					 * propagated into src_reg by find_equal_scalars()
9200 					 */
9201 					dst_reg->id = 0;
9202 					dst_reg->live |= REG_LIVE_WRITTEN;
9203 					dst_reg->subreg_def = env->insn_idx + 1;
9204 				} else {
9205 					mark_reg_unknown(env, regs,
9206 							 insn->dst_reg);
9207 				}
9208 				zext_32_to_64(dst_reg);
9209 				reg_bounds_sync(dst_reg);
9210 			}
9211 		} else {
9212 			/* case: R = imm
9213 			 * remember the value we stored into this reg
9214 			 */
9215 			/* clear any state __mark_reg_known doesn't set */
9216 			mark_reg_unknown(env, regs, insn->dst_reg);
9217 			regs[insn->dst_reg].type = SCALAR_VALUE;
9218 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9219 				__mark_reg_known(regs + insn->dst_reg,
9220 						 insn->imm);
9221 			} else {
9222 				__mark_reg_known(regs + insn->dst_reg,
9223 						 (u32)insn->imm);
9224 			}
9225 		}
9226 
9227 	} else if (opcode > BPF_END) {
9228 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9229 		return -EINVAL;
9230 
9231 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9232 
9233 		if (BPF_SRC(insn->code) == BPF_X) {
9234 			if (insn->imm != 0 || insn->off != 0) {
9235 				verbose(env, "BPF_ALU uses reserved fields\n");
9236 				return -EINVAL;
9237 			}
9238 			/* check src1 operand */
9239 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9240 			if (err)
9241 				return err;
9242 		} else {
9243 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9244 				verbose(env, "BPF_ALU uses reserved fields\n");
9245 				return -EINVAL;
9246 			}
9247 		}
9248 
9249 		/* check src2 operand */
9250 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9251 		if (err)
9252 			return err;
9253 
9254 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9255 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9256 			verbose(env, "div by zero\n");
9257 			return -EINVAL;
9258 		}
9259 
9260 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9261 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9262 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9263 
9264 			if (insn->imm < 0 || insn->imm >= size) {
9265 				verbose(env, "invalid shift %d\n", insn->imm);
9266 				return -EINVAL;
9267 			}
9268 		}
9269 
9270 		/* check dest operand */
9271 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9272 		if (err)
9273 			return err;
9274 
9275 		return adjust_reg_min_max_vals(env, insn);
9276 	}
9277 
9278 	return 0;
9279 }
9280 
9281 static void __find_good_pkt_pointers(struct bpf_func_state *state,
9282 				     struct bpf_reg_state *dst_reg,
9283 				     enum bpf_reg_type type, int new_range)
9284 {
9285 	struct bpf_reg_state *reg;
9286 	int i;
9287 
9288 	for (i = 0; i < MAX_BPF_REG; i++) {
9289 		reg = &state->regs[i];
9290 		if (reg->type == type && reg->id == dst_reg->id)
9291 			/* keep the maximum range already checked */
9292 			reg->range = max(reg->range, new_range);
9293 	}
9294 
9295 	bpf_for_each_spilled_reg(i, state, reg) {
9296 		if (!reg)
9297 			continue;
9298 		if (reg->type == type && reg->id == dst_reg->id)
9299 			reg->range = max(reg->range, new_range);
9300 	}
9301 }
9302 
9303 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9304 				   struct bpf_reg_state *dst_reg,
9305 				   enum bpf_reg_type type,
9306 				   bool range_right_open)
9307 {
9308 	int new_range, i;
9309 
9310 	if (dst_reg->off < 0 ||
9311 	    (dst_reg->off == 0 && range_right_open))
9312 		/* This doesn't give us any range */
9313 		return;
9314 
9315 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9316 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9317 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9318 		 * than pkt_end, but that's because it's also less than pkt.
9319 		 */
9320 		return;
9321 
9322 	new_range = dst_reg->off;
9323 	if (range_right_open)
9324 		new_range++;
9325 
9326 	/* Examples for register markings:
9327 	 *
9328 	 * pkt_data in dst register:
9329 	 *
9330 	 *   r2 = r3;
9331 	 *   r2 += 8;
9332 	 *   if (r2 > pkt_end) goto <handle exception>
9333 	 *   <access okay>
9334 	 *
9335 	 *   r2 = r3;
9336 	 *   r2 += 8;
9337 	 *   if (r2 < pkt_end) goto <access okay>
9338 	 *   <handle exception>
9339 	 *
9340 	 *   Where:
9341 	 *     r2 == dst_reg, pkt_end == src_reg
9342 	 *     r2=pkt(id=n,off=8,r=0)
9343 	 *     r3=pkt(id=n,off=0,r=0)
9344 	 *
9345 	 * pkt_data in src register:
9346 	 *
9347 	 *   r2 = r3;
9348 	 *   r2 += 8;
9349 	 *   if (pkt_end >= r2) goto <access okay>
9350 	 *   <handle exception>
9351 	 *
9352 	 *   r2 = r3;
9353 	 *   r2 += 8;
9354 	 *   if (pkt_end <= r2) goto <handle exception>
9355 	 *   <access okay>
9356 	 *
9357 	 *   Where:
9358 	 *     pkt_end == dst_reg, r2 == src_reg
9359 	 *     r2=pkt(id=n,off=8,r=0)
9360 	 *     r3=pkt(id=n,off=0,r=0)
9361 	 *
9362 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9363 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9364 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9365 	 * the check.
9366 	 */
9367 
9368 	/* If our ids match, then we must have the same max_value.  And we
9369 	 * don't care about the other reg's fixed offset, since if it's too big
9370 	 * the range won't allow anything.
9371 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9372 	 */
9373 	for (i = 0; i <= vstate->curframe; i++)
9374 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
9375 					 new_range);
9376 }
9377 
9378 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9379 {
9380 	struct tnum subreg = tnum_subreg(reg->var_off);
9381 	s32 sval = (s32)val;
9382 
9383 	switch (opcode) {
9384 	case BPF_JEQ:
9385 		if (tnum_is_const(subreg))
9386 			return !!tnum_equals_const(subreg, val);
9387 		break;
9388 	case BPF_JNE:
9389 		if (tnum_is_const(subreg))
9390 			return !tnum_equals_const(subreg, val);
9391 		break;
9392 	case BPF_JSET:
9393 		if ((~subreg.mask & subreg.value) & val)
9394 			return 1;
9395 		if (!((subreg.mask | subreg.value) & val))
9396 			return 0;
9397 		break;
9398 	case BPF_JGT:
9399 		if (reg->u32_min_value > val)
9400 			return 1;
9401 		else if (reg->u32_max_value <= val)
9402 			return 0;
9403 		break;
9404 	case BPF_JSGT:
9405 		if (reg->s32_min_value > sval)
9406 			return 1;
9407 		else if (reg->s32_max_value <= sval)
9408 			return 0;
9409 		break;
9410 	case BPF_JLT:
9411 		if (reg->u32_max_value < val)
9412 			return 1;
9413 		else if (reg->u32_min_value >= val)
9414 			return 0;
9415 		break;
9416 	case BPF_JSLT:
9417 		if (reg->s32_max_value < sval)
9418 			return 1;
9419 		else if (reg->s32_min_value >= sval)
9420 			return 0;
9421 		break;
9422 	case BPF_JGE:
9423 		if (reg->u32_min_value >= val)
9424 			return 1;
9425 		else if (reg->u32_max_value < val)
9426 			return 0;
9427 		break;
9428 	case BPF_JSGE:
9429 		if (reg->s32_min_value >= sval)
9430 			return 1;
9431 		else if (reg->s32_max_value < sval)
9432 			return 0;
9433 		break;
9434 	case BPF_JLE:
9435 		if (reg->u32_max_value <= val)
9436 			return 1;
9437 		else if (reg->u32_min_value > val)
9438 			return 0;
9439 		break;
9440 	case BPF_JSLE:
9441 		if (reg->s32_max_value <= sval)
9442 			return 1;
9443 		else if (reg->s32_min_value > sval)
9444 			return 0;
9445 		break;
9446 	}
9447 
9448 	return -1;
9449 }
9450 
9451 
9452 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9453 {
9454 	s64 sval = (s64)val;
9455 
9456 	switch (opcode) {
9457 	case BPF_JEQ:
9458 		if (tnum_is_const(reg->var_off))
9459 			return !!tnum_equals_const(reg->var_off, val);
9460 		break;
9461 	case BPF_JNE:
9462 		if (tnum_is_const(reg->var_off))
9463 			return !tnum_equals_const(reg->var_off, val);
9464 		break;
9465 	case BPF_JSET:
9466 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9467 			return 1;
9468 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9469 			return 0;
9470 		break;
9471 	case BPF_JGT:
9472 		if (reg->umin_value > val)
9473 			return 1;
9474 		else if (reg->umax_value <= val)
9475 			return 0;
9476 		break;
9477 	case BPF_JSGT:
9478 		if (reg->smin_value > sval)
9479 			return 1;
9480 		else if (reg->smax_value <= sval)
9481 			return 0;
9482 		break;
9483 	case BPF_JLT:
9484 		if (reg->umax_value < val)
9485 			return 1;
9486 		else if (reg->umin_value >= val)
9487 			return 0;
9488 		break;
9489 	case BPF_JSLT:
9490 		if (reg->smax_value < sval)
9491 			return 1;
9492 		else if (reg->smin_value >= sval)
9493 			return 0;
9494 		break;
9495 	case BPF_JGE:
9496 		if (reg->umin_value >= val)
9497 			return 1;
9498 		else if (reg->umax_value < val)
9499 			return 0;
9500 		break;
9501 	case BPF_JSGE:
9502 		if (reg->smin_value >= sval)
9503 			return 1;
9504 		else if (reg->smax_value < sval)
9505 			return 0;
9506 		break;
9507 	case BPF_JLE:
9508 		if (reg->umax_value <= val)
9509 			return 1;
9510 		else if (reg->umin_value > val)
9511 			return 0;
9512 		break;
9513 	case BPF_JSLE:
9514 		if (reg->smax_value <= sval)
9515 			return 1;
9516 		else if (reg->smin_value > sval)
9517 			return 0;
9518 		break;
9519 	}
9520 
9521 	return -1;
9522 }
9523 
9524 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9525  * and return:
9526  *  1 - branch will be taken and "goto target" will be executed
9527  *  0 - branch will not be taken and fall-through to next insn
9528  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9529  *      range [0,10]
9530  */
9531 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9532 			   bool is_jmp32)
9533 {
9534 	if (__is_pointer_value(false, reg)) {
9535 		if (!reg_type_not_null(reg->type))
9536 			return -1;
9537 
9538 		/* If pointer is valid tests against zero will fail so we can
9539 		 * use this to direct branch taken.
9540 		 */
9541 		if (val != 0)
9542 			return -1;
9543 
9544 		switch (opcode) {
9545 		case BPF_JEQ:
9546 			return 0;
9547 		case BPF_JNE:
9548 			return 1;
9549 		default:
9550 			return -1;
9551 		}
9552 	}
9553 
9554 	if (is_jmp32)
9555 		return is_branch32_taken(reg, val, opcode);
9556 	return is_branch64_taken(reg, val, opcode);
9557 }
9558 
9559 static int flip_opcode(u32 opcode)
9560 {
9561 	/* How can we transform "a <op> b" into "b <op> a"? */
9562 	static const u8 opcode_flip[16] = {
9563 		/* these stay the same */
9564 		[BPF_JEQ  >> 4] = BPF_JEQ,
9565 		[BPF_JNE  >> 4] = BPF_JNE,
9566 		[BPF_JSET >> 4] = BPF_JSET,
9567 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9568 		[BPF_JGE  >> 4] = BPF_JLE,
9569 		[BPF_JGT  >> 4] = BPF_JLT,
9570 		[BPF_JLE  >> 4] = BPF_JGE,
9571 		[BPF_JLT  >> 4] = BPF_JGT,
9572 		[BPF_JSGE >> 4] = BPF_JSLE,
9573 		[BPF_JSGT >> 4] = BPF_JSLT,
9574 		[BPF_JSLE >> 4] = BPF_JSGE,
9575 		[BPF_JSLT >> 4] = BPF_JSGT
9576 	};
9577 	return opcode_flip[opcode >> 4];
9578 }
9579 
9580 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9581 				   struct bpf_reg_state *src_reg,
9582 				   u8 opcode)
9583 {
9584 	struct bpf_reg_state *pkt;
9585 
9586 	if (src_reg->type == PTR_TO_PACKET_END) {
9587 		pkt = dst_reg;
9588 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9589 		pkt = src_reg;
9590 		opcode = flip_opcode(opcode);
9591 	} else {
9592 		return -1;
9593 	}
9594 
9595 	if (pkt->range >= 0)
9596 		return -1;
9597 
9598 	switch (opcode) {
9599 	case BPF_JLE:
9600 		/* pkt <= pkt_end */
9601 		fallthrough;
9602 	case BPF_JGT:
9603 		/* pkt > pkt_end */
9604 		if (pkt->range == BEYOND_PKT_END)
9605 			/* pkt has at last one extra byte beyond pkt_end */
9606 			return opcode == BPF_JGT;
9607 		break;
9608 	case BPF_JLT:
9609 		/* pkt < pkt_end */
9610 		fallthrough;
9611 	case BPF_JGE:
9612 		/* pkt >= pkt_end */
9613 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9614 			return opcode == BPF_JGE;
9615 		break;
9616 	}
9617 	return -1;
9618 }
9619 
9620 /* Adjusts the register min/max values in the case that the dst_reg is the
9621  * variable register that we are working on, and src_reg is a constant or we're
9622  * simply doing a BPF_K check.
9623  * In JEQ/JNE cases we also adjust the var_off values.
9624  */
9625 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9626 			    struct bpf_reg_state *false_reg,
9627 			    u64 val, u32 val32,
9628 			    u8 opcode, bool is_jmp32)
9629 {
9630 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9631 	struct tnum false_64off = false_reg->var_off;
9632 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9633 	struct tnum true_64off = true_reg->var_off;
9634 	s64 sval = (s64)val;
9635 	s32 sval32 = (s32)val32;
9636 
9637 	/* If the dst_reg is a pointer, we can't learn anything about its
9638 	 * variable offset from the compare (unless src_reg were a pointer into
9639 	 * the same object, but we don't bother with that.
9640 	 * Since false_reg and true_reg have the same type by construction, we
9641 	 * only need to check one of them for pointerness.
9642 	 */
9643 	if (__is_pointer_value(false, false_reg))
9644 		return;
9645 
9646 	switch (opcode) {
9647 	/* JEQ/JNE comparison doesn't change the register equivalence.
9648 	 *
9649 	 * r1 = r2;
9650 	 * if (r1 == 42) goto label;
9651 	 * ...
9652 	 * label: // here both r1 and r2 are known to be 42.
9653 	 *
9654 	 * Hence when marking register as known preserve it's ID.
9655 	 */
9656 	case BPF_JEQ:
9657 		if (is_jmp32) {
9658 			__mark_reg32_known(true_reg, val32);
9659 			true_32off = tnum_subreg(true_reg->var_off);
9660 		} else {
9661 			___mark_reg_known(true_reg, val);
9662 			true_64off = true_reg->var_off;
9663 		}
9664 		break;
9665 	case BPF_JNE:
9666 		if (is_jmp32) {
9667 			__mark_reg32_known(false_reg, val32);
9668 			false_32off = tnum_subreg(false_reg->var_off);
9669 		} else {
9670 			___mark_reg_known(false_reg, val);
9671 			false_64off = false_reg->var_off;
9672 		}
9673 		break;
9674 	case BPF_JSET:
9675 		if (is_jmp32) {
9676 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9677 			if (is_power_of_2(val32))
9678 				true_32off = tnum_or(true_32off,
9679 						     tnum_const(val32));
9680 		} else {
9681 			false_64off = tnum_and(false_64off, tnum_const(~val));
9682 			if (is_power_of_2(val))
9683 				true_64off = tnum_or(true_64off,
9684 						     tnum_const(val));
9685 		}
9686 		break;
9687 	case BPF_JGE:
9688 	case BPF_JGT:
9689 	{
9690 		if (is_jmp32) {
9691 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9692 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9693 
9694 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9695 						       false_umax);
9696 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9697 						      true_umin);
9698 		} else {
9699 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9700 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9701 
9702 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9703 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9704 		}
9705 		break;
9706 	}
9707 	case BPF_JSGE:
9708 	case BPF_JSGT:
9709 	{
9710 		if (is_jmp32) {
9711 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9712 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9713 
9714 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9715 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9716 		} else {
9717 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9718 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9719 
9720 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9721 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9722 		}
9723 		break;
9724 	}
9725 	case BPF_JLE:
9726 	case BPF_JLT:
9727 	{
9728 		if (is_jmp32) {
9729 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9730 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9731 
9732 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9733 						       false_umin);
9734 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9735 						      true_umax);
9736 		} else {
9737 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9738 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9739 
9740 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9741 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9742 		}
9743 		break;
9744 	}
9745 	case BPF_JSLE:
9746 	case BPF_JSLT:
9747 	{
9748 		if (is_jmp32) {
9749 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9750 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9751 
9752 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9753 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9754 		} else {
9755 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9756 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9757 
9758 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9759 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9760 		}
9761 		break;
9762 	}
9763 	default:
9764 		return;
9765 	}
9766 
9767 	if (is_jmp32) {
9768 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9769 					     tnum_subreg(false_32off));
9770 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9771 					    tnum_subreg(true_32off));
9772 		__reg_combine_32_into_64(false_reg);
9773 		__reg_combine_32_into_64(true_reg);
9774 	} else {
9775 		false_reg->var_off = false_64off;
9776 		true_reg->var_off = true_64off;
9777 		__reg_combine_64_into_32(false_reg);
9778 		__reg_combine_64_into_32(true_reg);
9779 	}
9780 }
9781 
9782 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9783  * the variable reg.
9784  */
9785 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9786 				struct bpf_reg_state *false_reg,
9787 				u64 val, u32 val32,
9788 				u8 opcode, bool is_jmp32)
9789 {
9790 	opcode = flip_opcode(opcode);
9791 	/* This uses zero as "not present in table"; luckily the zero opcode,
9792 	 * BPF_JA, can't get here.
9793 	 */
9794 	if (opcode)
9795 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9796 }
9797 
9798 /* Regs are known to be equal, so intersect their min/max/var_off */
9799 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9800 				  struct bpf_reg_state *dst_reg)
9801 {
9802 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9803 							dst_reg->umin_value);
9804 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9805 							dst_reg->umax_value);
9806 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9807 							dst_reg->smin_value);
9808 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9809 							dst_reg->smax_value);
9810 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9811 							     dst_reg->var_off);
9812 	reg_bounds_sync(src_reg);
9813 	reg_bounds_sync(dst_reg);
9814 }
9815 
9816 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9817 				struct bpf_reg_state *true_dst,
9818 				struct bpf_reg_state *false_src,
9819 				struct bpf_reg_state *false_dst,
9820 				u8 opcode)
9821 {
9822 	switch (opcode) {
9823 	case BPF_JEQ:
9824 		__reg_combine_min_max(true_src, true_dst);
9825 		break;
9826 	case BPF_JNE:
9827 		__reg_combine_min_max(false_src, false_dst);
9828 		break;
9829 	}
9830 }
9831 
9832 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9833 				 struct bpf_reg_state *reg, u32 id,
9834 				 bool is_null)
9835 {
9836 	if (type_may_be_null(reg->type) && reg->id == id &&
9837 	    !WARN_ON_ONCE(!reg->id)) {
9838 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9839 				 !tnum_equals_const(reg->var_off, 0) ||
9840 				 reg->off)) {
9841 			/* Old offset (both fixed and variable parts) should
9842 			 * have been known-zero, because we don't allow pointer
9843 			 * arithmetic on pointers that might be NULL. If we
9844 			 * see this happening, don't convert the register.
9845 			 */
9846 			return;
9847 		}
9848 		if (is_null) {
9849 			reg->type = SCALAR_VALUE;
9850 			/* We don't need id and ref_obj_id from this point
9851 			 * onwards anymore, thus we should better reset it,
9852 			 * so that state pruning has chances to take effect.
9853 			 */
9854 			reg->id = 0;
9855 			reg->ref_obj_id = 0;
9856 
9857 			return;
9858 		}
9859 
9860 		mark_ptr_not_null_reg(reg);
9861 
9862 		if (!reg_may_point_to_spin_lock(reg)) {
9863 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9864 			 * in release_reg_references().
9865 			 *
9866 			 * reg->id is still used by spin_lock ptr. Other
9867 			 * than spin_lock ptr type, reg->id can be reset.
9868 			 */
9869 			reg->id = 0;
9870 		}
9871 	}
9872 }
9873 
9874 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9875 				    bool is_null)
9876 {
9877 	struct bpf_reg_state *reg;
9878 	int i;
9879 
9880 	for (i = 0; i < MAX_BPF_REG; i++)
9881 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9882 
9883 	bpf_for_each_spilled_reg(i, state, reg) {
9884 		if (!reg)
9885 			continue;
9886 		mark_ptr_or_null_reg(state, reg, id, is_null);
9887 	}
9888 }
9889 
9890 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9891  * be folded together at some point.
9892  */
9893 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9894 				  bool is_null)
9895 {
9896 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9897 	struct bpf_reg_state *regs = state->regs;
9898 	u32 ref_obj_id = regs[regno].ref_obj_id;
9899 	u32 id = regs[regno].id;
9900 	int i;
9901 
9902 	if (ref_obj_id && ref_obj_id == id && is_null)
9903 		/* regs[regno] is in the " == NULL" branch.
9904 		 * No one could have freed the reference state before
9905 		 * doing the NULL check.
9906 		 */
9907 		WARN_ON_ONCE(release_reference_state(state, id));
9908 
9909 	for (i = 0; i <= vstate->curframe; i++)
9910 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9911 }
9912 
9913 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9914 				   struct bpf_reg_state *dst_reg,
9915 				   struct bpf_reg_state *src_reg,
9916 				   struct bpf_verifier_state *this_branch,
9917 				   struct bpf_verifier_state *other_branch)
9918 {
9919 	if (BPF_SRC(insn->code) != BPF_X)
9920 		return false;
9921 
9922 	/* Pointers are always 64-bit. */
9923 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9924 		return false;
9925 
9926 	switch (BPF_OP(insn->code)) {
9927 	case BPF_JGT:
9928 		if ((dst_reg->type == PTR_TO_PACKET &&
9929 		     src_reg->type == PTR_TO_PACKET_END) ||
9930 		    (dst_reg->type == PTR_TO_PACKET_META &&
9931 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9932 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9933 			find_good_pkt_pointers(this_branch, dst_reg,
9934 					       dst_reg->type, false);
9935 			mark_pkt_end(other_branch, insn->dst_reg, true);
9936 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9937 			    src_reg->type == PTR_TO_PACKET) ||
9938 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9939 			    src_reg->type == PTR_TO_PACKET_META)) {
9940 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9941 			find_good_pkt_pointers(other_branch, src_reg,
9942 					       src_reg->type, true);
9943 			mark_pkt_end(this_branch, insn->src_reg, false);
9944 		} else {
9945 			return false;
9946 		}
9947 		break;
9948 	case BPF_JLT:
9949 		if ((dst_reg->type == PTR_TO_PACKET &&
9950 		     src_reg->type == PTR_TO_PACKET_END) ||
9951 		    (dst_reg->type == PTR_TO_PACKET_META &&
9952 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9953 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9954 			find_good_pkt_pointers(other_branch, dst_reg,
9955 					       dst_reg->type, true);
9956 			mark_pkt_end(this_branch, insn->dst_reg, false);
9957 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9958 			    src_reg->type == PTR_TO_PACKET) ||
9959 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9960 			    src_reg->type == PTR_TO_PACKET_META)) {
9961 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9962 			find_good_pkt_pointers(this_branch, src_reg,
9963 					       src_reg->type, false);
9964 			mark_pkt_end(other_branch, insn->src_reg, true);
9965 		} else {
9966 			return false;
9967 		}
9968 		break;
9969 	case BPF_JGE:
9970 		if ((dst_reg->type == PTR_TO_PACKET &&
9971 		     src_reg->type == PTR_TO_PACKET_END) ||
9972 		    (dst_reg->type == PTR_TO_PACKET_META &&
9973 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9974 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9975 			find_good_pkt_pointers(this_branch, dst_reg,
9976 					       dst_reg->type, true);
9977 			mark_pkt_end(other_branch, insn->dst_reg, false);
9978 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9979 			    src_reg->type == PTR_TO_PACKET) ||
9980 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9981 			    src_reg->type == PTR_TO_PACKET_META)) {
9982 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9983 			find_good_pkt_pointers(other_branch, src_reg,
9984 					       src_reg->type, false);
9985 			mark_pkt_end(this_branch, insn->src_reg, true);
9986 		} else {
9987 			return false;
9988 		}
9989 		break;
9990 	case BPF_JLE:
9991 		if ((dst_reg->type == PTR_TO_PACKET &&
9992 		     src_reg->type == PTR_TO_PACKET_END) ||
9993 		    (dst_reg->type == PTR_TO_PACKET_META &&
9994 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9995 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9996 			find_good_pkt_pointers(other_branch, dst_reg,
9997 					       dst_reg->type, false);
9998 			mark_pkt_end(this_branch, insn->dst_reg, true);
9999 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10000 			    src_reg->type == PTR_TO_PACKET) ||
10001 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10002 			    src_reg->type == PTR_TO_PACKET_META)) {
10003 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10004 			find_good_pkt_pointers(this_branch, src_reg,
10005 					       src_reg->type, true);
10006 			mark_pkt_end(other_branch, insn->src_reg, false);
10007 		} else {
10008 			return false;
10009 		}
10010 		break;
10011 	default:
10012 		return false;
10013 	}
10014 
10015 	return true;
10016 }
10017 
10018 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10019 			       struct bpf_reg_state *known_reg)
10020 {
10021 	struct bpf_func_state *state;
10022 	struct bpf_reg_state *reg;
10023 	int i, j;
10024 
10025 	for (i = 0; i <= vstate->curframe; i++) {
10026 		state = vstate->frame[i];
10027 		for (j = 0; j < MAX_BPF_REG; j++) {
10028 			reg = &state->regs[j];
10029 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10030 				*reg = *known_reg;
10031 		}
10032 
10033 		bpf_for_each_spilled_reg(j, state, reg) {
10034 			if (!reg)
10035 				continue;
10036 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10037 				*reg = *known_reg;
10038 		}
10039 	}
10040 }
10041 
10042 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10043 			     struct bpf_insn *insn, int *insn_idx)
10044 {
10045 	struct bpf_verifier_state *this_branch = env->cur_state;
10046 	struct bpf_verifier_state *other_branch;
10047 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10048 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10049 	u8 opcode = BPF_OP(insn->code);
10050 	bool is_jmp32;
10051 	int pred = -1;
10052 	int err;
10053 
10054 	/* Only conditional jumps are expected to reach here. */
10055 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10056 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10057 		return -EINVAL;
10058 	}
10059 
10060 	if (BPF_SRC(insn->code) == BPF_X) {
10061 		if (insn->imm != 0) {
10062 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10063 			return -EINVAL;
10064 		}
10065 
10066 		/* check src1 operand */
10067 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10068 		if (err)
10069 			return err;
10070 
10071 		if (is_pointer_value(env, insn->src_reg)) {
10072 			verbose(env, "R%d pointer comparison prohibited\n",
10073 				insn->src_reg);
10074 			return -EACCES;
10075 		}
10076 		src_reg = &regs[insn->src_reg];
10077 	} else {
10078 		if (insn->src_reg != BPF_REG_0) {
10079 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10080 			return -EINVAL;
10081 		}
10082 	}
10083 
10084 	/* check src2 operand */
10085 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10086 	if (err)
10087 		return err;
10088 
10089 	dst_reg = &regs[insn->dst_reg];
10090 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10091 
10092 	if (BPF_SRC(insn->code) == BPF_K) {
10093 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10094 	} else if (src_reg->type == SCALAR_VALUE &&
10095 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10096 		pred = is_branch_taken(dst_reg,
10097 				       tnum_subreg(src_reg->var_off).value,
10098 				       opcode,
10099 				       is_jmp32);
10100 	} else if (src_reg->type == SCALAR_VALUE &&
10101 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10102 		pred = is_branch_taken(dst_reg,
10103 				       src_reg->var_off.value,
10104 				       opcode,
10105 				       is_jmp32);
10106 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10107 		   reg_is_pkt_pointer_any(src_reg) &&
10108 		   !is_jmp32) {
10109 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10110 	}
10111 
10112 	if (pred >= 0) {
10113 		/* If we get here with a dst_reg pointer type it is because
10114 		 * above is_branch_taken() special cased the 0 comparison.
10115 		 */
10116 		if (!__is_pointer_value(false, dst_reg))
10117 			err = mark_chain_precision(env, insn->dst_reg);
10118 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10119 		    !__is_pointer_value(false, src_reg))
10120 			err = mark_chain_precision(env, insn->src_reg);
10121 		if (err)
10122 			return err;
10123 	}
10124 
10125 	if (pred == 1) {
10126 		/* Only follow the goto, ignore fall-through. If needed, push
10127 		 * the fall-through branch for simulation under speculative
10128 		 * execution.
10129 		 */
10130 		if (!env->bypass_spec_v1 &&
10131 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10132 					       *insn_idx))
10133 			return -EFAULT;
10134 		*insn_idx += insn->off;
10135 		return 0;
10136 	} else if (pred == 0) {
10137 		/* Only follow the fall-through branch, since that's where the
10138 		 * program will go. If needed, push the goto branch for
10139 		 * simulation under speculative execution.
10140 		 */
10141 		if (!env->bypass_spec_v1 &&
10142 		    !sanitize_speculative_path(env, insn,
10143 					       *insn_idx + insn->off + 1,
10144 					       *insn_idx))
10145 			return -EFAULT;
10146 		return 0;
10147 	}
10148 
10149 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10150 				  false);
10151 	if (!other_branch)
10152 		return -EFAULT;
10153 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10154 
10155 	/* detect if we are comparing against a constant value so we can adjust
10156 	 * our min/max values for our dst register.
10157 	 * this is only legit if both are scalars (or pointers to the same
10158 	 * object, I suppose, but we don't support that right now), because
10159 	 * otherwise the different base pointers mean the offsets aren't
10160 	 * comparable.
10161 	 */
10162 	if (BPF_SRC(insn->code) == BPF_X) {
10163 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10164 
10165 		if (dst_reg->type == SCALAR_VALUE &&
10166 		    src_reg->type == SCALAR_VALUE) {
10167 			if (tnum_is_const(src_reg->var_off) ||
10168 			    (is_jmp32 &&
10169 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10170 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10171 						dst_reg,
10172 						src_reg->var_off.value,
10173 						tnum_subreg(src_reg->var_off).value,
10174 						opcode, is_jmp32);
10175 			else if (tnum_is_const(dst_reg->var_off) ||
10176 				 (is_jmp32 &&
10177 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10178 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10179 						    src_reg,
10180 						    dst_reg->var_off.value,
10181 						    tnum_subreg(dst_reg->var_off).value,
10182 						    opcode, is_jmp32);
10183 			else if (!is_jmp32 &&
10184 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10185 				/* Comparing for equality, we can combine knowledge */
10186 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10187 						    &other_branch_regs[insn->dst_reg],
10188 						    src_reg, dst_reg, opcode);
10189 			if (src_reg->id &&
10190 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10191 				find_equal_scalars(this_branch, src_reg);
10192 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10193 			}
10194 
10195 		}
10196 	} else if (dst_reg->type == SCALAR_VALUE) {
10197 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10198 					dst_reg, insn->imm, (u32)insn->imm,
10199 					opcode, is_jmp32);
10200 	}
10201 
10202 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10203 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10204 		find_equal_scalars(this_branch, dst_reg);
10205 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10206 	}
10207 
10208 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10209 	 * NOTE: these optimizations below are related with pointer comparison
10210 	 *       which will never be JMP32.
10211 	 */
10212 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10213 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10214 	    type_may_be_null(dst_reg->type)) {
10215 		/* Mark all identical registers in each branch as either
10216 		 * safe or unknown depending R == 0 or R != 0 conditional.
10217 		 */
10218 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10219 				      opcode == BPF_JNE);
10220 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10221 				      opcode == BPF_JEQ);
10222 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10223 					   this_branch, other_branch) &&
10224 		   is_pointer_value(env, insn->dst_reg)) {
10225 		verbose(env, "R%d pointer comparison prohibited\n",
10226 			insn->dst_reg);
10227 		return -EACCES;
10228 	}
10229 	if (env->log.level & BPF_LOG_LEVEL)
10230 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10231 	return 0;
10232 }
10233 
10234 /* verify BPF_LD_IMM64 instruction */
10235 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10236 {
10237 	struct bpf_insn_aux_data *aux = cur_aux(env);
10238 	struct bpf_reg_state *regs = cur_regs(env);
10239 	struct bpf_reg_state *dst_reg;
10240 	struct bpf_map *map;
10241 	int err;
10242 
10243 	if (BPF_SIZE(insn->code) != BPF_DW) {
10244 		verbose(env, "invalid BPF_LD_IMM insn\n");
10245 		return -EINVAL;
10246 	}
10247 	if (insn->off != 0) {
10248 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10249 		return -EINVAL;
10250 	}
10251 
10252 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10253 	if (err)
10254 		return err;
10255 
10256 	dst_reg = &regs[insn->dst_reg];
10257 	if (insn->src_reg == 0) {
10258 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10259 
10260 		dst_reg->type = SCALAR_VALUE;
10261 		__mark_reg_known(&regs[insn->dst_reg], imm);
10262 		return 0;
10263 	}
10264 
10265 	/* All special src_reg cases are listed below. From this point onwards
10266 	 * we either succeed and assign a corresponding dst_reg->type after
10267 	 * zeroing the offset, or fail and reject the program.
10268 	 */
10269 	mark_reg_known_zero(env, regs, insn->dst_reg);
10270 
10271 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10272 		dst_reg->type = aux->btf_var.reg_type;
10273 		switch (base_type(dst_reg->type)) {
10274 		case PTR_TO_MEM:
10275 			dst_reg->mem_size = aux->btf_var.mem_size;
10276 			break;
10277 		case PTR_TO_BTF_ID:
10278 			dst_reg->btf = aux->btf_var.btf;
10279 			dst_reg->btf_id = aux->btf_var.btf_id;
10280 			break;
10281 		default:
10282 			verbose(env, "bpf verifier is misconfigured\n");
10283 			return -EFAULT;
10284 		}
10285 		return 0;
10286 	}
10287 
10288 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10289 		struct bpf_prog_aux *aux = env->prog->aux;
10290 		u32 subprogno = find_subprog(env,
10291 					     env->insn_idx + insn->imm + 1);
10292 
10293 		if (!aux->func_info) {
10294 			verbose(env, "missing btf func_info\n");
10295 			return -EINVAL;
10296 		}
10297 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10298 			verbose(env, "callback function not static\n");
10299 			return -EINVAL;
10300 		}
10301 
10302 		dst_reg->type = PTR_TO_FUNC;
10303 		dst_reg->subprogno = subprogno;
10304 		return 0;
10305 	}
10306 
10307 	map = env->used_maps[aux->map_index];
10308 	dst_reg->map_ptr = map;
10309 
10310 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10311 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10312 		dst_reg->type = PTR_TO_MAP_VALUE;
10313 		dst_reg->off = aux->map_off;
10314 		if (map_value_has_spin_lock(map))
10315 			dst_reg->id = ++env->id_gen;
10316 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10317 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10318 		dst_reg->type = CONST_PTR_TO_MAP;
10319 	} else {
10320 		verbose(env, "bpf verifier is misconfigured\n");
10321 		return -EINVAL;
10322 	}
10323 
10324 	return 0;
10325 }
10326 
10327 static bool may_access_skb(enum bpf_prog_type type)
10328 {
10329 	switch (type) {
10330 	case BPF_PROG_TYPE_SOCKET_FILTER:
10331 	case BPF_PROG_TYPE_SCHED_CLS:
10332 	case BPF_PROG_TYPE_SCHED_ACT:
10333 		return true;
10334 	default:
10335 		return false;
10336 	}
10337 }
10338 
10339 /* verify safety of LD_ABS|LD_IND instructions:
10340  * - they can only appear in the programs where ctx == skb
10341  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10342  *   preserve R6-R9, and store return value into R0
10343  *
10344  * Implicit input:
10345  *   ctx == skb == R6 == CTX
10346  *
10347  * Explicit input:
10348  *   SRC == any register
10349  *   IMM == 32-bit immediate
10350  *
10351  * Output:
10352  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10353  */
10354 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10355 {
10356 	struct bpf_reg_state *regs = cur_regs(env);
10357 	static const int ctx_reg = BPF_REG_6;
10358 	u8 mode = BPF_MODE(insn->code);
10359 	int i, err;
10360 
10361 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10362 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10363 		return -EINVAL;
10364 	}
10365 
10366 	if (!env->ops->gen_ld_abs) {
10367 		verbose(env, "bpf verifier is misconfigured\n");
10368 		return -EINVAL;
10369 	}
10370 
10371 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10372 	    BPF_SIZE(insn->code) == BPF_DW ||
10373 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10374 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10375 		return -EINVAL;
10376 	}
10377 
10378 	/* check whether implicit source operand (register R6) is readable */
10379 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10380 	if (err)
10381 		return err;
10382 
10383 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10384 	 * gen_ld_abs() may terminate the program at runtime, leading to
10385 	 * reference leak.
10386 	 */
10387 	err = check_reference_leak(env);
10388 	if (err) {
10389 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10390 		return err;
10391 	}
10392 
10393 	if (env->cur_state->active_spin_lock) {
10394 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10395 		return -EINVAL;
10396 	}
10397 
10398 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10399 		verbose(env,
10400 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10401 		return -EINVAL;
10402 	}
10403 
10404 	if (mode == BPF_IND) {
10405 		/* check explicit source operand */
10406 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10407 		if (err)
10408 			return err;
10409 	}
10410 
10411 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10412 	if (err < 0)
10413 		return err;
10414 
10415 	/* reset caller saved regs to unreadable */
10416 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10417 		mark_reg_not_init(env, regs, caller_saved[i]);
10418 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10419 	}
10420 
10421 	/* mark destination R0 register as readable, since it contains
10422 	 * the value fetched from the packet.
10423 	 * Already marked as written above.
10424 	 */
10425 	mark_reg_unknown(env, regs, BPF_REG_0);
10426 	/* ld_abs load up to 32-bit skb data. */
10427 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10428 	return 0;
10429 }
10430 
10431 static int check_return_code(struct bpf_verifier_env *env)
10432 {
10433 	struct tnum enforce_attach_type_range = tnum_unknown;
10434 	const struct bpf_prog *prog = env->prog;
10435 	struct bpf_reg_state *reg;
10436 	struct tnum range = tnum_range(0, 1);
10437 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10438 	int err;
10439 	struct bpf_func_state *frame = env->cur_state->frame[0];
10440 	const bool is_subprog = frame->subprogno;
10441 
10442 	/* LSM and struct_ops func-ptr's return type could be "void" */
10443 	if (!is_subprog) {
10444 		switch (prog_type) {
10445 		case BPF_PROG_TYPE_LSM:
10446 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10447 				/* See below, can be 0 or 0-1 depending on hook. */
10448 				break;
10449 			fallthrough;
10450 		case BPF_PROG_TYPE_STRUCT_OPS:
10451 			if (!prog->aux->attach_func_proto->type)
10452 				return 0;
10453 			break;
10454 		default:
10455 			break;
10456 		}
10457 	}
10458 
10459 	/* eBPF calling convention is such that R0 is used
10460 	 * to return the value from eBPF program.
10461 	 * Make sure that it's readable at this time
10462 	 * of bpf_exit, which means that program wrote
10463 	 * something into it earlier
10464 	 */
10465 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10466 	if (err)
10467 		return err;
10468 
10469 	if (is_pointer_value(env, BPF_REG_0)) {
10470 		verbose(env, "R0 leaks addr as return value\n");
10471 		return -EACCES;
10472 	}
10473 
10474 	reg = cur_regs(env) + BPF_REG_0;
10475 
10476 	if (frame->in_async_callback_fn) {
10477 		/* enforce return zero from async callbacks like timer */
10478 		if (reg->type != SCALAR_VALUE) {
10479 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10480 				reg_type_str(env, reg->type));
10481 			return -EINVAL;
10482 		}
10483 
10484 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10485 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10486 			return -EINVAL;
10487 		}
10488 		return 0;
10489 	}
10490 
10491 	if (is_subprog) {
10492 		if (reg->type != SCALAR_VALUE) {
10493 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10494 				reg_type_str(env, reg->type));
10495 			return -EINVAL;
10496 		}
10497 		return 0;
10498 	}
10499 
10500 	switch (prog_type) {
10501 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10502 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10503 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10504 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10505 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10506 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10507 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10508 			range = tnum_range(1, 1);
10509 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10510 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10511 			range = tnum_range(0, 3);
10512 		break;
10513 	case BPF_PROG_TYPE_CGROUP_SKB:
10514 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10515 			range = tnum_range(0, 3);
10516 			enforce_attach_type_range = tnum_range(2, 3);
10517 		}
10518 		break;
10519 	case BPF_PROG_TYPE_CGROUP_SOCK:
10520 	case BPF_PROG_TYPE_SOCK_OPS:
10521 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10522 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10523 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10524 		break;
10525 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10526 		if (!env->prog->aux->attach_btf_id)
10527 			return 0;
10528 		range = tnum_const(0);
10529 		break;
10530 	case BPF_PROG_TYPE_TRACING:
10531 		switch (env->prog->expected_attach_type) {
10532 		case BPF_TRACE_FENTRY:
10533 		case BPF_TRACE_FEXIT:
10534 			range = tnum_const(0);
10535 			break;
10536 		case BPF_TRACE_RAW_TP:
10537 		case BPF_MODIFY_RETURN:
10538 			return 0;
10539 		case BPF_TRACE_ITER:
10540 			break;
10541 		default:
10542 			return -ENOTSUPP;
10543 		}
10544 		break;
10545 	case BPF_PROG_TYPE_SK_LOOKUP:
10546 		range = tnum_range(SK_DROP, SK_PASS);
10547 		break;
10548 
10549 	case BPF_PROG_TYPE_LSM:
10550 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10551 			/* Regular BPF_PROG_TYPE_LSM programs can return
10552 			 * any value.
10553 			 */
10554 			return 0;
10555 		}
10556 		if (!env->prog->aux->attach_func_proto->type) {
10557 			/* Make sure programs that attach to void
10558 			 * hooks don't try to modify return value.
10559 			 */
10560 			range = tnum_range(1, 1);
10561 		}
10562 		break;
10563 
10564 	case BPF_PROG_TYPE_EXT:
10565 		/* freplace program can return anything as its return value
10566 		 * depends on the to-be-replaced kernel func or bpf program.
10567 		 */
10568 	default:
10569 		return 0;
10570 	}
10571 
10572 	if (reg->type != SCALAR_VALUE) {
10573 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10574 			reg_type_str(env, reg->type));
10575 		return -EINVAL;
10576 	}
10577 
10578 	if (!tnum_in(range, reg->var_off)) {
10579 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10580 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10581 		    prog_type == BPF_PROG_TYPE_LSM &&
10582 		    !prog->aux->attach_func_proto->type)
10583 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10584 		return -EINVAL;
10585 	}
10586 
10587 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10588 	    tnum_in(enforce_attach_type_range, reg->var_off))
10589 		env->prog->enforce_expected_attach_type = 1;
10590 	return 0;
10591 }
10592 
10593 /* non-recursive DFS pseudo code
10594  * 1  procedure DFS-iterative(G,v):
10595  * 2      label v as discovered
10596  * 3      let S be a stack
10597  * 4      S.push(v)
10598  * 5      while S is not empty
10599  * 6            t <- S.pop()
10600  * 7            if t is what we're looking for:
10601  * 8                return t
10602  * 9            for all edges e in G.adjacentEdges(t) do
10603  * 10               if edge e is already labelled
10604  * 11                   continue with the next edge
10605  * 12               w <- G.adjacentVertex(t,e)
10606  * 13               if vertex w is not discovered and not explored
10607  * 14                   label e as tree-edge
10608  * 15                   label w as discovered
10609  * 16                   S.push(w)
10610  * 17                   continue at 5
10611  * 18               else if vertex w is discovered
10612  * 19                   label e as back-edge
10613  * 20               else
10614  * 21                   // vertex w is explored
10615  * 22                   label e as forward- or cross-edge
10616  * 23           label t as explored
10617  * 24           S.pop()
10618  *
10619  * convention:
10620  * 0x10 - discovered
10621  * 0x11 - discovered and fall-through edge labelled
10622  * 0x12 - discovered and fall-through and branch edges labelled
10623  * 0x20 - explored
10624  */
10625 
10626 enum {
10627 	DISCOVERED = 0x10,
10628 	EXPLORED = 0x20,
10629 	FALLTHROUGH = 1,
10630 	BRANCH = 2,
10631 };
10632 
10633 static u32 state_htab_size(struct bpf_verifier_env *env)
10634 {
10635 	return env->prog->len;
10636 }
10637 
10638 static struct bpf_verifier_state_list **explored_state(
10639 					struct bpf_verifier_env *env,
10640 					int idx)
10641 {
10642 	struct bpf_verifier_state *cur = env->cur_state;
10643 	struct bpf_func_state *state = cur->frame[cur->curframe];
10644 
10645 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10646 }
10647 
10648 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10649 {
10650 	env->insn_aux_data[idx].prune_point = true;
10651 }
10652 
10653 enum {
10654 	DONE_EXPLORING = 0,
10655 	KEEP_EXPLORING = 1,
10656 };
10657 
10658 /* t, w, e - match pseudo-code above:
10659  * t - index of current instruction
10660  * w - next instruction
10661  * e - edge
10662  */
10663 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10664 		     bool loop_ok)
10665 {
10666 	int *insn_stack = env->cfg.insn_stack;
10667 	int *insn_state = env->cfg.insn_state;
10668 
10669 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10670 		return DONE_EXPLORING;
10671 
10672 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10673 		return DONE_EXPLORING;
10674 
10675 	if (w < 0 || w >= env->prog->len) {
10676 		verbose_linfo(env, t, "%d: ", t);
10677 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10678 		return -EINVAL;
10679 	}
10680 
10681 	if (e == BRANCH)
10682 		/* mark branch target for state pruning */
10683 		init_explored_state(env, w);
10684 
10685 	if (insn_state[w] == 0) {
10686 		/* tree-edge */
10687 		insn_state[t] = DISCOVERED | e;
10688 		insn_state[w] = DISCOVERED;
10689 		if (env->cfg.cur_stack >= env->prog->len)
10690 			return -E2BIG;
10691 		insn_stack[env->cfg.cur_stack++] = w;
10692 		return KEEP_EXPLORING;
10693 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10694 		if (loop_ok && env->bpf_capable)
10695 			return DONE_EXPLORING;
10696 		verbose_linfo(env, t, "%d: ", t);
10697 		verbose_linfo(env, w, "%d: ", w);
10698 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10699 		return -EINVAL;
10700 	} else if (insn_state[w] == EXPLORED) {
10701 		/* forward- or cross-edge */
10702 		insn_state[t] = DISCOVERED | e;
10703 	} else {
10704 		verbose(env, "insn state internal bug\n");
10705 		return -EFAULT;
10706 	}
10707 	return DONE_EXPLORING;
10708 }
10709 
10710 static int visit_func_call_insn(int t, int insn_cnt,
10711 				struct bpf_insn *insns,
10712 				struct bpf_verifier_env *env,
10713 				bool visit_callee)
10714 {
10715 	int ret;
10716 
10717 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10718 	if (ret)
10719 		return ret;
10720 
10721 	if (t + 1 < insn_cnt)
10722 		init_explored_state(env, t + 1);
10723 	if (visit_callee) {
10724 		init_explored_state(env, t);
10725 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10726 				/* It's ok to allow recursion from CFG point of
10727 				 * view. __check_func_call() will do the actual
10728 				 * check.
10729 				 */
10730 				bpf_pseudo_func(insns + t));
10731 	}
10732 	return ret;
10733 }
10734 
10735 /* Visits the instruction at index t and returns one of the following:
10736  *  < 0 - an error occurred
10737  *  DONE_EXPLORING - the instruction was fully explored
10738  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10739  */
10740 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10741 {
10742 	struct bpf_insn *insns = env->prog->insnsi;
10743 	int ret;
10744 
10745 	if (bpf_pseudo_func(insns + t))
10746 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10747 
10748 	/* All non-branch instructions have a single fall-through edge. */
10749 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10750 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10751 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10752 
10753 	switch (BPF_OP(insns[t].code)) {
10754 	case BPF_EXIT:
10755 		return DONE_EXPLORING;
10756 
10757 	case BPF_CALL:
10758 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10759 			/* Mark this call insn to trigger is_state_visited() check
10760 			 * before call itself is processed by __check_func_call().
10761 			 * Otherwise new async state will be pushed for further
10762 			 * exploration.
10763 			 */
10764 			init_explored_state(env, t);
10765 		return visit_func_call_insn(t, insn_cnt, insns, env,
10766 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10767 
10768 	case BPF_JA:
10769 		if (BPF_SRC(insns[t].code) != BPF_K)
10770 			return -EINVAL;
10771 
10772 		/* unconditional jump with single edge */
10773 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10774 				true);
10775 		if (ret)
10776 			return ret;
10777 
10778 		/* unconditional jmp is not a good pruning point,
10779 		 * but it's marked, since backtracking needs
10780 		 * to record jmp history in is_state_visited().
10781 		 */
10782 		init_explored_state(env, t + insns[t].off + 1);
10783 		/* tell verifier to check for equivalent states
10784 		 * after every call and jump
10785 		 */
10786 		if (t + 1 < insn_cnt)
10787 			init_explored_state(env, t + 1);
10788 
10789 		return ret;
10790 
10791 	default:
10792 		/* conditional jump with two edges */
10793 		init_explored_state(env, t);
10794 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10795 		if (ret)
10796 			return ret;
10797 
10798 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10799 	}
10800 }
10801 
10802 /* non-recursive depth-first-search to detect loops in BPF program
10803  * loop == back-edge in directed graph
10804  */
10805 static int check_cfg(struct bpf_verifier_env *env)
10806 {
10807 	int insn_cnt = env->prog->len;
10808 	int *insn_stack, *insn_state;
10809 	int ret = 0;
10810 	int i;
10811 
10812 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10813 	if (!insn_state)
10814 		return -ENOMEM;
10815 
10816 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10817 	if (!insn_stack) {
10818 		kvfree(insn_state);
10819 		return -ENOMEM;
10820 	}
10821 
10822 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10823 	insn_stack[0] = 0; /* 0 is the first instruction */
10824 	env->cfg.cur_stack = 1;
10825 
10826 	while (env->cfg.cur_stack > 0) {
10827 		int t = insn_stack[env->cfg.cur_stack - 1];
10828 
10829 		ret = visit_insn(t, insn_cnt, env);
10830 		switch (ret) {
10831 		case DONE_EXPLORING:
10832 			insn_state[t] = EXPLORED;
10833 			env->cfg.cur_stack--;
10834 			break;
10835 		case KEEP_EXPLORING:
10836 			break;
10837 		default:
10838 			if (ret > 0) {
10839 				verbose(env, "visit_insn internal bug\n");
10840 				ret = -EFAULT;
10841 			}
10842 			goto err_free;
10843 		}
10844 	}
10845 
10846 	if (env->cfg.cur_stack < 0) {
10847 		verbose(env, "pop stack internal bug\n");
10848 		ret = -EFAULT;
10849 		goto err_free;
10850 	}
10851 
10852 	for (i = 0; i < insn_cnt; i++) {
10853 		if (insn_state[i] != EXPLORED) {
10854 			verbose(env, "unreachable insn %d\n", i);
10855 			ret = -EINVAL;
10856 			goto err_free;
10857 		}
10858 	}
10859 	ret = 0; /* cfg looks good */
10860 
10861 err_free:
10862 	kvfree(insn_state);
10863 	kvfree(insn_stack);
10864 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10865 	return ret;
10866 }
10867 
10868 static int check_abnormal_return(struct bpf_verifier_env *env)
10869 {
10870 	int i;
10871 
10872 	for (i = 1; i < env->subprog_cnt; i++) {
10873 		if (env->subprog_info[i].has_ld_abs) {
10874 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10875 			return -EINVAL;
10876 		}
10877 		if (env->subprog_info[i].has_tail_call) {
10878 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10879 			return -EINVAL;
10880 		}
10881 	}
10882 	return 0;
10883 }
10884 
10885 /* The minimum supported BTF func info size */
10886 #define MIN_BPF_FUNCINFO_SIZE	8
10887 #define MAX_FUNCINFO_REC_SIZE	252
10888 
10889 static int check_btf_func(struct bpf_verifier_env *env,
10890 			  const union bpf_attr *attr,
10891 			  bpfptr_t uattr)
10892 {
10893 	const struct btf_type *type, *func_proto, *ret_type;
10894 	u32 i, nfuncs, urec_size, min_size;
10895 	u32 krec_size = sizeof(struct bpf_func_info);
10896 	struct bpf_func_info *krecord;
10897 	struct bpf_func_info_aux *info_aux = NULL;
10898 	struct bpf_prog *prog;
10899 	const struct btf *btf;
10900 	bpfptr_t urecord;
10901 	u32 prev_offset = 0;
10902 	bool scalar_return;
10903 	int ret = -ENOMEM;
10904 
10905 	nfuncs = attr->func_info_cnt;
10906 	if (!nfuncs) {
10907 		if (check_abnormal_return(env))
10908 			return -EINVAL;
10909 		return 0;
10910 	}
10911 
10912 	if (nfuncs != env->subprog_cnt) {
10913 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10914 		return -EINVAL;
10915 	}
10916 
10917 	urec_size = attr->func_info_rec_size;
10918 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10919 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10920 	    urec_size % sizeof(u32)) {
10921 		verbose(env, "invalid func info rec size %u\n", urec_size);
10922 		return -EINVAL;
10923 	}
10924 
10925 	prog = env->prog;
10926 	btf = prog->aux->btf;
10927 
10928 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10929 	min_size = min_t(u32, krec_size, urec_size);
10930 
10931 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10932 	if (!krecord)
10933 		return -ENOMEM;
10934 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10935 	if (!info_aux)
10936 		goto err_free;
10937 
10938 	for (i = 0; i < nfuncs; i++) {
10939 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10940 		if (ret) {
10941 			if (ret == -E2BIG) {
10942 				verbose(env, "nonzero tailing record in func info");
10943 				/* set the size kernel expects so loader can zero
10944 				 * out the rest of the record.
10945 				 */
10946 				if (copy_to_bpfptr_offset(uattr,
10947 							  offsetof(union bpf_attr, func_info_rec_size),
10948 							  &min_size, sizeof(min_size)))
10949 					ret = -EFAULT;
10950 			}
10951 			goto err_free;
10952 		}
10953 
10954 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10955 			ret = -EFAULT;
10956 			goto err_free;
10957 		}
10958 
10959 		/* check insn_off */
10960 		ret = -EINVAL;
10961 		if (i == 0) {
10962 			if (krecord[i].insn_off) {
10963 				verbose(env,
10964 					"nonzero insn_off %u for the first func info record",
10965 					krecord[i].insn_off);
10966 				goto err_free;
10967 			}
10968 		} else if (krecord[i].insn_off <= prev_offset) {
10969 			verbose(env,
10970 				"same or smaller insn offset (%u) than previous func info record (%u)",
10971 				krecord[i].insn_off, prev_offset);
10972 			goto err_free;
10973 		}
10974 
10975 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10976 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10977 			goto err_free;
10978 		}
10979 
10980 		/* check type_id */
10981 		type = btf_type_by_id(btf, krecord[i].type_id);
10982 		if (!type || !btf_type_is_func(type)) {
10983 			verbose(env, "invalid type id %d in func info",
10984 				krecord[i].type_id);
10985 			goto err_free;
10986 		}
10987 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10988 
10989 		func_proto = btf_type_by_id(btf, type->type);
10990 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10991 			/* btf_func_check() already verified it during BTF load */
10992 			goto err_free;
10993 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10994 		scalar_return =
10995 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
10996 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10997 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10998 			goto err_free;
10999 		}
11000 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11001 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11002 			goto err_free;
11003 		}
11004 
11005 		prev_offset = krecord[i].insn_off;
11006 		bpfptr_add(&urecord, urec_size);
11007 	}
11008 
11009 	prog->aux->func_info = krecord;
11010 	prog->aux->func_info_cnt = nfuncs;
11011 	prog->aux->func_info_aux = info_aux;
11012 	return 0;
11013 
11014 err_free:
11015 	kvfree(krecord);
11016 	kfree(info_aux);
11017 	return ret;
11018 }
11019 
11020 static void adjust_btf_func(struct bpf_verifier_env *env)
11021 {
11022 	struct bpf_prog_aux *aux = env->prog->aux;
11023 	int i;
11024 
11025 	if (!aux->func_info)
11026 		return;
11027 
11028 	for (i = 0; i < env->subprog_cnt; i++)
11029 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11030 }
11031 
11032 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11033 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11034 
11035 static int check_btf_line(struct bpf_verifier_env *env,
11036 			  const union bpf_attr *attr,
11037 			  bpfptr_t uattr)
11038 {
11039 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11040 	struct bpf_subprog_info *sub;
11041 	struct bpf_line_info *linfo;
11042 	struct bpf_prog *prog;
11043 	const struct btf *btf;
11044 	bpfptr_t ulinfo;
11045 	int err;
11046 
11047 	nr_linfo = attr->line_info_cnt;
11048 	if (!nr_linfo)
11049 		return 0;
11050 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11051 		return -EINVAL;
11052 
11053 	rec_size = attr->line_info_rec_size;
11054 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11055 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11056 	    rec_size & (sizeof(u32) - 1))
11057 		return -EINVAL;
11058 
11059 	/* Need to zero it in case the userspace may
11060 	 * pass in a smaller bpf_line_info object.
11061 	 */
11062 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11063 			 GFP_KERNEL | __GFP_NOWARN);
11064 	if (!linfo)
11065 		return -ENOMEM;
11066 
11067 	prog = env->prog;
11068 	btf = prog->aux->btf;
11069 
11070 	s = 0;
11071 	sub = env->subprog_info;
11072 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11073 	expected_size = sizeof(struct bpf_line_info);
11074 	ncopy = min_t(u32, expected_size, rec_size);
11075 	for (i = 0; i < nr_linfo; i++) {
11076 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11077 		if (err) {
11078 			if (err == -E2BIG) {
11079 				verbose(env, "nonzero tailing record in line_info");
11080 				if (copy_to_bpfptr_offset(uattr,
11081 							  offsetof(union bpf_attr, line_info_rec_size),
11082 							  &expected_size, sizeof(expected_size)))
11083 					err = -EFAULT;
11084 			}
11085 			goto err_free;
11086 		}
11087 
11088 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11089 			err = -EFAULT;
11090 			goto err_free;
11091 		}
11092 
11093 		/*
11094 		 * Check insn_off to ensure
11095 		 * 1) strictly increasing AND
11096 		 * 2) bounded by prog->len
11097 		 *
11098 		 * The linfo[0].insn_off == 0 check logically falls into
11099 		 * the later "missing bpf_line_info for func..." case
11100 		 * because the first linfo[0].insn_off must be the
11101 		 * first sub also and the first sub must have
11102 		 * subprog_info[0].start == 0.
11103 		 */
11104 		if ((i && linfo[i].insn_off <= prev_offset) ||
11105 		    linfo[i].insn_off >= prog->len) {
11106 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11107 				i, linfo[i].insn_off, prev_offset,
11108 				prog->len);
11109 			err = -EINVAL;
11110 			goto err_free;
11111 		}
11112 
11113 		if (!prog->insnsi[linfo[i].insn_off].code) {
11114 			verbose(env,
11115 				"Invalid insn code at line_info[%u].insn_off\n",
11116 				i);
11117 			err = -EINVAL;
11118 			goto err_free;
11119 		}
11120 
11121 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11122 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11123 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11124 			err = -EINVAL;
11125 			goto err_free;
11126 		}
11127 
11128 		if (s != env->subprog_cnt) {
11129 			if (linfo[i].insn_off == sub[s].start) {
11130 				sub[s].linfo_idx = i;
11131 				s++;
11132 			} else if (sub[s].start < linfo[i].insn_off) {
11133 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11134 				err = -EINVAL;
11135 				goto err_free;
11136 			}
11137 		}
11138 
11139 		prev_offset = linfo[i].insn_off;
11140 		bpfptr_add(&ulinfo, rec_size);
11141 	}
11142 
11143 	if (s != env->subprog_cnt) {
11144 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11145 			env->subprog_cnt - s, s);
11146 		err = -EINVAL;
11147 		goto err_free;
11148 	}
11149 
11150 	prog->aux->linfo = linfo;
11151 	prog->aux->nr_linfo = nr_linfo;
11152 
11153 	return 0;
11154 
11155 err_free:
11156 	kvfree(linfo);
11157 	return err;
11158 }
11159 
11160 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11161 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11162 
11163 static int check_core_relo(struct bpf_verifier_env *env,
11164 			   const union bpf_attr *attr,
11165 			   bpfptr_t uattr)
11166 {
11167 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11168 	struct bpf_core_relo core_relo = {};
11169 	struct bpf_prog *prog = env->prog;
11170 	const struct btf *btf = prog->aux->btf;
11171 	struct bpf_core_ctx ctx = {
11172 		.log = &env->log,
11173 		.btf = btf,
11174 	};
11175 	bpfptr_t u_core_relo;
11176 	int err;
11177 
11178 	nr_core_relo = attr->core_relo_cnt;
11179 	if (!nr_core_relo)
11180 		return 0;
11181 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11182 		return -EINVAL;
11183 
11184 	rec_size = attr->core_relo_rec_size;
11185 	if (rec_size < MIN_CORE_RELO_SIZE ||
11186 	    rec_size > MAX_CORE_RELO_SIZE ||
11187 	    rec_size % sizeof(u32))
11188 		return -EINVAL;
11189 
11190 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11191 	expected_size = sizeof(struct bpf_core_relo);
11192 	ncopy = min_t(u32, expected_size, rec_size);
11193 
11194 	/* Unlike func_info and line_info, copy and apply each CO-RE
11195 	 * relocation record one at a time.
11196 	 */
11197 	for (i = 0; i < nr_core_relo; i++) {
11198 		/* future proofing when sizeof(bpf_core_relo) changes */
11199 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11200 		if (err) {
11201 			if (err == -E2BIG) {
11202 				verbose(env, "nonzero tailing record in core_relo");
11203 				if (copy_to_bpfptr_offset(uattr,
11204 							  offsetof(union bpf_attr, core_relo_rec_size),
11205 							  &expected_size, sizeof(expected_size)))
11206 					err = -EFAULT;
11207 			}
11208 			break;
11209 		}
11210 
11211 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11212 			err = -EFAULT;
11213 			break;
11214 		}
11215 
11216 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11217 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11218 				i, core_relo.insn_off, prog->len);
11219 			err = -EINVAL;
11220 			break;
11221 		}
11222 
11223 		err = bpf_core_apply(&ctx, &core_relo, i,
11224 				     &prog->insnsi[core_relo.insn_off / 8]);
11225 		if (err)
11226 			break;
11227 		bpfptr_add(&u_core_relo, rec_size);
11228 	}
11229 	return err;
11230 }
11231 
11232 static int check_btf_info(struct bpf_verifier_env *env,
11233 			  const union bpf_attr *attr,
11234 			  bpfptr_t uattr)
11235 {
11236 	struct btf *btf;
11237 	int err;
11238 
11239 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11240 		if (check_abnormal_return(env))
11241 			return -EINVAL;
11242 		return 0;
11243 	}
11244 
11245 	btf = btf_get_by_fd(attr->prog_btf_fd);
11246 	if (IS_ERR(btf))
11247 		return PTR_ERR(btf);
11248 	if (btf_is_kernel(btf)) {
11249 		btf_put(btf);
11250 		return -EACCES;
11251 	}
11252 	env->prog->aux->btf = btf;
11253 
11254 	err = check_btf_func(env, attr, uattr);
11255 	if (err)
11256 		return err;
11257 
11258 	err = check_btf_line(env, attr, uattr);
11259 	if (err)
11260 		return err;
11261 
11262 	err = check_core_relo(env, attr, uattr);
11263 	if (err)
11264 		return err;
11265 
11266 	return 0;
11267 }
11268 
11269 /* check %cur's range satisfies %old's */
11270 static bool range_within(struct bpf_reg_state *old,
11271 			 struct bpf_reg_state *cur)
11272 {
11273 	return old->umin_value <= cur->umin_value &&
11274 	       old->umax_value >= cur->umax_value &&
11275 	       old->smin_value <= cur->smin_value &&
11276 	       old->smax_value >= cur->smax_value &&
11277 	       old->u32_min_value <= cur->u32_min_value &&
11278 	       old->u32_max_value >= cur->u32_max_value &&
11279 	       old->s32_min_value <= cur->s32_min_value &&
11280 	       old->s32_max_value >= cur->s32_max_value;
11281 }
11282 
11283 /* If in the old state two registers had the same id, then they need to have
11284  * the same id in the new state as well.  But that id could be different from
11285  * the old state, so we need to track the mapping from old to new ids.
11286  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11287  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11288  * regs with a different old id could still have new id 9, we don't care about
11289  * that.
11290  * So we look through our idmap to see if this old id has been seen before.  If
11291  * so, we require the new id to match; otherwise, we add the id pair to the map.
11292  */
11293 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11294 {
11295 	unsigned int i;
11296 
11297 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11298 		if (!idmap[i].old) {
11299 			/* Reached an empty slot; haven't seen this id before */
11300 			idmap[i].old = old_id;
11301 			idmap[i].cur = cur_id;
11302 			return true;
11303 		}
11304 		if (idmap[i].old == old_id)
11305 			return idmap[i].cur == cur_id;
11306 	}
11307 	/* We ran out of idmap slots, which should be impossible */
11308 	WARN_ON_ONCE(1);
11309 	return false;
11310 }
11311 
11312 static void clean_func_state(struct bpf_verifier_env *env,
11313 			     struct bpf_func_state *st)
11314 {
11315 	enum bpf_reg_liveness live;
11316 	int i, j;
11317 
11318 	for (i = 0; i < BPF_REG_FP; i++) {
11319 		live = st->regs[i].live;
11320 		/* liveness must not touch this register anymore */
11321 		st->regs[i].live |= REG_LIVE_DONE;
11322 		if (!(live & REG_LIVE_READ))
11323 			/* since the register is unused, clear its state
11324 			 * to make further comparison simpler
11325 			 */
11326 			__mark_reg_not_init(env, &st->regs[i]);
11327 	}
11328 
11329 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11330 		live = st->stack[i].spilled_ptr.live;
11331 		/* liveness must not touch this stack slot anymore */
11332 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11333 		if (!(live & REG_LIVE_READ)) {
11334 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11335 			for (j = 0; j < BPF_REG_SIZE; j++)
11336 				st->stack[i].slot_type[j] = STACK_INVALID;
11337 		}
11338 	}
11339 }
11340 
11341 static void clean_verifier_state(struct bpf_verifier_env *env,
11342 				 struct bpf_verifier_state *st)
11343 {
11344 	int i;
11345 
11346 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11347 		/* all regs in this state in all frames were already marked */
11348 		return;
11349 
11350 	for (i = 0; i <= st->curframe; i++)
11351 		clean_func_state(env, st->frame[i]);
11352 }
11353 
11354 /* the parentage chains form a tree.
11355  * the verifier states are added to state lists at given insn and
11356  * pushed into state stack for future exploration.
11357  * when the verifier reaches bpf_exit insn some of the verifer states
11358  * stored in the state lists have their final liveness state already,
11359  * but a lot of states will get revised from liveness point of view when
11360  * the verifier explores other branches.
11361  * Example:
11362  * 1: r0 = 1
11363  * 2: if r1 == 100 goto pc+1
11364  * 3: r0 = 2
11365  * 4: exit
11366  * when the verifier reaches exit insn the register r0 in the state list of
11367  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11368  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11369  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11370  *
11371  * Since the verifier pushes the branch states as it sees them while exploring
11372  * the program the condition of walking the branch instruction for the second
11373  * time means that all states below this branch were already explored and
11374  * their final liveness marks are already propagated.
11375  * Hence when the verifier completes the search of state list in is_state_visited()
11376  * we can call this clean_live_states() function to mark all liveness states
11377  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11378  * will not be used.
11379  * This function also clears the registers and stack for states that !READ
11380  * to simplify state merging.
11381  *
11382  * Important note here that walking the same branch instruction in the callee
11383  * doesn't meant that the states are DONE. The verifier has to compare
11384  * the callsites
11385  */
11386 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11387 			      struct bpf_verifier_state *cur)
11388 {
11389 	struct bpf_verifier_state_list *sl;
11390 	int i;
11391 
11392 	sl = *explored_state(env, insn);
11393 	while (sl) {
11394 		if (sl->state.branches)
11395 			goto next;
11396 		if (sl->state.insn_idx != insn ||
11397 		    sl->state.curframe != cur->curframe)
11398 			goto next;
11399 		for (i = 0; i <= cur->curframe; i++)
11400 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11401 				goto next;
11402 		clean_verifier_state(env, &sl->state);
11403 next:
11404 		sl = sl->next;
11405 	}
11406 }
11407 
11408 /* Returns true if (rold safe implies rcur safe) */
11409 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11410 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11411 {
11412 	bool equal;
11413 
11414 	if (!(rold->live & REG_LIVE_READ))
11415 		/* explored state didn't use this */
11416 		return true;
11417 
11418 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11419 
11420 	if (rold->type == PTR_TO_STACK)
11421 		/* two stack pointers are equal only if they're pointing to
11422 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11423 		 */
11424 		return equal && rold->frameno == rcur->frameno;
11425 
11426 	if (equal)
11427 		return true;
11428 
11429 	if (rold->type == NOT_INIT)
11430 		/* explored state can't have used this */
11431 		return true;
11432 	if (rcur->type == NOT_INIT)
11433 		return false;
11434 	switch (base_type(rold->type)) {
11435 	case SCALAR_VALUE:
11436 		if (env->explore_alu_limits)
11437 			return false;
11438 		if (rcur->type == SCALAR_VALUE) {
11439 			if (!rold->precise && !rcur->precise)
11440 				return true;
11441 			/* new val must satisfy old val knowledge */
11442 			return range_within(rold, rcur) &&
11443 			       tnum_in(rold->var_off, rcur->var_off);
11444 		} else {
11445 			/* We're trying to use a pointer in place of a scalar.
11446 			 * Even if the scalar was unbounded, this could lead to
11447 			 * pointer leaks because scalars are allowed to leak
11448 			 * while pointers are not. We could make this safe in
11449 			 * special cases if root is calling us, but it's
11450 			 * probably not worth the hassle.
11451 			 */
11452 			return false;
11453 		}
11454 	case PTR_TO_MAP_KEY:
11455 	case PTR_TO_MAP_VALUE:
11456 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11457 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11458 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11459 		 * checked, doing so could have affected others with the same
11460 		 * id, and we can't check for that because we lost the id when
11461 		 * we converted to a PTR_TO_MAP_VALUE.
11462 		 */
11463 		if (type_may_be_null(rold->type)) {
11464 			if (!type_may_be_null(rcur->type))
11465 				return false;
11466 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11467 				return false;
11468 			/* Check our ids match any regs they're supposed to */
11469 			return check_ids(rold->id, rcur->id, idmap);
11470 		}
11471 
11472 		/* If the new min/max/var_off satisfy the old ones and
11473 		 * everything else matches, we are OK.
11474 		 * 'id' is not compared, since it's only used for maps with
11475 		 * bpf_spin_lock inside map element and in such cases if
11476 		 * the rest of the prog is valid for one map element then
11477 		 * it's valid for all map elements regardless of the key
11478 		 * used in bpf_map_lookup()
11479 		 */
11480 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11481 		       range_within(rold, rcur) &&
11482 		       tnum_in(rold->var_off, rcur->var_off);
11483 	case PTR_TO_PACKET_META:
11484 	case PTR_TO_PACKET:
11485 		if (rcur->type != rold->type)
11486 			return false;
11487 		/* We must have at least as much range as the old ptr
11488 		 * did, so that any accesses which were safe before are
11489 		 * still safe.  This is true even if old range < old off,
11490 		 * since someone could have accessed through (ptr - k), or
11491 		 * even done ptr -= k in a register, to get a safe access.
11492 		 */
11493 		if (rold->range > rcur->range)
11494 			return false;
11495 		/* If the offsets don't match, we can't trust our alignment;
11496 		 * nor can we be sure that we won't fall out of range.
11497 		 */
11498 		if (rold->off != rcur->off)
11499 			return false;
11500 		/* id relations must be preserved */
11501 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11502 			return false;
11503 		/* new val must satisfy old val knowledge */
11504 		return range_within(rold, rcur) &&
11505 		       tnum_in(rold->var_off, rcur->var_off);
11506 	case PTR_TO_CTX:
11507 	case CONST_PTR_TO_MAP:
11508 	case PTR_TO_PACKET_END:
11509 	case PTR_TO_FLOW_KEYS:
11510 	case PTR_TO_SOCKET:
11511 	case PTR_TO_SOCK_COMMON:
11512 	case PTR_TO_TCP_SOCK:
11513 	case PTR_TO_XDP_SOCK:
11514 		/* Only valid matches are exact, which memcmp() above
11515 		 * would have accepted
11516 		 */
11517 	default:
11518 		/* Don't know what's going on, just say it's not safe */
11519 		return false;
11520 	}
11521 
11522 	/* Shouldn't get here; if we do, say it's not safe */
11523 	WARN_ON_ONCE(1);
11524 	return false;
11525 }
11526 
11527 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11528 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11529 {
11530 	int i, spi;
11531 
11532 	/* walk slots of the explored stack and ignore any additional
11533 	 * slots in the current stack, since explored(safe) state
11534 	 * didn't use them
11535 	 */
11536 	for (i = 0; i < old->allocated_stack; i++) {
11537 		spi = i / BPF_REG_SIZE;
11538 
11539 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11540 			i += BPF_REG_SIZE - 1;
11541 			/* explored state didn't use this */
11542 			continue;
11543 		}
11544 
11545 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11546 			continue;
11547 
11548 		/* explored stack has more populated slots than current stack
11549 		 * and these slots were used
11550 		 */
11551 		if (i >= cur->allocated_stack)
11552 			return false;
11553 
11554 		/* if old state was safe with misc data in the stack
11555 		 * it will be safe with zero-initialized stack.
11556 		 * The opposite is not true
11557 		 */
11558 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11559 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11560 			continue;
11561 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11562 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11563 			/* Ex: old explored (safe) state has STACK_SPILL in
11564 			 * this stack slot, but current has STACK_MISC ->
11565 			 * this verifier states are not equivalent,
11566 			 * return false to continue verification of this path
11567 			 */
11568 			return false;
11569 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11570 			continue;
11571 		if (!is_spilled_reg(&old->stack[spi]))
11572 			continue;
11573 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11574 			     &cur->stack[spi].spilled_ptr, idmap))
11575 			/* when explored and current stack slot are both storing
11576 			 * spilled registers, check that stored pointers types
11577 			 * are the same as well.
11578 			 * Ex: explored safe path could have stored
11579 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11580 			 * but current path has stored:
11581 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11582 			 * such verifier states are not equivalent.
11583 			 * return false to continue verification of this path
11584 			 */
11585 			return false;
11586 	}
11587 	return true;
11588 }
11589 
11590 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11591 {
11592 	if (old->acquired_refs != cur->acquired_refs)
11593 		return false;
11594 	return !memcmp(old->refs, cur->refs,
11595 		       sizeof(*old->refs) * old->acquired_refs);
11596 }
11597 
11598 /* compare two verifier states
11599  *
11600  * all states stored in state_list are known to be valid, since
11601  * verifier reached 'bpf_exit' instruction through them
11602  *
11603  * this function is called when verifier exploring different branches of
11604  * execution popped from the state stack. If it sees an old state that has
11605  * more strict register state and more strict stack state then this execution
11606  * branch doesn't need to be explored further, since verifier already
11607  * concluded that more strict state leads to valid finish.
11608  *
11609  * Therefore two states are equivalent if register state is more conservative
11610  * and explored stack state is more conservative than the current one.
11611  * Example:
11612  *       explored                   current
11613  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11614  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11615  *
11616  * In other words if current stack state (one being explored) has more
11617  * valid slots than old one that already passed validation, it means
11618  * the verifier can stop exploring and conclude that current state is valid too
11619  *
11620  * Similarly with registers. If explored state has register type as invalid
11621  * whereas register type in current state is meaningful, it means that
11622  * the current state will reach 'bpf_exit' instruction safely
11623  */
11624 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11625 			      struct bpf_func_state *cur)
11626 {
11627 	int i;
11628 
11629 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11630 	for (i = 0; i < MAX_BPF_REG; i++)
11631 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11632 			     env->idmap_scratch))
11633 			return false;
11634 
11635 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11636 		return false;
11637 
11638 	if (!refsafe(old, cur))
11639 		return false;
11640 
11641 	return true;
11642 }
11643 
11644 static bool states_equal(struct bpf_verifier_env *env,
11645 			 struct bpf_verifier_state *old,
11646 			 struct bpf_verifier_state *cur)
11647 {
11648 	int i;
11649 
11650 	if (old->curframe != cur->curframe)
11651 		return false;
11652 
11653 	/* Verification state from speculative execution simulation
11654 	 * must never prune a non-speculative execution one.
11655 	 */
11656 	if (old->speculative && !cur->speculative)
11657 		return false;
11658 
11659 	if (old->active_spin_lock != cur->active_spin_lock)
11660 		return false;
11661 
11662 	/* for states to be equal callsites have to be the same
11663 	 * and all frame states need to be equivalent
11664 	 */
11665 	for (i = 0; i <= old->curframe; i++) {
11666 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11667 			return false;
11668 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11669 			return false;
11670 	}
11671 	return true;
11672 }
11673 
11674 /* Return 0 if no propagation happened. Return negative error code if error
11675  * happened. Otherwise, return the propagated bit.
11676  */
11677 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11678 				  struct bpf_reg_state *reg,
11679 				  struct bpf_reg_state *parent_reg)
11680 {
11681 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11682 	u8 flag = reg->live & REG_LIVE_READ;
11683 	int err;
11684 
11685 	/* When comes here, read flags of PARENT_REG or REG could be any of
11686 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11687 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11688 	 */
11689 	if (parent_flag == REG_LIVE_READ64 ||
11690 	    /* Or if there is no read flag from REG. */
11691 	    !flag ||
11692 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11693 	    parent_flag == flag)
11694 		return 0;
11695 
11696 	err = mark_reg_read(env, reg, parent_reg, flag);
11697 	if (err)
11698 		return err;
11699 
11700 	return flag;
11701 }
11702 
11703 /* A write screens off any subsequent reads; but write marks come from the
11704  * straight-line code between a state and its parent.  When we arrive at an
11705  * equivalent state (jump target or such) we didn't arrive by the straight-line
11706  * code, so read marks in the state must propagate to the parent regardless
11707  * of the state's write marks. That's what 'parent == state->parent' comparison
11708  * in mark_reg_read() is for.
11709  */
11710 static int propagate_liveness(struct bpf_verifier_env *env,
11711 			      const struct bpf_verifier_state *vstate,
11712 			      struct bpf_verifier_state *vparent)
11713 {
11714 	struct bpf_reg_state *state_reg, *parent_reg;
11715 	struct bpf_func_state *state, *parent;
11716 	int i, frame, err = 0;
11717 
11718 	if (vparent->curframe != vstate->curframe) {
11719 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11720 		     vparent->curframe, vstate->curframe);
11721 		return -EFAULT;
11722 	}
11723 	/* Propagate read liveness of registers... */
11724 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11725 	for (frame = 0; frame <= vstate->curframe; frame++) {
11726 		parent = vparent->frame[frame];
11727 		state = vstate->frame[frame];
11728 		parent_reg = parent->regs;
11729 		state_reg = state->regs;
11730 		/* We don't need to worry about FP liveness, it's read-only */
11731 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11732 			err = propagate_liveness_reg(env, &state_reg[i],
11733 						     &parent_reg[i]);
11734 			if (err < 0)
11735 				return err;
11736 			if (err == REG_LIVE_READ64)
11737 				mark_insn_zext(env, &parent_reg[i]);
11738 		}
11739 
11740 		/* Propagate stack slots. */
11741 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11742 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11743 			parent_reg = &parent->stack[i].spilled_ptr;
11744 			state_reg = &state->stack[i].spilled_ptr;
11745 			err = propagate_liveness_reg(env, state_reg,
11746 						     parent_reg);
11747 			if (err < 0)
11748 				return err;
11749 		}
11750 	}
11751 	return 0;
11752 }
11753 
11754 /* find precise scalars in the previous equivalent state and
11755  * propagate them into the current state
11756  */
11757 static int propagate_precision(struct bpf_verifier_env *env,
11758 			       const struct bpf_verifier_state *old)
11759 {
11760 	struct bpf_reg_state *state_reg;
11761 	struct bpf_func_state *state;
11762 	int i, err = 0;
11763 
11764 	state = old->frame[old->curframe];
11765 	state_reg = state->regs;
11766 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11767 		if (state_reg->type != SCALAR_VALUE ||
11768 		    !state_reg->precise)
11769 			continue;
11770 		if (env->log.level & BPF_LOG_LEVEL2)
11771 			verbose(env, "propagating r%d\n", i);
11772 		err = mark_chain_precision(env, i);
11773 		if (err < 0)
11774 			return err;
11775 	}
11776 
11777 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11778 		if (!is_spilled_reg(&state->stack[i]))
11779 			continue;
11780 		state_reg = &state->stack[i].spilled_ptr;
11781 		if (state_reg->type != SCALAR_VALUE ||
11782 		    !state_reg->precise)
11783 			continue;
11784 		if (env->log.level & BPF_LOG_LEVEL2)
11785 			verbose(env, "propagating fp%d\n",
11786 				(-i - 1) * BPF_REG_SIZE);
11787 		err = mark_chain_precision_stack(env, i);
11788 		if (err < 0)
11789 			return err;
11790 	}
11791 	return 0;
11792 }
11793 
11794 static bool states_maybe_looping(struct bpf_verifier_state *old,
11795 				 struct bpf_verifier_state *cur)
11796 {
11797 	struct bpf_func_state *fold, *fcur;
11798 	int i, fr = cur->curframe;
11799 
11800 	if (old->curframe != fr)
11801 		return false;
11802 
11803 	fold = old->frame[fr];
11804 	fcur = cur->frame[fr];
11805 	for (i = 0; i < MAX_BPF_REG; i++)
11806 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11807 			   offsetof(struct bpf_reg_state, parent)))
11808 			return false;
11809 	return true;
11810 }
11811 
11812 
11813 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11814 {
11815 	struct bpf_verifier_state_list *new_sl;
11816 	struct bpf_verifier_state_list *sl, **pprev;
11817 	struct bpf_verifier_state *cur = env->cur_state, *new;
11818 	int i, j, err, states_cnt = 0;
11819 	bool add_new_state = env->test_state_freq ? true : false;
11820 
11821 	cur->last_insn_idx = env->prev_insn_idx;
11822 	if (!env->insn_aux_data[insn_idx].prune_point)
11823 		/* this 'insn_idx' instruction wasn't marked, so we will not
11824 		 * be doing state search here
11825 		 */
11826 		return 0;
11827 
11828 	/* bpf progs typically have pruning point every 4 instructions
11829 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11830 	 * Do not add new state for future pruning if the verifier hasn't seen
11831 	 * at least 2 jumps and at least 8 instructions.
11832 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11833 	 * In tests that amounts to up to 50% reduction into total verifier
11834 	 * memory consumption and 20% verifier time speedup.
11835 	 */
11836 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11837 	    env->insn_processed - env->prev_insn_processed >= 8)
11838 		add_new_state = true;
11839 
11840 	pprev = explored_state(env, insn_idx);
11841 	sl = *pprev;
11842 
11843 	clean_live_states(env, insn_idx, cur);
11844 
11845 	while (sl) {
11846 		states_cnt++;
11847 		if (sl->state.insn_idx != insn_idx)
11848 			goto next;
11849 
11850 		if (sl->state.branches) {
11851 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11852 
11853 			if (frame->in_async_callback_fn &&
11854 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11855 				/* Different async_entry_cnt means that the verifier is
11856 				 * processing another entry into async callback.
11857 				 * Seeing the same state is not an indication of infinite
11858 				 * loop or infinite recursion.
11859 				 * But finding the same state doesn't mean that it's safe
11860 				 * to stop processing the current state. The previous state
11861 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11862 				 * Checking in_async_callback_fn alone is not enough either.
11863 				 * Since the verifier still needs to catch infinite loops
11864 				 * inside async callbacks.
11865 				 */
11866 			} else if (states_maybe_looping(&sl->state, cur) &&
11867 				   states_equal(env, &sl->state, cur)) {
11868 				verbose_linfo(env, insn_idx, "; ");
11869 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11870 				return -EINVAL;
11871 			}
11872 			/* if the verifier is processing a loop, avoid adding new state
11873 			 * too often, since different loop iterations have distinct
11874 			 * states and may not help future pruning.
11875 			 * This threshold shouldn't be too low to make sure that
11876 			 * a loop with large bound will be rejected quickly.
11877 			 * The most abusive loop will be:
11878 			 * r1 += 1
11879 			 * if r1 < 1000000 goto pc-2
11880 			 * 1M insn_procssed limit / 100 == 10k peak states.
11881 			 * This threshold shouldn't be too high either, since states
11882 			 * at the end of the loop are likely to be useful in pruning.
11883 			 */
11884 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11885 			    env->insn_processed - env->prev_insn_processed < 100)
11886 				add_new_state = false;
11887 			goto miss;
11888 		}
11889 		if (states_equal(env, &sl->state, cur)) {
11890 			sl->hit_cnt++;
11891 			/* reached equivalent register/stack state,
11892 			 * prune the search.
11893 			 * Registers read by the continuation are read by us.
11894 			 * If we have any write marks in env->cur_state, they
11895 			 * will prevent corresponding reads in the continuation
11896 			 * from reaching our parent (an explored_state).  Our
11897 			 * own state will get the read marks recorded, but
11898 			 * they'll be immediately forgotten as we're pruning
11899 			 * this state and will pop a new one.
11900 			 */
11901 			err = propagate_liveness(env, &sl->state, cur);
11902 
11903 			/* if previous state reached the exit with precision and
11904 			 * current state is equivalent to it (except precsion marks)
11905 			 * the precision needs to be propagated back in
11906 			 * the current state.
11907 			 */
11908 			err = err ? : push_jmp_history(env, cur);
11909 			err = err ? : propagate_precision(env, &sl->state);
11910 			if (err)
11911 				return err;
11912 			return 1;
11913 		}
11914 miss:
11915 		/* when new state is not going to be added do not increase miss count.
11916 		 * Otherwise several loop iterations will remove the state
11917 		 * recorded earlier. The goal of these heuristics is to have
11918 		 * states from some iterations of the loop (some in the beginning
11919 		 * and some at the end) to help pruning.
11920 		 */
11921 		if (add_new_state)
11922 			sl->miss_cnt++;
11923 		/* heuristic to determine whether this state is beneficial
11924 		 * to keep checking from state equivalence point of view.
11925 		 * Higher numbers increase max_states_per_insn and verification time,
11926 		 * but do not meaningfully decrease insn_processed.
11927 		 */
11928 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11929 			/* the state is unlikely to be useful. Remove it to
11930 			 * speed up verification
11931 			 */
11932 			*pprev = sl->next;
11933 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11934 				u32 br = sl->state.branches;
11935 
11936 				WARN_ONCE(br,
11937 					  "BUG live_done but branches_to_explore %d\n",
11938 					  br);
11939 				free_verifier_state(&sl->state, false);
11940 				kfree(sl);
11941 				env->peak_states--;
11942 			} else {
11943 				/* cannot free this state, since parentage chain may
11944 				 * walk it later. Add it for free_list instead to
11945 				 * be freed at the end of verification
11946 				 */
11947 				sl->next = env->free_list;
11948 				env->free_list = sl;
11949 			}
11950 			sl = *pprev;
11951 			continue;
11952 		}
11953 next:
11954 		pprev = &sl->next;
11955 		sl = *pprev;
11956 	}
11957 
11958 	if (env->max_states_per_insn < states_cnt)
11959 		env->max_states_per_insn = states_cnt;
11960 
11961 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11962 		return push_jmp_history(env, cur);
11963 
11964 	if (!add_new_state)
11965 		return push_jmp_history(env, cur);
11966 
11967 	/* There were no equivalent states, remember the current one.
11968 	 * Technically the current state is not proven to be safe yet,
11969 	 * but it will either reach outer most bpf_exit (which means it's safe)
11970 	 * or it will be rejected. When there are no loops the verifier won't be
11971 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11972 	 * again on the way to bpf_exit.
11973 	 * When looping the sl->state.branches will be > 0 and this state
11974 	 * will not be considered for equivalence until branches == 0.
11975 	 */
11976 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11977 	if (!new_sl)
11978 		return -ENOMEM;
11979 	env->total_states++;
11980 	env->peak_states++;
11981 	env->prev_jmps_processed = env->jmps_processed;
11982 	env->prev_insn_processed = env->insn_processed;
11983 
11984 	/* add new state to the head of linked list */
11985 	new = &new_sl->state;
11986 	err = copy_verifier_state(new, cur);
11987 	if (err) {
11988 		free_verifier_state(new, false);
11989 		kfree(new_sl);
11990 		return err;
11991 	}
11992 	new->insn_idx = insn_idx;
11993 	WARN_ONCE(new->branches != 1,
11994 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11995 
11996 	cur->parent = new;
11997 	cur->first_insn_idx = insn_idx;
11998 	clear_jmp_history(cur);
11999 	new_sl->next = *explored_state(env, insn_idx);
12000 	*explored_state(env, insn_idx) = new_sl;
12001 	/* connect new state to parentage chain. Current frame needs all
12002 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12003 	 * to the stack implicitly by JITs) so in callers' frames connect just
12004 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12005 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12006 	 * from callee with its full parentage chain, anyway.
12007 	 */
12008 	/* clear write marks in current state: the writes we did are not writes
12009 	 * our child did, so they don't screen off its reads from us.
12010 	 * (There are no read marks in current state, because reads always mark
12011 	 * their parent and current state never has children yet.  Only
12012 	 * explored_states can get read marks.)
12013 	 */
12014 	for (j = 0; j <= cur->curframe; j++) {
12015 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12016 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12017 		for (i = 0; i < BPF_REG_FP; i++)
12018 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12019 	}
12020 
12021 	/* all stack frames are accessible from callee, clear them all */
12022 	for (j = 0; j <= cur->curframe; j++) {
12023 		struct bpf_func_state *frame = cur->frame[j];
12024 		struct bpf_func_state *newframe = new->frame[j];
12025 
12026 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12027 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12028 			frame->stack[i].spilled_ptr.parent =
12029 						&newframe->stack[i].spilled_ptr;
12030 		}
12031 	}
12032 	return 0;
12033 }
12034 
12035 /* Return true if it's OK to have the same insn return a different type. */
12036 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12037 {
12038 	switch (base_type(type)) {
12039 	case PTR_TO_CTX:
12040 	case PTR_TO_SOCKET:
12041 	case PTR_TO_SOCK_COMMON:
12042 	case PTR_TO_TCP_SOCK:
12043 	case PTR_TO_XDP_SOCK:
12044 	case PTR_TO_BTF_ID:
12045 		return false;
12046 	default:
12047 		return true;
12048 	}
12049 }
12050 
12051 /* If an instruction was previously used with particular pointer types, then we
12052  * need to be careful to avoid cases such as the below, where it may be ok
12053  * for one branch accessing the pointer, but not ok for the other branch:
12054  *
12055  * R1 = sock_ptr
12056  * goto X;
12057  * ...
12058  * R1 = some_other_valid_ptr;
12059  * goto X;
12060  * ...
12061  * R2 = *(u32 *)(R1 + 0);
12062  */
12063 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12064 {
12065 	return src != prev && (!reg_type_mismatch_ok(src) ||
12066 			       !reg_type_mismatch_ok(prev));
12067 }
12068 
12069 static int do_check(struct bpf_verifier_env *env)
12070 {
12071 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12072 	struct bpf_verifier_state *state = env->cur_state;
12073 	struct bpf_insn *insns = env->prog->insnsi;
12074 	struct bpf_reg_state *regs;
12075 	int insn_cnt = env->prog->len;
12076 	bool do_print_state = false;
12077 	int prev_insn_idx = -1;
12078 
12079 	for (;;) {
12080 		struct bpf_insn *insn;
12081 		u8 class;
12082 		int err;
12083 
12084 		env->prev_insn_idx = prev_insn_idx;
12085 		if (env->insn_idx >= insn_cnt) {
12086 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12087 				env->insn_idx, insn_cnt);
12088 			return -EFAULT;
12089 		}
12090 
12091 		insn = &insns[env->insn_idx];
12092 		class = BPF_CLASS(insn->code);
12093 
12094 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12095 			verbose(env,
12096 				"BPF program is too large. Processed %d insn\n",
12097 				env->insn_processed);
12098 			return -E2BIG;
12099 		}
12100 
12101 		err = is_state_visited(env, env->insn_idx);
12102 		if (err < 0)
12103 			return err;
12104 		if (err == 1) {
12105 			/* found equivalent state, can prune the search */
12106 			if (env->log.level & BPF_LOG_LEVEL) {
12107 				if (do_print_state)
12108 					verbose(env, "\nfrom %d to %d%s: safe\n",
12109 						env->prev_insn_idx, env->insn_idx,
12110 						env->cur_state->speculative ?
12111 						" (speculative execution)" : "");
12112 				else
12113 					verbose(env, "%d: safe\n", env->insn_idx);
12114 			}
12115 			goto process_bpf_exit;
12116 		}
12117 
12118 		if (signal_pending(current))
12119 			return -EAGAIN;
12120 
12121 		if (need_resched())
12122 			cond_resched();
12123 
12124 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12125 			verbose(env, "\nfrom %d to %d%s:",
12126 				env->prev_insn_idx, env->insn_idx,
12127 				env->cur_state->speculative ?
12128 				" (speculative execution)" : "");
12129 			print_verifier_state(env, state->frame[state->curframe], true);
12130 			do_print_state = false;
12131 		}
12132 
12133 		if (env->log.level & BPF_LOG_LEVEL) {
12134 			const struct bpf_insn_cbs cbs = {
12135 				.cb_call	= disasm_kfunc_name,
12136 				.cb_print	= verbose,
12137 				.private_data	= env,
12138 			};
12139 
12140 			if (verifier_state_scratched(env))
12141 				print_insn_state(env, state->frame[state->curframe]);
12142 
12143 			verbose_linfo(env, env->insn_idx, "; ");
12144 			env->prev_log_len = env->log.len_used;
12145 			verbose(env, "%d: ", env->insn_idx);
12146 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12147 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12148 			env->prev_log_len = env->log.len_used;
12149 		}
12150 
12151 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12152 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12153 							   env->prev_insn_idx);
12154 			if (err)
12155 				return err;
12156 		}
12157 
12158 		regs = cur_regs(env);
12159 		sanitize_mark_insn_seen(env);
12160 		prev_insn_idx = env->insn_idx;
12161 
12162 		if (class == BPF_ALU || class == BPF_ALU64) {
12163 			err = check_alu_op(env, insn);
12164 			if (err)
12165 				return err;
12166 
12167 		} else if (class == BPF_LDX) {
12168 			enum bpf_reg_type *prev_src_type, src_reg_type;
12169 
12170 			/* check for reserved fields is already done */
12171 
12172 			/* check src operand */
12173 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12174 			if (err)
12175 				return err;
12176 
12177 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12178 			if (err)
12179 				return err;
12180 
12181 			src_reg_type = regs[insn->src_reg].type;
12182 
12183 			/* check that memory (src_reg + off) is readable,
12184 			 * the state of dst_reg will be updated by this func
12185 			 */
12186 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12187 					       insn->off, BPF_SIZE(insn->code),
12188 					       BPF_READ, insn->dst_reg, false);
12189 			if (err)
12190 				return err;
12191 
12192 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12193 
12194 			if (*prev_src_type == NOT_INIT) {
12195 				/* saw a valid insn
12196 				 * dst_reg = *(u32 *)(src_reg + off)
12197 				 * save type to validate intersecting paths
12198 				 */
12199 				*prev_src_type = src_reg_type;
12200 
12201 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12202 				/* ABuser program is trying to use the same insn
12203 				 * dst_reg = *(u32*) (src_reg + off)
12204 				 * with different pointer types:
12205 				 * src_reg == ctx in one branch and
12206 				 * src_reg == stack|map in some other branch.
12207 				 * Reject it.
12208 				 */
12209 				verbose(env, "same insn cannot be used with different pointers\n");
12210 				return -EINVAL;
12211 			}
12212 
12213 		} else if (class == BPF_STX) {
12214 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12215 
12216 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12217 				err = check_atomic(env, env->insn_idx, insn);
12218 				if (err)
12219 					return err;
12220 				env->insn_idx++;
12221 				continue;
12222 			}
12223 
12224 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12225 				verbose(env, "BPF_STX uses reserved fields\n");
12226 				return -EINVAL;
12227 			}
12228 
12229 			/* check src1 operand */
12230 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12231 			if (err)
12232 				return err;
12233 			/* check src2 operand */
12234 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12235 			if (err)
12236 				return err;
12237 
12238 			dst_reg_type = regs[insn->dst_reg].type;
12239 
12240 			/* check that memory (dst_reg + off) is writeable */
12241 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12242 					       insn->off, BPF_SIZE(insn->code),
12243 					       BPF_WRITE, insn->src_reg, false);
12244 			if (err)
12245 				return err;
12246 
12247 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12248 
12249 			if (*prev_dst_type == NOT_INIT) {
12250 				*prev_dst_type = dst_reg_type;
12251 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12252 				verbose(env, "same insn cannot be used with different pointers\n");
12253 				return -EINVAL;
12254 			}
12255 
12256 		} else if (class == BPF_ST) {
12257 			if (BPF_MODE(insn->code) != BPF_MEM ||
12258 			    insn->src_reg != BPF_REG_0) {
12259 				verbose(env, "BPF_ST uses reserved fields\n");
12260 				return -EINVAL;
12261 			}
12262 			/* check src operand */
12263 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12264 			if (err)
12265 				return err;
12266 
12267 			if (is_ctx_reg(env, insn->dst_reg)) {
12268 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12269 					insn->dst_reg,
12270 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12271 				return -EACCES;
12272 			}
12273 
12274 			/* check that memory (dst_reg + off) is writeable */
12275 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12276 					       insn->off, BPF_SIZE(insn->code),
12277 					       BPF_WRITE, -1, false);
12278 			if (err)
12279 				return err;
12280 
12281 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12282 			u8 opcode = BPF_OP(insn->code);
12283 
12284 			env->jmps_processed++;
12285 			if (opcode == BPF_CALL) {
12286 				if (BPF_SRC(insn->code) != BPF_K ||
12287 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12288 				     && insn->off != 0) ||
12289 				    (insn->src_reg != BPF_REG_0 &&
12290 				     insn->src_reg != BPF_PSEUDO_CALL &&
12291 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12292 				    insn->dst_reg != BPF_REG_0 ||
12293 				    class == BPF_JMP32) {
12294 					verbose(env, "BPF_CALL uses reserved fields\n");
12295 					return -EINVAL;
12296 				}
12297 
12298 				if (env->cur_state->active_spin_lock &&
12299 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12300 				     insn->imm != BPF_FUNC_spin_unlock)) {
12301 					verbose(env, "function calls are not allowed while holding a lock\n");
12302 					return -EINVAL;
12303 				}
12304 				if (insn->src_reg == BPF_PSEUDO_CALL)
12305 					err = check_func_call(env, insn, &env->insn_idx);
12306 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12307 					err = check_kfunc_call(env, insn, &env->insn_idx);
12308 				else
12309 					err = check_helper_call(env, insn, &env->insn_idx);
12310 				if (err)
12311 					return err;
12312 			} else if (opcode == BPF_JA) {
12313 				if (BPF_SRC(insn->code) != BPF_K ||
12314 				    insn->imm != 0 ||
12315 				    insn->src_reg != BPF_REG_0 ||
12316 				    insn->dst_reg != BPF_REG_0 ||
12317 				    class == BPF_JMP32) {
12318 					verbose(env, "BPF_JA uses reserved fields\n");
12319 					return -EINVAL;
12320 				}
12321 
12322 				env->insn_idx += insn->off + 1;
12323 				continue;
12324 
12325 			} else if (opcode == BPF_EXIT) {
12326 				if (BPF_SRC(insn->code) != BPF_K ||
12327 				    insn->imm != 0 ||
12328 				    insn->src_reg != BPF_REG_0 ||
12329 				    insn->dst_reg != BPF_REG_0 ||
12330 				    class == BPF_JMP32) {
12331 					verbose(env, "BPF_EXIT uses reserved fields\n");
12332 					return -EINVAL;
12333 				}
12334 
12335 				if (env->cur_state->active_spin_lock) {
12336 					verbose(env, "bpf_spin_unlock is missing\n");
12337 					return -EINVAL;
12338 				}
12339 
12340 				if (state->curframe) {
12341 					/* exit from nested function */
12342 					err = prepare_func_exit(env, &env->insn_idx);
12343 					if (err)
12344 						return err;
12345 					do_print_state = true;
12346 					continue;
12347 				}
12348 
12349 				err = check_reference_leak(env);
12350 				if (err)
12351 					return err;
12352 
12353 				err = check_return_code(env);
12354 				if (err)
12355 					return err;
12356 process_bpf_exit:
12357 				mark_verifier_state_scratched(env);
12358 				update_branch_counts(env, env->cur_state);
12359 				err = pop_stack(env, &prev_insn_idx,
12360 						&env->insn_idx, pop_log);
12361 				if (err < 0) {
12362 					if (err != -ENOENT)
12363 						return err;
12364 					break;
12365 				} else {
12366 					do_print_state = true;
12367 					continue;
12368 				}
12369 			} else {
12370 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12371 				if (err)
12372 					return err;
12373 			}
12374 		} else if (class == BPF_LD) {
12375 			u8 mode = BPF_MODE(insn->code);
12376 
12377 			if (mode == BPF_ABS || mode == BPF_IND) {
12378 				err = check_ld_abs(env, insn);
12379 				if (err)
12380 					return err;
12381 
12382 			} else if (mode == BPF_IMM) {
12383 				err = check_ld_imm(env, insn);
12384 				if (err)
12385 					return err;
12386 
12387 				env->insn_idx++;
12388 				sanitize_mark_insn_seen(env);
12389 			} else {
12390 				verbose(env, "invalid BPF_LD mode\n");
12391 				return -EINVAL;
12392 			}
12393 		} else {
12394 			verbose(env, "unknown insn class %d\n", class);
12395 			return -EINVAL;
12396 		}
12397 
12398 		env->insn_idx++;
12399 	}
12400 
12401 	return 0;
12402 }
12403 
12404 static int find_btf_percpu_datasec(struct btf *btf)
12405 {
12406 	const struct btf_type *t;
12407 	const char *tname;
12408 	int i, n;
12409 
12410 	/*
12411 	 * Both vmlinux and module each have their own ".data..percpu"
12412 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12413 	 * types to look at only module's own BTF types.
12414 	 */
12415 	n = btf_nr_types(btf);
12416 	if (btf_is_module(btf))
12417 		i = btf_nr_types(btf_vmlinux);
12418 	else
12419 		i = 1;
12420 
12421 	for(; i < n; i++) {
12422 		t = btf_type_by_id(btf, i);
12423 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12424 			continue;
12425 
12426 		tname = btf_name_by_offset(btf, t->name_off);
12427 		if (!strcmp(tname, ".data..percpu"))
12428 			return i;
12429 	}
12430 
12431 	return -ENOENT;
12432 }
12433 
12434 /* replace pseudo btf_id with kernel symbol address */
12435 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12436 			       struct bpf_insn *insn,
12437 			       struct bpf_insn_aux_data *aux)
12438 {
12439 	const struct btf_var_secinfo *vsi;
12440 	const struct btf_type *datasec;
12441 	struct btf_mod_pair *btf_mod;
12442 	const struct btf_type *t;
12443 	const char *sym_name;
12444 	bool percpu = false;
12445 	u32 type, id = insn->imm;
12446 	struct btf *btf;
12447 	s32 datasec_id;
12448 	u64 addr;
12449 	int i, btf_fd, err;
12450 
12451 	btf_fd = insn[1].imm;
12452 	if (btf_fd) {
12453 		btf = btf_get_by_fd(btf_fd);
12454 		if (IS_ERR(btf)) {
12455 			verbose(env, "invalid module BTF object FD specified.\n");
12456 			return -EINVAL;
12457 		}
12458 	} else {
12459 		if (!btf_vmlinux) {
12460 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12461 			return -EINVAL;
12462 		}
12463 		btf = btf_vmlinux;
12464 		btf_get(btf);
12465 	}
12466 
12467 	t = btf_type_by_id(btf, id);
12468 	if (!t) {
12469 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12470 		err = -ENOENT;
12471 		goto err_put;
12472 	}
12473 
12474 	if (!btf_type_is_var(t)) {
12475 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12476 		err = -EINVAL;
12477 		goto err_put;
12478 	}
12479 
12480 	sym_name = btf_name_by_offset(btf, t->name_off);
12481 	addr = kallsyms_lookup_name(sym_name);
12482 	if (!addr) {
12483 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12484 			sym_name);
12485 		err = -ENOENT;
12486 		goto err_put;
12487 	}
12488 
12489 	datasec_id = find_btf_percpu_datasec(btf);
12490 	if (datasec_id > 0) {
12491 		datasec = btf_type_by_id(btf, datasec_id);
12492 		for_each_vsi(i, datasec, vsi) {
12493 			if (vsi->type == id) {
12494 				percpu = true;
12495 				break;
12496 			}
12497 		}
12498 	}
12499 
12500 	insn[0].imm = (u32)addr;
12501 	insn[1].imm = addr >> 32;
12502 
12503 	type = t->type;
12504 	t = btf_type_skip_modifiers(btf, type, NULL);
12505 	if (percpu) {
12506 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12507 		aux->btf_var.btf = btf;
12508 		aux->btf_var.btf_id = type;
12509 	} else if (!btf_type_is_struct(t)) {
12510 		const struct btf_type *ret;
12511 		const char *tname;
12512 		u32 tsize;
12513 
12514 		/* resolve the type size of ksym. */
12515 		ret = btf_resolve_size(btf, t, &tsize);
12516 		if (IS_ERR(ret)) {
12517 			tname = btf_name_by_offset(btf, t->name_off);
12518 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12519 				tname, PTR_ERR(ret));
12520 			err = -EINVAL;
12521 			goto err_put;
12522 		}
12523 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12524 		aux->btf_var.mem_size = tsize;
12525 	} else {
12526 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12527 		aux->btf_var.btf = btf;
12528 		aux->btf_var.btf_id = type;
12529 	}
12530 
12531 	/* check whether we recorded this BTF (and maybe module) already */
12532 	for (i = 0; i < env->used_btf_cnt; i++) {
12533 		if (env->used_btfs[i].btf == btf) {
12534 			btf_put(btf);
12535 			return 0;
12536 		}
12537 	}
12538 
12539 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12540 		err = -E2BIG;
12541 		goto err_put;
12542 	}
12543 
12544 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12545 	btf_mod->btf = btf;
12546 	btf_mod->module = NULL;
12547 
12548 	/* if we reference variables from kernel module, bump its refcount */
12549 	if (btf_is_module(btf)) {
12550 		btf_mod->module = btf_try_get_module(btf);
12551 		if (!btf_mod->module) {
12552 			err = -ENXIO;
12553 			goto err_put;
12554 		}
12555 	}
12556 
12557 	env->used_btf_cnt++;
12558 
12559 	return 0;
12560 err_put:
12561 	btf_put(btf);
12562 	return err;
12563 }
12564 
12565 static int check_map_prealloc(struct bpf_map *map)
12566 {
12567 	return (map->map_type != BPF_MAP_TYPE_HASH &&
12568 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
12569 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
12570 		!(map->map_flags & BPF_F_NO_PREALLOC);
12571 }
12572 
12573 static bool is_tracing_prog_type(enum bpf_prog_type type)
12574 {
12575 	switch (type) {
12576 	case BPF_PROG_TYPE_KPROBE:
12577 	case BPF_PROG_TYPE_TRACEPOINT:
12578 	case BPF_PROG_TYPE_PERF_EVENT:
12579 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12580 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12581 		return true;
12582 	default:
12583 		return false;
12584 	}
12585 }
12586 
12587 static bool is_preallocated_map(struct bpf_map *map)
12588 {
12589 	if (!check_map_prealloc(map))
12590 		return false;
12591 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
12592 		return false;
12593 	return true;
12594 }
12595 
12596 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12597 					struct bpf_map *map,
12598 					struct bpf_prog *prog)
12599 
12600 {
12601 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12602 	/*
12603 	 * Validate that trace type programs use preallocated hash maps.
12604 	 *
12605 	 * For programs attached to PERF events this is mandatory as the
12606 	 * perf NMI can hit any arbitrary code sequence.
12607 	 *
12608 	 * All other trace types using preallocated hash maps are unsafe as
12609 	 * well because tracepoint or kprobes can be inside locked regions
12610 	 * of the memory allocator or at a place where a recursion into the
12611 	 * memory allocator would see inconsistent state.
12612 	 *
12613 	 * On RT enabled kernels run-time allocation of all trace type
12614 	 * programs is strictly prohibited due to lock type constraints. On
12615 	 * !RT kernels it is allowed for backwards compatibility reasons for
12616 	 * now, but warnings are emitted so developers are made aware of
12617 	 * the unsafety and can fix their programs before this is enforced.
12618 	 */
12619 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
12620 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
12621 			verbose(env, "perf_event programs can only use preallocated hash map\n");
12622 			return -EINVAL;
12623 		}
12624 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
12625 			verbose(env, "trace type programs can only use preallocated hash map\n");
12626 			return -EINVAL;
12627 		}
12628 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
12629 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
12630 	}
12631 
12632 	if (map_value_has_spin_lock(map)) {
12633 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12634 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12635 			return -EINVAL;
12636 		}
12637 
12638 		if (is_tracing_prog_type(prog_type)) {
12639 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12640 			return -EINVAL;
12641 		}
12642 
12643 		if (prog->aux->sleepable) {
12644 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12645 			return -EINVAL;
12646 		}
12647 	}
12648 
12649 	if (map_value_has_timer(map)) {
12650 		if (is_tracing_prog_type(prog_type)) {
12651 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12652 			return -EINVAL;
12653 		}
12654 	}
12655 
12656 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12657 	    !bpf_offload_prog_map_match(prog, map)) {
12658 		verbose(env, "offload device mismatch between prog and map\n");
12659 		return -EINVAL;
12660 	}
12661 
12662 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12663 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12664 		return -EINVAL;
12665 	}
12666 
12667 	if (prog->aux->sleepable)
12668 		switch (map->map_type) {
12669 		case BPF_MAP_TYPE_HASH:
12670 		case BPF_MAP_TYPE_LRU_HASH:
12671 		case BPF_MAP_TYPE_ARRAY:
12672 		case BPF_MAP_TYPE_PERCPU_HASH:
12673 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12674 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12675 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12676 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12677 			if (!is_preallocated_map(map)) {
12678 				verbose(env,
12679 					"Sleepable programs can only use preallocated maps\n");
12680 				return -EINVAL;
12681 			}
12682 			break;
12683 		case BPF_MAP_TYPE_RINGBUF:
12684 		case BPF_MAP_TYPE_INODE_STORAGE:
12685 		case BPF_MAP_TYPE_SK_STORAGE:
12686 		case BPF_MAP_TYPE_TASK_STORAGE:
12687 			break;
12688 		default:
12689 			verbose(env,
12690 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12691 			return -EINVAL;
12692 		}
12693 
12694 	return 0;
12695 }
12696 
12697 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12698 {
12699 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12700 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12701 }
12702 
12703 /* find and rewrite pseudo imm in ld_imm64 instructions:
12704  *
12705  * 1. if it accesses map FD, replace it with actual map pointer.
12706  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12707  *
12708  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12709  */
12710 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12711 {
12712 	struct bpf_insn *insn = env->prog->insnsi;
12713 	int insn_cnt = env->prog->len;
12714 	int i, j, err;
12715 
12716 	err = bpf_prog_calc_tag(env->prog);
12717 	if (err)
12718 		return err;
12719 
12720 	for (i = 0; i < insn_cnt; i++, insn++) {
12721 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12722 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12723 			verbose(env, "BPF_LDX uses reserved fields\n");
12724 			return -EINVAL;
12725 		}
12726 
12727 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12728 			struct bpf_insn_aux_data *aux;
12729 			struct bpf_map *map;
12730 			struct fd f;
12731 			u64 addr;
12732 			u32 fd;
12733 
12734 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12735 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12736 			    insn[1].off != 0) {
12737 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12738 				return -EINVAL;
12739 			}
12740 
12741 			if (insn[0].src_reg == 0)
12742 				/* valid generic load 64-bit imm */
12743 				goto next_insn;
12744 
12745 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12746 				aux = &env->insn_aux_data[i];
12747 				err = check_pseudo_btf_id(env, insn, aux);
12748 				if (err)
12749 					return err;
12750 				goto next_insn;
12751 			}
12752 
12753 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12754 				aux = &env->insn_aux_data[i];
12755 				aux->ptr_type = PTR_TO_FUNC;
12756 				goto next_insn;
12757 			}
12758 
12759 			/* In final convert_pseudo_ld_imm64() step, this is
12760 			 * converted into regular 64-bit imm load insn.
12761 			 */
12762 			switch (insn[0].src_reg) {
12763 			case BPF_PSEUDO_MAP_VALUE:
12764 			case BPF_PSEUDO_MAP_IDX_VALUE:
12765 				break;
12766 			case BPF_PSEUDO_MAP_FD:
12767 			case BPF_PSEUDO_MAP_IDX:
12768 				if (insn[1].imm == 0)
12769 					break;
12770 				fallthrough;
12771 			default:
12772 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12773 				return -EINVAL;
12774 			}
12775 
12776 			switch (insn[0].src_reg) {
12777 			case BPF_PSEUDO_MAP_IDX_VALUE:
12778 			case BPF_PSEUDO_MAP_IDX:
12779 				if (bpfptr_is_null(env->fd_array)) {
12780 					verbose(env, "fd_idx without fd_array is invalid\n");
12781 					return -EPROTO;
12782 				}
12783 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12784 							    insn[0].imm * sizeof(fd),
12785 							    sizeof(fd)))
12786 					return -EFAULT;
12787 				break;
12788 			default:
12789 				fd = insn[0].imm;
12790 				break;
12791 			}
12792 
12793 			f = fdget(fd);
12794 			map = __bpf_map_get(f);
12795 			if (IS_ERR(map)) {
12796 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12797 					insn[0].imm);
12798 				return PTR_ERR(map);
12799 			}
12800 
12801 			err = check_map_prog_compatibility(env, map, env->prog);
12802 			if (err) {
12803 				fdput(f);
12804 				return err;
12805 			}
12806 
12807 			aux = &env->insn_aux_data[i];
12808 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12809 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12810 				addr = (unsigned long)map;
12811 			} else {
12812 				u32 off = insn[1].imm;
12813 
12814 				if (off >= BPF_MAX_VAR_OFF) {
12815 					verbose(env, "direct value offset of %u is not allowed\n", off);
12816 					fdput(f);
12817 					return -EINVAL;
12818 				}
12819 
12820 				if (!map->ops->map_direct_value_addr) {
12821 					verbose(env, "no direct value access support for this map type\n");
12822 					fdput(f);
12823 					return -EINVAL;
12824 				}
12825 
12826 				err = map->ops->map_direct_value_addr(map, &addr, off);
12827 				if (err) {
12828 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12829 						map->value_size, off);
12830 					fdput(f);
12831 					return err;
12832 				}
12833 
12834 				aux->map_off = off;
12835 				addr += off;
12836 			}
12837 
12838 			insn[0].imm = (u32)addr;
12839 			insn[1].imm = addr >> 32;
12840 
12841 			/* check whether we recorded this map already */
12842 			for (j = 0; j < env->used_map_cnt; j++) {
12843 				if (env->used_maps[j] == map) {
12844 					aux->map_index = j;
12845 					fdput(f);
12846 					goto next_insn;
12847 				}
12848 			}
12849 
12850 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12851 				fdput(f);
12852 				return -E2BIG;
12853 			}
12854 
12855 			/* hold the map. If the program is rejected by verifier,
12856 			 * the map will be released by release_maps() or it
12857 			 * will be used by the valid program until it's unloaded
12858 			 * and all maps are released in free_used_maps()
12859 			 */
12860 			bpf_map_inc(map);
12861 
12862 			aux->map_index = env->used_map_cnt;
12863 			env->used_maps[env->used_map_cnt++] = map;
12864 
12865 			if (bpf_map_is_cgroup_storage(map) &&
12866 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12867 				verbose(env, "only one cgroup storage of each type is allowed\n");
12868 				fdput(f);
12869 				return -EBUSY;
12870 			}
12871 
12872 			fdput(f);
12873 next_insn:
12874 			insn++;
12875 			i++;
12876 			continue;
12877 		}
12878 
12879 		/* Basic sanity check before we invest more work here. */
12880 		if (!bpf_opcode_in_insntable(insn->code)) {
12881 			verbose(env, "unknown opcode %02x\n", insn->code);
12882 			return -EINVAL;
12883 		}
12884 	}
12885 
12886 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12887 	 * 'struct bpf_map *' into a register instead of user map_fd.
12888 	 * These pointers will be used later by verifier to validate map access.
12889 	 */
12890 	return 0;
12891 }
12892 
12893 /* drop refcnt of maps used by the rejected program */
12894 static void release_maps(struct bpf_verifier_env *env)
12895 {
12896 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12897 			     env->used_map_cnt);
12898 }
12899 
12900 /* drop refcnt of maps used by the rejected program */
12901 static void release_btfs(struct bpf_verifier_env *env)
12902 {
12903 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12904 			     env->used_btf_cnt);
12905 }
12906 
12907 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12908 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12909 {
12910 	struct bpf_insn *insn = env->prog->insnsi;
12911 	int insn_cnt = env->prog->len;
12912 	int i;
12913 
12914 	for (i = 0; i < insn_cnt; i++, insn++) {
12915 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12916 			continue;
12917 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12918 			continue;
12919 		insn->src_reg = 0;
12920 	}
12921 }
12922 
12923 /* single env->prog->insni[off] instruction was replaced with the range
12924  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12925  * [0, off) and [off, end) to new locations, so the patched range stays zero
12926  */
12927 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12928 				 struct bpf_insn_aux_data *new_data,
12929 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12930 {
12931 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12932 	struct bpf_insn *insn = new_prog->insnsi;
12933 	u32 old_seen = old_data[off].seen;
12934 	u32 prog_len;
12935 	int i;
12936 
12937 	/* aux info at OFF always needs adjustment, no matter fast path
12938 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12939 	 * original insn at old prog.
12940 	 */
12941 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12942 
12943 	if (cnt == 1)
12944 		return;
12945 	prog_len = new_prog->len;
12946 
12947 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12948 	memcpy(new_data + off + cnt - 1, old_data + off,
12949 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12950 	for (i = off; i < off + cnt - 1; i++) {
12951 		/* Expand insni[off]'s seen count to the patched range. */
12952 		new_data[i].seen = old_seen;
12953 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12954 	}
12955 	env->insn_aux_data = new_data;
12956 	vfree(old_data);
12957 }
12958 
12959 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12960 {
12961 	int i;
12962 
12963 	if (len == 1)
12964 		return;
12965 	/* NOTE: fake 'exit' subprog should be updated as well. */
12966 	for (i = 0; i <= env->subprog_cnt; i++) {
12967 		if (env->subprog_info[i].start <= off)
12968 			continue;
12969 		env->subprog_info[i].start += len - 1;
12970 	}
12971 }
12972 
12973 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12974 {
12975 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12976 	int i, sz = prog->aux->size_poke_tab;
12977 	struct bpf_jit_poke_descriptor *desc;
12978 
12979 	for (i = 0; i < sz; i++) {
12980 		desc = &tab[i];
12981 		if (desc->insn_idx <= off)
12982 			continue;
12983 		desc->insn_idx += len - 1;
12984 	}
12985 }
12986 
12987 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12988 					    const struct bpf_insn *patch, u32 len)
12989 {
12990 	struct bpf_prog *new_prog;
12991 	struct bpf_insn_aux_data *new_data = NULL;
12992 
12993 	if (len > 1) {
12994 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12995 					      sizeof(struct bpf_insn_aux_data)));
12996 		if (!new_data)
12997 			return NULL;
12998 	}
12999 
13000 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13001 	if (IS_ERR(new_prog)) {
13002 		if (PTR_ERR(new_prog) == -ERANGE)
13003 			verbose(env,
13004 				"insn %d cannot be patched due to 16-bit range\n",
13005 				env->insn_aux_data[off].orig_idx);
13006 		vfree(new_data);
13007 		return NULL;
13008 	}
13009 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
13010 	adjust_subprog_starts(env, off, len);
13011 	adjust_poke_descs(new_prog, off, len);
13012 	return new_prog;
13013 }
13014 
13015 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13016 					      u32 off, u32 cnt)
13017 {
13018 	int i, j;
13019 
13020 	/* find first prog starting at or after off (first to remove) */
13021 	for (i = 0; i < env->subprog_cnt; i++)
13022 		if (env->subprog_info[i].start >= off)
13023 			break;
13024 	/* find first prog starting at or after off + cnt (first to stay) */
13025 	for (j = i; j < env->subprog_cnt; j++)
13026 		if (env->subprog_info[j].start >= off + cnt)
13027 			break;
13028 	/* if j doesn't start exactly at off + cnt, we are just removing
13029 	 * the front of previous prog
13030 	 */
13031 	if (env->subprog_info[j].start != off + cnt)
13032 		j--;
13033 
13034 	if (j > i) {
13035 		struct bpf_prog_aux *aux = env->prog->aux;
13036 		int move;
13037 
13038 		/* move fake 'exit' subprog as well */
13039 		move = env->subprog_cnt + 1 - j;
13040 
13041 		memmove(env->subprog_info + i,
13042 			env->subprog_info + j,
13043 			sizeof(*env->subprog_info) * move);
13044 		env->subprog_cnt -= j - i;
13045 
13046 		/* remove func_info */
13047 		if (aux->func_info) {
13048 			move = aux->func_info_cnt - j;
13049 
13050 			memmove(aux->func_info + i,
13051 				aux->func_info + j,
13052 				sizeof(*aux->func_info) * move);
13053 			aux->func_info_cnt -= j - i;
13054 			/* func_info->insn_off is set after all code rewrites,
13055 			 * in adjust_btf_func() - no need to adjust
13056 			 */
13057 		}
13058 	} else {
13059 		/* convert i from "first prog to remove" to "first to adjust" */
13060 		if (env->subprog_info[i].start == off)
13061 			i++;
13062 	}
13063 
13064 	/* update fake 'exit' subprog as well */
13065 	for (; i <= env->subprog_cnt; i++)
13066 		env->subprog_info[i].start -= cnt;
13067 
13068 	return 0;
13069 }
13070 
13071 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13072 				      u32 cnt)
13073 {
13074 	struct bpf_prog *prog = env->prog;
13075 	u32 i, l_off, l_cnt, nr_linfo;
13076 	struct bpf_line_info *linfo;
13077 
13078 	nr_linfo = prog->aux->nr_linfo;
13079 	if (!nr_linfo)
13080 		return 0;
13081 
13082 	linfo = prog->aux->linfo;
13083 
13084 	/* find first line info to remove, count lines to be removed */
13085 	for (i = 0; i < nr_linfo; i++)
13086 		if (linfo[i].insn_off >= off)
13087 			break;
13088 
13089 	l_off = i;
13090 	l_cnt = 0;
13091 	for (; i < nr_linfo; i++)
13092 		if (linfo[i].insn_off < off + cnt)
13093 			l_cnt++;
13094 		else
13095 			break;
13096 
13097 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13098 	 * last removed linfo.  prog is already modified, so prog->len == off
13099 	 * means no live instructions after (tail of the program was removed).
13100 	 */
13101 	if (prog->len != off && l_cnt &&
13102 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13103 		l_cnt--;
13104 		linfo[--i].insn_off = off + cnt;
13105 	}
13106 
13107 	/* remove the line info which refer to the removed instructions */
13108 	if (l_cnt) {
13109 		memmove(linfo + l_off, linfo + i,
13110 			sizeof(*linfo) * (nr_linfo - i));
13111 
13112 		prog->aux->nr_linfo -= l_cnt;
13113 		nr_linfo = prog->aux->nr_linfo;
13114 	}
13115 
13116 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13117 	for (i = l_off; i < nr_linfo; i++)
13118 		linfo[i].insn_off -= cnt;
13119 
13120 	/* fix up all subprogs (incl. 'exit') which start >= off */
13121 	for (i = 0; i <= env->subprog_cnt; i++)
13122 		if (env->subprog_info[i].linfo_idx > l_off) {
13123 			/* program may have started in the removed region but
13124 			 * may not be fully removed
13125 			 */
13126 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13127 				env->subprog_info[i].linfo_idx -= l_cnt;
13128 			else
13129 				env->subprog_info[i].linfo_idx = l_off;
13130 		}
13131 
13132 	return 0;
13133 }
13134 
13135 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13136 {
13137 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13138 	unsigned int orig_prog_len = env->prog->len;
13139 	int err;
13140 
13141 	if (bpf_prog_is_dev_bound(env->prog->aux))
13142 		bpf_prog_offload_remove_insns(env, off, cnt);
13143 
13144 	err = bpf_remove_insns(env->prog, off, cnt);
13145 	if (err)
13146 		return err;
13147 
13148 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13149 	if (err)
13150 		return err;
13151 
13152 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13153 	if (err)
13154 		return err;
13155 
13156 	memmove(aux_data + off,	aux_data + off + cnt,
13157 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13158 
13159 	return 0;
13160 }
13161 
13162 /* The verifier does more data flow analysis than llvm and will not
13163  * explore branches that are dead at run time. Malicious programs can
13164  * have dead code too. Therefore replace all dead at-run-time code
13165  * with 'ja -1'.
13166  *
13167  * Just nops are not optimal, e.g. if they would sit at the end of the
13168  * program and through another bug we would manage to jump there, then
13169  * we'd execute beyond program memory otherwise. Returning exception
13170  * code also wouldn't work since we can have subprogs where the dead
13171  * code could be located.
13172  */
13173 static void sanitize_dead_code(struct bpf_verifier_env *env)
13174 {
13175 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13176 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13177 	struct bpf_insn *insn = env->prog->insnsi;
13178 	const int insn_cnt = env->prog->len;
13179 	int i;
13180 
13181 	for (i = 0; i < insn_cnt; i++) {
13182 		if (aux_data[i].seen)
13183 			continue;
13184 		memcpy(insn + i, &trap, sizeof(trap));
13185 		aux_data[i].zext_dst = false;
13186 	}
13187 }
13188 
13189 static bool insn_is_cond_jump(u8 code)
13190 {
13191 	u8 op;
13192 
13193 	if (BPF_CLASS(code) == BPF_JMP32)
13194 		return true;
13195 
13196 	if (BPF_CLASS(code) != BPF_JMP)
13197 		return false;
13198 
13199 	op = BPF_OP(code);
13200 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13201 }
13202 
13203 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13204 {
13205 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13206 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13207 	struct bpf_insn *insn = env->prog->insnsi;
13208 	const int insn_cnt = env->prog->len;
13209 	int i;
13210 
13211 	for (i = 0; i < insn_cnt; i++, insn++) {
13212 		if (!insn_is_cond_jump(insn->code))
13213 			continue;
13214 
13215 		if (!aux_data[i + 1].seen)
13216 			ja.off = insn->off;
13217 		else if (!aux_data[i + 1 + insn->off].seen)
13218 			ja.off = 0;
13219 		else
13220 			continue;
13221 
13222 		if (bpf_prog_is_dev_bound(env->prog->aux))
13223 			bpf_prog_offload_replace_insn(env, i, &ja);
13224 
13225 		memcpy(insn, &ja, sizeof(ja));
13226 	}
13227 }
13228 
13229 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13230 {
13231 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13232 	int insn_cnt = env->prog->len;
13233 	int i, err;
13234 
13235 	for (i = 0; i < insn_cnt; i++) {
13236 		int j;
13237 
13238 		j = 0;
13239 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13240 			j++;
13241 		if (!j)
13242 			continue;
13243 
13244 		err = verifier_remove_insns(env, i, j);
13245 		if (err)
13246 			return err;
13247 		insn_cnt = env->prog->len;
13248 	}
13249 
13250 	return 0;
13251 }
13252 
13253 static int opt_remove_nops(struct bpf_verifier_env *env)
13254 {
13255 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13256 	struct bpf_insn *insn = env->prog->insnsi;
13257 	int insn_cnt = env->prog->len;
13258 	int i, err;
13259 
13260 	for (i = 0; i < insn_cnt; i++) {
13261 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13262 			continue;
13263 
13264 		err = verifier_remove_insns(env, i, 1);
13265 		if (err)
13266 			return err;
13267 		insn_cnt--;
13268 		i--;
13269 	}
13270 
13271 	return 0;
13272 }
13273 
13274 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13275 					 const union bpf_attr *attr)
13276 {
13277 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13278 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13279 	int i, patch_len, delta = 0, len = env->prog->len;
13280 	struct bpf_insn *insns = env->prog->insnsi;
13281 	struct bpf_prog *new_prog;
13282 	bool rnd_hi32;
13283 
13284 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13285 	zext_patch[1] = BPF_ZEXT_REG(0);
13286 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13287 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13288 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13289 	for (i = 0; i < len; i++) {
13290 		int adj_idx = i + delta;
13291 		struct bpf_insn insn;
13292 		int load_reg;
13293 
13294 		insn = insns[adj_idx];
13295 		load_reg = insn_def_regno(&insn);
13296 		if (!aux[adj_idx].zext_dst) {
13297 			u8 code, class;
13298 			u32 imm_rnd;
13299 
13300 			if (!rnd_hi32)
13301 				continue;
13302 
13303 			code = insn.code;
13304 			class = BPF_CLASS(code);
13305 			if (load_reg == -1)
13306 				continue;
13307 
13308 			/* NOTE: arg "reg" (the fourth one) is only used for
13309 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13310 			 *       here.
13311 			 */
13312 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13313 				if (class == BPF_LD &&
13314 				    BPF_MODE(code) == BPF_IMM)
13315 					i++;
13316 				continue;
13317 			}
13318 
13319 			/* ctx load could be transformed into wider load. */
13320 			if (class == BPF_LDX &&
13321 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13322 				continue;
13323 
13324 			imm_rnd = get_random_int();
13325 			rnd_hi32_patch[0] = insn;
13326 			rnd_hi32_patch[1].imm = imm_rnd;
13327 			rnd_hi32_patch[3].dst_reg = load_reg;
13328 			patch = rnd_hi32_patch;
13329 			patch_len = 4;
13330 			goto apply_patch_buffer;
13331 		}
13332 
13333 		/* Add in an zero-extend instruction if a) the JIT has requested
13334 		 * it or b) it's a CMPXCHG.
13335 		 *
13336 		 * The latter is because: BPF_CMPXCHG always loads a value into
13337 		 * R0, therefore always zero-extends. However some archs'
13338 		 * equivalent instruction only does this load when the
13339 		 * comparison is successful. This detail of CMPXCHG is
13340 		 * orthogonal to the general zero-extension behaviour of the
13341 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13342 		 */
13343 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13344 			continue;
13345 
13346 		if (WARN_ON(load_reg == -1)) {
13347 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13348 			return -EFAULT;
13349 		}
13350 
13351 		zext_patch[0] = insn;
13352 		zext_patch[1].dst_reg = load_reg;
13353 		zext_patch[1].src_reg = load_reg;
13354 		patch = zext_patch;
13355 		patch_len = 2;
13356 apply_patch_buffer:
13357 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13358 		if (!new_prog)
13359 			return -ENOMEM;
13360 		env->prog = new_prog;
13361 		insns = new_prog->insnsi;
13362 		aux = env->insn_aux_data;
13363 		delta += patch_len - 1;
13364 	}
13365 
13366 	return 0;
13367 }
13368 
13369 /* convert load instructions that access fields of a context type into a
13370  * sequence of instructions that access fields of the underlying structure:
13371  *     struct __sk_buff    -> struct sk_buff
13372  *     struct bpf_sock_ops -> struct sock
13373  */
13374 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13375 {
13376 	const struct bpf_verifier_ops *ops = env->ops;
13377 	int i, cnt, size, ctx_field_size, delta = 0;
13378 	const int insn_cnt = env->prog->len;
13379 	struct bpf_insn insn_buf[16], *insn;
13380 	u32 target_size, size_default, off;
13381 	struct bpf_prog *new_prog;
13382 	enum bpf_access_type type;
13383 	bool is_narrower_load;
13384 
13385 	if (ops->gen_prologue || env->seen_direct_write) {
13386 		if (!ops->gen_prologue) {
13387 			verbose(env, "bpf verifier is misconfigured\n");
13388 			return -EINVAL;
13389 		}
13390 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13391 					env->prog);
13392 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13393 			verbose(env, "bpf verifier is misconfigured\n");
13394 			return -EINVAL;
13395 		} else if (cnt) {
13396 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13397 			if (!new_prog)
13398 				return -ENOMEM;
13399 
13400 			env->prog = new_prog;
13401 			delta += cnt - 1;
13402 		}
13403 	}
13404 
13405 	if (bpf_prog_is_dev_bound(env->prog->aux))
13406 		return 0;
13407 
13408 	insn = env->prog->insnsi + delta;
13409 
13410 	for (i = 0; i < insn_cnt; i++, insn++) {
13411 		bpf_convert_ctx_access_t convert_ctx_access;
13412 		bool ctx_access;
13413 
13414 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13415 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13416 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13417 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13418 			type = BPF_READ;
13419 			ctx_access = true;
13420 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13421 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13422 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13423 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13424 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13425 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13426 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13427 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13428 			type = BPF_WRITE;
13429 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13430 		} else {
13431 			continue;
13432 		}
13433 
13434 		if (type == BPF_WRITE &&
13435 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13436 			struct bpf_insn patch[] = {
13437 				*insn,
13438 				BPF_ST_NOSPEC(),
13439 			};
13440 
13441 			cnt = ARRAY_SIZE(patch);
13442 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13443 			if (!new_prog)
13444 				return -ENOMEM;
13445 
13446 			delta    += cnt - 1;
13447 			env->prog = new_prog;
13448 			insn      = new_prog->insnsi + i + delta;
13449 			continue;
13450 		}
13451 
13452 		if (!ctx_access)
13453 			continue;
13454 
13455 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13456 		case PTR_TO_CTX:
13457 			if (!ops->convert_ctx_access)
13458 				continue;
13459 			convert_ctx_access = ops->convert_ctx_access;
13460 			break;
13461 		case PTR_TO_SOCKET:
13462 		case PTR_TO_SOCK_COMMON:
13463 			convert_ctx_access = bpf_sock_convert_ctx_access;
13464 			break;
13465 		case PTR_TO_TCP_SOCK:
13466 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13467 			break;
13468 		case PTR_TO_XDP_SOCK:
13469 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13470 			break;
13471 		case PTR_TO_BTF_ID:
13472 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13473 			if (type == BPF_READ) {
13474 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13475 					BPF_SIZE((insn)->code);
13476 				env->prog->aux->num_exentries++;
13477 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
13478 				verbose(env, "Writes through BTF pointers are not allowed\n");
13479 				return -EINVAL;
13480 			}
13481 			continue;
13482 		default:
13483 			continue;
13484 		}
13485 
13486 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13487 		size = BPF_LDST_BYTES(insn);
13488 
13489 		/* If the read access is a narrower load of the field,
13490 		 * convert to a 4/8-byte load, to minimum program type specific
13491 		 * convert_ctx_access changes. If conversion is successful,
13492 		 * we will apply proper mask to the result.
13493 		 */
13494 		is_narrower_load = size < ctx_field_size;
13495 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13496 		off = insn->off;
13497 		if (is_narrower_load) {
13498 			u8 size_code;
13499 
13500 			if (type == BPF_WRITE) {
13501 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13502 				return -EINVAL;
13503 			}
13504 
13505 			size_code = BPF_H;
13506 			if (ctx_field_size == 4)
13507 				size_code = BPF_W;
13508 			else if (ctx_field_size == 8)
13509 				size_code = BPF_DW;
13510 
13511 			insn->off = off & ~(size_default - 1);
13512 			insn->code = BPF_LDX | BPF_MEM | size_code;
13513 		}
13514 
13515 		target_size = 0;
13516 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13517 					 &target_size);
13518 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13519 		    (ctx_field_size && !target_size)) {
13520 			verbose(env, "bpf verifier is misconfigured\n");
13521 			return -EINVAL;
13522 		}
13523 
13524 		if (is_narrower_load && size < target_size) {
13525 			u8 shift = bpf_ctx_narrow_access_offset(
13526 				off, size, size_default) * 8;
13527 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13528 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13529 				return -EINVAL;
13530 			}
13531 			if (ctx_field_size <= 4) {
13532 				if (shift)
13533 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13534 									insn->dst_reg,
13535 									shift);
13536 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13537 								(1 << size * 8) - 1);
13538 			} else {
13539 				if (shift)
13540 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13541 									insn->dst_reg,
13542 									shift);
13543 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13544 								(1ULL << size * 8) - 1);
13545 			}
13546 		}
13547 
13548 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13549 		if (!new_prog)
13550 			return -ENOMEM;
13551 
13552 		delta += cnt - 1;
13553 
13554 		/* keep walking new program and skip insns we just inserted */
13555 		env->prog = new_prog;
13556 		insn      = new_prog->insnsi + i + delta;
13557 	}
13558 
13559 	return 0;
13560 }
13561 
13562 static int jit_subprogs(struct bpf_verifier_env *env)
13563 {
13564 	struct bpf_prog *prog = env->prog, **func, *tmp;
13565 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13566 	struct bpf_map *map_ptr;
13567 	struct bpf_insn *insn;
13568 	void *old_bpf_func;
13569 	int err, num_exentries;
13570 
13571 	if (env->subprog_cnt <= 1)
13572 		return 0;
13573 
13574 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13575 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13576 			continue;
13577 
13578 		/* Upon error here we cannot fall back to interpreter but
13579 		 * need a hard reject of the program. Thus -EFAULT is
13580 		 * propagated in any case.
13581 		 */
13582 		subprog = find_subprog(env, i + insn->imm + 1);
13583 		if (subprog < 0) {
13584 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13585 				  i + insn->imm + 1);
13586 			return -EFAULT;
13587 		}
13588 		/* temporarily remember subprog id inside insn instead of
13589 		 * aux_data, since next loop will split up all insns into funcs
13590 		 */
13591 		insn->off = subprog;
13592 		/* remember original imm in case JIT fails and fallback
13593 		 * to interpreter will be needed
13594 		 */
13595 		env->insn_aux_data[i].call_imm = insn->imm;
13596 		/* point imm to __bpf_call_base+1 from JITs point of view */
13597 		insn->imm = 1;
13598 		if (bpf_pseudo_func(insn))
13599 			/* jit (e.g. x86_64) may emit fewer instructions
13600 			 * if it learns a u32 imm is the same as a u64 imm.
13601 			 * Force a non zero here.
13602 			 */
13603 			insn[1].imm = 1;
13604 	}
13605 
13606 	err = bpf_prog_alloc_jited_linfo(prog);
13607 	if (err)
13608 		goto out_undo_insn;
13609 
13610 	err = -ENOMEM;
13611 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13612 	if (!func)
13613 		goto out_undo_insn;
13614 
13615 	for (i = 0; i < env->subprog_cnt; i++) {
13616 		subprog_start = subprog_end;
13617 		subprog_end = env->subprog_info[i + 1].start;
13618 
13619 		len = subprog_end - subprog_start;
13620 		/* bpf_prog_run() doesn't call subprogs directly,
13621 		 * hence main prog stats include the runtime of subprogs.
13622 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13623 		 * func[i]->stats will never be accessed and stays NULL
13624 		 */
13625 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13626 		if (!func[i])
13627 			goto out_free;
13628 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13629 		       len * sizeof(struct bpf_insn));
13630 		func[i]->type = prog->type;
13631 		func[i]->len = len;
13632 		if (bpf_prog_calc_tag(func[i]))
13633 			goto out_free;
13634 		func[i]->is_func = 1;
13635 		func[i]->aux->func_idx = i;
13636 		/* Below members will be freed only at prog->aux */
13637 		func[i]->aux->btf = prog->aux->btf;
13638 		func[i]->aux->func_info = prog->aux->func_info;
13639 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13640 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13641 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13642 
13643 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13644 			struct bpf_jit_poke_descriptor *poke;
13645 
13646 			poke = &prog->aux->poke_tab[j];
13647 			if (poke->insn_idx < subprog_end &&
13648 			    poke->insn_idx >= subprog_start)
13649 				poke->aux = func[i]->aux;
13650 		}
13651 
13652 		func[i]->aux->name[0] = 'F';
13653 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13654 		func[i]->jit_requested = 1;
13655 		func[i]->blinding_requested = prog->blinding_requested;
13656 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13657 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13658 		func[i]->aux->linfo = prog->aux->linfo;
13659 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13660 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13661 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13662 		num_exentries = 0;
13663 		insn = func[i]->insnsi;
13664 		for (j = 0; j < func[i]->len; j++, insn++) {
13665 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13666 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13667 				num_exentries++;
13668 		}
13669 		func[i]->aux->num_exentries = num_exentries;
13670 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13671 		func[i] = bpf_int_jit_compile(func[i]);
13672 		if (!func[i]->jited) {
13673 			err = -ENOTSUPP;
13674 			goto out_free;
13675 		}
13676 		cond_resched();
13677 	}
13678 
13679 	/* at this point all bpf functions were successfully JITed
13680 	 * now populate all bpf_calls with correct addresses and
13681 	 * run last pass of JIT
13682 	 */
13683 	for (i = 0; i < env->subprog_cnt; i++) {
13684 		insn = func[i]->insnsi;
13685 		for (j = 0; j < func[i]->len; j++, insn++) {
13686 			if (bpf_pseudo_func(insn)) {
13687 				subprog = insn->off;
13688 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13689 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13690 				continue;
13691 			}
13692 			if (!bpf_pseudo_call(insn))
13693 				continue;
13694 			subprog = insn->off;
13695 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13696 		}
13697 
13698 		/* we use the aux data to keep a list of the start addresses
13699 		 * of the JITed images for each function in the program
13700 		 *
13701 		 * for some architectures, such as powerpc64, the imm field
13702 		 * might not be large enough to hold the offset of the start
13703 		 * address of the callee's JITed image from __bpf_call_base
13704 		 *
13705 		 * in such cases, we can lookup the start address of a callee
13706 		 * by using its subprog id, available from the off field of
13707 		 * the call instruction, as an index for this list
13708 		 */
13709 		func[i]->aux->func = func;
13710 		func[i]->aux->func_cnt = env->subprog_cnt;
13711 	}
13712 	for (i = 0; i < env->subprog_cnt; i++) {
13713 		old_bpf_func = func[i]->bpf_func;
13714 		tmp = bpf_int_jit_compile(func[i]);
13715 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13716 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13717 			err = -ENOTSUPP;
13718 			goto out_free;
13719 		}
13720 		cond_resched();
13721 	}
13722 
13723 	/* finally lock prog and jit images for all functions and
13724 	 * populate kallsysm
13725 	 */
13726 	for (i = 0; i < env->subprog_cnt; i++) {
13727 		bpf_prog_lock_ro(func[i]);
13728 		bpf_prog_kallsyms_add(func[i]);
13729 	}
13730 
13731 	/* Last step: make now unused interpreter insns from main
13732 	 * prog consistent for later dump requests, so they can
13733 	 * later look the same as if they were interpreted only.
13734 	 */
13735 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13736 		if (bpf_pseudo_func(insn)) {
13737 			insn[0].imm = env->insn_aux_data[i].call_imm;
13738 			insn[1].imm = insn->off;
13739 			insn->off = 0;
13740 			continue;
13741 		}
13742 		if (!bpf_pseudo_call(insn))
13743 			continue;
13744 		insn->off = env->insn_aux_data[i].call_imm;
13745 		subprog = find_subprog(env, i + insn->off + 1);
13746 		insn->imm = subprog;
13747 	}
13748 
13749 	prog->jited = 1;
13750 	prog->bpf_func = func[0]->bpf_func;
13751 	prog->jited_len = func[0]->jited_len;
13752 	prog->aux->func = func;
13753 	prog->aux->func_cnt = env->subprog_cnt;
13754 	bpf_prog_jit_attempt_done(prog);
13755 	return 0;
13756 out_free:
13757 	/* We failed JIT'ing, so at this point we need to unregister poke
13758 	 * descriptors from subprogs, so that kernel is not attempting to
13759 	 * patch it anymore as we're freeing the subprog JIT memory.
13760 	 */
13761 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13762 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13763 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13764 	}
13765 	/* At this point we're guaranteed that poke descriptors are not
13766 	 * live anymore. We can just unlink its descriptor table as it's
13767 	 * released with the main prog.
13768 	 */
13769 	for (i = 0; i < env->subprog_cnt; i++) {
13770 		if (!func[i])
13771 			continue;
13772 		func[i]->aux->poke_tab = NULL;
13773 		bpf_jit_free(func[i]);
13774 	}
13775 	kfree(func);
13776 out_undo_insn:
13777 	/* cleanup main prog to be interpreted */
13778 	prog->jit_requested = 0;
13779 	prog->blinding_requested = 0;
13780 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13781 		if (!bpf_pseudo_call(insn))
13782 			continue;
13783 		insn->off = 0;
13784 		insn->imm = env->insn_aux_data[i].call_imm;
13785 	}
13786 	bpf_prog_jit_attempt_done(prog);
13787 	return err;
13788 }
13789 
13790 static int fixup_call_args(struct bpf_verifier_env *env)
13791 {
13792 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13793 	struct bpf_prog *prog = env->prog;
13794 	struct bpf_insn *insn = prog->insnsi;
13795 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13796 	int i, depth;
13797 #endif
13798 	int err = 0;
13799 
13800 	if (env->prog->jit_requested &&
13801 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13802 		err = jit_subprogs(env);
13803 		if (err == 0)
13804 			return 0;
13805 		if (err == -EFAULT)
13806 			return err;
13807 	}
13808 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13809 	if (has_kfunc_call) {
13810 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13811 		return -EINVAL;
13812 	}
13813 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13814 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13815 		 * have to be rejected, since interpreter doesn't support them yet.
13816 		 */
13817 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13818 		return -EINVAL;
13819 	}
13820 	for (i = 0; i < prog->len; i++, insn++) {
13821 		if (bpf_pseudo_func(insn)) {
13822 			/* When JIT fails the progs with callback calls
13823 			 * have to be rejected, since interpreter doesn't support them yet.
13824 			 */
13825 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13826 			return -EINVAL;
13827 		}
13828 
13829 		if (!bpf_pseudo_call(insn))
13830 			continue;
13831 		depth = get_callee_stack_depth(env, insn, i);
13832 		if (depth < 0)
13833 			return depth;
13834 		bpf_patch_call_args(insn, depth);
13835 	}
13836 	err = 0;
13837 #endif
13838 	return err;
13839 }
13840 
13841 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13842 			    struct bpf_insn *insn)
13843 {
13844 	const struct bpf_kfunc_desc *desc;
13845 
13846 	if (!insn->imm) {
13847 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13848 		return -EINVAL;
13849 	}
13850 
13851 	/* insn->imm has the btf func_id. Replace it with
13852 	 * an address (relative to __bpf_base_call).
13853 	 */
13854 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13855 	if (!desc) {
13856 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13857 			insn->imm);
13858 		return -EFAULT;
13859 	}
13860 
13861 	insn->imm = desc->imm;
13862 
13863 	return 0;
13864 }
13865 
13866 /* Do various post-verification rewrites in a single program pass.
13867  * These rewrites simplify JIT and interpreter implementations.
13868  */
13869 static int do_misc_fixups(struct bpf_verifier_env *env)
13870 {
13871 	struct bpf_prog *prog = env->prog;
13872 	enum bpf_attach_type eatype = prog->expected_attach_type;
13873 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13874 	struct bpf_insn *insn = prog->insnsi;
13875 	const struct bpf_func_proto *fn;
13876 	const int insn_cnt = prog->len;
13877 	const struct bpf_map_ops *ops;
13878 	struct bpf_insn_aux_data *aux;
13879 	struct bpf_insn insn_buf[16];
13880 	struct bpf_prog *new_prog;
13881 	struct bpf_map *map_ptr;
13882 	int i, ret, cnt, delta = 0;
13883 
13884 	for (i = 0; i < insn_cnt; i++, insn++) {
13885 		/* Make divide-by-zero exceptions impossible. */
13886 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13887 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13888 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13889 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13890 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13891 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13892 			struct bpf_insn *patchlet;
13893 			struct bpf_insn chk_and_div[] = {
13894 				/* [R,W]x div 0 -> 0 */
13895 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13896 					     BPF_JNE | BPF_K, insn->src_reg,
13897 					     0, 2, 0),
13898 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13899 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13900 				*insn,
13901 			};
13902 			struct bpf_insn chk_and_mod[] = {
13903 				/* [R,W]x mod 0 -> [R,W]x */
13904 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13905 					     BPF_JEQ | BPF_K, insn->src_reg,
13906 					     0, 1 + (is64 ? 0 : 1), 0),
13907 				*insn,
13908 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13909 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13910 			};
13911 
13912 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13913 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13914 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13915 
13916 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13917 			if (!new_prog)
13918 				return -ENOMEM;
13919 
13920 			delta    += cnt - 1;
13921 			env->prog = prog = new_prog;
13922 			insn      = new_prog->insnsi + i + delta;
13923 			continue;
13924 		}
13925 
13926 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13927 		if (BPF_CLASS(insn->code) == BPF_LD &&
13928 		    (BPF_MODE(insn->code) == BPF_ABS ||
13929 		     BPF_MODE(insn->code) == BPF_IND)) {
13930 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13931 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13932 				verbose(env, "bpf verifier is misconfigured\n");
13933 				return -EINVAL;
13934 			}
13935 
13936 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13937 			if (!new_prog)
13938 				return -ENOMEM;
13939 
13940 			delta    += cnt - 1;
13941 			env->prog = prog = new_prog;
13942 			insn      = new_prog->insnsi + i + delta;
13943 			continue;
13944 		}
13945 
13946 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
13947 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13948 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13949 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13950 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13951 			struct bpf_insn *patch = &insn_buf[0];
13952 			bool issrc, isneg, isimm;
13953 			u32 off_reg;
13954 
13955 			aux = &env->insn_aux_data[i + delta];
13956 			if (!aux->alu_state ||
13957 			    aux->alu_state == BPF_ALU_NON_POINTER)
13958 				continue;
13959 
13960 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13961 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13962 				BPF_ALU_SANITIZE_SRC;
13963 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13964 
13965 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13966 			if (isimm) {
13967 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13968 			} else {
13969 				if (isneg)
13970 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13971 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13972 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13973 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13974 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13975 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13976 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13977 			}
13978 			if (!issrc)
13979 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13980 			insn->src_reg = BPF_REG_AX;
13981 			if (isneg)
13982 				insn->code = insn->code == code_add ?
13983 					     code_sub : code_add;
13984 			*patch++ = *insn;
13985 			if (issrc && isneg && !isimm)
13986 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13987 			cnt = patch - insn_buf;
13988 
13989 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13990 			if (!new_prog)
13991 				return -ENOMEM;
13992 
13993 			delta    += cnt - 1;
13994 			env->prog = prog = new_prog;
13995 			insn      = new_prog->insnsi + i + delta;
13996 			continue;
13997 		}
13998 
13999 		if (insn->code != (BPF_JMP | BPF_CALL))
14000 			continue;
14001 		if (insn->src_reg == BPF_PSEUDO_CALL)
14002 			continue;
14003 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14004 			ret = fixup_kfunc_call(env, insn);
14005 			if (ret)
14006 				return ret;
14007 			continue;
14008 		}
14009 
14010 		if (insn->imm == BPF_FUNC_get_route_realm)
14011 			prog->dst_needed = 1;
14012 		if (insn->imm == BPF_FUNC_get_prandom_u32)
14013 			bpf_user_rnd_init_once();
14014 		if (insn->imm == BPF_FUNC_override_return)
14015 			prog->kprobe_override = 1;
14016 		if (insn->imm == BPF_FUNC_tail_call) {
14017 			/* If we tail call into other programs, we
14018 			 * cannot make any assumptions since they can
14019 			 * be replaced dynamically during runtime in
14020 			 * the program array.
14021 			 */
14022 			prog->cb_access = 1;
14023 			if (!allow_tail_call_in_subprogs(env))
14024 				prog->aux->stack_depth = MAX_BPF_STACK;
14025 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14026 
14027 			/* mark bpf_tail_call as different opcode to avoid
14028 			 * conditional branch in the interpreter for every normal
14029 			 * call and to prevent accidental JITing by JIT compiler
14030 			 * that doesn't support bpf_tail_call yet
14031 			 */
14032 			insn->imm = 0;
14033 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14034 
14035 			aux = &env->insn_aux_data[i + delta];
14036 			if (env->bpf_capable && !prog->blinding_requested &&
14037 			    prog->jit_requested &&
14038 			    !bpf_map_key_poisoned(aux) &&
14039 			    !bpf_map_ptr_poisoned(aux) &&
14040 			    !bpf_map_ptr_unpriv(aux)) {
14041 				struct bpf_jit_poke_descriptor desc = {
14042 					.reason = BPF_POKE_REASON_TAIL_CALL,
14043 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14044 					.tail_call.key = bpf_map_key_immediate(aux),
14045 					.insn_idx = i + delta,
14046 				};
14047 
14048 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14049 				if (ret < 0) {
14050 					verbose(env, "adding tail call poke descriptor failed\n");
14051 					return ret;
14052 				}
14053 
14054 				insn->imm = ret + 1;
14055 				continue;
14056 			}
14057 
14058 			if (!bpf_map_ptr_unpriv(aux))
14059 				continue;
14060 
14061 			/* instead of changing every JIT dealing with tail_call
14062 			 * emit two extra insns:
14063 			 * if (index >= max_entries) goto out;
14064 			 * index &= array->index_mask;
14065 			 * to avoid out-of-bounds cpu speculation
14066 			 */
14067 			if (bpf_map_ptr_poisoned(aux)) {
14068 				verbose(env, "tail_call abusing map_ptr\n");
14069 				return -EINVAL;
14070 			}
14071 
14072 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14073 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14074 						  map_ptr->max_entries, 2);
14075 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14076 						    container_of(map_ptr,
14077 								 struct bpf_array,
14078 								 map)->index_mask);
14079 			insn_buf[2] = *insn;
14080 			cnt = 3;
14081 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14082 			if (!new_prog)
14083 				return -ENOMEM;
14084 
14085 			delta    += cnt - 1;
14086 			env->prog = prog = new_prog;
14087 			insn      = new_prog->insnsi + i + delta;
14088 			continue;
14089 		}
14090 
14091 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14092 			/* The verifier will process callback_fn as many times as necessary
14093 			 * with different maps and the register states prepared by
14094 			 * set_timer_callback_state will be accurate.
14095 			 *
14096 			 * The following use case is valid:
14097 			 *   map1 is shared by prog1, prog2, prog3.
14098 			 *   prog1 calls bpf_timer_init for some map1 elements
14099 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14100 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14101 			 *   prog3 calls bpf_timer_start for some map1 elements.
14102 			 *     Those that were not both bpf_timer_init-ed and
14103 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14104 			 */
14105 			struct bpf_insn ld_addrs[2] = {
14106 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14107 			};
14108 
14109 			insn_buf[0] = ld_addrs[0];
14110 			insn_buf[1] = ld_addrs[1];
14111 			insn_buf[2] = *insn;
14112 			cnt = 3;
14113 
14114 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14115 			if (!new_prog)
14116 				return -ENOMEM;
14117 
14118 			delta    += cnt - 1;
14119 			env->prog = prog = new_prog;
14120 			insn      = new_prog->insnsi + i + delta;
14121 			goto patch_call_imm;
14122 		}
14123 
14124 		if (insn->imm == BPF_FUNC_task_storage_get ||
14125 		    insn->imm == BPF_FUNC_sk_storage_get ||
14126 		    insn->imm == BPF_FUNC_inode_storage_get) {
14127 			if (env->prog->aux->sleepable)
14128 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14129 			else
14130 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14131 			insn_buf[1] = *insn;
14132 			cnt = 2;
14133 
14134 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14135 			if (!new_prog)
14136 				return -ENOMEM;
14137 
14138 			delta += cnt - 1;
14139 			env->prog = prog = new_prog;
14140 			insn = new_prog->insnsi + i + delta;
14141 			goto patch_call_imm;
14142 		}
14143 
14144 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14145 		 * and other inlining handlers are currently limited to 64 bit
14146 		 * only.
14147 		 */
14148 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14149 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14150 		     insn->imm == BPF_FUNC_map_update_elem ||
14151 		     insn->imm == BPF_FUNC_map_delete_elem ||
14152 		     insn->imm == BPF_FUNC_map_push_elem   ||
14153 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14154 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14155 		     insn->imm == BPF_FUNC_redirect_map    ||
14156 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14157 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14158 			aux = &env->insn_aux_data[i + delta];
14159 			if (bpf_map_ptr_poisoned(aux))
14160 				goto patch_call_imm;
14161 
14162 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14163 			ops = map_ptr->ops;
14164 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14165 			    ops->map_gen_lookup) {
14166 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14167 				if (cnt == -EOPNOTSUPP)
14168 					goto patch_map_ops_generic;
14169 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14170 					verbose(env, "bpf verifier is misconfigured\n");
14171 					return -EINVAL;
14172 				}
14173 
14174 				new_prog = bpf_patch_insn_data(env, i + delta,
14175 							       insn_buf, cnt);
14176 				if (!new_prog)
14177 					return -ENOMEM;
14178 
14179 				delta    += cnt - 1;
14180 				env->prog = prog = new_prog;
14181 				insn      = new_prog->insnsi + i + delta;
14182 				continue;
14183 			}
14184 
14185 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14186 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14187 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14188 				     (int (*)(struct bpf_map *map, void *key))NULL));
14189 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14190 				     (int (*)(struct bpf_map *map, void *key, void *value,
14191 					      u64 flags))NULL));
14192 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14193 				     (int (*)(struct bpf_map *map, void *value,
14194 					      u64 flags))NULL));
14195 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14196 				     (int (*)(struct bpf_map *map, void *value))NULL));
14197 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14198 				     (int (*)(struct bpf_map *map, void *value))NULL));
14199 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14200 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14201 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14202 				     (int (*)(struct bpf_map *map,
14203 					      bpf_callback_t callback_fn,
14204 					      void *callback_ctx,
14205 					      u64 flags))NULL));
14206 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14207 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14208 
14209 patch_map_ops_generic:
14210 			switch (insn->imm) {
14211 			case BPF_FUNC_map_lookup_elem:
14212 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14213 				continue;
14214 			case BPF_FUNC_map_update_elem:
14215 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14216 				continue;
14217 			case BPF_FUNC_map_delete_elem:
14218 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14219 				continue;
14220 			case BPF_FUNC_map_push_elem:
14221 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14222 				continue;
14223 			case BPF_FUNC_map_pop_elem:
14224 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14225 				continue;
14226 			case BPF_FUNC_map_peek_elem:
14227 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14228 				continue;
14229 			case BPF_FUNC_redirect_map:
14230 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14231 				continue;
14232 			case BPF_FUNC_for_each_map_elem:
14233 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14234 				continue;
14235 			case BPF_FUNC_map_lookup_percpu_elem:
14236 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14237 				continue;
14238 			}
14239 
14240 			goto patch_call_imm;
14241 		}
14242 
14243 		/* Implement bpf_jiffies64 inline. */
14244 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14245 		    insn->imm == BPF_FUNC_jiffies64) {
14246 			struct bpf_insn ld_jiffies_addr[2] = {
14247 				BPF_LD_IMM64(BPF_REG_0,
14248 					     (unsigned long)&jiffies),
14249 			};
14250 
14251 			insn_buf[0] = ld_jiffies_addr[0];
14252 			insn_buf[1] = ld_jiffies_addr[1];
14253 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14254 						  BPF_REG_0, 0);
14255 			cnt = 3;
14256 
14257 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14258 						       cnt);
14259 			if (!new_prog)
14260 				return -ENOMEM;
14261 
14262 			delta    += cnt - 1;
14263 			env->prog = prog = new_prog;
14264 			insn      = new_prog->insnsi + i + delta;
14265 			continue;
14266 		}
14267 
14268 		/* Implement bpf_get_func_arg inline. */
14269 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14270 		    insn->imm == BPF_FUNC_get_func_arg) {
14271 			/* Load nr_args from ctx - 8 */
14272 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14273 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14274 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14275 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14276 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14277 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14278 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14279 			insn_buf[7] = BPF_JMP_A(1);
14280 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14281 			cnt = 9;
14282 
14283 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14284 			if (!new_prog)
14285 				return -ENOMEM;
14286 
14287 			delta    += cnt - 1;
14288 			env->prog = prog = new_prog;
14289 			insn      = new_prog->insnsi + i + delta;
14290 			continue;
14291 		}
14292 
14293 		/* Implement bpf_get_func_ret inline. */
14294 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14295 		    insn->imm == BPF_FUNC_get_func_ret) {
14296 			if (eatype == BPF_TRACE_FEXIT ||
14297 			    eatype == BPF_MODIFY_RETURN) {
14298 				/* Load nr_args from ctx - 8 */
14299 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14300 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14301 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14302 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14303 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14304 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14305 				cnt = 6;
14306 			} else {
14307 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14308 				cnt = 1;
14309 			}
14310 
14311 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14312 			if (!new_prog)
14313 				return -ENOMEM;
14314 
14315 			delta    += cnt - 1;
14316 			env->prog = prog = new_prog;
14317 			insn      = new_prog->insnsi + i + delta;
14318 			continue;
14319 		}
14320 
14321 		/* Implement get_func_arg_cnt inline. */
14322 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14323 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14324 			/* Load nr_args from ctx - 8 */
14325 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14326 
14327 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14328 			if (!new_prog)
14329 				return -ENOMEM;
14330 
14331 			env->prog = prog = new_prog;
14332 			insn      = new_prog->insnsi + i + delta;
14333 			continue;
14334 		}
14335 
14336 		/* Implement bpf_get_func_ip inline. */
14337 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14338 		    insn->imm == BPF_FUNC_get_func_ip) {
14339 			/* Load IP address from ctx - 16 */
14340 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14341 
14342 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14343 			if (!new_prog)
14344 				return -ENOMEM;
14345 
14346 			env->prog = prog = new_prog;
14347 			insn      = new_prog->insnsi + i + delta;
14348 			continue;
14349 		}
14350 
14351 patch_call_imm:
14352 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14353 		/* all functions that have prototype and verifier allowed
14354 		 * programs to call them, must be real in-kernel functions
14355 		 */
14356 		if (!fn->func) {
14357 			verbose(env,
14358 				"kernel subsystem misconfigured func %s#%d\n",
14359 				func_id_name(insn->imm), insn->imm);
14360 			return -EFAULT;
14361 		}
14362 		insn->imm = fn->func - __bpf_call_base;
14363 	}
14364 
14365 	/* Since poke tab is now finalized, publish aux to tracker. */
14366 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14367 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14368 		if (!map_ptr->ops->map_poke_track ||
14369 		    !map_ptr->ops->map_poke_untrack ||
14370 		    !map_ptr->ops->map_poke_run) {
14371 			verbose(env, "bpf verifier is misconfigured\n");
14372 			return -EINVAL;
14373 		}
14374 
14375 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14376 		if (ret < 0) {
14377 			verbose(env, "tracking tail call prog failed\n");
14378 			return ret;
14379 		}
14380 	}
14381 
14382 	sort_kfunc_descs_by_imm(env->prog);
14383 
14384 	return 0;
14385 }
14386 
14387 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14388 					int position,
14389 					s32 stack_base,
14390 					u32 callback_subprogno,
14391 					u32 *cnt)
14392 {
14393 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14394 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14395 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14396 	int reg_loop_max = BPF_REG_6;
14397 	int reg_loop_cnt = BPF_REG_7;
14398 	int reg_loop_ctx = BPF_REG_8;
14399 
14400 	struct bpf_prog *new_prog;
14401 	u32 callback_start;
14402 	u32 call_insn_offset;
14403 	s32 callback_offset;
14404 
14405 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14406 	 * be careful to modify this code in sync.
14407 	 */
14408 	struct bpf_insn insn_buf[] = {
14409 		/* Return error and jump to the end of the patch if
14410 		 * expected number of iterations is too big.
14411 		 */
14412 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14413 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14414 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14415 		/* spill R6, R7, R8 to use these as loop vars */
14416 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14417 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14418 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14419 		/* initialize loop vars */
14420 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14421 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14422 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14423 		/* loop header,
14424 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14425 		 */
14426 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14427 		/* callback call,
14428 		 * correct callback offset would be set after patching
14429 		 */
14430 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14431 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14432 		BPF_CALL_REL(0),
14433 		/* increment loop counter */
14434 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14435 		/* jump to loop header if callback returned 0 */
14436 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14437 		/* return value of bpf_loop,
14438 		 * set R0 to the number of iterations
14439 		 */
14440 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14441 		/* restore original values of R6, R7, R8 */
14442 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14443 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14444 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14445 	};
14446 
14447 	*cnt = ARRAY_SIZE(insn_buf);
14448 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14449 	if (!new_prog)
14450 		return new_prog;
14451 
14452 	/* callback start is known only after patching */
14453 	callback_start = env->subprog_info[callback_subprogno].start;
14454 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14455 	call_insn_offset = position + 12;
14456 	callback_offset = callback_start - call_insn_offset - 1;
14457 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14458 
14459 	return new_prog;
14460 }
14461 
14462 static bool is_bpf_loop_call(struct bpf_insn *insn)
14463 {
14464 	return insn->code == (BPF_JMP | BPF_CALL) &&
14465 		insn->src_reg == 0 &&
14466 		insn->imm == BPF_FUNC_loop;
14467 }
14468 
14469 /* For all sub-programs in the program (including main) check
14470  * insn_aux_data to see if there are bpf_loop calls that require
14471  * inlining. If such calls are found the calls are replaced with a
14472  * sequence of instructions produced by `inline_bpf_loop` function and
14473  * subprog stack_depth is increased by the size of 3 registers.
14474  * This stack space is used to spill values of the R6, R7, R8.  These
14475  * registers are used to store the loop bound, counter and context
14476  * variables.
14477  */
14478 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14479 {
14480 	struct bpf_subprog_info *subprogs = env->subprog_info;
14481 	int i, cur_subprog = 0, cnt, delta = 0;
14482 	struct bpf_insn *insn = env->prog->insnsi;
14483 	int insn_cnt = env->prog->len;
14484 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14485 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14486 	u16 stack_depth_extra = 0;
14487 
14488 	for (i = 0; i < insn_cnt; i++, insn++) {
14489 		struct bpf_loop_inline_state *inline_state =
14490 			&env->insn_aux_data[i + delta].loop_inline_state;
14491 
14492 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14493 			struct bpf_prog *new_prog;
14494 
14495 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14496 			new_prog = inline_bpf_loop(env,
14497 						   i + delta,
14498 						   -(stack_depth + stack_depth_extra),
14499 						   inline_state->callback_subprogno,
14500 						   &cnt);
14501 			if (!new_prog)
14502 				return -ENOMEM;
14503 
14504 			delta     += cnt - 1;
14505 			env->prog  = new_prog;
14506 			insn       = new_prog->insnsi + i + delta;
14507 		}
14508 
14509 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14510 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14511 			cur_subprog++;
14512 			stack_depth = subprogs[cur_subprog].stack_depth;
14513 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14514 			stack_depth_extra = 0;
14515 		}
14516 	}
14517 
14518 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14519 
14520 	return 0;
14521 }
14522 
14523 static void free_states(struct bpf_verifier_env *env)
14524 {
14525 	struct bpf_verifier_state_list *sl, *sln;
14526 	int i;
14527 
14528 	sl = env->free_list;
14529 	while (sl) {
14530 		sln = sl->next;
14531 		free_verifier_state(&sl->state, false);
14532 		kfree(sl);
14533 		sl = sln;
14534 	}
14535 	env->free_list = NULL;
14536 
14537 	if (!env->explored_states)
14538 		return;
14539 
14540 	for (i = 0; i < state_htab_size(env); i++) {
14541 		sl = env->explored_states[i];
14542 
14543 		while (sl) {
14544 			sln = sl->next;
14545 			free_verifier_state(&sl->state, false);
14546 			kfree(sl);
14547 			sl = sln;
14548 		}
14549 		env->explored_states[i] = NULL;
14550 	}
14551 }
14552 
14553 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14554 {
14555 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14556 	struct bpf_verifier_state *state;
14557 	struct bpf_reg_state *regs;
14558 	int ret, i;
14559 
14560 	env->prev_linfo = NULL;
14561 	env->pass_cnt++;
14562 
14563 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14564 	if (!state)
14565 		return -ENOMEM;
14566 	state->curframe = 0;
14567 	state->speculative = false;
14568 	state->branches = 1;
14569 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14570 	if (!state->frame[0]) {
14571 		kfree(state);
14572 		return -ENOMEM;
14573 	}
14574 	env->cur_state = state;
14575 	init_func_state(env, state->frame[0],
14576 			BPF_MAIN_FUNC /* callsite */,
14577 			0 /* frameno */,
14578 			subprog);
14579 
14580 	regs = state->frame[state->curframe]->regs;
14581 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14582 		ret = btf_prepare_func_args(env, subprog, regs);
14583 		if (ret)
14584 			goto out;
14585 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14586 			if (regs[i].type == PTR_TO_CTX)
14587 				mark_reg_known_zero(env, regs, i);
14588 			else if (regs[i].type == SCALAR_VALUE)
14589 				mark_reg_unknown(env, regs, i);
14590 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14591 				const u32 mem_size = regs[i].mem_size;
14592 
14593 				mark_reg_known_zero(env, regs, i);
14594 				regs[i].mem_size = mem_size;
14595 				regs[i].id = ++env->id_gen;
14596 			}
14597 		}
14598 	} else {
14599 		/* 1st arg to a function */
14600 		regs[BPF_REG_1].type = PTR_TO_CTX;
14601 		mark_reg_known_zero(env, regs, BPF_REG_1);
14602 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14603 		if (ret == -EFAULT)
14604 			/* unlikely verifier bug. abort.
14605 			 * ret == 0 and ret < 0 are sadly acceptable for
14606 			 * main() function due to backward compatibility.
14607 			 * Like socket filter program may be written as:
14608 			 * int bpf_prog(struct pt_regs *ctx)
14609 			 * and never dereference that ctx in the program.
14610 			 * 'struct pt_regs' is a type mismatch for socket
14611 			 * filter that should be using 'struct __sk_buff'.
14612 			 */
14613 			goto out;
14614 	}
14615 
14616 	ret = do_check(env);
14617 out:
14618 	/* check for NULL is necessary, since cur_state can be freed inside
14619 	 * do_check() under memory pressure.
14620 	 */
14621 	if (env->cur_state) {
14622 		free_verifier_state(env->cur_state, true);
14623 		env->cur_state = NULL;
14624 	}
14625 	while (!pop_stack(env, NULL, NULL, false));
14626 	if (!ret && pop_log)
14627 		bpf_vlog_reset(&env->log, 0);
14628 	free_states(env);
14629 	return ret;
14630 }
14631 
14632 /* Verify all global functions in a BPF program one by one based on their BTF.
14633  * All global functions must pass verification. Otherwise the whole program is rejected.
14634  * Consider:
14635  * int bar(int);
14636  * int foo(int f)
14637  * {
14638  *    return bar(f);
14639  * }
14640  * int bar(int b)
14641  * {
14642  *    ...
14643  * }
14644  * foo() will be verified first for R1=any_scalar_value. During verification it
14645  * will be assumed that bar() already verified successfully and call to bar()
14646  * from foo() will be checked for type match only. Later bar() will be verified
14647  * independently to check that it's safe for R1=any_scalar_value.
14648  */
14649 static int do_check_subprogs(struct bpf_verifier_env *env)
14650 {
14651 	struct bpf_prog_aux *aux = env->prog->aux;
14652 	int i, ret;
14653 
14654 	if (!aux->func_info)
14655 		return 0;
14656 
14657 	for (i = 1; i < env->subprog_cnt; i++) {
14658 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14659 			continue;
14660 		env->insn_idx = env->subprog_info[i].start;
14661 		WARN_ON_ONCE(env->insn_idx == 0);
14662 		ret = do_check_common(env, i);
14663 		if (ret) {
14664 			return ret;
14665 		} else if (env->log.level & BPF_LOG_LEVEL) {
14666 			verbose(env,
14667 				"Func#%d is safe for any args that match its prototype\n",
14668 				i);
14669 		}
14670 	}
14671 	return 0;
14672 }
14673 
14674 static int do_check_main(struct bpf_verifier_env *env)
14675 {
14676 	int ret;
14677 
14678 	env->insn_idx = 0;
14679 	ret = do_check_common(env, 0);
14680 	if (!ret)
14681 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14682 	return ret;
14683 }
14684 
14685 
14686 static void print_verification_stats(struct bpf_verifier_env *env)
14687 {
14688 	int i;
14689 
14690 	if (env->log.level & BPF_LOG_STATS) {
14691 		verbose(env, "verification time %lld usec\n",
14692 			div_u64(env->verification_time, 1000));
14693 		verbose(env, "stack depth ");
14694 		for (i = 0; i < env->subprog_cnt; i++) {
14695 			u32 depth = env->subprog_info[i].stack_depth;
14696 
14697 			verbose(env, "%d", depth);
14698 			if (i + 1 < env->subprog_cnt)
14699 				verbose(env, "+");
14700 		}
14701 		verbose(env, "\n");
14702 	}
14703 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14704 		"total_states %d peak_states %d mark_read %d\n",
14705 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14706 		env->max_states_per_insn, env->total_states,
14707 		env->peak_states, env->longest_mark_read_walk);
14708 }
14709 
14710 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14711 {
14712 	const struct btf_type *t, *func_proto;
14713 	const struct bpf_struct_ops *st_ops;
14714 	const struct btf_member *member;
14715 	struct bpf_prog *prog = env->prog;
14716 	u32 btf_id, member_idx;
14717 	const char *mname;
14718 
14719 	if (!prog->gpl_compatible) {
14720 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14721 		return -EINVAL;
14722 	}
14723 
14724 	btf_id = prog->aux->attach_btf_id;
14725 	st_ops = bpf_struct_ops_find(btf_id);
14726 	if (!st_ops) {
14727 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14728 			btf_id);
14729 		return -ENOTSUPP;
14730 	}
14731 
14732 	t = st_ops->type;
14733 	member_idx = prog->expected_attach_type;
14734 	if (member_idx >= btf_type_vlen(t)) {
14735 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14736 			member_idx, st_ops->name);
14737 		return -EINVAL;
14738 	}
14739 
14740 	member = &btf_type_member(t)[member_idx];
14741 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14742 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14743 					       NULL);
14744 	if (!func_proto) {
14745 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14746 			mname, member_idx, st_ops->name);
14747 		return -EINVAL;
14748 	}
14749 
14750 	if (st_ops->check_member) {
14751 		int err = st_ops->check_member(t, member);
14752 
14753 		if (err) {
14754 			verbose(env, "attach to unsupported member %s of struct %s\n",
14755 				mname, st_ops->name);
14756 			return err;
14757 		}
14758 	}
14759 
14760 	prog->aux->attach_func_proto = func_proto;
14761 	prog->aux->attach_func_name = mname;
14762 	env->ops = st_ops->verifier_ops;
14763 
14764 	return 0;
14765 }
14766 #define SECURITY_PREFIX "security_"
14767 
14768 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14769 {
14770 	if (within_error_injection_list(addr) ||
14771 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14772 		return 0;
14773 
14774 	return -EINVAL;
14775 }
14776 
14777 /* list of non-sleepable functions that are otherwise on
14778  * ALLOW_ERROR_INJECTION list
14779  */
14780 BTF_SET_START(btf_non_sleepable_error_inject)
14781 /* Three functions below can be called from sleepable and non-sleepable context.
14782  * Assume non-sleepable from bpf safety point of view.
14783  */
14784 BTF_ID(func, __filemap_add_folio)
14785 BTF_ID(func, should_fail_alloc_page)
14786 BTF_ID(func, should_failslab)
14787 BTF_SET_END(btf_non_sleepable_error_inject)
14788 
14789 static int check_non_sleepable_error_inject(u32 btf_id)
14790 {
14791 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14792 }
14793 
14794 int bpf_check_attach_target(struct bpf_verifier_log *log,
14795 			    const struct bpf_prog *prog,
14796 			    const struct bpf_prog *tgt_prog,
14797 			    u32 btf_id,
14798 			    struct bpf_attach_target_info *tgt_info)
14799 {
14800 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14801 	const char prefix[] = "btf_trace_";
14802 	int ret = 0, subprog = -1, i;
14803 	const struct btf_type *t;
14804 	bool conservative = true;
14805 	const char *tname;
14806 	struct btf *btf;
14807 	long addr = 0;
14808 
14809 	if (!btf_id) {
14810 		bpf_log(log, "Tracing programs must provide btf_id\n");
14811 		return -EINVAL;
14812 	}
14813 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14814 	if (!btf) {
14815 		bpf_log(log,
14816 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14817 		return -EINVAL;
14818 	}
14819 	t = btf_type_by_id(btf, btf_id);
14820 	if (!t) {
14821 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14822 		return -EINVAL;
14823 	}
14824 	tname = btf_name_by_offset(btf, t->name_off);
14825 	if (!tname) {
14826 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14827 		return -EINVAL;
14828 	}
14829 	if (tgt_prog) {
14830 		struct bpf_prog_aux *aux = tgt_prog->aux;
14831 
14832 		for (i = 0; i < aux->func_info_cnt; i++)
14833 			if (aux->func_info[i].type_id == btf_id) {
14834 				subprog = i;
14835 				break;
14836 			}
14837 		if (subprog == -1) {
14838 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
14839 			return -EINVAL;
14840 		}
14841 		conservative = aux->func_info_aux[subprog].unreliable;
14842 		if (prog_extension) {
14843 			if (conservative) {
14844 				bpf_log(log,
14845 					"Cannot replace static functions\n");
14846 				return -EINVAL;
14847 			}
14848 			if (!prog->jit_requested) {
14849 				bpf_log(log,
14850 					"Extension programs should be JITed\n");
14851 				return -EINVAL;
14852 			}
14853 		}
14854 		if (!tgt_prog->jited) {
14855 			bpf_log(log, "Can attach to only JITed progs\n");
14856 			return -EINVAL;
14857 		}
14858 		if (tgt_prog->type == prog->type) {
14859 			/* Cannot fentry/fexit another fentry/fexit program.
14860 			 * Cannot attach program extension to another extension.
14861 			 * It's ok to attach fentry/fexit to extension program.
14862 			 */
14863 			bpf_log(log, "Cannot recursively attach\n");
14864 			return -EINVAL;
14865 		}
14866 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14867 		    prog_extension &&
14868 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14869 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14870 			/* Program extensions can extend all program types
14871 			 * except fentry/fexit. The reason is the following.
14872 			 * The fentry/fexit programs are used for performance
14873 			 * analysis, stats and can be attached to any program
14874 			 * type except themselves. When extension program is
14875 			 * replacing XDP function it is necessary to allow
14876 			 * performance analysis of all functions. Both original
14877 			 * XDP program and its program extension. Hence
14878 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14879 			 * allowed. If extending of fentry/fexit was allowed it
14880 			 * would be possible to create long call chain
14881 			 * fentry->extension->fentry->extension beyond
14882 			 * reasonable stack size. Hence extending fentry is not
14883 			 * allowed.
14884 			 */
14885 			bpf_log(log, "Cannot extend fentry/fexit\n");
14886 			return -EINVAL;
14887 		}
14888 	} else {
14889 		if (prog_extension) {
14890 			bpf_log(log, "Cannot replace kernel functions\n");
14891 			return -EINVAL;
14892 		}
14893 	}
14894 
14895 	switch (prog->expected_attach_type) {
14896 	case BPF_TRACE_RAW_TP:
14897 		if (tgt_prog) {
14898 			bpf_log(log,
14899 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14900 			return -EINVAL;
14901 		}
14902 		if (!btf_type_is_typedef(t)) {
14903 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
14904 				btf_id);
14905 			return -EINVAL;
14906 		}
14907 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14908 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14909 				btf_id, tname);
14910 			return -EINVAL;
14911 		}
14912 		tname += sizeof(prefix) - 1;
14913 		t = btf_type_by_id(btf, t->type);
14914 		if (!btf_type_is_ptr(t))
14915 			/* should never happen in valid vmlinux build */
14916 			return -EINVAL;
14917 		t = btf_type_by_id(btf, t->type);
14918 		if (!btf_type_is_func_proto(t))
14919 			/* should never happen in valid vmlinux build */
14920 			return -EINVAL;
14921 
14922 		break;
14923 	case BPF_TRACE_ITER:
14924 		if (!btf_type_is_func(t)) {
14925 			bpf_log(log, "attach_btf_id %u is not a function\n",
14926 				btf_id);
14927 			return -EINVAL;
14928 		}
14929 		t = btf_type_by_id(btf, t->type);
14930 		if (!btf_type_is_func_proto(t))
14931 			return -EINVAL;
14932 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14933 		if (ret)
14934 			return ret;
14935 		break;
14936 	default:
14937 		if (!prog_extension)
14938 			return -EINVAL;
14939 		fallthrough;
14940 	case BPF_MODIFY_RETURN:
14941 	case BPF_LSM_MAC:
14942 	case BPF_LSM_CGROUP:
14943 	case BPF_TRACE_FENTRY:
14944 	case BPF_TRACE_FEXIT:
14945 		if (!btf_type_is_func(t)) {
14946 			bpf_log(log, "attach_btf_id %u is not a function\n",
14947 				btf_id);
14948 			return -EINVAL;
14949 		}
14950 		if (prog_extension &&
14951 		    btf_check_type_match(log, prog, btf, t))
14952 			return -EINVAL;
14953 		t = btf_type_by_id(btf, t->type);
14954 		if (!btf_type_is_func_proto(t))
14955 			return -EINVAL;
14956 
14957 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14958 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14959 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14960 			return -EINVAL;
14961 
14962 		if (tgt_prog && conservative)
14963 			t = NULL;
14964 
14965 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14966 		if (ret < 0)
14967 			return ret;
14968 
14969 		if (tgt_prog) {
14970 			if (subprog == 0)
14971 				addr = (long) tgt_prog->bpf_func;
14972 			else
14973 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14974 		} else {
14975 			addr = kallsyms_lookup_name(tname);
14976 			if (!addr) {
14977 				bpf_log(log,
14978 					"The address of function %s cannot be found\n",
14979 					tname);
14980 				return -ENOENT;
14981 			}
14982 		}
14983 
14984 		if (prog->aux->sleepable) {
14985 			ret = -EINVAL;
14986 			switch (prog->type) {
14987 			case BPF_PROG_TYPE_TRACING:
14988 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
14989 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14990 				 */
14991 				if (!check_non_sleepable_error_inject(btf_id) &&
14992 				    within_error_injection_list(addr))
14993 					ret = 0;
14994 				break;
14995 			case BPF_PROG_TYPE_LSM:
14996 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
14997 				 * Only some of them are sleepable.
14998 				 */
14999 				if (bpf_lsm_is_sleepable_hook(btf_id))
15000 					ret = 0;
15001 				break;
15002 			default:
15003 				break;
15004 			}
15005 			if (ret) {
15006 				bpf_log(log, "%s is not sleepable\n", tname);
15007 				return ret;
15008 			}
15009 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15010 			if (tgt_prog) {
15011 				bpf_log(log, "can't modify return codes of BPF programs\n");
15012 				return -EINVAL;
15013 			}
15014 			ret = check_attach_modify_return(addr, tname);
15015 			if (ret) {
15016 				bpf_log(log, "%s() is not modifiable\n", tname);
15017 				return ret;
15018 			}
15019 		}
15020 
15021 		break;
15022 	}
15023 	tgt_info->tgt_addr = addr;
15024 	tgt_info->tgt_name = tname;
15025 	tgt_info->tgt_type = t;
15026 	return 0;
15027 }
15028 
15029 BTF_SET_START(btf_id_deny)
15030 BTF_ID_UNUSED
15031 #ifdef CONFIG_SMP
15032 BTF_ID(func, migrate_disable)
15033 BTF_ID(func, migrate_enable)
15034 #endif
15035 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15036 BTF_ID(func, rcu_read_unlock_strict)
15037 #endif
15038 BTF_SET_END(btf_id_deny)
15039 
15040 static int check_attach_btf_id(struct bpf_verifier_env *env)
15041 {
15042 	struct bpf_prog *prog = env->prog;
15043 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15044 	struct bpf_attach_target_info tgt_info = {};
15045 	u32 btf_id = prog->aux->attach_btf_id;
15046 	struct bpf_trampoline *tr;
15047 	int ret;
15048 	u64 key;
15049 
15050 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15051 		if (prog->aux->sleepable)
15052 			/* attach_btf_id checked to be zero already */
15053 			return 0;
15054 		verbose(env, "Syscall programs can only be sleepable\n");
15055 		return -EINVAL;
15056 	}
15057 
15058 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15059 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15060 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15061 		return -EINVAL;
15062 	}
15063 
15064 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15065 		return check_struct_ops_btf_id(env);
15066 
15067 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15068 	    prog->type != BPF_PROG_TYPE_LSM &&
15069 	    prog->type != BPF_PROG_TYPE_EXT)
15070 		return 0;
15071 
15072 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15073 	if (ret)
15074 		return ret;
15075 
15076 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15077 		/* to make freplace equivalent to their targets, they need to
15078 		 * inherit env->ops and expected_attach_type for the rest of the
15079 		 * verification
15080 		 */
15081 		env->ops = bpf_verifier_ops[tgt_prog->type];
15082 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15083 	}
15084 
15085 	/* store info about the attachment target that will be used later */
15086 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15087 	prog->aux->attach_func_name = tgt_info.tgt_name;
15088 
15089 	if (tgt_prog) {
15090 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15091 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15092 	}
15093 
15094 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15095 		prog->aux->attach_btf_trace = true;
15096 		return 0;
15097 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15098 		if (!bpf_iter_prog_supported(prog))
15099 			return -EINVAL;
15100 		return 0;
15101 	}
15102 
15103 	if (prog->type == BPF_PROG_TYPE_LSM) {
15104 		ret = bpf_lsm_verify_prog(&env->log, prog);
15105 		if (ret < 0)
15106 			return ret;
15107 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15108 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15109 		return -EINVAL;
15110 	}
15111 
15112 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15113 	tr = bpf_trampoline_get(key, &tgt_info);
15114 	if (!tr)
15115 		return -ENOMEM;
15116 
15117 	prog->aux->dst_trampoline = tr;
15118 	return 0;
15119 }
15120 
15121 struct btf *bpf_get_btf_vmlinux(void)
15122 {
15123 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15124 		mutex_lock(&bpf_verifier_lock);
15125 		if (!btf_vmlinux)
15126 			btf_vmlinux = btf_parse_vmlinux();
15127 		mutex_unlock(&bpf_verifier_lock);
15128 	}
15129 	return btf_vmlinux;
15130 }
15131 
15132 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15133 {
15134 	u64 start_time = ktime_get_ns();
15135 	struct bpf_verifier_env *env;
15136 	struct bpf_verifier_log *log;
15137 	int i, len, ret = -EINVAL;
15138 	bool is_priv;
15139 
15140 	/* no program is valid */
15141 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15142 		return -EINVAL;
15143 
15144 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15145 	 * allocate/free it every time bpf_check() is called
15146 	 */
15147 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15148 	if (!env)
15149 		return -ENOMEM;
15150 	log = &env->log;
15151 
15152 	len = (*prog)->len;
15153 	env->insn_aux_data =
15154 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15155 	ret = -ENOMEM;
15156 	if (!env->insn_aux_data)
15157 		goto err_free_env;
15158 	for (i = 0; i < len; i++)
15159 		env->insn_aux_data[i].orig_idx = i;
15160 	env->prog = *prog;
15161 	env->ops = bpf_verifier_ops[env->prog->type];
15162 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15163 	is_priv = bpf_capable();
15164 
15165 	bpf_get_btf_vmlinux();
15166 
15167 	/* grab the mutex to protect few globals used by verifier */
15168 	if (!is_priv)
15169 		mutex_lock(&bpf_verifier_lock);
15170 
15171 	if (attr->log_level || attr->log_buf || attr->log_size) {
15172 		/* user requested verbose verifier output
15173 		 * and supplied buffer to store the verification trace
15174 		 */
15175 		log->level = attr->log_level;
15176 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15177 		log->len_total = attr->log_size;
15178 
15179 		/* log attributes have to be sane */
15180 		if (!bpf_verifier_log_attr_valid(log)) {
15181 			ret = -EINVAL;
15182 			goto err_unlock;
15183 		}
15184 	}
15185 
15186 	mark_verifier_state_clean(env);
15187 
15188 	if (IS_ERR(btf_vmlinux)) {
15189 		/* Either gcc or pahole or kernel are broken. */
15190 		verbose(env, "in-kernel BTF is malformed\n");
15191 		ret = PTR_ERR(btf_vmlinux);
15192 		goto skip_full_check;
15193 	}
15194 
15195 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15196 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15197 		env->strict_alignment = true;
15198 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15199 		env->strict_alignment = false;
15200 
15201 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15202 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15203 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15204 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15205 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15206 	env->bpf_capable = bpf_capable();
15207 
15208 	if (is_priv)
15209 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15210 
15211 	env->explored_states = kvcalloc(state_htab_size(env),
15212 				       sizeof(struct bpf_verifier_state_list *),
15213 				       GFP_USER);
15214 	ret = -ENOMEM;
15215 	if (!env->explored_states)
15216 		goto skip_full_check;
15217 
15218 	ret = add_subprog_and_kfunc(env);
15219 	if (ret < 0)
15220 		goto skip_full_check;
15221 
15222 	ret = check_subprogs(env);
15223 	if (ret < 0)
15224 		goto skip_full_check;
15225 
15226 	ret = check_btf_info(env, attr, uattr);
15227 	if (ret < 0)
15228 		goto skip_full_check;
15229 
15230 	ret = check_attach_btf_id(env);
15231 	if (ret)
15232 		goto skip_full_check;
15233 
15234 	ret = resolve_pseudo_ldimm64(env);
15235 	if (ret < 0)
15236 		goto skip_full_check;
15237 
15238 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15239 		ret = bpf_prog_offload_verifier_prep(env->prog);
15240 		if (ret)
15241 			goto skip_full_check;
15242 	}
15243 
15244 	ret = check_cfg(env);
15245 	if (ret < 0)
15246 		goto skip_full_check;
15247 
15248 	ret = do_check_subprogs(env);
15249 	ret = ret ?: do_check_main(env);
15250 
15251 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15252 		ret = bpf_prog_offload_finalize(env);
15253 
15254 skip_full_check:
15255 	kvfree(env->explored_states);
15256 
15257 	if (ret == 0)
15258 		ret = check_max_stack_depth(env);
15259 
15260 	/* instruction rewrites happen after this point */
15261 	if (ret == 0)
15262 		ret = optimize_bpf_loop(env);
15263 
15264 	if (is_priv) {
15265 		if (ret == 0)
15266 			opt_hard_wire_dead_code_branches(env);
15267 		if (ret == 0)
15268 			ret = opt_remove_dead_code(env);
15269 		if (ret == 0)
15270 			ret = opt_remove_nops(env);
15271 	} else {
15272 		if (ret == 0)
15273 			sanitize_dead_code(env);
15274 	}
15275 
15276 	if (ret == 0)
15277 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15278 		ret = convert_ctx_accesses(env);
15279 
15280 	if (ret == 0)
15281 		ret = do_misc_fixups(env);
15282 
15283 	/* do 32-bit optimization after insn patching has done so those patched
15284 	 * insns could be handled correctly.
15285 	 */
15286 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15287 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15288 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15289 								     : false;
15290 	}
15291 
15292 	if (ret == 0)
15293 		ret = fixup_call_args(env);
15294 
15295 	env->verification_time = ktime_get_ns() - start_time;
15296 	print_verification_stats(env);
15297 	env->prog->aux->verified_insns = env->insn_processed;
15298 
15299 	if (log->level && bpf_verifier_log_full(log))
15300 		ret = -ENOSPC;
15301 	if (log->level && !log->ubuf) {
15302 		ret = -EFAULT;
15303 		goto err_release_maps;
15304 	}
15305 
15306 	if (ret)
15307 		goto err_release_maps;
15308 
15309 	if (env->used_map_cnt) {
15310 		/* if program passed verifier, update used_maps in bpf_prog_info */
15311 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15312 							  sizeof(env->used_maps[0]),
15313 							  GFP_KERNEL);
15314 
15315 		if (!env->prog->aux->used_maps) {
15316 			ret = -ENOMEM;
15317 			goto err_release_maps;
15318 		}
15319 
15320 		memcpy(env->prog->aux->used_maps, env->used_maps,
15321 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15322 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15323 	}
15324 	if (env->used_btf_cnt) {
15325 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15326 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15327 							  sizeof(env->used_btfs[0]),
15328 							  GFP_KERNEL);
15329 		if (!env->prog->aux->used_btfs) {
15330 			ret = -ENOMEM;
15331 			goto err_release_maps;
15332 		}
15333 
15334 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15335 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15336 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15337 	}
15338 	if (env->used_map_cnt || env->used_btf_cnt) {
15339 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15340 		 * bpf_ld_imm64 instructions
15341 		 */
15342 		convert_pseudo_ld_imm64(env);
15343 	}
15344 
15345 	adjust_btf_func(env);
15346 
15347 err_release_maps:
15348 	if (!env->prog->aux->used_maps)
15349 		/* if we didn't copy map pointers into bpf_prog_info, release
15350 		 * them now. Otherwise free_used_maps() will release them.
15351 		 */
15352 		release_maps(env);
15353 	if (!env->prog->aux->used_btfs)
15354 		release_btfs(env);
15355 
15356 	/* extension progs temporarily inherit the attach_type of their targets
15357 	   for verification purposes, so set it back to zero before returning
15358 	 */
15359 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15360 		env->prog->expected_attach_type = 0;
15361 
15362 	*prog = env->prog;
15363 err_unlock:
15364 	if (!is_priv)
15365 		mutex_unlock(&bpf_verifier_lock);
15366 	vfree(env->insn_aux_data);
15367 err_free_env:
15368 	kfree(env);
15369 	return ret;
15370 }
15371