xref: /linux/kernel/bpf/verifier.c (revision 1ab3d4175775378106965ce32a07248675680c2c)
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 		err = mark_chain_precision(env, regno);
6076 		if (err)
6077 			return err;
6078 		break;
6079 	case ARG_PTR_TO_INT:
6080 	case ARG_PTR_TO_LONG:
6081 	{
6082 		int size = int_ptr_type_to_size(arg_type);
6083 
6084 		err = check_helper_mem_access(env, regno, size, false, meta);
6085 		if (err)
6086 			return err;
6087 		err = check_ptr_alignment(env, reg, 0, size, true);
6088 		break;
6089 	}
6090 	case ARG_PTR_TO_CONST_STR:
6091 	{
6092 		struct bpf_map *map = reg->map_ptr;
6093 		int map_off;
6094 		u64 map_addr;
6095 		char *str_ptr;
6096 
6097 		if (!bpf_map_is_rdonly(map)) {
6098 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6099 			return -EACCES;
6100 		}
6101 
6102 		if (!tnum_is_const(reg->var_off)) {
6103 			verbose(env, "R%d is not a constant address'\n", regno);
6104 			return -EACCES;
6105 		}
6106 
6107 		if (!map->ops->map_direct_value_addr) {
6108 			verbose(env, "no direct value access support for this map type\n");
6109 			return -EACCES;
6110 		}
6111 
6112 		err = check_map_access(env, regno, reg->off,
6113 				       map->value_size - reg->off, false,
6114 				       ACCESS_HELPER);
6115 		if (err)
6116 			return err;
6117 
6118 		map_off = reg->off + reg->var_off.value;
6119 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6120 		if (err) {
6121 			verbose(env, "direct value access on string failed\n");
6122 			return err;
6123 		}
6124 
6125 		str_ptr = (char *)(long)(map_addr);
6126 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6127 			verbose(env, "string is not zero-terminated\n");
6128 			return -EINVAL;
6129 		}
6130 		break;
6131 	}
6132 	case ARG_PTR_TO_KPTR:
6133 		if (process_kptr_func(env, regno, meta))
6134 			return -EACCES;
6135 		break;
6136 	}
6137 
6138 	return err;
6139 }
6140 
6141 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6142 {
6143 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6144 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6145 
6146 	if (func_id != BPF_FUNC_map_update_elem)
6147 		return false;
6148 
6149 	/* It's not possible to get access to a locked struct sock in these
6150 	 * contexts, so updating is safe.
6151 	 */
6152 	switch (type) {
6153 	case BPF_PROG_TYPE_TRACING:
6154 		if (eatype == BPF_TRACE_ITER)
6155 			return true;
6156 		break;
6157 	case BPF_PROG_TYPE_SOCKET_FILTER:
6158 	case BPF_PROG_TYPE_SCHED_CLS:
6159 	case BPF_PROG_TYPE_SCHED_ACT:
6160 	case BPF_PROG_TYPE_XDP:
6161 	case BPF_PROG_TYPE_SK_REUSEPORT:
6162 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6163 	case BPF_PROG_TYPE_SK_LOOKUP:
6164 		return true;
6165 	default:
6166 		break;
6167 	}
6168 
6169 	verbose(env, "cannot update sockmap in this context\n");
6170 	return false;
6171 }
6172 
6173 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6174 {
6175 	return env->prog->jit_requested &&
6176 	       bpf_jit_supports_subprog_tailcalls();
6177 }
6178 
6179 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6180 					struct bpf_map *map, int func_id)
6181 {
6182 	if (!map)
6183 		return 0;
6184 
6185 	/* We need a two way check, first is from map perspective ... */
6186 	switch (map->map_type) {
6187 	case BPF_MAP_TYPE_PROG_ARRAY:
6188 		if (func_id != BPF_FUNC_tail_call)
6189 			goto error;
6190 		break;
6191 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6192 		if (func_id != BPF_FUNC_perf_event_read &&
6193 		    func_id != BPF_FUNC_perf_event_output &&
6194 		    func_id != BPF_FUNC_skb_output &&
6195 		    func_id != BPF_FUNC_perf_event_read_value &&
6196 		    func_id != BPF_FUNC_xdp_output)
6197 			goto error;
6198 		break;
6199 	case BPF_MAP_TYPE_RINGBUF:
6200 		if (func_id != BPF_FUNC_ringbuf_output &&
6201 		    func_id != BPF_FUNC_ringbuf_reserve &&
6202 		    func_id != BPF_FUNC_ringbuf_query &&
6203 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6204 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6205 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6206 			goto error;
6207 		break;
6208 	case BPF_MAP_TYPE_STACK_TRACE:
6209 		if (func_id != BPF_FUNC_get_stackid)
6210 			goto error;
6211 		break;
6212 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6213 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6214 		    func_id != BPF_FUNC_current_task_under_cgroup)
6215 			goto error;
6216 		break;
6217 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6218 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6219 		if (func_id != BPF_FUNC_get_local_storage)
6220 			goto error;
6221 		break;
6222 	case BPF_MAP_TYPE_DEVMAP:
6223 	case BPF_MAP_TYPE_DEVMAP_HASH:
6224 		if (func_id != BPF_FUNC_redirect_map &&
6225 		    func_id != BPF_FUNC_map_lookup_elem)
6226 			goto error;
6227 		break;
6228 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6229 	 * appear.
6230 	 */
6231 	case BPF_MAP_TYPE_CPUMAP:
6232 		if (func_id != BPF_FUNC_redirect_map)
6233 			goto error;
6234 		break;
6235 	case BPF_MAP_TYPE_XSKMAP:
6236 		if (func_id != BPF_FUNC_redirect_map &&
6237 		    func_id != BPF_FUNC_map_lookup_elem)
6238 			goto error;
6239 		break;
6240 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6241 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6242 		if (func_id != BPF_FUNC_map_lookup_elem)
6243 			goto error;
6244 		break;
6245 	case BPF_MAP_TYPE_SOCKMAP:
6246 		if (func_id != BPF_FUNC_sk_redirect_map &&
6247 		    func_id != BPF_FUNC_sock_map_update &&
6248 		    func_id != BPF_FUNC_map_delete_elem &&
6249 		    func_id != BPF_FUNC_msg_redirect_map &&
6250 		    func_id != BPF_FUNC_sk_select_reuseport &&
6251 		    func_id != BPF_FUNC_map_lookup_elem &&
6252 		    !may_update_sockmap(env, func_id))
6253 			goto error;
6254 		break;
6255 	case BPF_MAP_TYPE_SOCKHASH:
6256 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6257 		    func_id != BPF_FUNC_sock_hash_update &&
6258 		    func_id != BPF_FUNC_map_delete_elem &&
6259 		    func_id != BPF_FUNC_msg_redirect_hash &&
6260 		    func_id != BPF_FUNC_sk_select_reuseport &&
6261 		    func_id != BPF_FUNC_map_lookup_elem &&
6262 		    !may_update_sockmap(env, func_id))
6263 			goto error;
6264 		break;
6265 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6266 		if (func_id != BPF_FUNC_sk_select_reuseport)
6267 			goto error;
6268 		break;
6269 	case BPF_MAP_TYPE_QUEUE:
6270 	case BPF_MAP_TYPE_STACK:
6271 		if (func_id != BPF_FUNC_map_peek_elem &&
6272 		    func_id != BPF_FUNC_map_pop_elem &&
6273 		    func_id != BPF_FUNC_map_push_elem)
6274 			goto error;
6275 		break;
6276 	case BPF_MAP_TYPE_SK_STORAGE:
6277 		if (func_id != BPF_FUNC_sk_storage_get &&
6278 		    func_id != BPF_FUNC_sk_storage_delete)
6279 			goto error;
6280 		break;
6281 	case BPF_MAP_TYPE_INODE_STORAGE:
6282 		if (func_id != BPF_FUNC_inode_storage_get &&
6283 		    func_id != BPF_FUNC_inode_storage_delete)
6284 			goto error;
6285 		break;
6286 	case BPF_MAP_TYPE_TASK_STORAGE:
6287 		if (func_id != BPF_FUNC_task_storage_get &&
6288 		    func_id != BPF_FUNC_task_storage_delete)
6289 			goto error;
6290 		break;
6291 	case BPF_MAP_TYPE_BLOOM_FILTER:
6292 		if (func_id != BPF_FUNC_map_peek_elem &&
6293 		    func_id != BPF_FUNC_map_push_elem)
6294 			goto error;
6295 		break;
6296 	default:
6297 		break;
6298 	}
6299 
6300 	/* ... and second from the function itself. */
6301 	switch (func_id) {
6302 	case BPF_FUNC_tail_call:
6303 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6304 			goto error;
6305 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6306 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6307 			return -EINVAL;
6308 		}
6309 		break;
6310 	case BPF_FUNC_perf_event_read:
6311 	case BPF_FUNC_perf_event_output:
6312 	case BPF_FUNC_perf_event_read_value:
6313 	case BPF_FUNC_skb_output:
6314 	case BPF_FUNC_xdp_output:
6315 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6316 			goto error;
6317 		break;
6318 	case BPF_FUNC_ringbuf_output:
6319 	case BPF_FUNC_ringbuf_reserve:
6320 	case BPF_FUNC_ringbuf_query:
6321 	case BPF_FUNC_ringbuf_reserve_dynptr:
6322 	case BPF_FUNC_ringbuf_submit_dynptr:
6323 	case BPF_FUNC_ringbuf_discard_dynptr:
6324 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6325 			goto error;
6326 		break;
6327 	case BPF_FUNC_get_stackid:
6328 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6329 			goto error;
6330 		break;
6331 	case BPF_FUNC_current_task_under_cgroup:
6332 	case BPF_FUNC_skb_under_cgroup:
6333 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6334 			goto error;
6335 		break;
6336 	case BPF_FUNC_redirect_map:
6337 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6338 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6339 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6340 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6341 			goto error;
6342 		break;
6343 	case BPF_FUNC_sk_redirect_map:
6344 	case BPF_FUNC_msg_redirect_map:
6345 	case BPF_FUNC_sock_map_update:
6346 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6347 			goto error;
6348 		break;
6349 	case BPF_FUNC_sk_redirect_hash:
6350 	case BPF_FUNC_msg_redirect_hash:
6351 	case BPF_FUNC_sock_hash_update:
6352 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6353 			goto error;
6354 		break;
6355 	case BPF_FUNC_get_local_storage:
6356 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6357 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6358 			goto error;
6359 		break;
6360 	case BPF_FUNC_sk_select_reuseport:
6361 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6362 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6363 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6364 			goto error;
6365 		break;
6366 	case BPF_FUNC_map_pop_elem:
6367 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6368 		    map->map_type != BPF_MAP_TYPE_STACK)
6369 			goto error;
6370 		break;
6371 	case BPF_FUNC_map_peek_elem:
6372 	case BPF_FUNC_map_push_elem:
6373 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6374 		    map->map_type != BPF_MAP_TYPE_STACK &&
6375 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6376 			goto error;
6377 		break;
6378 	case BPF_FUNC_map_lookup_percpu_elem:
6379 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6380 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6381 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6382 			goto error;
6383 		break;
6384 	case BPF_FUNC_sk_storage_get:
6385 	case BPF_FUNC_sk_storage_delete:
6386 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6387 			goto error;
6388 		break;
6389 	case BPF_FUNC_inode_storage_get:
6390 	case BPF_FUNC_inode_storage_delete:
6391 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6392 			goto error;
6393 		break;
6394 	case BPF_FUNC_task_storage_get:
6395 	case BPF_FUNC_task_storage_delete:
6396 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6397 			goto error;
6398 		break;
6399 	default:
6400 		break;
6401 	}
6402 
6403 	return 0;
6404 error:
6405 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6406 		map->map_type, func_id_name(func_id), func_id);
6407 	return -EINVAL;
6408 }
6409 
6410 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6411 {
6412 	int count = 0;
6413 
6414 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6415 		count++;
6416 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6417 		count++;
6418 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6419 		count++;
6420 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6421 		count++;
6422 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6423 		count++;
6424 
6425 	/* We only support one arg being in raw mode at the moment,
6426 	 * which is sufficient for the helper functions we have
6427 	 * right now.
6428 	 */
6429 	return count <= 1;
6430 }
6431 
6432 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6433 {
6434 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6435 	bool has_size = fn->arg_size[arg] != 0;
6436 	bool is_next_size = false;
6437 
6438 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6439 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6440 
6441 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6442 		return is_next_size;
6443 
6444 	return has_size == is_next_size || is_next_size == is_fixed;
6445 }
6446 
6447 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6448 {
6449 	/* bpf_xxx(..., buf, len) call will access 'len'
6450 	 * bytes from memory 'buf'. Both arg types need
6451 	 * to be paired, so make sure there's no buggy
6452 	 * helper function specification.
6453 	 */
6454 	if (arg_type_is_mem_size(fn->arg1_type) ||
6455 	    check_args_pair_invalid(fn, 0) ||
6456 	    check_args_pair_invalid(fn, 1) ||
6457 	    check_args_pair_invalid(fn, 2) ||
6458 	    check_args_pair_invalid(fn, 3) ||
6459 	    check_args_pair_invalid(fn, 4))
6460 		return false;
6461 
6462 	return true;
6463 }
6464 
6465 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6466 {
6467 	int i;
6468 
6469 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6470 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6471 			return false;
6472 
6473 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6474 		    /* arg_btf_id and arg_size are in a union. */
6475 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6476 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6477 			return false;
6478 	}
6479 
6480 	return true;
6481 }
6482 
6483 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6484 {
6485 	return check_raw_mode_ok(fn) &&
6486 	       check_arg_pair_ok(fn) &&
6487 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6488 }
6489 
6490 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6491  * are now invalid, so turn them into unknown SCALAR_VALUE.
6492  */
6493 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
6494 				     struct bpf_func_state *state)
6495 {
6496 	struct bpf_reg_state *regs = state->regs, *reg;
6497 	int i;
6498 
6499 	for (i = 0; i < MAX_BPF_REG; i++)
6500 		if (reg_is_pkt_pointer_any(&regs[i]))
6501 			mark_reg_unknown(env, regs, i);
6502 
6503 	bpf_for_each_spilled_reg(i, state, reg) {
6504 		if (!reg)
6505 			continue;
6506 		if (reg_is_pkt_pointer_any(reg))
6507 			__mark_reg_unknown(env, reg);
6508 	}
6509 }
6510 
6511 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6512 {
6513 	struct bpf_verifier_state *vstate = env->cur_state;
6514 	int i;
6515 
6516 	for (i = 0; i <= vstate->curframe; i++)
6517 		__clear_all_pkt_pointers(env, vstate->frame[i]);
6518 }
6519 
6520 enum {
6521 	AT_PKT_END = -1,
6522 	BEYOND_PKT_END = -2,
6523 };
6524 
6525 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6526 {
6527 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6528 	struct bpf_reg_state *reg = &state->regs[regn];
6529 
6530 	if (reg->type != PTR_TO_PACKET)
6531 		/* PTR_TO_PACKET_META is not supported yet */
6532 		return;
6533 
6534 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6535 	 * How far beyond pkt_end it goes is unknown.
6536 	 * if (!range_open) it's the case of pkt >= pkt_end
6537 	 * if (range_open) it's the case of pkt > pkt_end
6538 	 * hence this pointer is at least 1 byte bigger than pkt_end
6539 	 */
6540 	if (range_open)
6541 		reg->range = BEYOND_PKT_END;
6542 	else
6543 		reg->range = AT_PKT_END;
6544 }
6545 
6546 static void release_reg_references(struct bpf_verifier_env *env,
6547 				   struct bpf_func_state *state,
6548 				   int ref_obj_id)
6549 {
6550 	struct bpf_reg_state *regs = state->regs, *reg;
6551 	int i;
6552 
6553 	for (i = 0; i < MAX_BPF_REG; i++)
6554 		if (regs[i].ref_obj_id == ref_obj_id)
6555 			mark_reg_unknown(env, regs, i);
6556 
6557 	bpf_for_each_spilled_reg(i, state, reg) {
6558 		if (!reg)
6559 			continue;
6560 		if (reg->ref_obj_id == ref_obj_id)
6561 			__mark_reg_unknown(env, reg);
6562 	}
6563 }
6564 
6565 /* The pointer with the specified id has released its reference to kernel
6566  * resources. Identify all copies of the same pointer and clear the reference.
6567  */
6568 static int release_reference(struct bpf_verifier_env *env,
6569 			     int ref_obj_id)
6570 {
6571 	struct bpf_verifier_state *vstate = env->cur_state;
6572 	int err;
6573 	int i;
6574 
6575 	err = release_reference_state(cur_func(env), ref_obj_id);
6576 	if (err)
6577 		return err;
6578 
6579 	for (i = 0; i <= vstate->curframe; i++)
6580 		release_reg_references(env, vstate->frame[i], ref_obj_id);
6581 
6582 	return 0;
6583 }
6584 
6585 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6586 				    struct bpf_reg_state *regs)
6587 {
6588 	int i;
6589 
6590 	/* after the call registers r0 - r5 were scratched */
6591 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6592 		mark_reg_not_init(env, regs, caller_saved[i]);
6593 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6594 	}
6595 }
6596 
6597 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6598 				   struct bpf_func_state *caller,
6599 				   struct bpf_func_state *callee,
6600 				   int insn_idx);
6601 
6602 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6603 			     int *insn_idx, int subprog,
6604 			     set_callee_state_fn set_callee_state_cb)
6605 {
6606 	struct bpf_verifier_state *state = env->cur_state;
6607 	struct bpf_func_info_aux *func_info_aux;
6608 	struct bpf_func_state *caller, *callee;
6609 	int err;
6610 	bool is_global = false;
6611 
6612 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6613 		verbose(env, "the call stack of %d frames is too deep\n",
6614 			state->curframe + 2);
6615 		return -E2BIG;
6616 	}
6617 
6618 	caller = state->frame[state->curframe];
6619 	if (state->frame[state->curframe + 1]) {
6620 		verbose(env, "verifier bug. Frame %d already allocated\n",
6621 			state->curframe + 1);
6622 		return -EFAULT;
6623 	}
6624 
6625 	func_info_aux = env->prog->aux->func_info_aux;
6626 	if (func_info_aux)
6627 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6628 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6629 	if (err == -EFAULT)
6630 		return err;
6631 	if (is_global) {
6632 		if (err) {
6633 			verbose(env, "Caller passes invalid args into func#%d\n",
6634 				subprog);
6635 			return err;
6636 		} else {
6637 			if (env->log.level & BPF_LOG_LEVEL)
6638 				verbose(env,
6639 					"Func#%d is global and valid. Skipping.\n",
6640 					subprog);
6641 			clear_caller_saved_regs(env, caller->regs);
6642 
6643 			/* All global functions return a 64-bit SCALAR_VALUE */
6644 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6645 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6646 
6647 			/* continue with next insn after call */
6648 			return 0;
6649 		}
6650 	}
6651 
6652 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6653 	    insn->src_reg == 0 &&
6654 	    insn->imm == BPF_FUNC_timer_set_callback) {
6655 		struct bpf_verifier_state *async_cb;
6656 
6657 		/* there is no real recursion here. timer callbacks are async */
6658 		env->subprog_info[subprog].is_async_cb = true;
6659 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6660 					 *insn_idx, subprog);
6661 		if (!async_cb)
6662 			return -EFAULT;
6663 		callee = async_cb->frame[0];
6664 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6665 
6666 		/* Convert bpf_timer_set_callback() args into timer callback args */
6667 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6668 		if (err)
6669 			return err;
6670 
6671 		clear_caller_saved_regs(env, caller->regs);
6672 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6673 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6674 		/* continue with next insn after call */
6675 		return 0;
6676 	}
6677 
6678 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6679 	if (!callee)
6680 		return -ENOMEM;
6681 	state->frame[state->curframe + 1] = callee;
6682 
6683 	/* callee cannot access r0, r6 - r9 for reading and has to write
6684 	 * into its own stack before reading from it.
6685 	 * callee can read/write into caller's stack
6686 	 */
6687 	init_func_state(env, callee,
6688 			/* remember the callsite, it will be used by bpf_exit */
6689 			*insn_idx /* callsite */,
6690 			state->curframe + 1 /* frameno within this callchain */,
6691 			subprog /* subprog number within this prog */);
6692 
6693 	/* Transfer references to the callee */
6694 	err = copy_reference_state(callee, caller);
6695 	if (err)
6696 		return err;
6697 
6698 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6699 	if (err)
6700 		return err;
6701 
6702 	clear_caller_saved_regs(env, caller->regs);
6703 
6704 	/* only increment it after check_reg_arg() finished */
6705 	state->curframe++;
6706 
6707 	/* and go analyze first insn of the callee */
6708 	*insn_idx = env->subprog_info[subprog].start - 1;
6709 
6710 	if (env->log.level & BPF_LOG_LEVEL) {
6711 		verbose(env, "caller:\n");
6712 		print_verifier_state(env, caller, true);
6713 		verbose(env, "callee:\n");
6714 		print_verifier_state(env, callee, true);
6715 	}
6716 	return 0;
6717 }
6718 
6719 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6720 				   struct bpf_func_state *caller,
6721 				   struct bpf_func_state *callee)
6722 {
6723 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6724 	 *      void *callback_ctx, u64 flags);
6725 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6726 	 *      void *callback_ctx);
6727 	 */
6728 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6729 
6730 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6731 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6732 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6733 
6734 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6735 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6736 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6737 
6738 	/* pointer to stack or null */
6739 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6740 
6741 	/* unused */
6742 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6743 	return 0;
6744 }
6745 
6746 static int set_callee_state(struct bpf_verifier_env *env,
6747 			    struct bpf_func_state *caller,
6748 			    struct bpf_func_state *callee, int insn_idx)
6749 {
6750 	int i;
6751 
6752 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6753 	 * pointers, which connects us up to the liveness chain
6754 	 */
6755 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6756 		callee->regs[i] = caller->regs[i];
6757 	return 0;
6758 }
6759 
6760 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6761 			   int *insn_idx)
6762 {
6763 	int subprog, target_insn;
6764 
6765 	target_insn = *insn_idx + insn->imm + 1;
6766 	subprog = find_subprog(env, target_insn);
6767 	if (subprog < 0) {
6768 		verbose(env, "verifier bug. No program starts at insn %d\n",
6769 			target_insn);
6770 		return -EFAULT;
6771 	}
6772 
6773 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6774 }
6775 
6776 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6777 				       struct bpf_func_state *caller,
6778 				       struct bpf_func_state *callee,
6779 				       int insn_idx)
6780 {
6781 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6782 	struct bpf_map *map;
6783 	int err;
6784 
6785 	if (bpf_map_ptr_poisoned(insn_aux)) {
6786 		verbose(env, "tail_call abusing map_ptr\n");
6787 		return -EINVAL;
6788 	}
6789 
6790 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6791 	if (!map->ops->map_set_for_each_callback_args ||
6792 	    !map->ops->map_for_each_callback) {
6793 		verbose(env, "callback function not allowed for map\n");
6794 		return -ENOTSUPP;
6795 	}
6796 
6797 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6798 	if (err)
6799 		return err;
6800 
6801 	callee->in_callback_fn = true;
6802 	return 0;
6803 }
6804 
6805 static int set_loop_callback_state(struct bpf_verifier_env *env,
6806 				   struct bpf_func_state *caller,
6807 				   struct bpf_func_state *callee,
6808 				   int insn_idx)
6809 {
6810 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6811 	 *	    u64 flags);
6812 	 * callback_fn(u32 index, void *callback_ctx);
6813 	 */
6814 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6815 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6816 
6817 	/* unused */
6818 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6819 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6820 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6821 
6822 	callee->in_callback_fn = true;
6823 	return 0;
6824 }
6825 
6826 static int set_timer_callback_state(struct bpf_verifier_env *env,
6827 				    struct bpf_func_state *caller,
6828 				    struct bpf_func_state *callee,
6829 				    int insn_idx)
6830 {
6831 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6832 
6833 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6834 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6835 	 */
6836 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6837 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6838 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6839 
6840 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6841 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6842 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6843 
6844 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6845 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6846 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6847 
6848 	/* unused */
6849 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6850 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6851 	callee->in_async_callback_fn = true;
6852 	return 0;
6853 }
6854 
6855 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6856 				       struct bpf_func_state *caller,
6857 				       struct bpf_func_state *callee,
6858 				       int insn_idx)
6859 {
6860 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6861 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6862 	 * (callback_fn)(struct task_struct *task,
6863 	 *               struct vm_area_struct *vma, void *callback_ctx);
6864 	 */
6865 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6866 
6867 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6868 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6869 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6870 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6871 
6872 	/* pointer to stack or null */
6873 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6874 
6875 	/* unused */
6876 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6877 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6878 	callee->in_callback_fn = true;
6879 	return 0;
6880 }
6881 
6882 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6883 {
6884 	struct bpf_verifier_state *state = env->cur_state;
6885 	struct bpf_func_state *caller, *callee;
6886 	struct bpf_reg_state *r0;
6887 	int err;
6888 
6889 	callee = state->frame[state->curframe];
6890 	r0 = &callee->regs[BPF_REG_0];
6891 	if (r0->type == PTR_TO_STACK) {
6892 		/* technically it's ok to return caller's stack pointer
6893 		 * (or caller's caller's pointer) back to the caller,
6894 		 * since these pointers are valid. Only current stack
6895 		 * pointer will be invalid as soon as function exits,
6896 		 * but let's be conservative
6897 		 */
6898 		verbose(env, "cannot return stack pointer to the caller\n");
6899 		return -EINVAL;
6900 	}
6901 
6902 	state->curframe--;
6903 	caller = state->frame[state->curframe];
6904 	if (callee->in_callback_fn) {
6905 		/* enforce R0 return value range [0, 1]. */
6906 		struct tnum range = tnum_range(0, 1);
6907 
6908 		if (r0->type != SCALAR_VALUE) {
6909 			verbose(env, "R0 not a scalar value\n");
6910 			return -EACCES;
6911 		}
6912 		if (!tnum_in(range, r0->var_off)) {
6913 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6914 			return -EINVAL;
6915 		}
6916 	} else {
6917 		/* return to the caller whatever r0 had in the callee */
6918 		caller->regs[BPF_REG_0] = *r0;
6919 	}
6920 
6921 	/* Transfer references to the caller */
6922 	err = copy_reference_state(caller, callee);
6923 	if (err)
6924 		return err;
6925 
6926 	*insn_idx = callee->callsite + 1;
6927 	if (env->log.level & BPF_LOG_LEVEL) {
6928 		verbose(env, "returning from callee:\n");
6929 		print_verifier_state(env, callee, true);
6930 		verbose(env, "to caller at %d:\n", *insn_idx);
6931 		print_verifier_state(env, caller, true);
6932 	}
6933 	/* clear everything in the callee */
6934 	free_func_state(callee);
6935 	state->frame[state->curframe + 1] = NULL;
6936 	return 0;
6937 }
6938 
6939 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6940 				   int func_id,
6941 				   struct bpf_call_arg_meta *meta)
6942 {
6943 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6944 
6945 	if (ret_type != RET_INTEGER ||
6946 	    (func_id != BPF_FUNC_get_stack &&
6947 	     func_id != BPF_FUNC_get_task_stack &&
6948 	     func_id != BPF_FUNC_probe_read_str &&
6949 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6950 	     func_id != BPF_FUNC_probe_read_user_str))
6951 		return;
6952 
6953 	ret_reg->smax_value = meta->msize_max_value;
6954 	ret_reg->s32_max_value = meta->msize_max_value;
6955 	ret_reg->smin_value = -MAX_ERRNO;
6956 	ret_reg->s32_min_value = -MAX_ERRNO;
6957 	reg_bounds_sync(ret_reg);
6958 }
6959 
6960 static int
6961 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6962 		int func_id, int insn_idx)
6963 {
6964 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6965 	struct bpf_map *map = meta->map_ptr;
6966 
6967 	if (func_id != BPF_FUNC_tail_call &&
6968 	    func_id != BPF_FUNC_map_lookup_elem &&
6969 	    func_id != BPF_FUNC_map_update_elem &&
6970 	    func_id != BPF_FUNC_map_delete_elem &&
6971 	    func_id != BPF_FUNC_map_push_elem &&
6972 	    func_id != BPF_FUNC_map_pop_elem &&
6973 	    func_id != BPF_FUNC_map_peek_elem &&
6974 	    func_id != BPF_FUNC_for_each_map_elem &&
6975 	    func_id != BPF_FUNC_redirect_map &&
6976 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
6977 		return 0;
6978 
6979 	if (map == NULL) {
6980 		verbose(env, "kernel subsystem misconfigured verifier\n");
6981 		return -EINVAL;
6982 	}
6983 
6984 	/* In case of read-only, some additional restrictions
6985 	 * need to be applied in order to prevent altering the
6986 	 * state of the map from program side.
6987 	 */
6988 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6989 	    (func_id == BPF_FUNC_map_delete_elem ||
6990 	     func_id == BPF_FUNC_map_update_elem ||
6991 	     func_id == BPF_FUNC_map_push_elem ||
6992 	     func_id == BPF_FUNC_map_pop_elem)) {
6993 		verbose(env, "write into map forbidden\n");
6994 		return -EACCES;
6995 	}
6996 
6997 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6998 		bpf_map_ptr_store(aux, meta->map_ptr,
6999 				  !meta->map_ptr->bypass_spec_v1);
7000 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7001 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7002 				  !meta->map_ptr->bypass_spec_v1);
7003 	return 0;
7004 }
7005 
7006 static int
7007 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7008 		int func_id, int insn_idx)
7009 {
7010 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7011 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7012 	struct bpf_map *map = meta->map_ptr;
7013 	u64 val, max;
7014 	int err;
7015 
7016 	if (func_id != BPF_FUNC_tail_call)
7017 		return 0;
7018 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7019 		verbose(env, "kernel subsystem misconfigured verifier\n");
7020 		return -EINVAL;
7021 	}
7022 
7023 	reg = &regs[BPF_REG_3];
7024 	val = reg->var_off.value;
7025 	max = map->max_entries;
7026 
7027 	if (!(register_is_const(reg) && val < max)) {
7028 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7029 		return 0;
7030 	}
7031 
7032 	err = mark_chain_precision(env, BPF_REG_3);
7033 	if (err)
7034 		return err;
7035 	if (bpf_map_key_unseen(aux))
7036 		bpf_map_key_store(aux, val);
7037 	else if (!bpf_map_key_poisoned(aux) &&
7038 		  bpf_map_key_immediate(aux) != val)
7039 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7040 	return 0;
7041 }
7042 
7043 static int check_reference_leak(struct bpf_verifier_env *env)
7044 {
7045 	struct bpf_func_state *state = cur_func(env);
7046 	int i;
7047 
7048 	for (i = 0; i < state->acquired_refs; i++) {
7049 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7050 			state->refs[i].id, state->refs[i].insn_idx);
7051 	}
7052 	return state->acquired_refs ? -EINVAL : 0;
7053 }
7054 
7055 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7056 				   struct bpf_reg_state *regs)
7057 {
7058 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7059 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7060 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7061 	int err, fmt_map_off, num_args;
7062 	u64 fmt_addr;
7063 	char *fmt;
7064 
7065 	/* data must be an array of u64 */
7066 	if (data_len_reg->var_off.value % 8)
7067 		return -EINVAL;
7068 	num_args = data_len_reg->var_off.value / 8;
7069 
7070 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7071 	 * and map_direct_value_addr is set.
7072 	 */
7073 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7074 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7075 						  fmt_map_off);
7076 	if (err) {
7077 		verbose(env, "verifier bug\n");
7078 		return -EFAULT;
7079 	}
7080 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7081 
7082 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7083 	 * can focus on validating the format specifiers.
7084 	 */
7085 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7086 	if (err < 0)
7087 		verbose(env, "Invalid format string\n");
7088 
7089 	return err;
7090 }
7091 
7092 static int check_get_func_ip(struct bpf_verifier_env *env)
7093 {
7094 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7095 	int func_id = BPF_FUNC_get_func_ip;
7096 
7097 	if (type == BPF_PROG_TYPE_TRACING) {
7098 		if (!bpf_prog_has_trampoline(env->prog)) {
7099 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7100 				func_id_name(func_id), func_id);
7101 			return -ENOTSUPP;
7102 		}
7103 		return 0;
7104 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7105 		return 0;
7106 	}
7107 
7108 	verbose(env, "func %s#%d not supported for program type %d\n",
7109 		func_id_name(func_id), func_id, type);
7110 	return -ENOTSUPP;
7111 }
7112 
7113 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7114 {
7115 	return &env->insn_aux_data[env->insn_idx];
7116 }
7117 
7118 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7119 {
7120 	struct bpf_reg_state *regs = cur_regs(env);
7121 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7122 	bool reg_is_null = register_is_null(reg);
7123 
7124 	if (reg_is_null)
7125 		mark_chain_precision(env, BPF_REG_4);
7126 
7127 	return reg_is_null;
7128 }
7129 
7130 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7131 {
7132 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7133 
7134 	if (!state->initialized) {
7135 		state->initialized = 1;
7136 		state->fit_for_inline = loop_flag_is_zero(env);
7137 		state->callback_subprogno = subprogno;
7138 		return;
7139 	}
7140 
7141 	if (!state->fit_for_inline)
7142 		return;
7143 
7144 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7145 				 state->callback_subprogno == subprogno);
7146 }
7147 
7148 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7149 			     int *insn_idx_p)
7150 {
7151 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7152 	const struct bpf_func_proto *fn = NULL;
7153 	enum bpf_return_type ret_type;
7154 	enum bpf_type_flag ret_flag;
7155 	struct bpf_reg_state *regs;
7156 	struct bpf_call_arg_meta meta;
7157 	int insn_idx = *insn_idx_p;
7158 	bool changes_data;
7159 	int i, err, func_id;
7160 
7161 	/* find function prototype */
7162 	func_id = insn->imm;
7163 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7164 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7165 			func_id);
7166 		return -EINVAL;
7167 	}
7168 
7169 	if (env->ops->get_func_proto)
7170 		fn = env->ops->get_func_proto(func_id, env->prog);
7171 	if (!fn) {
7172 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7173 			func_id);
7174 		return -EINVAL;
7175 	}
7176 
7177 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7178 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7179 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7180 		return -EINVAL;
7181 	}
7182 
7183 	if (fn->allowed && !fn->allowed(env->prog)) {
7184 		verbose(env, "helper call is not allowed in probe\n");
7185 		return -EINVAL;
7186 	}
7187 
7188 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7189 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7190 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7191 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7192 			func_id_name(func_id), func_id);
7193 		return -EINVAL;
7194 	}
7195 
7196 	memset(&meta, 0, sizeof(meta));
7197 	meta.pkt_access = fn->pkt_access;
7198 
7199 	err = check_func_proto(fn, func_id);
7200 	if (err) {
7201 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7202 			func_id_name(func_id), func_id);
7203 		return err;
7204 	}
7205 
7206 	meta.func_id = func_id;
7207 	/* check args */
7208 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7209 		err = check_func_arg(env, i, &meta, fn);
7210 		if (err)
7211 			return err;
7212 	}
7213 
7214 	err = record_func_map(env, &meta, func_id, insn_idx);
7215 	if (err)
7216 		return err;
7217 
7218 	err = record_func_key(env, &meta, func_id, insn_idx);
7219 	if (err)
7220 		return err;
7221 
7222 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7223 	 * is inferred from register state.
7224 	 */
7225 	for (i = 0; i < meta.access_size; i++) {
7226 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7227 				       BPF_WRITE, -1, false);
7228 		if (err)
7229 			return err;
7230 	}
7231 
7232 	regs = cur_regs(env);
7233 
7234 	if (meta.uninit_dynptr_regno) {
7235 		/* we write BPF_DW bits (8 bytes) at a time */
7236 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7237 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7238 					       i, BPF_DW, BPF_WRITE, -1, false);
7239 			if (err)
7240 				return err;
7241 		}
7242 
7243 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7244 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7245 					      insn_idx);
7246 		if (err)
7247 			return err;
7248 	}
7249 
7250 	if (meta.release_regno) {
7251 		err = -EINVAL;
7252 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7253 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7254 		else if (meta.ref_obj_id)
7255 			err = release_reference(env, meta.ref_obj_id);
7256 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7257 		 * released is NULL, which must be > R0.
7258 		 */
7259 		else if (register_is_null(&regs[meta.release_regno]))
7260 			err = 0;
7261 		if (err) {
7262 			verbose(env, "func %s#%d reference has not been acquired before\n",
7263 				func_id_name(func_id), func_id);
7264 			return err;
7265 		}
7266 	}
7267 
7268 	switch (func_id) {
7269 	case BPF_FUNC_tail_call:
7270 		err = check_reference_leak(env);
7271 		if (err) {
7272 			verbose(env, "tail_call would lead to reference leak\n");
7273 			return err;
7274 		}
7275 		break;
7276 	case BPF_FUNC_get_local_storage:
7277 		/* check that flags argument in get_local_storage(map, flags) is 0,
7278 		 * this is required because get_local_storage() can't return an error.
7279 		 */
7280 		if (!register_is_null(&regs[BPF_REG_2])) {
7281 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7282 			return -EINVAL;
7283 		}
7284 		break;
7285 	case BPF_FUNC_for_each_map_elem:
7286 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7287 					set_map_elem_callback_state);
7288 		break;
7289 	case BPF_FUNC_timer_set_callback:
7290 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7291 					set_timer_callback_state);
7292 		break;
7293 	case BPF_FUNC_find_vma:
7294 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7295 					set_find_vma_callback_state);
7296 		break;
7297 	case BPF_FUNC_snprintf:
7298 		err = check_bpf_snprintf_call(env, regs);
7299 		break;
7300 	case BPF_FUNC_loop:
7301 		update_loop_inline_state(env, meta.subprogno);
7302 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7303 					set_loop_callback_state);
7304 		break;
7305 	case BPF_FUNC_dynptr_from_mem:
7306 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7307 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7308 				reg_type_str(env, regs[BPF_REG_1].type));
7309 			return -EACCES;
7310 		}
7311 		break;
7312 	case BPF_FUNC_set_retval:
7313 		if (prog_type == BPF_PROG_TYPE_LSM &&
7314 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7315 			if (!env->prog->aux->attach_func_proto->type) {
7316 				/* Make sure programs that attach to void
7317 				 * hooks don't try to modify return value.
7318 				 */
7319 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7320 				return -EINVAL;
7321 			}
7322 		}
7323 		break;
7324 	case BPF_FUNC_dynptr_data:
7325 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7326 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7327 				if (meta.ref_obj_id) {
7328 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7329 					return -EFAULT;
7330 				}
7331 				/* Find the id of the dynptr we're tracking the reference of */
7332 				meta.ref_obj_id = stack_slot_get_id(env, &regs[BPF_REG_1 + i]);
7333 				break;
7334 			}
7335 		}
7336 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7337 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7338 			return -EFAULT;
7339 		}
7340 		break;
7341 	}
7342 
7343 	if (err)
7344 		return err;
7345 
7346 	/* reset caller saved regs */
7347 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7348 		mark_reg_not_init(env, regs, caller_saved[i]);
7349 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7350 	}
7351 
7352 	/* helper call returns 64-bit value. */
7353 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7354 
7355 	/* update return register (already marked as written above) */
7356 	ret_type = fn->ret_type;
7357 	ret_flag = type_flag(ret_type);
7358 
7359 	switch (base_type(ret_type)) {
7360 	case RET_INTEGER:
7361 		/* sets type to SCALAR_VALUE */
7362 		mark_reg_unknown(env, regs, BPF_REG_0);
7363 		break;
7364 	case RET_VOID:
7365 		regs[BPF_REG_0].type = NOT_INIT;
7366 		break;
7367 	case RET_PTR_TO_MAP_VALUE:
7368 		/* There is no offset yet applied, variable or fixed */
7369 		mark_reg_known_zero(env, regs, BPF_REG_0);
7370 		/* remember map_ptr, so that check_map_access()
7371 		 * can check 'value_size' boundary of memory access
7372 		 * to map element returned from bpf_map_lookup_elem()
7373 		 */
7374 		if (meta.map_ptr == NULL) {
7375 			verbose(env,
7376 				"kernel subsystem misconfigured verifier\n");
7377 			return -EINVAL;
7378 		}
7379 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7380 		regs[BPF_REG_0].map_uid = meta.map_uid;
7381 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7382 		if (!type_may_be_null(ret_type) &&
7383 		    map_value_has_spin_lock(meta.map_ptr)) {
7384 			regs[BPF_REG_0].id = ++env->id_gen;
7385 		}
7386 		break;
7387 	case RET_PTR_TO_SOCKET:
7388 		mark_reg_known_zero(env, regs, BPF_REG_0);
7389 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7390 		break;
7391 	case RET_PTR_TO_SOCK_COMMON:
7392 		mark_reg_known_zero(env, regs, BPF_REG_0);
7393 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7394 		break;
7395 	case RET_PTR_TO_TCP_SOCK:
7396 		mark_reg_known_zero(env, regs, BPF_REG_0);
7397 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7398 		break;
7399 	case RET_PTR_TO_ALLOC_MEM:
7400 		mark_reg_known_zero(env, regs, BPF_REG_0);
7401 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7402 		regs[BPF_REG_0].mem_size = meta.mem_size;
7403 		break;
7404 	case RET_PTR_TO_MEM_OR_BTF_ID:
7405 	{
7406 		const struct btf_type *t;
7407 
7408 		mark_reg_known_zero(env, regs, BPF_REG_0);
7409 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7410 		if (!btf_type_is_struct(t)) {
7411 			u32 tsize;
7412 			const struct btf_type *ret;
7413 			const char *tname;
7414 
7415 			/* resolve the type size of ksym. */
7416 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7417 			if (IS_ERR(ret)) {
7418 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7419 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7420 					tname, PTR_ERR(ret));
7421 				return -EINVAL;
7422 			}
7423 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7424 			regs[BPF_REG_0].mem_size = tsize;
7425 		} else {
7426 			/* MEM_RDONLY may be carried from ret_flag, but it
7427 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7428 			 * it will confuse the check of PTR_TO_BTF_ID in
7429 			 * check_mem_access().
7430 			 */
7431 			ret_flag &= ~MEM_RDONLY;
7432 
7433 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7434 			regs[BPF_REG_0].btf = meta.ret_btf;
7435 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7436 		}
7437 		break;
7438 	}
7439 	case RET_PTR_TO_BTF_ID:
7440 	{
7441 		struct btf *ret_btf;
7442 		int ret_btf_id;
7443 
7444 		mark_reg_known_zero(env, regs, BPF_REG_0);
7445 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7446 		if (func_id == BPF_FUNC_kptr_xchg) {
7447 			ret_btf = meta.kptr_off_desc->kptr.btf;
7448 			ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7449 		} else {
7450 			ret_btf = btf_vmlinux;
7451 			ret_btf_id = *fn->ret_btf_id;
7452 		}
7453 		if (ret_btf_id == 0) {
7454 			verbose(env, "invalid return type %u of func %s#%d\n",
7455 				base_type(ret_type), func_id_name(func_id),
7456 				func_id);
7457 			return -EINVAL;
7458 		}
7459 		regs[BPF_REG_0].btf = ret_btf;
7460 		regs[BPF_REG_0].btf_id = ret_btf_id;
7461 		break;
7462 	}
7463 	default:
7464 		verbose(env, "unknown return type %u of func %s#%d\n",
7465 			base_type(ret_type), func_id_name(func_id), func_id);
7466 		return -EINVAL;
7467 	}
7468 
7469 	if (type_may_be_null(regs[BPF_REG_0].type))
7470 		regs[BPF_REG_0].id = ++env->id_gen;
7471 
7472 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7473 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7474 			func_id_name(func_id), func_id);
7475 		return -EFAULT;
7476 	}
7477 
7478 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7479 		/* For release_reference() */
7480 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7481 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7482 		int id = acquire_reference_state(env, insn_idx);
7483 
7484 		if (id < 0)
7485 			return id;
7486 		/* For mark_ptr_or_null_reg() */
7487 		regs[BPF_REG_0].id = id;
7488 		/* For release_reference() */
7489 		regs[BPF_REG_0].ref_obj_id = id;
7490 	}
7491 
7492 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7493 
7494 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7495 	if (err)
7496 		return err;
7497 
7498 	if ((func_id == BPF_FUNC_get_stack ||
7499 	     func_id == BPF_FUNC_get_task_stack) &&
7500 	    !env->prog->has_callchain_buf) {
7501 		const char *err_str;
7502 
7503 #ifdef CONFIG_PERF_EVENTS
7504 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7505 		err_str = "cannot get callchain buffer for func %s#%d\n";
7506 #else
7507 		err = -ENOTSUPP;
7508 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7509 #endif
7510 		if (err) {
7511 			verbose(env, err_str, func_id_name(func_id), func_id);
7512 			return err;
7513 		}
7514 
7515 		env->prog->has_callchain_buf = true;
7516 	}
7517 
7518 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7519 		env->prog->call_get_stack = true;
7520 
7521 	if (func_id == BPF_FUNC_get_func_ip) {
7522 		if (check_get_func_ip(env))
7523 			return -ENOTSUPP;
7524 		env->prog->call_get_func_ip = true;
7525 	}
7526 
7527 	if (changes_data)
7528 		clear_all_pkt_pointers(env);
7529 	return 0;
7530 }
7531 
7532 /* mark_btf_func_reg_size() is used when the reg size is determined by
7533  * the BTF func_proto's return value size and argument.
7534  */
7535 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7536 				   size_t reg_size)
7537 {
7538 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7539 
7540 	if (regno == BPF_REG_0) {
7541 		/* Function return value */
7542 		reg->live |= REG_LIVE_WRITTEN;
7543 		reg->subreg_def = reg_size == sizeof(u64) ?
7544 			DEF_NOT_SUBREG : env->insn_idx + 1;
7545 	} else {
7546 		/* Function argument */
7547 		if (reg_size == sizeof(u64)) {
7548 			mark_insn_zext(env, reg);
7549 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7550 		} else {
7551 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7552 		}
7553 	}
7554 }
7555 
7556 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7557 			    int *insn_idx_p)
7558 {
7559 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7560 	struct bpf_reg_state *regs = cur_regs(env);
7561 	const char *func_name, *ptr_type_name;
7562 	u32 i, nargs, func_id, ptr_type_id;
7563 	int err, insn_idx = *insn_idx_p;
7564 	const struct btf_param *args;
7565 	struct btf *desc_btf;
7566 	u32 *kfunc_flags;
7567 	bool acq;
7568 
7569 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7570 	if (!insn->imm)
7571 		return 0;
7572 
7573 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7574 	if (IS_ERR(desc_btf))
7575 		return PTR_ERR(desc_btf);
7576 
7577 	func_id = insn->imm;
7578 	func = btf_type_by_id(desc_btf, func_id);
7579 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7580 	func_proto = btf_type_by_id(desc_btf, func->type);
7581 
7582 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7583 	if (!kfunc_flags) {
7584 		verbose(env, "calling kernel function %s is not allowed\n",
7585 			func_name);
7586 		return -EACCES;
7587 	}
7588 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7589 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7590 		return -EACCES;
7591 	}
7592 
7593 	acq = *kfunc_flags & KF_ACQUIRE;
7594 
7595 	/* Check the arguments */
7596 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, *kfunc_flags);
7597 	if (err < 0)
7598 		return err;
7599 	/* In case of release function, we get register number of refcounted
7600 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7601 	 */
7602 	if (err) {
7603 		err = release_reference(env, regs[err].ref_obj_id);
7604 		if (err) {
7605 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7606 				func_name, func_id);
7607 			return err;
7608 		}
7609 	}
7610 
7611 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7612 		mark_reg_not_init(env, regs, caller_saved[i]);
7613 
7614 	/* Check return type */
7615 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7616 
7617 	if (acq && !btf_type_is_ptr(t)) {
7618 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7619 		return -EINVAL;
7620 	}
7621 
7622 	if (btf_type_is_scalar(t)) {
7623 		mark_reg_unknown(env, regs, BPF_REG_0);
7624 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7625 	} else if (btf_type_is_ptr(t)) {
7626 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7627 						   &ptr_type_id);
7628 		if (!btf_type_is_struct(ptr_type)) {
7629 			ptr_type_name = btf_name_by_offset(desc_btf,
7630 							   ptr_type->name_off);
7631 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7632 				func_name, btf_type_str(ptr_type),
7633 				ptr_type_name);
7634 			return -EINVAL;
7635 		}
7636 		mark_reg_known_zero(env, regs, BPF_REG_0);
7637 		regs[BPF_REG_0].btf = desc_btf;
7638 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7639 		regs[BPF_REG_0].btf_id = ptr_type_id;
7640 		if (*kfunc_flags & KF_RET_NULL) {
7641 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7642 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7643 			regs[BPF_REG_0].id = ++env->id_gen;
7644 		}
7645 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7646 		if (acq) {
7647 			int id = acquire_reference_state(env, insn_idx);
7648 
7649 			if (id < 0)
7650 				return id;
7651 			regs[BPF_REG_0].id = id;
7652 			regs[BPF_REG_0].ref_obj_id = id;
7653 		}
7654 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7655 
7656 	nargs = btf_type_vlen(func_proto);
7657 	args = (const struct btf_param *)(func_proto + 1);
7658 	for (i = 0; i < nargs; i++) {
7659 		u32 regno = i + 1;
7660 
7661 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7662 		if (btf_type_is_ptr(t))
7663 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7664 		else
7665 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7666 			mark_btf_func_reg_size(env, regno, t->size);
7667 	}
7668 
7669 	return 0;
7670 }
7671 
7672 static bool signed_add_overflows(s64 a, s64 b)
7673 {
7674 	/* Do the add in u64, where overflow is well-defined */
7675 	s64 res = (s64)((u64)a + (u64)b);
7676 
7677 	if (b < 0)
7678 		return res > a;
7679 	return res < a;
7680 }
7681 
7682 static bool signed_add32_overflows(s32 a, s32 b)
7683 {
7684 	/* Do the add in u32, where overflow is well-defined */
7685 	s32 res = (s32)((u32)a + (u32)b);
7686 
7687 	if (b < 0)
7688 		return res > a;
7689 	return res < a;
7690 }
7691 
7692 static bool signed_sub_overflows(s64 a, s64 b)
7693 {
7694 	/* Do the sub in u64, where overflow is well-defined */
7695 	s64 res = (s64)((u64)a - (u64)b);
7696 
7697 	if (b < 0)
7698 		return res < a;
7699 	return res > a;
7700 }
7701 
7702 static bool signed_sub32_overflows(s32 a, s32 b)
7703 {
7704 	/* Do the sub in u32, where overflow is well-defined */
7705 	s32 res = (s32)((u32)a - (u32)b);
7706 
7707 	if (b < 0)
7708 		return res < a;
7709 	return res > a;
7710 }
7711 
7712 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7713 				  const struct bpf_reg_state *reg,
7714 				  enum bpf_reg_type type)
7715 {
7716 	bool known = tnum_is_const(reg->var_off);
7717 	s64 val = reg->var_off.value;
7718 	s64 smin = reg->smin_value;
7719 
7720 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7721 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7722 			reg_type_str(env, type), val);
7723 		return false;
7724 	}
7725 
7726 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7727 		verbose(env, "%s pointer offset %d is not allowed\n",
7728 			reg_type_str(env, type), reg->off);
7729 		return false;
7730 	}
7731 
7732 	if (smin == S64_MIN) {
7733 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7734 			reg_type_str(env, type));
7735 		return false;
7736 	}
7737 
7738 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7739 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7740 			smin, reg_type_str(env, type));
7741 		return false;
7742 	}
7743 
7744 	return true;
7745 }
7746 
7747 enum {
7748 	REASON_BOUNDS	= -1,
7749 	REASON_TYPE	= -2,
7750 	REASON_PATHS	= -3,
7751 	REASON_LIMIT	= -4,
7752 	REASON_STACK	= -5,
7753 };
7754 
7755 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7756 			      u32 *alu_limit, bool mask_to_left)
7757 {
7758 	u32 max = 0, ptr_limit = 0;
7759 
7760 	switch (ptr_reg->type) {
7761 	case PTR_TO_STACK:
7762 		/* Offset 0 is out-of-bounds, but acceptable start for the
7763 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7764 		 * offset where we would need to deal with min/max bounds is
7765 		 * currently prohibited for unprivileged.
7766 		 */
7767 		max = MAX_BPF_STACK + mask_to_left;
7768 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7769 		break;
7770 	case PTR_TO_MAP_VALUE:
7771 		max = ptr_reg->map_ptr->value_size;
7772 		ptr_limit = (mask_to_left ?
7773 			     ptr_reg->smin_value :
7774 			     ptr_reg->umax_value) + ptr_reg->off;
7775 		break;
7776 	default:
7777 		return REASON_TYPE;
7778 	}
7779 
7780 	if (ptr_limit >= max)
7781 		return REASON_LIMIT;
7782 	*alu_limit = ptr_limit;
7783 	return 0;
7784 }
7785 
7786 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7787 				    const struct bpf_insn *insn)
7788 {
7789 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7790 }
7791 
7792 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7793 				       u32 alu_state, u32 alu_limit)
7794 {
7795 	/* If we arrived here from different branches with different
7796 	 * state or limits to sanitize, then this won't work.
7797 	 */
7798 	if (aux->alu_state &&
7799 	    (aux->alu_state != alu_state ||
7800 	     aux->alu_limit != alu_limit))
7801 		return REASON_PATHS;
7802 
7803 	/* Corresponding fixup done in do_misc_fixups(). */
7804 	aux->alu_state = alu_state;
7805 	aux->alu_limit = alu_limit;
7806 	return 0;
7807 }
7808 
7809 static int sanitize_val_alu(struct bpf_verifier_env *env,
7810 			    struct bpf_insn *insn)
7811 {
7812 	struct bpf_insn_aux_data *aux = cur_aux(env);
7813 
7814 	if (can_skip_alu_sanitation(env, insn))
7815 		return 0;
7816 
7817 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7818 }
7819 
7820 static bool sanitize_needed(u8 opcode)
7821 {
7822 	return opcode == BPF_ADD || opcode == BPF_SUB;
7823 }
7824 
7825 struct bpf_sanitize_info {
7826 	struct bpf_insn_aux_data aux;
7827 	bool mask_to_left;
7828 };
7829 
7830 static struct bpf_verifier_state *
7831 sanitize_speculative_path(struct bpf_verifier_env *env,
7832 			  const struct bpf_insn *insn,
7833 			  u32 next_idx, u32 curr_idx)
7834 {
7835 	struct bpf_verifier_state *branch;
7836 	struct bpf_reg_state *regs;
7837 
7838 	branch = push_stack(env, next_idx, curr_idx, true);
7839 	if (branch && insn) {
7840 		regs = branch->frame[branch->curframe]->regs;
7841 		if (BPF_SRC(insn->code) == BPF_K) {
7842 			mark_reg_unknown(env, regs, insn->dst_reg);
7843 		} else if (BPF_SRC(insn->code) == BPF_X) {
7844 			mark_reg_unknown(env, regs, insn->dst_reg);
7845 			mark_reg_unknown(env, regs, insn->src_reg);
7846 		}
7847 	}
7848 	return branch;
7849 }
7850 
7851 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7852 			    struct bpf_insn *insn,
7853 			    const struct bpf_reg_state *ptr_reg,
7854 			    const struct bpf_reg_state *off_reg,
7855 			    struct bpf_reg_state *dst_reg,
7856 			    struct bpf_sanitize_info *info,
7857 			    const bool commit_window)
7858 {
7859 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7860 	struct bpf_verifier_state *vstate = env->cur_state;
7861 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7862 	bool off_is_neg = off_reg->smin_value < 0;
7863 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7864 	u8 opcode = BPF_OP(insn->code);
7865 	u32 alu_state, alu_limit;
7866 	struct bpf_reg_state tmp;
7867 	bool ret;
7868 	int err;
7869 
7870 	if (can_skip_alu_sanitation(env, insn))
7871 		return 0;
7872 
7873 	/* We already marked aux for masking from non-speculative
7874 	 * paths, thus we got here in the first place. We only care
7875 	 * to explore bad access from here.
7876 	 */
7877 	if (vstate->speculative)
7878 		goto do_sim;
7879 
7880 	if (!commit_window) {
7881 		if (!tnum_is_const(off_reg->var_off) &&
7882 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7883 			return REASON_BOUNDS;
7884 
7885 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7886 				     (opcode == BPF_SUB && !off_is_neg);
7887 	}
7888 
7889 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7890 	if (err < 0)
7891 		return err;
7892 
7893 	if (commit_window) {
7894 		/* In commit phase we narrow the masking window based on
7895 		 * the observed pointer move after the simulated operation.
7896 		 */
7897 		alu_state = info->aux.alu_state;
7898 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7899 	} else {
7900 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7901 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7902 		alu_state |= ptr_is_dst_reg ?
7903 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7904 
7905 		/* Limit pruning on unknown scalars to enable deep search for
7906 		 * potential masking differences from other program paths.
7907 		 */
7908 		if (!off_is_imm)
7909 			env->explore_alu_limits = true;
7910 	}
7911 
7912 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7913 	if (err < 0)
7914 		return err;
7915 do_sim:
7916 	/* If we're in commit phase, we're done here given we already
7917 	 * pushed the truncated dst_reg into the speculative verification
7918 	 * stack.
7919 	 *
7920 	 * Also, when register is a known constant, we rewrite register-based
7921 	 * operation to immediate-based, and thus do not need masking (and as
7922 	 * a consequence, do not need to simulate the zero-truncation either).
7923 	 */
7924 	if (commit_window || off_is_imm)
7925 		return 0;
7926 
7927 	/* Simulate and find potential out-of-bounds access under
7928 	 * speculative execution from truncation as a result of
7929 	 * masking when off was not within expected range. If off
7930 	 * sits in dst, then we temporarily need to move ptr there
7931 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7932 	 * for cases where we use K-based arithmetic in one direction
7933 	 * and truncated reg-based in the other in order to explore
7934 	 * bad access.
7935 	 */
7936 	if (!ptr_is_dst_reg) {
7937 		tmp = *dst_reg;
7938 		*dst_reg = *ptr_reg;
7939 	}
7940 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7941 					env->insn_idx);
7942 	if (!ptr_is_dst_reg && ret)
7943 		*dst_reg = tmp;
7944 	return !ret ? REASON_STACK : 0;
7945 }
7946 
7947 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7948 {
7949 	struct bpf_verifier_state *vstate = env->cur_state;
7950 
7951 	/* If we simulate paths under speculation, we don't update the
7952 	 * insn as 'seen' such that when we verify unreachable paths in
7953 	 * the non-speculative domain, sanitize_dead_code() can still
7954 	 * rewrite/sanitize them.
7955 	 */
7956 	if (!vstate->speculative)
7957 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7958 }
7959 
7960 static int sanitize_err(struct bpf_verifier_env *env,
7961 			const struct bpf_insn *insn, int reason,
7962 			const struct bpf_reg_state *off_reg,
7963 			const struct bpf_reg_state *dst_reg)
7964 {
7965 	static const char *err = "pointer arithmetic with it prohibited for !root";
7966 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7967 	u32 dst = insn->dst_reg, src = insn->src_reg;
7968 
7969 	switch (reason) {
7970 	case REASON_BOUNDS:
7971 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7972 			off_reg == dst_reg ? dst : src, err);
7973 		break;
7974 	case REASON_TYPE:
7975 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7976 			off_reg == dst_reg ? src : dst, err);
7977 		break;
7978 	case REASON_PATHS:
7979 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7980 			dst, op, err);
7981 		break;
7982 	case REASON_LIMIT:
7983 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7984 			dst, op, err);
7985 		break;
7986 	case REASON_STACK:
7987 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7988 			dst, err);
7989 		break;
7990 	default:
7991 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7992 			reason);
7993 		break;
7994 	}
7995 
7996 	return -EACCES;
7997 }
7998 
7999 /* check that stack access falls within stack limits and that 'reg' doesn't
8000  * have a variable offset.
8001  *
8002  * Variable offset is prohibited for unprivileged mode for simplicity since it
8003  * requires corresponding support in Spectre masking for stack ALU.  See also
8004  * retrieve_ptr_limit().
8005  *
8006  *
8007  * 'off' includes 'reg->off'.
8008  */
8009 static int check_stack_access_for_ptr_arithmetic(
8010 				struct bpf_verifier_env *env,
8011 				int regno,
8012 				const struct bpf_reg_state *reg,
8013 				int off)
8014 {
8015 	if (!tnum_is_const(reg->var_off)) {
8016 		char tn_buf[48];
8017 
8018 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8019 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8020 			regno, tn_buf, off);
8021 		return -EACCES;
8022 	}
8023 
8024 	if (off >= 0 || off < -MAX_BPF_STACK) {
8025 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8026 			"prohibited for !root; off=%d\n", regno, off);
8027 		return -EACCES;
8028 	}
8029 
8030 	return 0;
8031 }
8032 
8033 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8034 				 const struct bpf_insn *insn,
8035 				 const struct bpf_reg_state *dst_reg)
8036 {
8037 	u32 dst = insn->dst_reg;
8038 
8039 	/* For unprivileged we require that resulting offset must be in bounds
8040 	 * in order to be able to sanitize access later on.
8041 	 */
8042 	if (env->bypass_spec_v1)
8043 		return 0;
8044 
8045 	switch (dst_reg->type) {
8046 	case PTR_TO_STACK:
8047 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8048 					dst_reg->off + dst_reg->var_off.value))
8049 			return -EACCES;
8050 		break;
8051 	case PTR_TO_MAP_VALUE:
8052 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8053 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8054 				"prohibited for !root\n", dst);
8055 			return -EACCES;
8056 		}
8057 		break;
8058 	default:
8059 		break;
8060 	}
8061 
8062 	return 0;
8063 }
8064 
8065 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8066  * Caller should also handle BPF_MOV case separately.
8067  * If we return -EACCES, caller may want to try again treating pointer as a
8068  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8069  */
8070 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8071 				   struct bpf_insn *insn,
8072 				   const struct bpf_reg_state *ptr_reg,
8073 				   const struct bpf_reg_state *off_reg)
8074 {
8075 	struct bpf_verifier_state *vstate = env->cur_state;
8076 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8077 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8078 	bool known = tnum_is_const(off_reg->var_off);
8079 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8080 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8081 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8082 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8083 	struct bpf_sanitize_info info = {};
8084 	u8 opcode = BPF_OP(insn->code);
8085 	u32 dst = insn->dst_reg;
8086 	int ret;
8087 
8088 	dst_reg = &regs[dst];
8089 
8090 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8091 	    smin_val > smax_val || umin_val > umax_val) {
8092 		/* Taint dst register if offset had invalid bounds derived from
8093 		 * e.g. dead branches.
8094 		 */
8095 		__mark_reg_unknown(env, dst_reg);
8096 		return 0;
8097 	}
8098 
8099 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8100 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8101 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8102 			__mark_reg_unknown(env, dst_reg);
8103 			return 0;
8104 		}
8105 
8106 		verbose(env,
8107 			"R%d 32-bit pointer arithmetic prohibited\n",
8108 			dst);
8109 		return -EACCES;
8110 	}
8111 
8112 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8113 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8114 			dst, reg_type_str(env, ptr_reg->type));
8115 		return -EACCES;
8116 	}
8117 
8118 	switch (base_type(ptr_reg->type)) {
8119 	case CONST_PTR_TO_MAP:
8120 		/* smin_val represents the known value */
8121 		if (known && smin_val == 0 && opcode == BPF_ADD)
8122 			break;
8123 		fallthrough;
8124 	case PTR_TO_PACKET_END:
8125 	case PTR_TO_SOCKET:
8126 	case PTR_TO_SOCK_COMMON:
8127 	case PTR_TO_TCP_SOCK:
8128 	case PTR_TO_XDP_SOCK:
8129 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8130 			dst, reg_type_str(env, ptr_reg->type));
8131 		return -EACCES;
8132 	default:
8133 		break;
8134 	}
8135 
8136 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8137 	 * The id may be overwritten later if we create a new variable offset.
8138 	 */
8139 	dst_reg->type = ptr_reg->type;
8140 	dst_reg->id = ptr_reg->id;
8141 
8142 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8143 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8144 		return -EINVAL;
8145 
8146 	/* pointer types do not carry 32-bit bounds at the moment. */
8147 	__mark_reg32_unbounded(dst_reg);
8148 
8149 	if (sanitize_needed(opcode)) {
8150 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8151 				       &info, false);
8152 		if (ret < 0)
8153 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8154 	}
8155 
8156 	switch (opcode) {
8157 	case BPF_ADD:
8158 		/* We can take a fixed offset as long as it doesn't overflow
8159 		 * the s32 'off' field
8160 		 */
8161 		if (known && (ptr_reg->off + smin_val ==
8162 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8163 			/* pointer += K.  Accumulate it into fixed offset */
8164 			dst_reg->smin_value = smin_ptr;
8165 			dst_reg->smax_value = smax_ptr;
8166 			dst_reg->umin_value = umin_ptr;
8167 			dst_reg->umax_value = umax_ptr;
8168 			dst_reg->var_off = ptr_reg->var_off;
8169 			dst_reg->off = ptr_reg->off + smin_val;
8170 			dst_reg->raw = ptr_reg->raw;
8171 			break;
8172 		}
8173 		/* A new variable offset is created.  Note that off_reg->off
8174 		 * == 0, since it's a scalar.
8175 		 * dst_reg gets the pointer type and since some positive
8176 		 * integer value was added to the pointer, give it a new 'id'
8177 		 * if it's a PTR_TO_PACKET.
8178 		 * this creates a new 'base' pointer, off_reg (variable) gets
8179 		 * added into the variable offset, and we copy the fixed offset
8180 		 * from ptr_reg.
8181 		 */
8182 		if (signed_add_overflows(smin_ptr, smin_val) ||
8183 		    signed_add_overflows(smax_ptr, smax_val)) {
8184 			dst_reg->smin_value = S64_MIN;
8185 			dst_reg->smax_value = S64_MAX;
8186 		} else {
8187 			dst_reg->smin_value = smin_ptr + smin_val;
8188 			dst_reg->smax_value = smax_ptr + smax_val;
8189 		}
8190 		if (umin_ptr + umin_val < umin_ptr ||
8191 		    umax_ptr + umax_val < umax_ptr) {
8192 			dst_reg->umin_value = 0;
8193 			dst_reg->umax_value = U64_MAX;
8194 		} else {
8195 			dst_reg->umin_value = umin_ptr + umin_val;
8196 			dst_reg->umax_value = umax_ptr + umax_val;
8197 		}
8198 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8199 		dst_reg->off = ptr_reg->off;
8200 		dst_reg->raw = ptr_reg->raw;
8201 		if (reg_is_pkt_pointer(ptr_reg)) {
8202 			dst_reg->id = ++env->id_gen;
8203 			/* something was added to pkt_ptr, set range to zero */
8204 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8205 		}
8206 		break;
8207 	case BPF_SUB:
8208 		if (dst_reg == off_reg) {
8209 			/* scalar -= pointer.  Creates an unknown scalar */
8210 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8211 				dst);
8212 			return -EACCES;
8213 		}
8214 		/* We don't allow subtraction from FP, because (according to
8215 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8216 		 * be able to deal with it.
8217 		 */
8218 		if (ptr_reg->type == PTR_TO_STACK) {
8219 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8220 				dst);
8221 			return -EACCES;
8222 		}
8223 		if (known && (ptr_reg->off - smin_val ==
8224 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8225 			/* pointer -= K.  Subtract it from fixed offset */
8226 			dst_reg->smin_value = smin_ptr;
8227 			dst_reg->smax_value = smax_ptr;
8228 			dst_reg->umin_value = umin_ptr;
8229 			dst_reg->umax_value = umax_ptr;
8230 			dst_reg->var_off = ptr_reg->var_off;
8231 			dst_reg->id = ptr_reg->id;
8232 			dst_reg->off = ptr_reg->off - smin_val;
8233 			dst_reg->raw = ptr_reg->raw;
8234 			break;
8235 		}
8236 		/* A new variable offset is created.  If the subtrahend is known
8237 		 * nonnegative, then any reg->range we had before is still good.
8238 		 */
8239 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8240 		    signed_sub_overflows(smax_ptr, smin_val)) {
8241 			/* Overflow possible, we know nothing */
8242 			dst_reg->smin_value = S64_MIN;
8243 			dst_reg->smax_value = S64_MAX;
8244 		} else {
8245 			dst_reg->smin_value = smin_ptr - smax_val;
8246 			dst_reg->smax_value = smax_ptr - smin_val;
8247 		}
8248 		if (umin_ptr < umax_val) {
8249 			/* Overflow possible, we know nothing */
8250 			dst_reg->umin_value = 0;
8251 			dst_reg->umax_value = U64_MAX;
8252 		} else {
8253 			/* Cannot overflow (as long as bounds are consistent) */
8254 			dst_reg->umin_value = umin_ptr - umax_val;
8255 			dst_reg->umax_value = umax_ptr - umin_val;
8256 		}
8257 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8258 		dst_reg->off = ptr_reg->off;
8259 		dst_reg->raw = ptr_reg->raw;
8260 		if (reg_is_pkt_pointer(ptr_reg)) {
8261 			dst_reg->id = ++env->id_gen;
8262 			/* something was added to pkt_ptr, set range to zero */
8263 			if (smin_val < 0)
8264 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8265 		}
8266 		break;
8267 	case BPF_AND:
8268 	case BPF_OR:
8269 	case BPF_XOR:
8270 		/* bitwise ops on pointers are troublesome, prohibit. */
8271 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8272 			dst, bpf_alu_string[opcode >> 4]);
8273 		return -EACCES;
8274 	default:
8275 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8276 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8277 			dst, bpf_alu_string[opcode >> 4]);
8278 		return -EACCES;
8279 	}
8280 
8281 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8282 		return -EINVAL;
8283 	reg_bounds_sync(dst_reg);
8284 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8285 		return -EACCES;
8286 	if (sanitize_needed(opcode)) {
8287 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8288 				       &info, true);
8289 		if (ret < 0)
8290 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8291 	}
8292 
8293 	return 0;
8294 }
8295 
8296 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8297 				 struct bpf_reg_state *src_reg)
8298 {
8299 	s32 smin_val = src_reg->s32_min_value;
8300 	s32 smax_val = src_reg->s32_max_value;
8301 	u32 umin_val = src_reg->u32_min_value;
8302 	u32 umax_val = src_reg->u32_max_value;
8303 
8304 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8305 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8306 		dst_reg->s32_min_value = S32_MIN;
8307 		dst_reg->s32_max_value = S32_MAX;
8308 	} else {
8309 		dst_reg->s32_min_value += smin_val;
8310 		dst_reg->s32_max_value += smax_val;
8311 	}
8312 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8313 	    dst_reg->u32_max_value + umax_val < umax_val) {
8314 		dst_reg->u32_min_value = 0;
8315 		dst_reg->u32_max_value = U32_MAX;
8316 	} else {
8317 		dst_reg->u32_min_value += umin_val;
8318 		dst_reg->u32_max_value += umax_val;
8319 	}
8320 }
8321 
8322 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8323 			       struct bpf_reg_state *src_reg)
8324 {
8325 	s64 smin_val = src_reg->smin_value;
8326 	s64 smax_val = src_reg->smax_value;
8327 	u64 umin_val = src_reg->umin_value;
8328 	u64 umax_val = src_reg->umax_value;
8329 
8330 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8331 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8332 		dst_reg->smin_value = S64_MIN;
8333 		dst_reg->smax_value = S64_MAX;
8334 	} else {
8335 		dst_reg->smin_value += smin_val;
8336 		dst_reg->smax_value += smax_val;
8337 	}
8338 	if (dst_reg->umin_value + umin_val < umin_val ||
8339 	    dst_reg->umax_value + umax_val < umax_val) {
8340 		dst_reg->umin_value = 0;
8341 		dst_reg->umax_value = U64_MAX;
8342 	} else {
8343 		dst_reg->umin_value += umin_val;
8344 		dst_reg->umax_value += umax_val;
8345 	}
8346 }
8347 
8348 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8349 				 struct bpf_reg_state *src_reg)
8350 {
8351 	s32 smin_val = src_reg->s32_min_value;
8352 	s32 smax_val = src_reg->s32_max_value;
8353 	u32 umin_val = src_reg->u32_min_value;
8354 	u32 umax_val = src_reg->u32_max_value;
8355 
8356 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8357 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8358 		/* Overflow possible, we know nothing */
8359 		dst_reg->s32_min_value = S32_MIN;
8360 		dst_reg->s32_max_value = S32_MAX;
8361 	} else {
8362 		dst_reg->s32_min_value -= smax_val;
8363 		dst_reg->s32_max_value -= smin_val;
8364 	}
8365 	if (dst_reg->u32_min_value < umax_val) {
8366 		/* Overflow possible, we know nothing */
8367 		dst_reg->u32_min_value = 0;
8368 		dst_reg->u32_max_value = U32_MAX;
8369 	} else {
8370 		/* Cannot overflow (as long as bounds are consistent) */
8371 		dst_reg->u32_min_value -= umax_val;
8372 		dst_reg->u32_max_value -= umin_val;
8373 	}
8374 }
8375 
8376 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8377 			       struct bpf_reg_state *src_reg)
8378 {
8379 	s64 smin_val = src_reg->smin_value;
8380 	s64 smax_val = src_reg->smax_value;
8381 	u64 umin_val = src_reg->umin_value;
8382 	u64 umax_val = src_reg->umax_value;
8383 
8384 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8385 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8386 		/* Overflow possible, we know nothing */
8387 		dst_reg->smin_value = S64_MIN;
8388 		dst_reg->smax_value = S64_MAX;
8389 	} else {
8390 		dst_reg->smin_value -= smax_val;
8391 		dst_reg->smax_value -= smin_val;
8392 	}
8393 	if (dst_reg->umin_value < umax_val) {
8394 		/* Overflow possible, we know nothing */
8395 		dst_reg->umin_value = 0;
8396 		dst_reg->umax_value = U64_MAX;
8397 	} else {
8398 		/* Cannot overflow (as long as bounds are consistent) */
8399 		dst_reg->umin_value -= umax_val;
8400 		dst_reg->umax_value -= umin_val;
8401 	}
8402 }
8403 
8404 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8405 				 struct bpf_reg_state *src_reg)
8406 {
8407 	s32 smin_val = src_reg->s32_min_value;
8408 	u32 umin_val = src_reg->u32_min_value;
8409 	u32 umax_val = src_reg->u32_max_value;
8410 
8411 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8412 		/* Ain't nobody got time to multiply that sign */
8413 		__mark_reg32_unbounded(dst_reg);
8414 		return;
8415 	}
8416 	/* Both values are positive, so we can work with unsigned and
8417 	 * copy the result to signed (unless it exceeds S32_MAX).
8418 	 */
8419 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8420 		/* Potential overflow, we know nothing */
8421 		__mark_reg32_unbounded(dst_reg);
8422 		return;
8423 	}
8424 	dst_reg->u32_min_value *= umin_val;
8425 	dst_reg->u32_max_value *= umax_val;
8426 	if (dst_reg->u32_max_value > S32_MAX) {
8427 		/* Overflow possible, we know nothing */
8428 		dst_reg->s32_min_value = S32_MIN;
8429 		dst_reg->s32_max_value = S32_MAX;
8430 	} else {
8431 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8432 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8433 	}
8434 }
8435 
8436 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8437 			       struct bpf_reg_state *src_reg)
8438 {
8439 	s64 smin_val = src_reg->smin_value;
8440 	u64 umin_val = src_reg->umin_value;
8441 	u64 umax_val = src_reg->umax_value;
8442 
8443 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8444 		/* Ain't nobody got time to multiply that sign */
8445 		__mark_reg64_unbounded(dst_reg);
8446 		return;
8447 	}
8448 	/* Both values are positive, so we can work with unsigned and
8449 	 * copy the result to signed (unless it exceeds S64_MAX).
8450 	 */
8451 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8452 		/* Potential overflow, we know nothing */
8453 		__mark_reg64_unbounded(dst_reg);
8454 		return;
8455 	}
8456 	dst_reg->umin_value *= umin_val;
8457 	dst_reg->umax_value *= umax_val;
8458 	if (dst_reg->umax_value > S64_MAX) {
8459 		/* Overflow possible, we know nothing */
8460 		dst_reg->smin_value = S64_MIN;
8461 		dst_reg->smax_value = S64_MAX;
8462 	} else {
8463 		dst_reg->smin_value = dst_reg->umin_value;
8464 		dst_reg->smax_value = dst_reg->umax_value;
8465 	}
8466 }
8467 
8468 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8469 				 struct bpf_reg_state *src_reg)
8470 {
8471 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8472 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8473 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8474 	s32 smin_val = src_reg->s32_min_value;
8475 	u32 umax_val = src_reg->u32_max_value;
8476 
8477 	if (src_known && dst_known) {
8478 		__mark_reg32_known(dst_reg, var32_off.value);
8479 		return;
8480 	}
8481 
8482 	/* We get our minimum from the var_off, since that's inherently
8483 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8484 	 */
8485 	dst_reg->u32_min_value = var32_off.value;
8486 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8487 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8488 		/* Lose signed bounds when ANDing negative numbers,
8489 		 * ain't nobody got time for that.
8490 		 */
8491 		dst_reg->s32_min_value = S32_MIN;
8492 		dst_reg->s32_max_value = S32_MAX;
8493 	} else {
8494 		/* ANDing two positives gives a positive, so safe to
8495 		 * cast result into s64.
8496 		 */
8497 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8498 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8499 	}
8500 }
8501 
8502 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8503 			       struct bpf_reg_state *src_reg)
8504 {
8505 	bool src_known = tnum_is_const(src_reg->var_off);
8506 	bool dst_known = tnum_is_const(dst_reg->var_off);
8507 	s64 smin_val = src_reg->smin_value;
8508 	u64 umax_val = src_reg->umax_value;
8509 
8510 	if (src_known && dst_known) {
8511 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8512 		return;
8513 	}
8514 
8515 	/* We get our minimum from the var_off, since that's inherently
8516 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8517 	 */
8518 	dst_reg->umin_value = dst_reg->var_off.value;
8519 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8520 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8521 		/* Lose signed bounds when ANDing negative numbers,
8522 		 * ain't nobody got time for that.
8523 		 */
8524 		dst_reg->smin_value = S64_MIN;
8525 		dst_reg->smax_value = S64_MAX;
8526 	} else {
8527 		/* ANDing two positives gives a positive, so safe to
8528 		 * cast result into s64.
8529 		 */
8530 		dst_reg->smin_value = dst_reg->umin_value;
8531 		dst_reg->smax_value = dst_reg->umax_value;
8532 	}
8533 	/* We may learn something more from the var_off */
8534 	__update_reg_bounds(dst_reg);
8535 }
8536 
8537 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8538 				struct bpf_reg_state *src_reg)
8539 {
8540 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8541 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8542 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8543 	s32 smin_val = src_reg->s32_min_value;
8544 	u32 umin_val = src_reg->u32_min_value;
8545 
8546 	if (src_known && dst_known) {
8547 		__mark_reg32_known(dst_reg, var32_off.value);
8548 		return;
8549 	}
8550 
8551 	/* We get our maximum from the var_off, and our minimum is the
8552 	 * maximum of the operands' minima
8553 	 */
8554 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8555 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8556 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8557 		/* Lose signed bounds when ORing negative numbers,
8558 		 * ain't nobody got time for that.
8559 		 */
8560 		dst_reg->s32_min_value = S32_MIN;
8561 		dst_reg->s32_max_value = S32_MAX;
8562 	} else {
8563 		/* ORing two positives gives a positive, so safe to
8564 		 * cast result into s64.
8565 		 */
8566 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8567 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8568 	}
8569 }
8570 
8571 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8572 			      struct bpf_reg_state *src_reg)
8573 {
8574 	bool src_known = tnum_is_const(src_reg->var_off);
8575 	bool dst_known = tnum_is_const(dst_reg->var_off);
8576 	s64 smin_val = src_reg->smin_value;
8577 	u64 umin_val = src_reg->umin_value;
8578 
8579 	if (src_known && dst_known) {
8580 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8581 		return;
8582 	}
8583 
8584 	/* We get our maximum from the var_off, and our minimum is the
8585 	 * maximum of the operands' minima
8586 	 */
8587 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8588 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8589 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8590 		/* Lose signed bounds when ORing negative numbers,
8591 		 * ain't nobody got time for that.
8592 		 */
8593 		dst_reg->smin_value = S64_MIN;
8594 		dst_reg->smax_value = S64_MAX;
8595 	} else {
8596 		/* ORing two positives gives a positive, so safe to
8597 		 * cast result into s64.
8598 		 */
8599 		dst_reg->smin_value = dst_reg->umin_value;
8600 		dst_reg->smax_value = dst_reg->umax_value;
8601 	}
8602 	/* We may learn something more from the var_off */
8603 	__update_reg_bounds(dst_reg);
8604 }
8605 
8606 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8607 				 struct bpf_reg_state *src_reg)
8608 {
8609 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8610 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8611 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8612 	s32 smin_val = src_reg->s32_min_value;
8613 
8614 	if (src_known && dst_known) {
8615 		__mark_reg32_known(dst_reg, var32_off.value);
8616 		return;
8617 	}
8618 
8619 	/* We get both minimum and maximum from the var32_off. */
8620 	dst_reg->u32_min_value = var32_off.value;
8621 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8622 
8623 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8624 		/* XORing two positive sign numbers gives a positive,
8625 		 * so safe to cast u32 result into s32.
8626 		 */
8627 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8628 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8629 	} else {
8630 		dst_reg->s32_min_value = S32_MIN;
8631 		dst_reg->s32_max_value = S32_MAX;
8632 	}
8633 }
8634 
8635 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8636 			       struct bpf_reg_state *src_reg)
8637 {
8638 	bool src_known = tnum_is_const(src_reg->var_off);
8639 	bool dst_known = tnum_is_const(dst_reg->var_off);
8640 	s64 smin_val = src_reg->smin_value;
8641 
8642 	if (src_known && dst_known) {
8643 		/* dst_reg->var_off.value has been updated earlier */
8644 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8645 		return;
8646 	}
8647 
8648 	/* We get both minimum and maximum from the var_off. */
8649 	dst_reg->umin_value = dst_reg->var_off.value;
8650 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8651 
8652 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8653 		/* XORing two positive sign numbers gives a positive,
8654 		 * so safe to cast u64 result into s64.
8655 		 */
8656 		dst_reg->smin_value = dst_reg->umin_value;
8657 		dst_reg->smax_value = dst_reg->umax_value;
8658 	} else {
8659 		dst_reg->smin_value = S64_MIN;
8660 		dst_reg->smax_value = S64_MAX;
8661 	}
8662 
8663 	__update_reg_bounds(dst_reg);
8664 }
8665 
8666 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8667 				   u64 umin_val, u64 umax_val)
8668 {
8669 	/* We lose all sign bit information (except what we can pick
8670 	 * up from var_off)
8671 	 */
8672 	dst_reg->s32_min_value = S32_MIN;
8673 	dst_reg->s32_max_value = S32_MAX;
8674 	/* If we might shift our top bit out, then we know nothing */
8675 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8676 		dst_reg->u32_min_value = 0;
8677 		dst_reg->u32_max_value = U32_MAX;
8678 	} else {
8679 		dst_reg->u32_min_value <<= umin_val;
8680 		dst_reg->u32_max_value <<= umax_val;
8681 	}
8682 }
8683 
8684 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8685 				 struct bpf_reg_state *src_reg)
8686 {
8687 	u32 umax_val = src_reg->u32_max_value;
8688 	u32 umin_val = src_reg->u32_min_value;
8689 	/* u32 alu operation will zext upper bits */
8690 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8691 
8692 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8693 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8694 	/* Not required but being careful mark reg64 bounds as unknown so
8695 	 * that we are forced to pick them up from tnum and zext later and
8696 	 * if some path skips this step we are still safe.
8697 	 */
8698 	__mark_reg64_unbounded(dst_reg);
8699 	__update_reg32_bounds(dst_reg);
8700 }
8701 
8702 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8703 				   u64 umin_val, u64 umax_val)
8704 {
8705 	/* Special case <<32 because it is a common compiler pattern to sign
8706 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8707 	 * positive we know this shift will also be positive so we can track
8708 	 * bounds correctly. Otherwise we lose all sign bit information except
8709 	 * what we can pick up from var_off. Perhaps we can generalize this
8710 	 * later to shifts of any length.
8711 	 */
8712 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8713 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8714 	else
8715 		dst_reg->smax_value = S64_MAX;
8716 
8717 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8718 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8719 	else
8720 		dst_reg->smin_value = S64_MIN;
8721 
8722 	/* If we might shift our top bit out, then we know nothing */
8723 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8724 		dst_reg->umin_value = 0;
8725 		dst_reg->umax_value = U64_MAX;
8726 	} else {
8727 		dst_reg->umin_value <<= umin_val;
8728 		dst_reg->umax_value <<= umax_val;
8729 	}
8730 }
8731 
8732 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8733 			       struct bpf_reg_state *src_reg)
8734 {
8735 	u64 umax_val = src_reg->umax_value;
8736 	u64 umin_val = src_reg->umin_value;
8737 
8738 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8739 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8740 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8741 
8742 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8743 	/* We may learn something more from the var_off */
8744 	__update_reg_bounds(dst_reg);
8745 }
8746 
8747 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8748 				 struct bpf_reg_state *src_reg)
8749 {
8750 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8751 	u32 umax_val = src_reg->u32_max_value;
8752 	u32 umin_val = src_reg->u32_min_value;
8753 
8754 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8755 	 * be negative, then either:
8756 	 * 1) src_reg might be zero, so the sign bit of the result is
8757 	 *    unknown, so we lose our signed bounds
8758 	 * 2) it's known negative, thus the unsigned bounds capture the
8759 	 *    signed bounds
8760 	 * 3) the signed bounds cross zero, so they tell us nothing
8761 	 *    about the result
8762 	 * If the value in dst_reg is known nonnegative, then again the
8763 	 * unsigned bounds capture the signed bounds.
8764 	 * Thus, in all cases it suffices to blow away our signed bounds
8765 	 * and rely on inferring new ones from the unsigned bounds and
8766 	 * var_off of the result.
8767 	 */
8768 	dst_reg->s32_min_value = S32_MIN;
8769 	dst_reg->s32_max_value = S32_MAX;
8770 
8771 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8772 	dst_reg->u32_min_value >>= umax_val;
8773 	dst_reg->u32_max_value >>= umin_val;
8774 
8775 	__mark_reg64_unbounded(dst_reg);
8776 	__update_reg32_bounds(dst_reg);
8777 }
8778 
8779 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8780 			       struct bpf_reg_state *src_reg)
8781 {
8782 	u64 umax_val = src_reg->umax_value;
8783 	u64 umin_val = src_reg->umin_value;
8784 
8785 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8786 	 * be negative, then either:
8787 	 * 1) src_reg might be zero, so the sign bit of the result is
8788 	 *    unknown, so we lose our signed bounds
8789 	 * 2) it's known negative, thus the unsigned bounds capture the
8790 	 *    signed bounds
8791 	 * 3) the signed bounds cross zero, so they tell us nothing
8792 	 *    about the result
8793 	 * If the value in dst_reg is known nonnegative, then again the
8794 	 * unsigned bounds capture the signed bounds.
8795 	 * Thus, in all cases it suffices to blow away our signed bounds
8796 	 * and rely on inferring new ones from the unsigned bounds and
8797 	 * var_off of the result.
8798 	 */
8799 	dst_reg->smin_value = S64_MIN;
8800 	dst_reg->smax_value = S64_MAX;
8801 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8802 	dst_reg->umin_value >>= umax_val;
8803 	dst_reg->umax_value >>= umin_val;
8804 
8805 	/* Its not easy to operate on alu32 bounds here because it depends
8806 	 * on bits being shifted in. Take easy way out and mark unbounded
8807 	 * so we can recalculate later from tnum.
8808 	 */
8809 	__mark_reg32_unbounded(dst_reg);
8810 	__update_reg_bounds(dst_reg);
8811 }
8812 
8813 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8814 				  struct bpf_reg_state *src_reg)
8815 {
8816 	u64 umin_val = src_reg->u32_min_value;
8817 
8818 	/* Upon reaching here, src_known is true and
8819 	 * umax_val is equal to umin_val.
8820 	 */
8821 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8822 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8823 
8824 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8825 
8826 	/* blow away the dst_reg umin_value/umax_value and rely on
8827 	 * dst_reg var_off to refine the result.
8828 	 */
8829 	dst_reg->u32_min_value = 0;
8830 	dst_reg->u32_max_value = U32_MAX;
8831 
8832 	__mark_reg64_unbounded(dst_reg);
8833 	__update_reg32_bounds(dst_reg);
8834 }
8835 
8836 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8837 				struct bpf_reg_state *src_reg)
8838 {
8839 	u64 umin_val = src_reg->umin_value;
8840 
8841 	/* Upon reaching here, src_known is true and umax_val is equal
8842 	 * to umin_val.
8843 	 */
8844 	dst_reg->smin_value >>= umin_val;
8845 	dst_reg->smax_value >>= umin_val;
8846 
8847 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8848 
8849 	/* blow away the dst_reg umin_value/umax_value and rely on
8850 	 * dst_reg var_off to refine the result.
8851 	 */
8852 	dst_reg->umin_value = 0;
8853 	dst_reg->umax_value = U64_MAX;
8854 
8855 	/* Its not easy to operate on alu32 bounds here because it depends
8856 	 * on bits being shifted in from upper 32-bits. Take easy way out
8857 	 * and mark unbounded so we can recalculate later from tnum.
8858 	 */
8859 	__mark_reg32_unbounded(dst_reg);
8860 	__update_reg_bounds(dst_reg);
8861 }
8862 
8863 /* WARNING: This function does calculations on 64-bit values, but the actual
8864  * execution may occur on 32-bit values. Therefore, things like bitshifts
8865  * need extra checks in the 32-bit case.
8866  */
8867 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8868 				      struct bpf_insn *insn,
8869 				      struct bpf_reg_state *dst_reg,
8870 				      struct bpf_reg_state src_reg)
8871 {
8872 	struct bpf_reg_state *regs = cur_regs(env);
8873 	u8 opcode = BPF_OP(insn->code);
8874 	bool src_known;
8875 	s64 smin_val, smax_val;
8876 	u64 umin_val, umax_val;
8877 	s32 s32_min_val, s32_max_val;
8878 	u32 u32_min_val, u32_max_val;
8879 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8880 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8881 	int ret;
8882 
8883 	smin_val = src_reg.smin_value;
8884 	smax_val = src_reg.smax_value;
8885 	umin_val = src_reg.umin_value;
8886 	umax_val = src_reg.umax_value;
8887 
8888 	s32_min_val = src_reg.s32_min_value;
8889 	s32_max_val = src_reg.s32_max_value;
8890 	u32_min_val = src_reg.u32_min_value;
8891 	u32_max_val = src_reg.u32_max_value;
8892 
8893 	if (alu32) {
8894 		src_known = tnum_subreg_is_const(src_reg.var_off);
8895 		if ((src_known &&
8896 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8897 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8898 			/* Taint dst register if offset had invalid bounds
8899 			 * derived from e.g. dead branches.
8900 			 */
8901 			__mark_reg_unknown(env, dst_reg);
8902 			return 0;
8903 		}
8904 	} else {
8905 		src_known = tnum_is_const(src_reg.var_off);
8906 		if ((src_known &&
8907 		     (smin_val != smax_val || umin_val != umax_val)) ||
8908 		    smin_val > smax_val || umin_val > umax_val) {
8909 			/* Taint dst register if offset had invalid bounds
8910 			 * derived from e.g. dead branches.
8911 			 */
8912 			__mark_reg_unknown(env, dst_reg);
8913 			return 0;
8914 		}
8915 	}
8916 
8917 	if (!src_known &&
8918 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8919 		__mark_reg_unknown(env, dst_reg);
8920 		return 0;
8921 	}
8922 
8923 	if (sanitize_needed(opcode)) {
8924 		ret = sanitize_val_alu(env, insn);
8925 		if (ret < 0)
8926 			return sanitize_err(env, insn, ret, NULL, NULL);
8927 	}
8928 
8929 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8930 	 * There are two classes of instructions: The first class we track both
8931 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8932 	 * greatest amount of precision when alu operations are mixed with jmp32
8933 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8934 	 * and BPF_OR. This is possible because these ops have fairly easy to
8935 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8936 	 * See alu32 verifier tests for examples. The second class of
8937 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8938 	 * with regards to tracking sign/unsigned bounds because the bits may
8939 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8940 	 * the reg unbounded in the subreg bound space and use the resulting
8941 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8942 	 */
8943 	switch (opcode) {
8944 	case BPF_ADD:
8945 		scalar32_min_max_add(dst_reg, &src_reg);
8946 		scalar_min_max_add(dst_reg, &src_reg);
8947 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8948 		break;
8949 	case BPF_SUB:
8950 		scalar32_min_max_sub(dst_reg, &src_reg);
8951 		scalar_min_max_sub(dst_reg, &src_reg);
8952 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8953 		break;
8954 	case BPF_MUL:
8955 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8956 		scalar32_min_max_mul(dst_reg, &src_reg);
8957 		scalar_min_max_mul(dst_reg, &src_reg);
8958 		break;
8959 	case BPF_AND:
8960 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8961 		scalar32_min_max_and(dst_reg, &src_reg);
8962 		scalar_min_max_and(dst_reg, &src_reg);
8963 		break;
8964 	case BPF_OR:
8965 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8966 		scalar32_min_max_or(dst_reg, &src_reg);
8967 		scalar_min_max_or(dst_reg, &src_reg);
8968 		break;
8969 	case BPF_XOR:
8970 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8971 		scalar32_min_max_xor(dst_reg, &src_reg);
8972 		scalar_min_max_xor(dst_reg, &src_reg);
8973 		break;
8974 	case BPF_LSH:
8975 		if (umax_val >= insn_bitness) {
8976 			/* Shifts greater than 31 or 63 are undefined.
8977 			 * This includes shifts by a negative number.
8978 			 */
8979 			mark_reg_unknown(env, regs, insn->dst_reg);
8980 			break;
8981 		}
8982 		if (alu32)
8983 			scalar32_min_max_lsh(dst_reg, &src_reg);
8984 		else
8985 			scalar_min_max_lsh(dst_reg, &src_reg);
8986 		break;
8987 	case BPF_RSH:
8988 		if (umax_val >= insn_bitness) {
8989 			/* Shifts greater than 31 or 63 are undefined.
8990 			 * This includes shifts by a negative number.
8991 			 */
8992 			mark_reg_unknown(env, regs, insn->dst_reg);
8993 			break;
8994 		}
8995 		if (alu32)
8996 			scalar32_min_max_rsh(dst_reg, &src_reg);
8997 		else
8998 			scalar_min_max_rsh(dst_reg, &src_reg);
8999 		break;
9000 	case BPF_ARSH:
9001 		if (umax_val >= insn_bitness) {
9002 			/* Shifts greater than 31 or 63 are undefined.
9003 			 * This includes shifts by a negative number.
9004 			 */
9005 			mark_reg_unknown(env, regs, insn->dst_reg);
9006 			break;
9007 		}
9008 		if (alu32)
9009 			scalar32_min_max_arsh(dst_reg, &src_reg);
9010 		else
9011 			scalar_min_max_arsh(dst_reg, &src_reg);
9012 		break;
9013 	default:
9014 		mark_reg_unknown(env, regs, insn->dst_reg);
9015 		break;
9016 	}
9017 
9018 	/* ALU32 ops are zero extended into 64bit register */
9019 	if (alu32)
9020 		zext_32_to_64(dst_reg);
9021 	reg_bounds_sync(dst_reg);
9022 	return 0;
9023 }
9024 
9025 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9026  * and var_off.
9027  */
9028 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9029 				   struct bpf_insn *insn)
9030 {
9031 	struct bpf_verifier_state *vstate = env->cur_state;
9032 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9033 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9034 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9035 	u8 opcode = BPF_OP(insn->code);
9036 	int err;
9037 
9038 	dst_reg = &regs[insn->dst_reg];
9039 	src_reg = NULL;
9040 	if (dst_reg->type != SCALAR_VALUE)
9041 		ptr_reg = dst_reg;
9042 	else
9043 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9044 		 * incorrectly propagated into other registers by find_equal_scalars()
9045 		 */
9046 		dst_reg->id = 0;
9047 	if (BPF_SRC(insn->code) == BPF_X) {
9048 		src_reg = &regs[insn->src_reg];
9049 		if (src_reg->type != SCALAR_VALUE) {
9050 			if (dst_reg->type != SCALAR_VALUE) {
9051 				/* Combining two pointers by any ALU op yields
9052 				 * an arbitrary scalar. Disallow all math except
9053 				 * pointer subtraction
9054 				 */
9055 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9056 					mark_reg_unknown(env, regs, insn->dst_reg);
9057 					return 0;
9058 				}
9059 				verbose(env, "R%d pointer %s pointer prohibited\n",
9060 					insn->dst_reg,
9061 					bpf_alu_string[opcode >> 4]);
9062 				return -EACCES;
9063 			} else {
9064 				/* scalar += pointer
9065 				 * This is legal, but we have to reverse our
9066 				 * src/dest handling in computing the range
9067 				 */
9068 				err = mark_chain_precision(env, insn->dst_reg);
9069 				if (err)
9070 					return err;
9071 				return adjust_ptr_min_max_vals(env, insn,
9072 							       src_reg, dst_reg);
9073 			}
9074 		} else if (ptr_reg) {
9075 			/* pointer += scalar */
9076 			err = mark_chain_precision(env, insn->src_reg);
9077 			if (err)
9078 				return err;
9079 			return adjust_ptr_min_max_vals(env, insn,
9080 						       dst_reg, src_reg);
9081 		}
9082 	} else {
9083 		/* Pretend the src is a reg with a known value, since we only
9084 		 * need to be able to read from this state.
9085 		 */
9086 		off_reg.type = SCALAR_VALUE;
9087 		__mark_reg_known(&off_reg, insn->imm);
9088 		src_reg = &off_reg;
9089 		if (ptr_reg) /* pointer += K */
9090 			return adjust_ptr_min_max_vals(env, insn,
9091 						       ptr_reg, src_reg);
9092 	}
9093 
9094 	/* Got here implies adding two SCALAR_VALUEs */
9095 	if (WARN_ON_ONCE(ptr_reg)) {
9096 		print_verifier_state(env, state, true);
9097 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9098 		return -EINVAL;
9099 	}
9100 	if (WARN_ON(!src_reg)) {
9101 		print_verifier_state(env, state, true);
9102 		verbose(env, "verifier internal error: no src_reg\n");
9103 		return -EINVAL;
9104 	}
9105 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9106 }
9107 
9108 /* check validity of 32-bit and 64-bit arithmetic operations */
9109 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9110 {
9111 	struct bpf_reg_state *regs = cur_regs(env);
9112 	u8 opcode = BPF_OP(insn->code);
9113 	int err;
9114 
9115 	if (opcode == BPF_END || opcode == BPF_NEG) {
9116 		if (opcode == BPF_NEG) {
9117 			if (BPF_SRC(insn->code) != BPF_K ||
9118 			    insn->src_reg != BPF_REG_0 ||
9119 			    insn->off != 0 || insn->imm != 0) {
9120 				verbose(env, "BPF_NEG uses reserved fields\n");
9121 				return -EINVAL;
9122 			}
9123 		} else {
9124 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9125 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9126 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9127 				verbose(env, "BPF_END uses reserved fields\n");
9128 				return -EINVAL;
9129 			}
9130 		}
9131 
9132 		/* check src operand */
9133 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9134 		if (err)
9135 			return err;
9136 
9137 		if (is_pointer_value(env, insn->dst_reg)) {
9138 			verbose(env, "R%d pointer arithmetic prohibited\n",
9139 				insn->dst_reg);
9140 			return -EACCES;
9141 		}
9142 
9143 		/* check dest operand */
9144 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9145 		if (err)
9146 			return err;
9147 
9148 	} else if (opcode == BPF_MOV) {
9149 
9150 		if (BPF_SRC(insn->code) == BPF_X) {
9151 			if (insn->imm != 0 || insn->off != 0) {
9152 				verbose(env, "BPF_MOV uses reserved fields\n");
9153 				return -EINVAL;
9154 			}
9155 
9156 			/* check src operand */
9157 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9158 			if (err)
9159 				return err;
9160 		} else {
9161 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9162 				verbose(env, "BPF_MOV uses reserved fields\n");
9163 				return -EINVAL;
9164 			}
9165 		}
9166 
9167 		/* check dest operand, mark as required later */
9168 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9169 		if (err)
9170 			return err;
9171 
9172 		if (BPF_SRC(insn->code) == BPF_X) {
9173 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9174 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9175 
9176 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9177 				/* case: R1 = R2
9178 				 * copy register state to dest reg
9179 				 */
9180 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9181 					/* Assign src and dst registers the same ID
9182 					 * that will be used by find_equal_scalars()
9183 					 * to propagate min/max range.
9184 					 */
9185 					src_reg->id = ++env->id_gen;
9186 				*dst_reg = *src_reg;
9187 				dst_reg->live |= REG_LIVE_WRITTEN;
9188 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9189 			} else {
9190 				/* R1 = (u32) R2 */
9191 				if (is_pointer_value(env, insn->src_reg)) {
9192 					verbose(env,
9193 						"R%d partial copy of pointer\n",
9194 						insn->src_reg);
9195 					return -EACCES;
9196 				} else if (src_reg->type == SCALAR_VALUE) {
9197 					*dst_reg = *src_reg;
9198 					/* Make sure ID is cleared otherwise
9199 					 * dst_reg min/max could be incorrectly
9200 					 * propagated into src_reg by find_equal_scalars()
9201 					 */
9202 					dst_reg->id = 0;
9203 					dst_reg->live |= REG_LIVE_WRITTEN;
9204 					dst_reg->subreg_def = env->insn_idx + 1;
9205 				} else {
9206 					mark_reg_unknown(env, regs,
9207 							 insn->dst_reg);
9208 				}
9209 				zext_32_to_64(dst_reg);
9210 				reg_bounds_sync(dst_reg);
9211 			}
9212 		} else {
9213 			/* case: R = imm
9214 			 * remember the value we stored into this reg
9215 			 */
9216 			/* clear any state __mark_reg_known doesn't set */
9217 			mark_reg_unknown(env, regs, insn->dst_reg);
9218 			regs[insn->dst_reg].type = SCALAR_VALUE;
9219 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9220 				__mark_reg_known(regs + insn->dst_reg,
9221 						 insn->imm);
9222 			} else {
9223 				__mark_reg_known(regs + insn->dst_reg,
9224 						 (u32)insn->imm);
9225 			}
9226 		}
9227 
9228 	} else if (opcode > BPF_END) {
9229 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9230 		return -EINVAL;
9231 
9232 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9233 
9234 		if (BPF_SRC(insn->code) == BPF_X) {
9235 			if (insn->imm != 0 || insn->off != 0) {
9236 				verbose(env, "BPF_ALU uses reserved fields\n");
9237 				return -EINVAL;
9238 			}
9239 			/* check src1 operand */
9240 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9241 			if (err)
9242 				return err;
9243 		} else {
9244 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9245 				verbose(env, "BPF_ALU uses reserved fields\n");
9246 				return -EINVAL;
9247 			}
9248 		}
9249 
9250 		/* check src2 operand */
9251 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9252 		if (err)
9253 			return err;
9254 
9255 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9256 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9257 			verbose(env, "div by zero\n");
9258 			return -EINVAL;
9259 		}
9260 
9261 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9262 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9263 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9264 
9265 			if (insn->imm < 0 || insn->imm >= size) {
9266 				verbose(env, "invalid shift %d\n", insn->imm);
9267 				return -EINVAL;
9268 			}
9269 		}
9270 
9271 		/* check dest operand */
9272 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9273 		if (err)
9274 			return err;
9275 
9276 		return adjust_reg_min_max_vals(env, insn);
9277 	}
9278 
9279 	return 0;
9280 }
9281 
9282 static void __find_good_pkt_pointers(struct bpf_func_state *state,
9283 				     struct bpf_reg_state *dst_reg,
9284 				     enum bpf_reg_type type, int new_range)
9285 {
9286 	struct bpf_reg_state *reg;
9287 	int i;
9288 
9289 	for (i = 0; i < MAX_BPF_REG; i++) {
9290 		reg = &state->regs[i];
9291 		if (reg->type == type && reg->id == dst_reg->id)
9292 			/* keep the maximum range already checked */
9293 			reg->range = max(reg->range, new_range);
9294 	}
9295 
9296 	bpf_for_each_spilled_reg(i, state, reg) {
9297 		if (!reg)
9298 			continue;
9299 		if (reg->type == type && reg->id == dst_reg->id)
9300 			reg->range = max(reg->range, new_range);
9301 	}
9302 }
9303 
9304 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9305 				   struct bpf_reg_state *dst_reg,
9306 				   enum bpf_reg_type type,
9307 				   bool range_right_open)
9308 {
9309 	int new_range, i;
9310 
9311 	if (dst_reg->off < 0 ||
9312 	    (dst_reg->off == 0 && range_right_open))
9313 		/* This doesn't give us any range */
9314 		return;
9315 
9316 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9317 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9318 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9319 		 * than pkt_end, but that's because it's also less than pkt.
9320 		 */
9321 		return;
9322 
9323 	new_range = dst_reg->off;
9324 	if (range_right_open)
9325 		new_range++;
9326 
9327 	/* Examples for register markings:
9328 	 *
9329 	 * pkt_data in dst register:
9330 	 *
9331 	 *   r2 = r3;
9332 	 *   r2 += 8;
9333 	 *   if (r2 > pkt_end) goto <handle exception>
9334 	 *   <access okay>
9335 	 *
9336 	 *   r2 = r3;
9337 	 *   r2 += 8;
9338 	 *   if (r2 < pkt_end) goto <access okay>
9339 	 *   <handle exception>
9340 	 *
9341 	 *   Where:
9342 	 *     r2 == dst_reg, pkt_end == src_reg
9343 	 *     r2=pkt(id=n,off=8,r=0)
9344 	 *     r3=pkt(id=n,off=0,r=0)
9345 	 *
9346 	 * pkt_data in src register:
9347 	 *
9348 	 *   r2 = r3;
9349 	 *   r2 += 8;
9350 	 *   if (pkt_end >= r2) goto <access okay>
9351 	 *   <handle exception>
9352 	 *
9353 	 *   r2 = r3;
9354 	 *   r2 += 8;
9355 	 *   if (pkt_end <= r2) goto <handle exception>
9356 	 *   <access okay>
9357 	 *
9358 	 *   Where:
9359 	 *     pkt_end == dst_reg, r2 == src_reg
9360 	 *     r2=pkt(id=n,off=8,r=0)
9361 	 *     r3=pkt(id=n,off=0,r=0)
9362 	 *
9363 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9364 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9365 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9366 	 * the check.
9367 	 */
9368 
9369 	/* If our ids match, then we must have the same max_value.  And we
9370 	 * don't care about the other reg's fixed offset, since if it's too big
9371 	 * the range won't allow anything.
9372 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9373 	 */
9374 	for (i = 0; i <= vstate->curframe; i++)
9375 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
9376 					 new_range);
9377 }
9378 
9379 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9380 {
9381 	struct tnum subreg = tnum_subreg(reg->var_off);
9382 	s32 sval = (s32)val;
9383 
9384 	switch (opcode) {
9385 	case BPF_JEQ:
9386 		if (tnum_is_const(subreg))
9387 			return !!tnum_equals_const(subreg, val);
9388 		break;
9389 	case BPF_JNE:
9390 		if (tnum_is_const(subreg))
9391 			return !tnum_equals_const(subreg, val);
9392 		break;
9393 	case BPF_JSET:
9394 		if ((~subreg.mask & subreg.value) & val)
9395 			return 1;
9396 		if (!((subreg.mask | subreg.value) & val))
9397 			return 0;
9398 		break;
9399 	case BPF_JGT:
9400 		if (reg->u32_min_value > val)
9401 			return 1;
9402 		else if (reg->u32_max_value <= val)
9403 			return 0;
9404 		break;
9405 	case BPF_JSGT:
9406 		if (reg->s32_min_value > sval)
9407 			return 1;
9408 		else if (reg->s32_max_value <= sval)
9409 			return 0;
9410 		break;
9411 	case BPF_JLT:
9412 		if (reg->u32_max_value < val)
9413 			return 1;
9414 		else if (reg->u32_min_value >= val)
9415 			return 0;
9416 		break;
9417 	case BPF_JSLT:
9418 		if (reg->s32_max_value < sval)
9419 			return 1;
9420 		else if (reg->s32_min_value >= sval)
9421 			return 0;
9422 		break;
9423 	case BPF_JGE:
9424 		if (reg->u32_min_value >= val)
9425 			return 1;
9426 		else if (reg->u32_max_value < val)
9427 			return 0;
9428 		break;
9429 	case BPF_JSGE:
9430 		if (reg->s32_min_value >= sval)
9431 			return 1;
9432 		else if (reg->s32_max_value < sval)
9433 			return 0;
9434 		break;
9435 	case BPF_JLE:
9436 		if (reg->u32_max_value <= val)
9437 			return 1;
9438 		else if (reg->u32_min_value > val)
9439 			return 0;
9440 		break;
9441 	case BPF_JSLE:
9442 		if (reg->s32_max_value <= sval)
9443 			return 1;
9444 		else if (reg->s32_min_value > sval)
9445 			return 0;
9446 		break;
9447 	}
9448 
9449 	return -1;
9450 }
9451 
9452 
9453 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9454 {
9455 	s64 sval = (s64)val;
9456 
9457 	switch (opcode) {
9458 	case BPF_JEQ:
9459 		if (tnum_is_const(reg->var_off))
9460 			return !!tnum_equals_const(reg->var_off, val);
9461 		break;
9462 	case BPF_JNE:
9463 		if (tnum_is_const(reg->var_off))
9464 			return !tnum_equals_const(reg->var_off, val);
9465 		break;
9466 	case BPF_JSET:
9467 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9468 			return 1;
9469 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9470 			return 0;
9471 		break;
9472 	case BPF_JGT:
9473 		if (reg->umin_value > val)
9474 			return 1;
9475 		else if (reg->umax_value <= val)
9476 			return 0;
9477 		break;
9478 	case BPF_JSGT:
9479 		if (reg->smin_value > sval)
9480 			return 1;
9481 		else if (reg->smax_value <= sval)
9482 			return 0;
9483 		break;
9484 	case BPF_JLT:
9485 		if (reg->umax_value < val)
9486 			return 1;
9487 		else if (reg->umin_value >= val)
9488 			return 0;
9489 		break;
9490 	case BPF_JSLT:
9491 		if (reg->smax_value < sval)
9492 			return 1;
9493 		else if (reg->smin_value >= sval)
9494 			return 0;
9495 		break;
9496 	case BPF_JGE:
9497 		if (reg->umin_value >= val)
9498 			return 1;
9499 		else if (reg->umax_value < val)
9500 			return 0;
9501 		break;
9502 	case BPF_JSGE:
9503 		if (reg->smin_value >= sval)
9504 			return 1;
9505 		else if (reg->smax_value < sval)
9506 			return 0;
9507 		break;
9508 	case BPF_JLE:
9509 		if (reg->umax_value <= val)
9510 			return 1;
9511 		else if (reg->umin_value > val)
9512 			return 0;
9513 		break;
9514 	case BPF_JSLE:
9515 		if (reg->smax_value <= sval)
9516 			return 1;
9517 		else if (reg->smin_value > sval)
9518 			return 0;
9519 		break;
9520 	}
9521 
9522 	return -1;
9523 }
9524 
9525 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9526  * and return:
9527  *  1 - branch will be taken and "goto target" will be executed
9528  *  0 - branch will not be taken and fall-through to next insn
9529  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9530  *      range [0,10]
9531  */
9532 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9533 			   bool is_jmp32)
9534 {
9535 	if (__is_pointer_value(false, reg)) {
9536 		if (!reg_type_not_null(reg->type))
9537 			return -1;
9538 
9539 		/* If pointer is valid tests against zero will fail so we can
9540 		 * use this to direct branch taken.
9541 		 */
9542 		if (val != 0)
9543 			return -1;
9544 
9545 		switch (opcode) {
9546 		case BPF_JEQ:
9547 			return 0;
9548 		case BPF_JNE:
9549 			return 1;
9550 		default:
9551 			return -1;
9552 		}
9553 	}
9554 
9555 	if (is_jmp32)
9556 		return is_branch32_taken(reg, val, opcode);
9557 	return is_branch64_taken(reg, val, opcode);
9558 }
9559 
9560 static int flip_opcode(u32 opcode)
9561 {
9562 	/* How can we transform "a <op> b" into "b <op> a"? */
9563 	static const u8 opcode_flip[16] = {
9564 		/* these stay the same */
9565 		[BPF_JEQ  >> 4] = BPF_JEQ,
9566 		[BPF_JNE  >> 4] = BPF_JNE,
9567 		[BPF_JSET >> 4] = BPF_JSET,
9568 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9569 		[BPF_JGE  >> 4] = BPF_JLE,
9570 		[BPF_JGT  >> 4] = BPF_JLT,
9571 		[BPF_JLE  >> 4] = BPF_JGE,
9572 		[BPF_JLT  >> 4] = BPF_JGT,
9573 		[BPF_JSGE >> 4] = BPF_JSLE,
9574 		[BPF_JSGT >> 4] = BPF_JSLT,
9575 		[BPF_JSLE >> 4] = BPF_JSGE,
9576 		[BPF_JSLT >> 4] = BPF_JSGT
9577 	};
9578 	return opcode_flip[opcode >> 4];
9579 }
9580 
9581 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9582 				   struct bpf_reg_state *src_reg,
9583 				   u8 opcode)
9584 {
9585 	struct bpf_reg_state *pkt;
9586 
9587 	if (src_reg->type == PTR_TO_PACKET_END) {
9588 		pkt = dst_reg;
9589 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9590 		pkt = src_reg;
9591 		opcode = flip_opcode(opcode);
9592 	} else {
9593 		return -1;
9594 	}
9595 
9596 	if (pkt->range >= 0)
9597 		return -1;
9598 
9599 	switch (opcode) {
9600 	case BPF_JLE:
9601 		/* pkt <= pkt_end */
9602 		fallthrough;
9603 	case BPF_JGT:
9604 		/* pkt > pkt_end */
9605 		if (pkt->range == BEYOND_PKT_END)
9606 			/* pkt has at last one extra byte beyond pkt_end */
9607 			return opcode == BPF_JGT;
9608 		break;
9609 	case BPF_JLT:
9610 		/* pkt < pkt_end */
9611 		fallthrough;
9612 	case BPF_JGE:
9613 		/* pkt >= pkt_end */
9614 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9615 			return opcode == BPF_JGE;
9616 		break;
9617 	}
9618 	return -1;
9619 }
9620 
9621 /* Adjusts the register min/max values in the case that the dst_reg is the
9622  * variable register that we are working on, and src_reg is a constant or we're
9623  * simply doing a BPF_K check.
9624  * In JEQ/JNE cases we also adjust the var_off values.
9625  */
9626 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9627 			    struct bpf_reg_state *false_reg,
9628 			    u64 val, u32 val32,
9629 			    u8 opcode, bool is_jmp32)
9630 {
9631 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9632 	struct tnum false_64off = false_reg->var_off;
9633 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9634 	struct tnum true_64off = true_reg->var_off;
9635 	s64 sval = (s64)val;
9636 	s32 sval32 = (s32)val32;
9637 
9638 	/* If the dst_reg is a pointer, we can't learn anything about its
9639 	 * variable offset from the compare (unless src_reg were a pointer into
9640 	 * the same object, but we don't bother with that.
9641 	 * Since false_reg and true_reg have the same type by construction, we
9642 	 * only need to check one of them for pointerness.
9643 	 */
9644 	if (__is_pointer_value(false, false_reg))
9645 		return;
9646 
9647 	switch (opcode) {
9648 	/* JEQ/JNE comparison doesn't change the register equivalence.
9649 	 *
9650 	 * r1 = r2;
9651 	 * if (r1 == 42) goto label;
9652 	 * ...
9653 	 * label: // here both r1 and r2 are known to be 42.
9654 	 *
9655 	 * Hence when marking register as known preserve it's ID.
9656 	 */
9657 	case BPF_JEQ:
9658 		if (is_jmp32) {
9659 			__mark_reg32_known(true_reg, val32);
9660 			true_32off = tnum_subreg(true_reg->var_off);
9661 		} else {
9662 			___mark_reg_known(true_reg, val);
9663 			true_64off = true_reg->var_off;
9664 		}
9665 		break;
9666 	case BPF_JNE:
9667 		if (is_jmp32) {
9668 			__mark_reg32_known(false_reg, val32);
9669 			false_32off = tnum_subreg(false_reg->var_off);
9670 		} else {
9671 			___mark_reg_known(false_reg, val);
9672 			false_64off = false_reg->var_off;
9673 		}
9674 		break;
9675 	case BPF_JSET:
9676 		if (is_jmp32) {
9677 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9678 			if (is_power_of_2(val32))
9679 				true_32off = tnum_or(true_32off,
9680 						     tnum_const(val32));
9681 		} else {
9682 			false_64off = tnum_and(false_64off, tnum_const(~val));
9683 			if (is_power_of_2(val))
9684 				true_64off = tnum_or(true_64off,
9685 						     tnum_const(val));
9686 		}
9687 		break;
9688 	case BPF_JGE:
9689 	case BPF_JGT:
9690 	{
9691 		if (is_jmp32) {
9692 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9693 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9694 
9695 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9696 						       false_umax);
9697 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9698 						      true_umin);
9699 		} else {
9700 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9701 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9702 
9703 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9704 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9705 		}
9706 		break;
9707 	}
9708 	case BPF_JSGE:
9709 	case BPF_JSGT:
9710 	{
9711 		if (is_jmp32) {
9712 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9713 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9714 
9715 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9716 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9717 		} else {
9718 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9719 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9720 
9721 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9722 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9723 		}
9724 		break;
9725 	}
9726 	case BPF_JLE:
9727 	case BPF_JLT:
9728 	{
9729 		if (is_jmp32) {
9730 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9731 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9732 
9733 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9734 						       false_umin);
9735 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9736 						      true_umax);
9737 		} else {
9738 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9739 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9740 
9741 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9742 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9743 		}
9744 		break;
9745 	}
9746 	case BPF_JSLE:
9747 	case BPF_JSLT:
9748 	{
9749 		if (is_jmp32) {
9750 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9751 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9752 
9753 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9754 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9755 		} else {
9756 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9757 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9758 
9759 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9760 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9761 		}
9762 		break;
9763 	}
9764 	default:
9765 		return;
9766 	}
9767 
9768 	if (is_jmp32) {
9769 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9770 					     tnum_subreg(false_32off));
9771 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9772 					    tnum_subreg(true_32off));
9773 		__reg_combine_32_into_64(false_reg);
9774 		__reg_combine_32_into_64(true_reg);
9775 	} else {
9776 		false_reg->var_off = false_64off;
9777 		true_reg->var_off = true_64off;
9778 		__reg_combine_64_into_32(false_reg);
9779 		__reg_combine_64_into_32(true_reg);
9780 	}
9781 }
9782 
9783 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9784  * the variable reg.
9785  */
9786 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9787 				struct bpf_reg_state *false_reg,
9788 				u64 val, u32 val32,
9789 				u8 opcode, bool is_jmp32)
9790 {
9791 	opcode = flip_opcode(opcode);
9792 	/* This uses zero as "not present in table"; luckily the zero opcode,
9793 	 * BPF_JA, can't get here.
9794 	 */
9795 	if (opcode)
9796 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9797 }
9798 
9799 /* Regs are known to be equal, so intersect their min/max/var_off */
9800 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9801 				  struct bpf_reg_state *dst_reg)
9802 {
9803 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9804 							dst_reg->umin_value);
9805 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9806 							dst_reg->umax_value);
9807 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9808 							dst_reg->smin_value);
9809 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9810 							dst_reg->smax_value);
9811 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9812 							     dst_reg->var_off);
9813 	reg_bounds_sync(src_reg);
9814 	reg_bounds_sync(dst_reg);
9815 }
9816 
9817 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9818 				struct bpf_reg_state *true_dst,
9819 				struct bpf_reg_state *false_src,
9820 				struct bpf_reg_state *false_dst,
9821 				u8 opcode)
9822 {
9823 	switch (opcode) {
9824 	case BPF_JEQ:
9825 		__reg_combine_min_max(true_src, true_dst);
9826 		break;
9827 	case BPF_JNE:
9828 		__reg_combine_min_max(false_src, false_dst);
9829 		break;
9830 	}
9831 }
9832 
9833 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9834 				 struct bpf_reg_state *reg, u32 id,
9835 				 bool is_null)
9836 {
9837 	if (type_may_be_null(reg->type) && reg->id == id &&
9838 	    !WARN_ON_ONCE(!reg->id)) {
9839 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9840 				 !tnum_equals_const(reg->var_off, 0) ||
9841 				 reg->off)) {
9842 			/* Old offset (both fixed and variable parts) should
9843 			 * have been known-zero, because we don't allow pointer
9844 			 * arithmetic on pointers that might be NULL. If we
9845 			 * see this happening, don't convert the register.
9846 			 */
9847 			return;
9848 		}
9849 		if (is_null) {
9850 			reg->type = SCALAR_VALUE;
9851 			/* We don't need id and ref_obj_id from this point
9852 			 * onwards anymore, thus we should better reset it,
9853 			 * so that state pruning has chances to take effect.
9854 			 */
9855 			reg->id = 0;
9856 			reg->ref_obj_id = 0;
9857 
9858 			return;
9859 		}
9860 
9861 		mark_ptr_not_null_reg(reg);
9862 
9863 		if (!reg_may_point_to_spin_lock(reg)) {
9864 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9865 			 * in release_reg_references().
9866 			 *
9867 			 * reg->id is still used by spin_lock ptr. Other
9868 			 * than spin_lock ptr type, reg->id can be reset.
9869 			 */
9870 			reg->id = 0;
9871 		}
9872 	}
9873 }
9874 
9875 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9876 				    bool is_null)
9877 {
9878 	struct bpf_reg_state *reg;
9879 	int i;
9880 
9881 	for (i = 0; i < MAX_BPF_REG; i++)
9882 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9883 
9884 	bpf_for_each_spilled_reg(i, state, reg) {
9885 		if (!reg)
9886 			continue;
9887 		mark_ptr_or_null_reg(state, reg, id, is_null);
9888 	}
9889 }
9890 
9891 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9892  * be folded together at some point.
9893  */
9894 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9895 				  bool is_null)
9896 {
9897 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9898 	struct bpf_reg_state *regs = state->regs;
9899 	u32 ref_obj_id = regs[regno].ref_obj_id;
9900 	u32 id = regs[regno].id;
9901 	int i;
9902 
9903 	if (ref_obj_id && ref_obj_id == id && is_null)
9904 		/* regs[regno] is in the " == NULL" branch.
9905 		 * No one could have freed the reference state before
9906 		 * doing the NULL check.
9907 		 */
9908 		WARN_ON_ONCE(release_reference_state(state, id));
9909 
9910 	for (i = 0; i <= vstate->curframe; i++)
9911 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9912 }
9913 
9914 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9915 				   struct bpf_reg_state *dst_reg,
9916 				   struct bpf_reg_state *src_reg,
9917 				   struct bpf_verifier_state *this_branch,
9918 				   struct bpf_verifier_state *other_branch)
9919 {
9920 	if (BPF_SRC(insn->code) != BPF_X)
9921 		return false;
9922 
9923 	/* Pointers are always 64-bit. */
9924 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9925 		return false;
9926 
9927 	switch (BPF_OP(insn->code)) {
9928 	case BPF_JGT:
9929 		if ((dst_reg->type == PTR_TO_PACKET &&
9930 		     src_reg->type == PTR_TO_PACKET_END) ||
9931 		    (dst_reg->type == PTR_TO_PACKET_META &&
9932 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9933 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9934 			find_good_pkt_pointers(this_branch, dst_reg,
9935 					       dst_reg->type, false);
9936 			mark_pkt_end(other_branch, insn->dst_reg, true);
9937 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9938 			    src_reg->type == PTR_TO_PACKET) ||
9939 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9940 			    src_reg->type == PTR_TO_PACKET_META)) {
9941 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9942 			find_good_pkt_pointers(other_branch, src_reg,
9943 					       src_reg->type, true);
9944 			mark_pkt_end(this_branch, insn->src_reg, false);
9945 		} else {
9946 			return false;
9947 		}
9948 		break;
9949 	case BPF_JLT:
9950 		if ((dst_reg->type == PTR_TO_PACKET &&
9951 		     src_reg->type == PTR_TO_PACKET_END) ||
9952 		    (dst_reg->type == PTR_TO_PACKET_META &&
9953 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9954 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9955 			find_good_pkt_pointers(other_branch, dst_reg,
9956 					       dst_reg->type, true);
9957 			mark_pkt_end(this_branch, insn->dst_reg, false);
9958 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9959 			    src_reg->type == PTR_TO_PACKET) ||
9960 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9961 			    src_reg->type == PTR_TO_PACKET_META)) {
9962 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9963 			find_good_pkt_pointers(this_branch, src_reg,
9964 					       src_reg->type, false);
9965 			mark_pkt_end(other_branch, insn->src_reg, true);
9966 		} else {
9967 			return false;
9968 		}
9969 		break;
9970 	case BPF_JGE:
9971 		if ((dst_reg->type == PTR_TO_PACKET &&
9972 		     src_reg->type == PTR_TO_PACKET_END) ||
9973 		    (dst_reg->type == PTR_TO_PACKET_META &&
9974 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9975 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9976 			find_good_pkt_pointers(this_branch, dst_reg,
9977 					       dst_reg->type, true);
9978 			mark_pkt_end(other_branch, insn->dst_reg, false);
9979 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9980 			    src_reg->type == PTR_TO_PACKET) ||
9981 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9982 			    src_reg->type == PTR_TO_PACKET_META)) {
9983 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9984 			find_good_pkt_pointers(other_branch, src_reg,
9985 					       src_reg->type, false);
9986 			mark_pkt_end(this_branch, insn->src_reg, true);
9987 		} else {
9988 			return false;
9989 		}
9990 		break;
9991 	case BPF_JLE:
9992 		if ((dst_reg->type == PTR_TO_PACKET &&
9993 		     src_reg->type == PTR_TO_PACKET_END) ||
9994 		    (dst_reg->type == PTR_TO_PACKET_META &&
9995 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9996 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9997 			find_good_pkt_pointers(other_branch, dst_reg,
9998 					       dst_reg->type, false);
9999 			mark_pkt_end(this_branch, insn->dst_reg, true);
10000 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10001 			    src_reg->type == PTR_TO_PACKET) ||
10002 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10003 			    src_reg->type == PTR_TO_PACKET_META)) {
10004 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10005 			find_good_pkt_pointers(this_branch, src_reg,
10006 					       src_reg->type, true);
10007 			mark_pkt_end(other_branch, insn->src_reg, false);
10008 		} else {
10009 			return false;
10010 		}
10011 		break;
10012 	default:
10013 		return false;
10014 	}
10015 
10016 	return true;
10017 }
10018 
10019 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10020 			       struct bpf_reg_state *known_reg)
10021 {
10022 	struct bpf_func_state *state;
10023 	struct bpf_reg_state *reg;
10024 	int i, j;
10025 
10026 	for (i = 0; i <= vstate->curframe; i++) {
10027 		state = vstate->frame[i];
10028 		for (j = 0; j < MAX_BPF_REG; j++) {
10029 			reg = &state->regs[j];
10030 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10031 				*reg = *known_reg;
10032 		}
10033 
10034 		bpf_for_each_spilled_reg(j, state, reg) {
10035 			if (!reg)
10036 				continue;
10037 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10038 				*reg = *known_reg;
10039 		}
10040 	}
10041 }
10042 
10043 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10044 			     struct bpf_insn *insn, int *insn_idx)
10045 {
10046 	struct bpf_verifier_state *this_branch = env->cur_state;
10047 	struct bpf_verifier_state *other_branch;
10048 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10049 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10050 	u8 opcode = BPF_OP(insn->code);
10051 	bool is_jmp32;
10052 	int pred = -1;
10053 	int err;
10054 
10055 	/* Only conditional jumps are expected to reach here. */
10056 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10057 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10058 		return -EINVAL;
10059 	}
10060 
10061 	if (BPF_SRC(insn->code) == BPF_X) {
10062 		if (insn->imm != 0) {
10063 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10064 			return -EINVAL;
10065 		}
10066 
10067 		/* check src1 operand */
10068 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10069 		if (err)
10070 			return err;
10071 
10072 		if (is_pointer_value(env, insn->src_reg)) {
10073 			verbose(env, "R%d pointer comparison prohibited\n",
10074 				insn->src_reg);
10075 			return -EACCES;
10076 		}
10077 		src_reg = &regs[insn->src_reg];
10078 	} else {
10079 		if (insn->src_reg != BPF_REG_0) {
10080 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10081 			return -EINVAL;
10082 		}
10083 	}
10084 
10085 	/* check src2 operand */
10086 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10087 	if (err)
10088 		return err;
10089 
10090 	dst_reg = &regs[insn->dst_reg];
10091 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10092 
10093 	if (BPF_SRC(insn->code) == BPF_K) {
10094 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10095 	} else if (src_reg->type == SCALAR_VALUE &&
10096 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10097 		pred = is_branch_taken(dst_reg,
10098 				       tnum_subreg(src_reg->var_off).value,
10099 				       opcode,
10100 				       is_jmp32);
10101 	} else if (src_reg->type == SCALAR_VALUE &&
10102 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10103 		pred = is_branch_taken(dst_reg,
10104 				       src_reg->var_off.value,
10105 				       opcode,
10106 				       is_jmp32);
10107 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10108 		   reg_is_pkt_pointer_any(src_reg) &&
10109 		   !is_jmp32) {
10110 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10111 	}
10112 
10113 	if (pred >= 0) {
10114 		/* If we get here with a dst_reg pointer type it is because
10115 		 * above is_branch_taken() special cased the 0 comparison.
10116 		 */
10117 		if (!__is_pointer_value(false, dst_reg))
10118 			err = mark_chain_precision(env, insn->dst_reg);
10119 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10120 		    !__is_pointer_value(false, src_reg))
10121 			err = mark_chain_precision(env, insn->src_reg);
10122 		if (err)
10123 			return err;
10124 	}
10125 
10126 	if (pred == 1) {
10127 		/* Only follow the goto, ignore fall-through. If needed, push
10128 		 * the fall-through branch for simulation under speculative
10129 		 * execution.
10130 		 */
10131 		if (!env->bypass_spec_v1 &&
10132 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10133 					       *insn_idx))
10134 			return -EFAULT;
10135 		*insn_idx += insn->off;
10136 		return 0;
10137 	} else if (pred == 0) {
10138 		/* Only follow the fall-through branch, since that's where the
10139 		 * program will go. If needed, push the goto branch for
10140 		 * simulation under speculative execution.
10141 		 */
10142 		if (!env->bypass_spec_v1 &&
10143 		    !sanitize_speculative_path(env, insn,
10144 					       *insn_idx + insn->off + 1,
10145 					       *insn_idx))
10146 			return -EFAULT;
10147 		return 0;
10148 	}
10149 
10150 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10151 				  false);
10152 	if (!other_branch)
10153 		return -EFAULT;
10154 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10155 
10156 	/* detect if we are comparing against a constant value so we can adjust
10157 	 * our min/max values for our dst register.
10158 	 * this is only legit if both are scalars (or pointers to the same
10159 	 * object, I suppose, but we don't support that right now), because
10160 	 * otherwise the different base pointers mean the offsets aren't
10161 	 * comparable.
10162 	 */
10163 	if (BPF_SRC(insn->code) == BPF_X) {
10164 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10165 
10166 		if (dst_reg->type == SCALAR_VALUE &&
10167 		    src_reg->type == SCALAR_VALUE) {
10168 			if (tnum_is_const(src_reg->var_off) ||
10169 			    (is_jmp32 &&
10170 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10171 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10172 						dst_reg,
10173 						src_reg->var_off.value,
10174 						tnum_subreg(src_reg->var_off).value,
10175 						opcode, is_jmp32);
10176 			else if (tnum_is_const(dst_reg->var_off) ||
10177 				 (is_jmp32 &&
10178 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10179 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10180 						    src_reg,
10181 						    dst_reg->var_off.value,
10182 						    tnum_subreg(dst_reg->var_off).value,
10183 						    opcode, is_jmp32);
10184 			else if (!is_jmp32 &&
10185 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10186 				/* Comparing for equality, we can combine knowledge */
10187 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10188 						    &other_branch_regs[insn->dst_reg],
10189 						    src_reg, dst_reg, opcode);
10190 			if (src_reg->id &&
10191 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10192 				find_equal_scalars(this_branch, src_reg);
10193 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10194 			}
10195 
10196 		}
10197 	} else if (dst_reg->type == SCALAR_VALUE) {
10198 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10199 					dst_reg, insn->imm, (u32)insn->imm,
10200 					opcode, is_jmp32);
10201 	}
10202 
10203 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10204 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10205 		find_equal_scalars(this_branch, dst_reg);
10206 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10207 	}
10208 
10209 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10210 	 * NOTE: these optimizations below are related with pointer comparison
10211 	 *       which will never be JMP32.
10212 	 */
10213 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10214 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10215 	    type_may_be_null(dst_reg->type)) {
10216 		/* Mark all identical registers in each branch as either
10217 		 * safe or unknown depending R == 0 or R != 0 conditional.
10218 		 */
10219 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10220 				      opcode == BPF_JNE);
10221 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10222 				      opcode == BPF_JEQ);
10223 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10224 					   this_branch, other_branch) &&
10225 		   is_pointer_value(env, insn->dst_reg)) {
10226 		verbose(env, "R%d pointer comparison prohibited\n",
10227 			insn->dst_reg);
10228 		return -EACCES;
10229 	}
10230 	if (env->log.level & BPF_LOG_LEVEL)
10231 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10232 	return 0;
10233 }
10234 
10235 /* verify BPF_LD_IMM64 instruction */
10236 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10237 {
10238 	struct bpf_insn_aux_data *aux = cur_aux(env);
10239 	struct bpf_reg_state *regs = cur_regs(env);
10240 	struct bpf_reg_state *dst_reg;
10241 	struct bpf_map *map;
10242 	int err;
10243 
10244 	if (BPF_SIZE(insn->code) != BPF_DW) {
10245 		verbose(env, "invalid BPF_LD_IMM insn\n");
10246 		return -EINVAL;
10247 	}
10248 	if (insn->off != 0) {
10249 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10250 		return -EINVAL;
10251 	}
10252 
10253 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10254 	if (err)
10255 		return err;
10256 
10257 	dst_reg = &regs[insn->dst_reg];
10258 	if (insn->src_reg == 0) {
10259 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10260 
10261 		dst_reg->type = SCALAR_VALUE;
10262 		__mark_reg_known(&regs[insn->dst_reg], imm);
10263 		return 0;
10264 	}
10265 
10266 	/* All special src_reg cases are listed below. From this point onwards
10267 	 * we either succeed and assign a corresponding dst_reg->type after
10268 	 * zeroing the offset, or fail and reject the program.
10269 	 */
10270 	mark_reg_known_zero(env, regs, insn->dst_reg);
10271 
10272 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10273 		dst_reg->type = aux->btf_var.reg_type;
10274 		switch (base_type(dst_reg->type)) {
10275 		case PTR_TO_MEM:
10276 			dst_reg->mem_size = aux->btf_var.mem_size;
10277 			break;
10278 		case PTR_TO_BTF_ID:
10279 			dst_reg->btf = aux->btf_var.btf;
10280 			dst_reg->btf_id = aux->btf_var.btf_id;
10281 			break;
10282 		default:
10283 			verbose(env, "bpf verifier is misconfigured\n");
10284 			return -EFAULT;
10285 		}
10286 		return 0;
10287 	}
10288 
10289 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10290 		struct bpf_prog_aux *aux = env->prog->aux;
10291 		u32 subprogno = find_subprog(env,
10292 					     env->insn_idx + insn->imm + 1);
10293 
10294 		if (!aux->func_info) {
10295 			verbose(env, "missing btf func_info\n");
10296 			return -EINVAL;
10297 		}
10298 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10299 			verbose(env, "callback function not static\n");
10300 			return -EINVAL;
10301 		}
10302 
10303 		dst_reg->type = PTR_TO_FUNC;
10304 		dst_reg->subprogno = subprogno;
10305 		return 0;
10306 	}
10307 
10308 	map = env->used_maps[aux->map_index];
10309 	dst_reg->map_ptr = map;
10310 
10311 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10312 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10313 		dst_reg->type = PTR_TO_MAP_VALUE;
10314 		dst_reg->off = aux->map_off;
10315 		if (map_value_has_spin_lock(map))
10316 			dst_reg->id = ++env->id_gen;
10317 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10318 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10319 		dst_reg->type = CONST_PTR_TO_MAP;
10320 	} else {
10321 		verbose(env, "bpf verifier is misconfigured\n");
10322 		return -EINVAL;
10323 	}
10324 
10325 	return 0;
10326 }
10327 
10328 static bool may_access_skb(enum bpf_prog_type type)
10329 {
10330 	switch (type) {
10331 	case BPF_PROG_TYPE_SOCKET_FILTER:
10332 	case BPF_PROG_TYPE_SCHED_CLS:
10333 	case BPF_PROG_TYPE_SCHED_ACT:
10334 		return true;
10335 	default:
10336 		return false;
10337 	}
10338 }
10339 
10340 /* verify safety of LD_ABS|LD_IND instructions:
10341  * - they can only appear in the programs where ctx == skb
10342  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10343  *   preserve R6-R9, and store return value into R0
10344  *
10345  * Implicit input:
10346  *   ctx == skb == R6 == CTX
10347  *
10348  * Explicit input:
10349  *   SRC == any register
10350  *   IMM == 32-bit immediate
10351  *
10352  * Output:
10353  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10354  */
10355 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10356 {
10357 	struct bpf_reg_state *regs = cur_regs(env);
10358 	static const int ctx_reg = BPF_REG_6;
10359 	u8 mode = BPF_MODE(insn->code);
10360 	int i, err;
10361 
10362 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10363 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10364 		return -EINVAL;
10365 	}
10366 
10367 	if (!env->ops->gen_ld_abs) {
10368 		verbose(env, "bpf verifier is misconfigured\n");
10369 		return -EINVAL;
10370 	}
10371 
10372 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10373 	    BPF_SIZE(insn->code) == BPF_DW ||
10374 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10375 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10376 		return -EINVAL;
10377 	}
10378 
10379 	/* check whether implicit source operand (register R6) is readable */
10380 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10381 	if (err)
10382 		return err;
10383 
10384 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10385 	 * gen_ld_abs() may terminate the program at runtime, leading to
10386 	 * reference leak.
10387 	 */
10388 	err = check_reference_leak(env);
10389 	if (err) {
10390 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10391 		return err;
10392 	}
10393 
10394 	if (env->cur_state->active_spin_lock) {
10395 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10396 		return -EINVAL;
10397 	}
10398 
10399 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10400 		verbose(env,
10401 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10402 		return -EINVAL;
10403 	}
10404 
10405 	if (mode == BPF_IND) {
10406 		/* check explicit source operand */
10407 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10408 		if (err)
10409 			return err;
10410 	}
10411 
10412 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10413 	if (err < 0)
10414 		return err;
10415 
10416 	/* reset caller saved regs to unreadable */
10417 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10418 		mark_reg_not_init(env, regs, caller_saved[i]);
10419 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10420 	}
10421 
10422 	/* mark destination R0 register as readable, since it contains
10423 	 * the value fetched from the packet.
10424 	 * Already marked as written above.
10425 	 */
10426 	mark_reg_unknown(env, regs, BPF_REG_0);
10427 	/* ld_abs load up to 32-bit skb data. */
10428 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10429 	return 0;
10430 }
10431 
10432 static int check_return_code(struct bpf_verifier_env *env)
10433 {
10434 	struct tnum enforce_attach_type_range = tnum_unknown;
10435 	const struct bpf_prog *prog = env->prog;
10436 	struct bpf_reg_state *reg;
10437 	struct tnum range = tnum_range(0, 1);
10438 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10439 	int err;
10440 	struct bpf_func_state *frame = env->cur_state->frame[0];
10441 	const bool is_subprog = frame->subprogno;
10442 
10443 	/* LSM and struct_ops func-ptr's return type could be "void" */
10444 	if (!is_subprog) {
10445 		switch (prog_type) {
10446 		case BPF_PROG_TYPE_LSM:
10447 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10448 				/* See below, can be 0 or 0-1 depending on hook. */
10449 				break;
10450 			fallthrough;
10451 		case BPF_PROG_TYPE_STRUCT_OPS:
10452 			if (!prog->aux->attach_func_proto->type)
10453 				return 0;
10454 			break;
10455 		default:
10456 			break;
10457 		}
10458 	}
10459 
10460 	/* eBPF calling convention is such that R0 is used
10461 	 * to return the value from eBPF program.
10462 	 * Make sure that it's readable at this time
10463 	 * of bpf_exit, which means that program wrote
10464 	 * something into it earlier
10465 	 */
10466 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10467 	if (err)
10468 		return err;
10469 
10470 	if (is_pointer_value(env, BPF_REG_0)) {
10471 		verbose(env, "R0 leaks addr as return value\n");
10472 		return -EACCES;
10473 	}
10474 
10475 	reg = cur_regs(env) + BPF_REG_0;
10476 
10477 	if (frame->in_async_callback_fn) {
10478 		/* enforce return zero from async callbacks like timer */
10479 		if (reg->type != SCALAR_VALUE) {
10480 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10481 				reg_type_str(env, reg->type));
10482 			return -EINVAL;
10483 		}
10484 
10485 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10486 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10487 			return -EINVAL;
10488 		}
10489 		return 0;
10490 	}
10491 
10492 	if (is_subprog) {
10493 		if (reg->type != SCALAR_VALUE) {
10494 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10495 				reg_type_str(env, reg->type));
10496 			return -EINVAL;
10497 		}
10498 		return 0;
10499 	}
10500 
10501 	switch (prog_type) {
10502 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10503 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10504 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10505 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10506 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10507 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10508 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10509 			range = tnum_range(1, 1);
10510 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10511 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10512 			range = tnum_range(0, 3);
10513 		break;
10514 	case BPF_PROG_TYPE_CGROUP_SKB:
10515 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10516 			range = tnum_range(0, 3);
10517 			enforce_attach_type_range = tnum_range(2, 3);
10518 		}
10519 		break;
10520 	case BPF_PROG_TYPE_CGROUP_SOCK:
10521 	case BPF_PROG_TYPE_SOCK_OPS:
10522 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10523 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10524 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10525 		break;
10526 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10527 		if (!env->prog->aux->attach_btf_id)
10528 			return 0;
10529 		range = tnum_const(0);
10530 		break;
10531 	case BPF_PROG_TYPE_TRACING:
10532 		switch (env->prog->expected_attach_type) {
10533 		case BPF_TRACE_FENTRY:
10534 		case BPF_TRACE_FEXIT:
10535 			range = tnum_const(0);
10536 			break;
10537 		case BPF_TRACE_RAW_TP:
10538 		case BPF_MODIFY_RETURN:
10539 			return 0;
10540 		case BPF_TRACE_ITER:
10541 			break;
10542 		default:
10543 			return -ENOTSUPP;
10544 		}
10545 		break;
10546 	case BPF_PROG_TYPE_SK_LOOKUP:
10547 		range = tnum_range(SK_DROP, SK_PASS);
10548 		break;
10549 
10550 	case BPF_PROG_TYPE_LSM:
10551 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10552 			/* Regular BPF_PROG_TYPE_LSM programs can return
10553 			 * any value.
10554 			 */
10555 			return 0;
10556 		}
10557 		if (!env->prog->aux->attach_func_proto->type) {
10558 			/* Make sure programs that attach to void
10559 			 * hooks don't try to modify return value.
10560 			 */
10561 			range = tnum_range(1, 1);
10562 		}
10563 		break;
10564 
10565 	case BPF_PROG_TYPE_EXT:
10566 		/* freplace program can return anything as its return value
10567 		 * depends on the to-be-replaced kernel func or bpf program.
10568 		 */
10569 	default:
10570 		return 0;
10571 	}
10572 
10573 	if (reg->type != SCALAR_VALUE) {
10574 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10575 			reg_type_str(env, reg->type));
10576 		return -EINVAL;
10577 	}
10578 
10579 	if (!tnum_in(range, reg->var_off)) {
10580 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10581 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10582 		    prog_type == BPF_PROG_TYPE_LSM &&
10583 		    !prog->aux->attach_func_proto->type)
10584 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10585 		return -EINVAL;
10586 	}
10587 
10588 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10589 	    tnum_in(enforce_attach_type_range, reg->var_off))
10590 		env->prog->enforce_expected_attach_type = 1;
10591 	return 0;
10592 }
10593 
10594 /* non-recursive DFS pseudo code
10595  * 1  procedure DFS-iterative(G,v):
10596  * 2      label v as discovered
10597  * 3      let S be a stack
10598  * 4      S.push(v)
10599  * 5      while S is not empty
10600  * 6            t <- S.pop()
10601  * 7            if t is what we're looking for:
10602  * 8                return t
10603  * 9            for all edges e in G.adjacentEdges(t) do
10604  * 10               if edge e is already labelled
10605  * 11                   continue with the next edge
10606  * 12               w <- G.adjacentVertex(t,e)
10607  * 13               if vertex w is not discovered and not explored
10608  * 14                   label e as tree-edge
10609  * 15                   label w as discovered
10610  * 16                   S.push(w)
10611  * 17                   continue at 5
10612  * 18               else if vertex w is discovered
10613  * 19                   label e as back-edge
10614  * 20               else
10615  * 21                   // vertex w is explored
10616  * 22                   label e as forward- or cross-edge
10617  * 23           label t as explored
10618  * 24           S.pop()
10619  *
10620  * convention:
10621  * 0x10 - discovered
10622  * 0x11 - discovered and fall-through edge labelled
10623  * 0x12 - discovered and fall-through and branch edges labelled
10624  * 0x20 - explored
10625  */
10626 
10627 enum {
10628 	DISCOVERED = 0x10,
10629 	EXPLORED = 0x20,
10630 	FALLTHROUGH = 1,
10631 	BRANCH = 2,
10632 };
10633 
10634 static u32 state_htab_size(struct bpf_verifier_env *env)
10635 {
10636 	return env->prog->len;
10637 }
10638 
10639 static struct bpf_verifier_state_list **explored_state(
10640 					struct bpf_verifier_env *env,
10641 					int idx)
10642 {
10643 	struct bpf_verifier_state *cur = env->cur_state;
10644 	struct bpf_func_state *state = cur->frame[cur->curframe];
10645 
10646 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10647 }
10648 
10649 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10650 {
10651 	env->insn_aux_data[idx].prune_point = true;
10652 }
10653 
10654 enum {
10655 	DONE_EXPLORING = 0,
10656 	KEEP_EXPLORING = 1,
10657 };
10658 
10659 /* t, w, e - match pseudo-code above:
10660  * t - index of current instruction
10661  * w - next instruction
10662  * e - edge
10663  */
10664 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10665 		     bool loop_ok)
10666 {
10667 	int *insn_stack = env->cfg.insn_stack;
10668 	int *insn_state = env->cfg.insn_state;
10669 
10670 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10671 		return DONE_EXPLORING;
10672 
10673 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10674 		return DONE_EXPLORING;
10675 
10676 	if (w < 0 || w >= env->prog->len) {
10677 		verbose_linfo(env, t, "%d: ", t);
10678 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10679 		return -EINVAL;
10680 	}
10681 
10682 	if (e == BRANCH)
10683 		/* mark branch target for state pruning */
10684 		init_explored_state(env, w);
10685 
10686 	if (insn_state[w] == 0) {
10687 		/* tree-edge */
10688 		insn_state[t] = DISCOVERED | e;
10689 		insn_state[w] = DISCOVERED;
10690 		if (env->cfg.cur_stack >= env->prog->len)
10691 			return -E2BIG;
10692 		insn_stack[env->cfg.cur_stack++] = w;
10693 		return KEEP_EXPLORING;
10694 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10695 		if (loop_ok && env->bpf_capable)
10696 			return DONE_EXPLORING;
10697 		verbose_linfo(env, t, "%d: ", t);
10698 		verbose_linfo(env, w, "%d: ", w);
10699 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10700 		return -EINVAL;
10701 	} else if (insn_state[w] == EXPLORED) {
10702 		/* forward- or cross-edge */
10703 		insn_state[t] = DISCOVERED | e;
10704 	} else {
10705 		verbose(env, "insn state internal bug\n");
10706 		return -EFAULT;
10707 	}
10708 	return DONE_EXPLORING;
10709 }
10710 
10711 static int visit_func_call_insn(int t, int insn_cnt,
10712 				struct bpf_insn *insns,
10713 				struct bpf_verifier_env *env,
10714 				bool visit_callee)
10715 {
10716 	int ret;
10717 
10718 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10719 	if (ret)
10720 		return ret;
10721 
10722 	if (t + 1 < insn_cnt)
10723 		init_explored_state(env, t + 1);
10724 	if (visit_callee) {
10725 		init_explored_state(env, t);
10726 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10727 				/* It's ok to allow recursion from CFG point of
10728 				 * view. __check_func_call() will do the actual
10729 				 * check.
10730 				 */
10731 				bpf_pseudo_func(insns + t));
10732 	}
10733 	return ret;
10734 }
10735 
10736 /* Visits the instruction at index t and returns one of the following:
10737  *  < 0 - an error occurred
10738  *  DONE_EXPLORING - the instruction was fully explored
10739  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10740  */
10741 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10742 {
10743 	struct bpf_insn *insns = env->prog->insnsi;
10744 	int ret;
10745 
10746 	if (bpf_pseudo_func(insns + t))
10747 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10748 
10749 	/* All non-branch instructions have a single fall-through edge. */
10750 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10751 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10752 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10753 
10754 	switch (BPF_OP(insns[t].code)) {
10755 	case BPF_EXIT:
10756 		return DONE_EXPLORING;
10757 
10758 	case BPF_CALL:
10759 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10760 			/* Mark this call insn to trigger is_state_visited() check
10761 			 * before call itself is processed by __check_func_call().
10762 			 * Otherwise new async state will be pushed for further
10763 			 * exploration.
10764 			 */
10765 			init_explored_state(env, t);
10766 		return visit_func_call_insn(t, insn_cnt, insns, env,
10767 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10768 
10769 	case BPF_JA:
10770 		if (BPF_SRC(insns[t].code) != BPF_K)
10771 			return -EINVAL;
10772 
10773 		/* unconditional jump with single edge */
10774 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10775 				true);
10776 		if (ret)
10777 			return ret;
10778 
10779 		/* unconditional jmp is not a good pruning point,
10780 		 * but it's marked, since backtracking needs
10781 		 * to record jmp history in is_state_visited().
10782 		 */
10783 		init_explored_state(env, t + insns[t].off + 1);
10784 		/* tell verifier to check for equivalent states
10785 		 * after every call and jump
10786 		 */
10787 		if (t + 1 < insn_cnt)
10788 			init_explored_state(env, t + 1);
10789 
10790 		return ret;
10791 
10792 	default:
10793 		/* conditional jump with two edges */
10794 		init_explored_state(env, t);
10795 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10796 		if (ret)
10797 			return ret;
10798 
10799 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10800 	}
10801 }
10802 
10803 /* non-recursive depth-first-search to detect loops in BPF program
10804  * loop == back-edge in directed graph
10805  */
10806 static int check_cfg(struct bpf_verifier_env *env)
10807 {
10808 	int insn_cnt = env->prog->len;
10809 	int *insn_stack, *insn_state;
10810 	int ret = 0;
10811 	int i;
10812 
10813 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10814 	if (!insn_state)
10815 		return -ENOMEM;
10816 
10817 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10818 	if (!insn_stack) {
10819 		kvfree(insn_state);
10820 		return -ENOMEM;
10821 	}
10822 
10823 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10824 	insn_stack[0] = 0; /* 0 is the first instruction */
10825 	env->cfg.cur_stack = 1;
10826 
10827 	while (env->cfg.cur_stack > 0) {
10828 		int t = insn_stack[env->cfg.cur_stack - 1];
10829 
10830 		ret = visit_insn(t, insn_cnt, env);
10831 		switch (ret) {
10832 		case DONE_EXPLORING:
10833 			insn_state[t] = EXPLORED;
10834 			env->cfg.cur_stack--;
10835 			break;
10836 		case KEEP_EXPLORING:
10837 			break;
10838 		default:
10839 			if (ret > 0) {
10840 				verbose(env, "visit_insn internal bug\n");
10841 				ret = -EFAULT;
10842 			}
10843 			goto err_free;
10844 		}
10845 	}
10846 
10847 	if (env->cfg.cur_stack < 0) {
10848 		verbose(env, "pop stack internal bug\n");
10849 		ret = -EFAULT;
10850 		goto err_free;
10851 	}
10852 
10853 	for (i = 0; i < insn_cnt; i++) {
10854 		if (insn_state[i] != EXPLORED) {
10855 			verbose(env, "unreachable insn %d\n", i);
10856 			ret = -EINVAL;
10857 			goto err_free;
10858 		}
10859 	}
10860 	ret = 0; /* cfg looks good */
10861 
10862 err_free:
10863 	kvfree(insn_state);
10864 	kvfree(insn_stack);
10865 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10866 	return ret;
10867 }
10868 
10869 static int check_abnormal_return(struct bpf_verifier_env *env)
10870 {
10871 	int i;
10872 
10873 	for (i = 1; i < env->subprog_cnt; i++) {
10874 		if (env->subprog_info[i].has_ld_abs) {
10875 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10876 			return -EINVAL;
10877 		}
10878 		if (env->subprog_info[i].has_tail_call) {
10879 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10880 			return -EINVAL;
10881 		}
10882 	}
10883 	return 0;
10884 }
10885 
10886 /* The minimum supported BTF func info size */
10887 #define MIN_BPF_FUNCINFO_SIZE	8
10888 #define MAX_FUNCINFO_REC_SIZE	252
10889 
10890 static int check_btf_func(struct bpf_verifier_env *env,
10891 			  const union bpf_attr *attr,
10892 			  bpfptr_t uattr)
10893 {
10894 	const struct btf_type *type, *func_proto, *ret_type;
10895 	u32 i, nfuncs, urec_size, min_size;
10896 	u32 krec_size = sizeof(struct bpf_func_info);
10897 	struct bpf_func_info *krecord;
10898 	struct bpf_func_info_aux *info_aux = NULL;
10899 	struct bpf_prog *prog;
10900 	const struct btf *btf;
10901 	bpfptr_t urecord;
10902 	u32 prev_offset = 0;
10903 	bool scalar_return;
10904 	int ret = -ENOMEM;
10905 
10906 	nfuncs = attr->func_info_cnt;
10907 	if (!nfuncs) {
10908 		if (check_abnormal_return(env))
10909 			return -EINVAL;
10910 		return 0;
10911 	}
10912 
10913 	if (nfuncs != env->subprog_cnt) {
10914 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10915 		return -EINVAL;
10916 	}
10917 
10918 	urec_size = attr->func_info_rec_size;
10919 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10920 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10921 	    urec_size % sizeof(u32)) {
10922 		verbose(env, "invalid func info rec size %u\n", urec_size);
10923 		return -EINVAL;
10924 	}
10925 
10926 	prog = env->prog;
10927 	btf = prog->aux->btf;
10928 
10929 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10930 	min_size = min_t(u32, krec_size, urec_size);
10931 
10932 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10933 	if (!krecord)
10934 		return -ENOMEM;
10935 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10936 	if (!info_aux)
10937 		goto err_free;
10938 
10939 	for (i = 0; i < nfuncs; i++) {
10940 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10941 		if (ret) {
10942 			if (ret == -E2BIG) {
10943 				verbose(env, "nonzero tailing record in func info");
10944 				/* set the size kernel expects so loader can zero
10945 				 * out the rest of the record.
10946 				 */
10947 				if (copy_to_bpfptr_offset(uattr,
10948 							  offsetof(union bpf_attr, func_info_rec_size),
10949 							  &min_size, sizeof(min_size)))
10950 					ret = -EFAULT;
10951 			}
10952 			goto err_free;
10953 		}
10954 
10955 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10956 			ret = -EFAULT;
10957 			goto err_free;
10958 		}
10959 
10960 		/* check insn_off */
10961 		ret = -EINVAL;
10962 		if (i == 0) {
10963 			if (krecord[i].insn_off) {
10964 				verbose(env,
10965 					"nonzero insn_off %u for the first func info record",
10966 					krecord[i].insn_off);
10967 				goto err_free;
10968 			}
10969 		} else if (krecord[i].insn_off <= prev_offset) {
10970 			verbose(env,
10971 				"same or smaller insn offset (%u) than previous func info record (%u)",
10972 				krecord[i].insn_off, prev_offset);
10973 			goto err_free;
10974 		}
10975 
10976 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10977 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10978 			goto err_free;
10979 		}
10980 
10981 		/* check type_id */
10982 		type = btf_type_by_id(btf, krecord[i].type_id);
10983 		if (!type || !btf_type_is_func(type)) {
10984 			verbose(env, "invalid type id %d in func info",
10985 				krecord[i].type_id);
10986 			goto err_free;
10987 		}
10988 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10989 
10990 		func_proto = btf_type_by_id(btf, type->type);
10991 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10992 			/* btf_func_check() already verified it during BTF load */
10993 			goto err_free;
10994 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10995 		scalar_return =
10996 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
10997 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10998 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10999 			goto err_free;
11000 		}
11001 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11002 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11003 			goto err_free;
11004 		}
11005 
11006 		prev_offset = krecord[i].insn_off;
11007 		bpfptr_add(&urecord, urec_size);
11008 	}
11009 
11010 	prog->aux->func_info = krecord;
11011 	prog->aux->func_info_cnt = nfuncs;
11012 	prog->aux->func_info_aux = info_aux;
11013 	return 0;
11014 
11015 err_free:
11016 	kvfree(krecord);
11017 	kfree(info_aux);
11018 	return ret;
11019 }
11020 
11021 static void adjust_btf_func(struct bpf_verifier_env *env)
11022 {
11023 	struct bpf_prog_aux *aux = env->prog->aux;
11024 	int i;
11025 
11026 	if (!aux->func_info)
11027 		return;
11028 
11029 	for (i = 0; i < env->subprog_cnt; i++)
11030 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11031 }
11032 
11033 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11034 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11035 
11036 static int check_btf_line(struct bpf_verifier_env *env,
11037 			  const union bpf_attr *attr,
11038 			  bpfptr_t uattr)
11039 {
11040 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11041 	struct bpf_subprog_info *sub;
11042 	struct bpf_line_info *linfo;
11043 	struct bpf_prog *prog;
11044 	const struct btf *btf;
11045 	bpfptr_t ulinfo;
11046 	int err;
11047 
11048 	nr_linfo = attr->line_info_cnt;
11049 	if (!nr_linfo)
11050 		return 0;
11051 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11052 		return -EINVAL;
11053 
11054 	rec_size = attr->line_info_rec_size;
11055 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11056 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11057 	    rec_size & (sizeof(u32) - 1))
11058 		return -EINVAL;
11059 
11060 	/* Need to zero it in case the userspace may
11061 	 * pass in a smaller bpf_line_info object.
11062 	 */
11063 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11064 			 GFP_KERNEL | __GFP_NOWARN);
11065 	if (!linfo)
11066 		return -ENOMEM;
11067 
11068 	prog = env->prog;
11069 	btf = prog->aux->btf;
11070 
11071 	s = 0;
11072 	sub = env->subprog_info;
11073 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11074 	expected_size = sizeof(struct bpf_line_info);
11075 	ncopy = min_t(u32, expected_size, rec_size);
11076 	for (i = 0; i < nr_linfo; i++) {
11077 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11078 		if (err) {
11079 			if (err == -E2BIG) {
11080 				verbose(env, "nonzero tailing record in line_info");
11081 				if (copy_to_bpfptr_offset(uattr,
11082 							  offsetof(union bpf_attr, line_info_rec_size),
11083 							  &expected_size, sizeof(expected_size)))
11084 					err = -EFAULT;
11085 			}
11086 			goto err_free;
11087 		}
11088 
11089 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11090 			err = -EFAULT;
11091 			goto err_free;
11092 		}
11093 
11094 		/*
11095 		 * Check insn_off to ensure
11096 		 * 1) strictly increasing AND
11097 		 * 2) bounded by prog->len
11098 		 *
11099 		 * The linfo[0].insn_off == 0 check logically falls into
11100 		 * the later "missing bpf_line_info for func..." case
11101 		 * because the first linfo[0].insn_off must be the
11102 		 * first sub also and the first sub must have
11103 		 * subprog_info[0].start == 0.
11104 		 */
11105 		if ((i && linfo[i].insn_off <= prev_offset) ||
11106 		    linfo[i].insn_off >= prog->len) {
11107 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11108 				i, linfo[i].insn_off, prev_offset,
11109 				prog->len);
11110 			err = -EINVAL;
11111 			goto err_free;
11112 		}
11113 
11114 		if (!prog->insnsi[linfo[i].insn_off].code) {
11115 			verbose(env,
11116 				"Invalid insn code at line_info[%u].insn_off\n",
11117 				i);
11118 			err = -EINVAL;
11119 			goto err_free;
11120 		}
11121 
11122 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11123 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11124 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11125 			err = -EINVAL;
11126 			goto err_free;
11127 		}
11128 
11129 		if (s != env->subprog_cnt) {
11130 			if (linfo[i].insn_off == sub[s].start) {
11131 				sub[s].linfo_idx = i;
11132 				s++;
11133 			} else if (sub[s].start < linfo[i].insn_off) {
11134 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11135 				err = -EINVAL;
11136 				goto err_free;
11137 			}
11138 		}
11139 
11140 		prev_offset = linfo[i].insn_off;
11141 		bpfptr_add(&ulinfo, rec_size);
11142 	}
11143 
11144 	if (s != env->subprog_cnt) {
11145 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11146 			env->subprog_cnt - s, s);
11147 		err = -EINVAL;
11148 		goto err_free;
11149 	}
11150 
11151 	prog->aux->linfo = linfo;
11152 	prog->aux->nr_linfo = nr_linfo;
11153 
11154 	return 0;
11155 
11156 err_free:
11157 	kvfree(linfo);
11158 	return err;
11159 }
11160 
11161 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11162 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11163 
11164 static int check_core_relo(struct bpf_verifier_env *env,
11165 			   const union bpf_attr *attr,
11166 			   bpfptr_t uattr)
11167 {
11168 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11169 	struct bpf_core_relo core_relo = {};
11170 	struct bpf_prog *prog = env->prog;
11171 	const struct btf *btf = prog->aux->btf;
11172 	struct bpf_core_ctx ctx = {
11173 		.log = &env->log,
11174 		.btf = btf,
11175 	};
11176 	bpfptr_t u_core_relo;
11177 	int err;
11178 
11179 	nr_core_relo = attr->core_relo_cnt;
11180 	if (!nr_core_relo)
11181 		return 0;
11182 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11183 		return -EINVAL;
11184 
11185 	rec_size = attr->core_relo_rec_size;
11186 	if (rec_size < MIN_CORE_RELO_SIZE ||
11187 	    rec_size > MAX_CORE_RELO_SIZE ||
11188 	    rec_size % sizeof(u32))
11189 		return -EINVAL;
11190 
11191 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11192 	expected_size = sizeof(struct bpf_core_relo);
11193 	ncopy = min_t(u32, expected_size, rec_size);
11194 
11195 	/* Unlike func_info and line_info, copy and apply each CO-RE
11196 	 * relocation record one at a time.
11197 	 */
11198 	for (i = 0; i < nr_core_relo; i++) {
11199 		/* future proofing when sizeof(bpf_core_relo) changes */
11200 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11201 		if (err) {
11202 			if (err == -E2BIG) {
11203 				verbose(env, "nonzero tailing record in core_relo");
11204 				if (copy_to_bpfptr_offset(uattr,
11205 							  offsetof(union bpf_attr, core_relo_rec_size),
11206 							  &expected_size, sizeof(expected_size)))
11207 					err = -EFAULT;
11208 			}
11209 			break;
11210 		}
11211 
11212 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11213 			err = -EFAULT;
11214 			break;
11215 		}
11216 
11217 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11218 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11219 				i, core_relo.insn_off, prog->len);
11220 			err = -EINVAL;
11221 			break;
11222 		}
11223 
11224 		err = bpf_core_apply(&ctx, &core_relo, i,
11225 				     &prog->insnsi[core_relo.insn_off / 8]);
11226 		if (err)
11227 			break;
11228 		bpfptr_add(&u_core_relo, rec_size);
11229 	}
11230 	return err;
11231 }
11232 
11233 static int check_btf_info(struct bpf_verifier_env *env,
11234 			  const union bpf_attr *attr,
11235 			  bpfptr_t uattr)
11236 {
11237 	struct btf *btf;
11238 	int err;
11239 
11240 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11241 		if (check_abnormal_return(env))
11242 			return -EINVAL;
11243 		return 0;
11244 	}
11245 
11246 	btf = btf_get_by_fd(attr->prog_btf_fd);
11247 	if (IS_ERR(btf))
11248 		return PTR_ERR(btf);
11249 	if (btf_is_kernel(btf)) {
11250 		btf_put(btf);
11251 		return -EACCES;
11252 	}
11253 	env->prog->aux->btf = btf;
11254 
11255 	err = check_btf_func(env, attr, uattr);
11256 	if (err)
11257 		return err;
11258 
11259 	err = check_btf_line(env, attr, uattr);
11260 	if (err)
11261 		return err;
11262 
11263 	err = check_core_relo(env, attr, uattr);
11264 	if (err)
11265 		return err;
11266 
11267 	return 0;
11268 }
11269 
11270 /* check %cur's range satisfies %old's */
11271 static bool range_within(struct bpf_reg_state *old,
11272 			 struct bpf_reg_state *cur)
11273 {
11274 	return old->umin_value <= cur->umin_value &&
11275 	       old->umax_value >= cur->umax_value &&
11276 	       old->smin_value <= cur->smin_value &&
11277 	       old->smax_value >= cur->smax_value &&
11278 	       old->u32_min_value <= cur->u32_min_value &&
11279 	       old->u32_max_value >= cur->u32_max_value &&
11280 	       old->s32_min_value <= cur->s32_min_value &&
11281 	       old->s32_max_value >= cur->s32_max_value;
11282 }
11283 
11284 /* If in the old state two registers had the same id, then they need to have
11285  * the same id in the new state as well.  But that id could be different from
11286  * the old state, so we need to track the mapping from old to new ids.
11287  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11288  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11289  * regs with a different old id could still have new id 9, we don't care about
11290  * that.
11291  * So we look through our idmap to see if this old id has been seen before.  If
11292  * so, we require the new id to match; otherwise, we add the id pair to the map.
11293  */
11294 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11295 {
11296 	unsigned int i;
11297 
11298 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11299 		if (!idmap[i].old) {
11300 			/* Reached an empty slot; haven't seen this id before */
11301 			idmap[i].old = old_id;
11302 			idmap[i].cur = cur_id;
11303 			return true;
11304 		}
11305 		if (idmap[i].old == old_id)
11306 			return idmap[i].cur == cur_id;
11307 	}
11308 	/* We ran out of idmap slots, which should be impossible */
11309 	WARN_ON_ONCE(1);
11310 	return false;
11311 }
11312 
11313 static void clean_func_state(struct bpf_verifier_env *env,
11314 			     struct bpf_func_state *st)
11315 {
11316 	enum bpf_reg_liveness live;
11317 	int i, j;
11318 
11319 	for (i = 0; i < BPF_REG_FP; i++) {
11320 		live = st->regs[i].live;
11321 		/* liveness must not touch this register anymore */
11322 		st->regs[i].live |= REG_LIVE_DONE;
11323 		if (!(live & REG_LIVE_READ))
11324 			/* since the register is unused, clear its state
11325 			 * to make further comparison simpler
11326 			 */
11327 			__mark_reg_not_init(env, &st->regs[i]);
11328 	}
11329 
11330 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11331 		live = st->stack[i].spilled_ptr.live;
11332 		/* liveness must not touch this stack slot anymore */
11333 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11334 		if (!(live & REG_LIVE_READ)) {
11335 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11336 			for (j = 0; j < BPF_REG_SIZE; j++)
11337 				st->stack[i].slot_type[j] = STACK_INVALID;
11338 		}
11339 	}
11340 }
11341 
11342 static void clean_verifier_state(struct bpf_verifier_env *env,
11343 				 struct bpf_verifier_state *st)
11344 {
11345 	int i;
11346 
11347 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11348 		/* all regs in this state in all frames were already marked */
11349 		return;
11350 
11351 	for (i = 0; i <= st->curframe; i++)
11352 		clean_func_state(env, st->frame[i]);
11353 }
11354 
11355 /* the parentage chains form a tree.
11356  * the verifier states are added to state lists at given insn and
11357  * pushed into state stack for future exploration.
11358  * when the verifier reaches bpf_exit insn some of the verifer states
11359  * stored in the state lists have their final liveness state already,
11360  * but a lot of states will get revised from liveness point of view when
11361  * the verifier explores other branches.
11362  * Example:
11363  * 1: r0 = 1
11364  * 2: if r1 == 100 goto pc+1
11365  * 3: r0 = 2
11366  * 4: exit
11367  * when the verifier reaches exit insn the register r0 in the state list of
11368  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11369  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11370  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11371  *
11372  * Since the verifier pushes the branch states as it sees them while exploring
11373  * the program the condition of walking the branch instruction for the second
11374  * time means that all states below this branch were already explored and
11375  * their final liveness marks are already propagated.
11376  * Hence when the verifier completes the search of state list in is_state_visited()
11377  * we can call this clean_live_states() function to mark all liveness states
11378  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11379  * will not be used.
11380  * This function also clears the registers and stack for states that !READ
11381  * to simplify state merging.
11382  *
11383  * Important note here that walking the same branch instruction in the callee
11384  * doesn't meant that the states are DONE. The verifier has to compare
11385  * the callsites
11386  */
11387 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11388 			      struct bpf_verifier_state *cur)
11389 {
11390 	struct bpf_verifier_state_list *sl;
11391 	int i;
11392 
11393 	sl = *explored_state(env, insn);
11394 	while (sl) {
11395 		if (sl->state.branches)
11396 			goto next;
11397 		if (sl->state.insn_idx != insn ||
11398 		    sl->state.curframe != cur->curframe)
11399 			goto next;
11400 		for (i = 0; i <= cur->curframe; i++)
11401 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11402 				goto next;
11403 		clean_verifier_state(env, &sl->state);
11404 next:
11405 		sl = sl->next;
11406 	}
11407 }
11408 
11409 /* Returns true if (rold safe implies rcur safe) */
11410 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11411 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11412 {
11413 	bool equal;
11414 
11415 	if (!(rold->live & REG_LIVE_READ))
11416 		/* explored state didn't use this */
11417 		return true;
11418 
11419 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11420 
11421 	if (rold->type == PTR_TO_STACK)
11422 		/* two stack pointers are equal only if they're pointing to
11423 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11424 		 */
11425 		return equal && rold->frameno == rcur->frameno;
11426 
11427 	if (equal)
11428 		return true;
11429 
11430 	if (rold->type == NOT_INIT)
11431 		/* explored state can't have used this */
11432 		return true;
11433 	if (rcur->type == NOT_INIT)
11434 		return false;
11435 	switch (base_type(rold->type)) {
11436 	case SCALAR_VALUE:
11437 		if (env->explore_alu_limits)
11438 			return false;
11439 		if (rcur->type == SCALAR_VALUE) {
11440 			if (!rold->precise && !rcur->precise)
11441 				return true;
11442 			/* new val must satisfy old val knowledge */
11443 			return range_within(rold, rcur) &&
11444 			       tnum_in(rold->var_off, rcur->var_off);
11445 		} else {
11446 			/* We're trying to use a pointer in place of a scalar.
11447 			 * Even if the scalar was unbounded, this could lead to
11448 			 * pointer leaks because scalars are allowed to leak
11449 			 * while pointers are not. We could make this safe in
11450 			 * special cases if root is calling us, but it's
11451 			 * probably not worth the hassle.
11452 			 */
11453 			return false;
11454 		}
11455 	case PTR_TO_MAP_KEY:
11456 	case PTR_TO_MAP_VALUE:
11457 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11458 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11459 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11460 		 * checked, doing so could have affected others with the same
11461 		 * id, and we can't check for that because we lost the id when
11462 		 * we converted to a PTR_TO_MAP_VALUE.
11463 		 */
11464 		if (type_may_be_null(rold->type)) {
11465 			if (!type_may_be_null(rcur->type))
11466 				return false;
11467 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11468 				return false;
11469 			/* Check our ids match any regs they're supposed to */
11470 			return check_ids(rold->id, rcur->id, idmap);
11471 		}
11472 
11473 		/* If the new min/max/var_off satisfy the old ones and
11474 		 * everything else matches, we are OK.
11475 		 * 'id' is not compared, since it's only used for maps with
11476 		 * bpf_spin_lock inside map element and in such cases if
11477 		 * the rest of the prog is valid for one map element then
11478 		 * it's valid for all map elements regardless of the key
11479 		 * used in bpf_map_lookup()
11480 		 */
11481 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11482 		       range_within(rold, rcur) &&
11483 		       tnum_in(rold->var_off, rcur->var_off);
11484 	case PTR_TO_PACKET_META:
11485 	case PTR_TO_PACKET:
11486 		if (rcur->type != rold->type)
11487 			return false;
11488 		/* We must have at least as much range as the old ptr
11489 		 * did, so that any accesses which were safe before are
11490 		 * still safe.  This is true even if old range < old off,
11491 		 * since someone could have accessed through (ptr - k), or
11492 		 * even done ptr -= k in a register, to get a safe access.
11493 		 */
11494 		if (rold->range > rcur->range)
11495 			return false;
11496 		/* If the offsets don't match, we can't trust our alignment;
11497 		 * nor can we be sure that we won't fall out of range.
11498 		 */
11499 		if (rold->off != rcur->off)
11500 			return false;
11501 		/* id relations must be preserved */
11502 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11503 			return false;
11504 		/* new val must satisfy old val knowledge */
11505 		return range_within(rold, rcur) &&
11506 		       tnum_in(rold->var_off, rcur->var_off);
11507 	case PTR_TO_CTX:
11508 	case CONST_PTR_TO_MAP:
11509 	case PTR_TO_PACKET_END:
11510 	case PTR_TO_FLOW_KEYS:
11511 	case PTR_TO_SOCKET:
11512 	case PTR_TO_SOCK_COMMON:
11513 	case PTR_TO_TCP_SOCK:
11514 	case PTR_TO_XDP_SOCK:
11515 		/* Only valid matches are exact, which memcmp() above
11516 		 * would have accepted
11517 		 */
11518 	default:
11519 		/* Don't know what's going on, just say it's not safe */
11520 		return false;
11521 	}
11522 
11523 	/* Shouldn't get here; if we do, say it's not safe */
11524 	WARN_ON_ONCE(1);
11525 	return false;
11526 }
11527 
11528 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11529 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11530 {
11531 	int i, spi;
11532 
11533 	/* walk slots of the explored stack and ignore any additional
11534 	 * slots in the current stack, since explored(safe) state
11535 	 * didn't use them
11536 	 */
11537 	for (i = 0; i < old->allocated_stack; i++) {
11538 		spi = i / BPF_REG_SIZE;
11539 
11540 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11541 			i += BPF_REG_SIZE - 1;
11542 			/* explored state didn't use this */
11543 			continue;
11544 		}
11545 
11546 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11547 			continue;
11548 
11549 		/* explored stack has more populated slots than current stack
11550 		 * and these slots were used
11551 		 */
11552 		if (i >= cur->allocated_stack)
11553 			return false;
11554 
11555 		/* if old state was safe with misc data in the stack
11556 		 * it will be safe with zero-initialized stack.
11557 		 * The opposite is not true
11558 		 */
11559 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11560 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11561 			continue;
11562 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11563 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11564 			/* Ex: old explored (safe) state has STACK_SPILL in
11565 			 * this stack slot, but current has STACK_MISC ->
11566 			 * this verifier states are not equivalent,
11567 			 * return false to continue verification of this path
11568 			 */
11569 			return false;
11570 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11571 			continue;
11572 		if (!is_spilled_reg(&old->stack[spi]))
11573 			continue;
11574 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11575 			     &cur->stack[spi].spilled_ptr, idmap))
11576 			/* when explored and current stack slot are both storing
11577 			 * spilled registers, check that stored pointers types
11578 			 * are the same as well.
11579 			 * Ex: explored safe path could have stored
11580 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11581 			 * but current path has stored:
11582 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11583 			 * such verifier states are not equivalent.
11584 			 * return false to continue verification of this path
11585 			 */
11586 			return false;
11587 	}
11588 	return true;
11589 }
11590 
11591 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11592 {
11593 	if (old->acquired_refs != cur->acquired_refs)
11594 		return false;
11595 	return !memcmp(old->refs, cur->refs,
11596 		       sizeof(*old->refs) * old->acquired_refs);
11597 }
11598 
11599 /* compare two verifier states
11600  *
11601  * all states stored in state_list are known to be valid, since
11602  * verifier reached 'bpf_exit' instruction through them
11603  *
11604  * this function is called when verifier exploring different branches of
11605  * execution popped from the state stack. If it sees an old state that has
11606  * more strict register state and more strict stack state then this execution
11607  * branch doesn't need to be explored further, since verifier already
11608  * concluded that more strict state leads to valid finish.
11609  *
11610  * Therefore two states are equivalent if register state is more conservative
11611  * and explored stack state is more conservative than the current one.
11612  * Example:
11613  *       explored                   current
11614  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11615  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11616  *
11617  * In other words if current stack state (one being explored) has more
11618  * valid slots than old one that already passed validation, it means
11619  * the verifier can stop exploring and conclude that current state is valid too
11620  *
11621  * Similarly with registers. If explored state has register type as invalid
11622  * whereas register type in current state is meaningful, it means that
11623  * the current state will reach 'bpf_exit' instruction safely
11624  */
11625 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11626 			      struct bpf_func_state *cur)
11627 {
11628 	int i;
11629 
11630 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11631 	for (i = 0; i < MAX_BPF_REG; i++)
11632 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11633 			     env->idmap_scratch))
11634 			return false;
11635 
11636 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11637 		return false;
11638 
11639 	if (!refsafe(old, cur))
11640 		return false;
11641 
11642 	return true;
11643 }
11644 
11645 static bool states_equal(struct bpf_verifier_env *env,
11646 			 struct bpf_verifier_state *old,
11647 			 struct bpf_verifier_state *cur)
11648 {
11649 	int i;
11650 
11651 	if (old->curframe != cur->curframe)
11652 		return false;
11653 
11654 	/* Verification state from speculative execution simulation
11655 	 * must never prune a non-speculative execution one.
11656 	 */
11657 	if (old->speculative && !cur->speculative)
11658 		return false;
11659 
11660 	if (old->active_spin_lock != cur->active_spin_lock)
11661 		return false;
11662 
11663 	/* for states to be equal callsites have to be the same
11664 	 * and all frame states need to be equivalent
11665 	 */
11666 	for (i = 0; i <= old->curframe; i++) {
11667 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11668 			return false;
11669 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11670 			return false;
11671 	}
11672 	return true;
11673 }
11674 
11675 /* Return 0 if no propagation happened. Return negative error code if error
11676  * happened. Otherwise, return the propagated bit.
11677  */
11678 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11679 				  struct bpf_reg_state *reg,
11680 				  struct bpf_reg_state *parent_reg)
11681 {
11682 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11683 	u8 flag = reg->live & REG_LIVE_READ;
11684 	int err;
11685 
11686 	/* When comes here, read flags of PARENT_REG or REG could be any of
11687 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11688 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11689 	 */
11690 	if (parent_flag == REG_LIVE_READ64 ||
11691 	    /* Or if there is no read flag from REG. */
11692 	    !flag ||
11693 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11694 	    parent_flag == flag)
11695 		return 0;
11696 
11697 	err = mark_reg_read(env, reg, parent_reg, flag);
11698 	if (err)
11699 		return err;
11700 
11701 	return flag;
11702 }
11703 
11704 /* A write screens off any subsequent reads; but write marks come from the
11705  * straight-line code between a state and its parent.  When we arrive at an
11706  * equivalent state (jump target or such) we didn't arrive by the straight-line
11707  * code, so read marks in the state must propagate to the parent regardless
11708  * of the state's write marks. That's what 'parent == state->parent' comparison
11709  * in mark_reg_read() is for.
11710  */
11711 static int propagate_liveness(struct bpf_verifier_env *env,
11712 			      const struct bpf_verifier_state *vstate,
11713 			      struct bpf_verifier_state *vparent)
11714 {
11715 	struct bpf_reg_state *state_reg, *parent_reg;
11716 	struct bpf_func_state *state, *parent;
11717 	int i, frame, err = 0;
11718 
11719 	if (vparent->curframe != vstate->curframe) {
11720 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11721 		     vparent->curframe, vstate->curframe);
11722 		return -EFAULT;
11723 	}
11724 	/* Propagate read liveness of registers... */
11725 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11726 	for (frame = 0; frame <= vstate->curframe; frame++) {
11727 		parent = vparent->frame[frame];
11728 		state = vstate->frame[frame];
11729 		parent_reg = parent->regs;
11730 		state_reg = state->regs;
11731 		/* We don't need to worry about FP liveness, it's read-only */
11732 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11733 			err = propagate_liveness_reg(env, &state_reg[i],
11734 						     &parent_reg[i]);
11735 			if (err < 0)
11736 				return err;
11737 			if (err == REG_LIVE_READ64)
11738 				mark_insn_zext(env, &parent_reg[i]);
11739 		}
11740 
11741 		/* Propagate stack slots. */
11742 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11743 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11744 			parent_reg = &parent->stack[i].spilled_ptr;
11745 			state_reg = &state->stack[i].spilled_ptr;
11746 			err = propagate_liveness_reg(env, state_reg,
11747 						     parent_reg);
11748 			if (err < 0)
11749 				return err;
11750 		}
11751 	}
11752 	return 0;
11753 }
11754 
11755 /* find precise scalars in the previous equivalent state and
11756  * propagate them into the current state
11757  */
11758 static int propagate_precision(struct bpf_verifier_env *env,
11759 			       const struct bpf_verifier_state *old)
11760 {
11761 	struct bpf_reg_state *state_reg;
11762 	struct bpf_func_state *state;
11763 	int i, err = 0;
11764 
11765 	state = old->frame[old->curframe];
11766 	state_reg = state->regs;
11767 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11768 		if (state_reg->type != SCALAR_VALUE ||
11769 		    !state_reg->precise)
11770 			continue;
11771 		if (env->log.level & BPF_LOG_LEVEL2)
11772 			verbose(env, "propagating r%d\n", i);
11773 		err = mark_chain_precision(env, i);
11774 		if (err < 0)
11775 			return err;
11776 	}
11777 
11778 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11779 		if (!is_spilled_reg(&state->stack[i]))
11780 			continue;
11781 		state_reg = &state->stack[i].spilled_ptr;
11782 		if (state_reg->type != SCALAR_VALUE ||
11783 		    !state_reg->precise)
11784 			continue;
11785 		if (env->log.level & BPF_LOG_LEVEL2)
11786 			verbose(env, "propagating fp%d\n",
11787 				(-i - 1) * BPF_REG_SIZE);
11788 		err = mark_chain_precision_stack(env, i);
11789 		if (err < 0)
11790 			return err;
11791 	}
11792 	return 0;
11793 }
11794 
11795 static bool states_maybe_looping(struct bpf_verifier_state *old,
11796 				 struct bpf_verifier_state *cur)
11797 {
11798 	struct bpf_func_state *fold, *fcur;
11799 	int i, fr = cur->curframe;
11800 
11801 	if (old->curframe != fr)
11802 		return false;
11803 
11804 	fold = old->frame[fr];
11805 	fcur = cur->frame[fr];
11806 	for (i = 0; i < MAX_BPF_REG; i++)
11807 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11808 			   offsetof(struct bpf_reg_state, parent)))
11809 			return false;
11810 	return true;
11811 }
11812 
11813 
11814 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11815 {
11816 	struct bpf_verifier_state_list *new_sl;
11817 	struct bpf_verifier_state_list *sl, **pprev;
11818 	struct bpf_verifier_state *cur = env->cur_state, *new;
11819 	int i, j, err, states_cnt = 0;
11820 	bool add_new_state = env->test_state_freq ? true : false;
11821 
11822 	cur->last_insn_idx = env->prev_insn_idx;
11823 	if (!env->insn_aux_data[insn_idx].prune_point)
11824 		/* this 'insn_idx' instruction wasn't marked, so we will not
11825 		 * be doing state search here
11826 		 */
11827 		return 0;
11828 
11829 	/* bpf progs typically have pruning point every 4 instructions
11830 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11831 	 * Do not add new state for future pruning if the verifier hasn't seen
11832 	 * at least 2 jumps and at least 8 instructions.
11833 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11834 	 * In tests that amounts to up to 50% reduction into total verifier
11835 	 * memory consumption and 20% verifier time speedup.
11836 	 */
11837 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11838 	    env->insn_processed - env->prev_insn_processed >= 8)
11839 		add_new_state = true;
11840 
11841 	pprev = explored_state(env, insn_idx);
11842 	sl = *pprev;
11843 
11844 	clean_live_states(env, insn_idx, cur);
11845 
11846 	while (sl) {
11847 		states_cnt++;
11848 		if (sl->state.insn_idx != insn_idx)
11849 			goto next;
11850 
11851 		if (sl->state.branches) {
11852 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11853 
11854 			if (frame->in_async_callback_fn &&
11855 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11856 				/* Different async_entry_cnt means that the verifier is
11857 				 * processing another entry into async callback.
11858 				 * Seeing the same state is not an indication of infinite
11859 				 * loop or infinite recursion.
11860 				 * But finding the same state doesn't mean that it's safe
11861 				 * to stop processing the current state. The previous state
11862 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11863 				 * Checking in_async_callback_fn alone is not enough either.
11864 				 * Since the verifier still needs to catch infinite loops
11865 				 * inside async callbacks.
11866 				 */
11867 			} else if (states_maybe_looping(&sl->state, cur) &&
11868 				   states_equal(env, &sl->state, cur)) {
11869 				verbose_linfo(env, insn_idx, "; ");
11870 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11871 				return -EINVAL;
11872 			}
11873 			/* if the verifier is processing a loop, avoid adding new state
11874 			 * too often, since different loop iterations have distinct
11875 			 * states and may not help future pruning.
11876 			 * This threshold shouldn't be too low to make sure that
11877 			 * a loop with large bound will be rejected quickly.
11878 			 * The most abusive loop will be:
11879 			 * r1 += 1
11880 			 * if r1 < 1000000 goto pc-2
11881 			 * 1M insn_procssed limit / 100 == 10k peak states.
11882 			 * This threshold shouldn't be too high either, since states
11883 			 * at the end of the loop are likely to be useful in pruning.
11884 			 */
11885 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11886 			    env->insn_processed - env->prev_insn_processed < 100)
11887 				add_new_state = false;
11888 			goto miss;
11889 		}
11890 		if (states_equal(env, &sl->state, cur)) {
11891 			sl->hit_cnt++;
11892 			/* reached equivalent register/stack state,
11893 			 * prune the search.
11894 			 * Registers read by the continuation are read by us.
11895 			 * If we have any write marks in env->cur_state, they
11896 			 * will prevent corresponding reads in the continuation
11897 			 * from reaching our parent (an explored_state).  Our
11898 			 * own state will get the read marks recorded, but
11899 			 * they'll be immediately forgotten as we're pruning
11900 			 * this state and will pop a new one.
11901 			 */
11902 			err = propagate_liveness(env, &sl->state, cur);
11903 
11904 			/* if previous state reached the exit with precision and
11905 			 * current state is equivalent to it (except precsion marks)
11906 			 * the precision needs to be propagated back in
11907 			 * the current state.
11908 			 */
11909 			err = err ? : push_jmp_history(env, cur);
11910 			err = err ? : propagate_precision(env, &sl->state);
11911 			if (err)
11912 				return err;
11913 			return 1;
11914 		}
11915 miss:
11916 		/* when new state is not going to be added do not increase miss count.
11917 		 * Otherwise several loop iterations will remove the state
11918 		 * recorded earlier. The goal of these heuristics is to have
11919 		 * states from some iterations of the loop (some in the beginning
11920 		 * and some at the end) to help pruning.
11921 		 */
11922 		if (add_new_state)
11923 			sl->miss_cnt++;
11924 		/* heuristic to determine whether this state is beneficial
11925 		 * to keep checking from state equivalence point of view.
11926 		 * Higher numbers increase max_states_per_insn and verification time,
11927 		 * but do not meaningfully decrease insn_processed.
11928 		 */
11929 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11930 			/* the state is unlikely to be useful. Remove it to
11931 			 * speed up verification
11932 			 */
11933 			*pprev = sl->next;
11934 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11935 				u32 br = sl->state.branches;
11936 
11937 				WARN_ONCE(br,
11938 					  "BUG live_done but branches_to_explore %d\n",
11939 					  br);
11940 				free_verifier_state(&sl->state, false);
11941 				kfree(sl);
11942 				env->peak_states--;
11943 			} else {
11944 				/* cannot free this state, since parentage chain may
11945 				 * walk it later. Add it for free_list instead to
11946 				 * be freed at the end of verification
11947 				 */
11948 				sl->next = env->free_list;
11949 				env->free_list = sl;
11950 			}
11951 			sl = *pprev;
11952 			continue;
11953 		}
11954 next:
11955 		pprev = &sl->next;
11956 		sl = *pprev;
11957 	}
11958 
11959 	if (env->max_states_per_insn < states_cnt)
11960 		env->max_states_per_insn = states_cnt;
11961 
11962 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11963 		return push_jmp_history(env, cur);
11964 
11965 	if (!add_new_state)
11966 		return push_jmp_history(env, cur);
11967 
11968 	/* There were no equivalent states, remember the current one.
11969 	 * Technically the current state is not proven to be safe yet,
11970 	 * but it will either reach outer most bpf_exit (which means it's safe)
11971 	 * or it will be rejected. When there are no loops the verifier won't be
11972 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11973 	 * again on the way to bpf_exit.
11974 	 * When looping the sl->state.branches will be > 0 and this state
11975 	 * will not be considered for equivalence until branches == 0.
11976 	 */
11977 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11978 	if (!new_sl)
11979 		return -ENOMEM;
11980 	env->total_states++;
11981 	env->peak_states++;
11982 	env->prev_jmps_processed = env->jmps_processed;
11983 	env->prev_insn_processed = env->insn_processed;
11984 
11985 	/* add new state to the head of linked list */
11986 	new = &new_sl->state;
11987 	err = copy_verifier_state(new, cur);
11988 	if (err) {
11989 		free_verifier_state(new, false);
11990 		kfree(new_sl);
11991 		return err;
11992 	}
11993 	new->insn_idx = insn_idx;
11994 	WARN_ONCE(new->branches != 1,
11995 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11996 
11997 	cur->parent = new;
11998 	cur->first_insn_idx = insn_idx;
11999 	clear_jmp_history(cur);
12000 	new_sl->next = *explored_state(env, insn_idx);
12001 	*explored_state(env, insn_idx) = new_sl;
12002 	/* connect new state to parentage chain. Current frame needs all
12003 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12004 	 * to the stack implicitly by JITs) so in callers' frames connect just
12005 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12006 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12007 	 * from callee with its full parentage chain, anyway.
12008 	 */
12009 	/* clear write marks in current state: the writes we did are not writes
12010 	 * our child did, so they don't screen off its reads from us.
12011 	 * (There are no read marks in current state, because reads always mark
12012 	 * their parent and current state never has children yet.  Only
12013 	 * explored_states can get read marks.)
12014 	 */
12015 	for (j = 0; j <= cur->curframe; j++) {
12016 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12017 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12018 		for (i = 0; i < BPF_REG_FP; i++)
12019 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12020 	}
12021 
12022 	/* all stack frames are accessible from callee, clear them all */
12023 	for (j = 0; j <= cur->curframe; j++) {
12024 		struct bpf_func_state *frame = cur->frame[j];
12025 		struct bpf_func_state *newframe = new->frame[j];
12026 
12027 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12028 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12029 			frame->stack[i].spilled_ptr.parent =
12030 						&newframe->stack[i].spilled_ptr;
12031 		}
12032 	}
12033 	return 0;
12034 }
12035 
12036 /* Return true if it's OK to have the same insn return a different type. */
12037 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12038 {
12039 	switch (base_type(type)) {
12040 	case PTR_TO_CTX:
12041 	case PTR_TO_SOCKET:
12042 	case PTR_TO_SOCK_COMMON:
12043 	case PTR_TO_TCP_SOCK:
12044 	case PTR_TO_XDP_SOCK:
12045 	case PTR_TO_BTF_ID:
12046 		return false;
12047 	default:
12048 		return true;
12049 	}
12050 }
12051 
12052 /* If an instruction was previously used with particular pointer types, then we
12053  * need to be careful to avoid cases such as the below, where it may be ok
12054  * for one branch accessing the pointer, but not ok for the other branch:
12055  *
12056  * R1 = sock_ptr
12057  * goto X;
12058  * ...
12059  * R1 = some_other_valid_ptr;
12060  * goto X;
12061  * ...
12062  * R2 = *(u32 *)(R1 + 0);
12063  */
12064 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12065 {
12066 	return src != prev && (!reg_type_mismatch_ok(src) ||
12067 			       !reg_type_mismatch_ok(prev));
12068 }
12069 
12070 static int do_check(struct bpf_verifier_env *env)
12071 {
12072 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12073 	struct bpf_verifier_state *state = env->cur_state;
12074 	struct bpf_insn *insns = env->prog->insnsi;
12075 	struct bpf_reg_state *regs;
12076 	int insn_cnt = env->prog->len;
12077 	bool do_print_state = false;
12078 	int prev_insn_idx = -1;
12079 
12080 	for (;;) {
12081 		struct bpf_insn *insn;
12082 		u8 class;
12083 		int err;
12084 
12085 		env->prev_insn_idx = prev_insn_idx;
12086 		if (env->insn_idx >= insn_cnt) {
12087 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12088 				env->insn_idx, insn_cnt);
12089 			return -EFAULT;
12090 		}
12091 
12092 		insn = &insns[env->insn_idx];
12093 		class = BPF_CLASS(insn->code);
12094 
12095 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12096 			verbose(env,
12097 				"BPF program is too large. Processed %d insn\n",
12098 				env->insn_processed);
12099 			return -E2BIG;
12100 		}
12101 
12102 		err = is_state_visited(env, env->insn_idx);
12103 		if (err < 0)
12104 			return err;
12105 		if (err == 1) {
12106 			/* found equivalent state, can prune the search */
12107 			if (env->log.level & BPF_LOG_LEVEL) {
12108 				if (do_print_state)
12109 					verbose(env, "\nfrom %d to %d%s: safe\n",
12110 						env->prev_insn_idx, env->insn_idx,
12111 						env->cur_state->speculative ?
12112 						" (speculative execution)" : "");
12113 				else
12114 					verbose(env, "%d: safe\n", env->insn_idx);
12115 			}
12116 			goto process_bpf_exit;
12117 		}
12118 
12119 		if (signal_pending(current))
12120 			return -EAGAIN;
12121 
12122 		if (need_resched())
12123 			cond_resched();
12124 
12125 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12126 			verbose(env, "\nfrom %d to %d%s:",
12127 				env->prev_insn_idx, env->insn_idx,
12128 				env->cur_state->speculative ?
12129 				" (speculative execution)" : "");
12130 			print_verifier_state(env, state->frame[state->curframe], true);
12131 			do_print_state = false;
12132 		}
12133 
12134 		if (env->log.level & BPF_LOG_LEVEL) {
12135 			const struct bpf_insn_cbs cbs = {
12136 				.cb_call	= disasm_kfunc_name,
12137 				.cb_print	= verbose,
12138 				.private_data	= env,
12139 			};
12140 
12141 			if (verifier_state_scratched(env))
12142 				print_insn_state(env, state->frame[state->curframe]);
12143 
12144 			verbose_linfo(env, env->insn_idx, "; ");
12145 			env->prev_log_len = env->log.len_used;
12146 			verbose(env, "%d: ", env->insn_idx);
12147 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12148 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12149 			env->prev_log_len = env->log.len_used;
12150 		}
12151 
12152 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12153 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12154 							   env->prev_insn_idx);
12155 			if (err)
12156 				return err;
12157 		}
12158 
12159 		regs = cur_regs(env);
12160 		sanitize_mark_insn_seen(env);
12161 		prev_insn_idx = env->insn_idx;
12162 
12163 		if (class == BPF_ALU || class == BPF_ALU64) {
12164 			err = check_alu_op(env, insn);
12165 			if (err)
12166 				return err;
12167 
12168 		} else if (class == BPF_LDX) {
12169 			enum bpf_reg_type *prev_src_type, src_reg_type;
12170 
12171 			/* check for reserved fields is already done */
12172 
12173 			/* check src operand */
12174 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12175 			if (err)
12176 				return err;
12177 
12178 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12179 			if (err)
12180 				return err;
12181 
12182 			src_reg_type = regs[insn->src_reg].type;
12183 
12184 			/* check that memory (src_reg + off) is readable,
12185 			 * the state of dst_reg will be updated by this func
12186 			 */
12187 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12188 					       insn->off, BPF_SIZE(insn->code),
12189 					       BPF_READ, insn->dst_reg, false);
12190 			if (err)
12191 				return err;
12192 
12193 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12194 
12195 			if (*prev_src_type == NOT_INIT) {
12196 				/* saw a valid insn
12197 				 * dst_reg = *(u32 *)(src_reg + off)
12198 				 * save type to validate intersecting paths
12199 				 */
12200 				*prev_src_type = src_reg_type;
12201 
12202 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12203 				/* ABuser program is trying to use the same insn
12204 				 * dst_reg = *(u32*) (src_reg + off)
12205 				 * with different pointer types:
12206 				 * src_reg == ctx in one branch and
12207 				 * src_reg == stack|map in some other branch.
12208 				 * Reject it.
12209 				 */
12210 				verbose(env, "same insn cannot be used with different pointers\n");
12211 				return -EINVAL;
12212 			}
12213 
12214 		} else if (class == BPF_STX) {
12215 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12216 
12217 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12218 				err = check_atomic(env, env->insn_idx, insn);
12219 				if (err)
12220 					return err;
12221 				env->insn_idx++;
12222 				continue;
12223 			}
12224 
12225 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12226 				verbose(env, "BPF_STX uses reserved fields\n");
12227 				return -EINVAL;
12228 			}
12229 
12230 			/* check src1 operand */
12231 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12232 			if (err)
12233 				return err;
12234 			/* check src2 operand */
12235 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12236 			if (err)
12237 				return err;
12238 
12239 			dst_reg_type = regs[insn->dst_reg].type;
12240 
12241 			/* check that memory (dst_reg + off) is writeable */
12242 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12243 					       insn->off, BPF_SIZE(insn->code),
12244 					       BPF_WRITE, insn->src_reg, false);
12245 			if (err)
12246 				return err;
12247 
12248 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12249 
12250 			if (*prev_dst_type == NOT_INIT) {
12251 				*prev_dst_type = dst_reg_type;
12252 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12253 				verbose(env, "same insn cannot be used with different pointers\n");
12254 				return -EINVAL;
12255 			}
12256 
12257 		} else if (class == BPF_ST) {
12258 			if (BPF_MODE(insn->code) != BPF_MEM ||
12259 			    insn->src_reg != BPF_REG_0) {
12260 				verbose(env, "BPF_ST uses reserved fields\n");
12261 				return -EINVAL;
12262 			}
12263 			/* check src operand */
12264 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12265 			if (err)
12266 				return err;
12267 
12268 			if (is_ctx_reg(env, insn->dst_reg)) {
12269 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12270 					insn->dst_reg,
12271 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12272 				return -EACCES;
12273 			}
12274 
12275 			/* check that memory (dst_reg + off) is writeable */
12276 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12277 					       insn->off, BPF_SIZE(insn->code),
12278 					       BPF_WRITE, -1, false);
12279 			if (err)
12280 				return err;
12281 
12282 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12283 			u8 opcode = BPF_OP(insn->code);
12284 
12285 			env->jmps_processed++;
12286 			if (opcode == BPF_CALL) {
12287 				if (BPF_SRC(insn->code) != BPF_K ||
12288 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12289 				     && insn->off != 0) ||
12290 				    (insn->src_reg != BPF_REG_0 &&
12291 				     insn->src_reg != BPF_PSEUDO_CALL &&
12292 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12293 				    insn->dst_reg != BPF_REG_0 ||
12294 				    class == BPF_JMP32) {
12295 					verbose(env, "BPF_CALL uses reserved fields\n");
12296 					return -EINVAL;
12297 				}
12298 
12299 				if (env->cur_state->active_spin_lock &&
12300 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12301 				     insn->imm != BPF_FUNC_spin_unlock)) {
12302 					verbose(env, "function calls are not allowed while holding a lock\n");
12303 					return -EINVAL;
12304 				}
12305 				if (insn->src_reg == BPF_PSEUDO_CALL)
12306 					err = check_func_call(env, insn, &env->insn_idx);
12307 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12308 					err = check_kfunc_call(env, insn, &env->insn_idx);
12309 				else
12310 					err = check_helper_call(env, insn, &env->insn_idx);
12311 				if (err)
12312 					return err;
12313 			} else if (opcode == BPF_JA) {
12314 				if (BPF_SRC(insn->code) != BPF_K ||
12315 				    insn->imm != 0 ||
12316 				    insn->src_reg != BPF_REG_0 ||
12317 				    insn->dst_reg != BPF_REG_0 ||
12318 				    class == BPF_JMP32) {
12319 					verbose(env, "BPF_JA uses reserved fields\n");
12320 					return -EINVAL;
12321 				}
12322 
12323 				env->insn_idx += insn->off + 1;
12324 				continue;
12325 
12326 			} else if (opcode == BPF_EXIT) {
12327 				if (BPF_SRC(insn->code) != BPF_K ||
12328 				    insn->imm != 0 ||
12329 				    insn->src_reg != BPF_REG_0 ||
12330 				    insn->dst_reg != BPF_REG_0 ||
12331 				    class == BPF_JMP32) {
12332 					verbose(env, "BPF_EXIT uses reserved fields\n");
12333 					return -EINVAL;
12334 				}
12335 
12336 				if (env->cur_state->active_spin_lock) {
12337 					verbose(env, "bpf_spin_unlock is missing\n");
12338 					return -EINVAL;
12339 				}
12340 
12341 				if (state->curframe) {
12342 					/* exit from nested function */
12343 					err = prepare_func_exit(env, &env->insn_idx);
12344 					if (err)
12345 						return err;
12346 					do_print_state = true;
12347 					continue;
12348 				}
12349 
12350 				err = check_reference_leak(env);
12351 				if (err)
12352 					return err;
12353 
12354 				err = check_return_code(env);
12355 				if (err)
12356 					return err;
12357 process_bpf_exit:
12358 				mark_verifier_state_scratched(env);
12359 				update_branch_counts(env, env->cur_state);
12360 				err = pop_stack(env, &prev_insn_idx,
12361 						&env->insn_idx, pop_log);
12362 				if (err < 0) {
12363 					if (err != -ENOENT)
12364 						return err;
12365 					break;
12366 				} else {
12367 					do_print_state = true;
12368 					continue;
12369 				}
12370 			} else {
12371 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12372 				if (err)
12373 					return err;
12374 			}
12375 		} else if (class == BPF_LD) {
12376 			u8 mode = BPF_MODE(insn->code);
12377 
12378 			if (mode == BPF_ABS || mode == BPF_IND) {
12379 				err = check_ld_abs(env, insn);
12380 				if (err)
12381 					return err;
12382 
12383 			} else if (mode == BPF_IMM) {
12384 				err = check_ld_imm(env, insn);
12385 				if (err)
12386 					return err;
12387 
12388 				env->insn_idx++;
12389 				sanitize_mark_insn_seen(env);
12390 			} else {
12391 				verbose(env, "invalid BPF_LD mode\n");
12392 				return -EINVAL;
12393 			}
12394 		} else {
12395 			verbose(env, "unknown insn class %d\n", class);
12396 			return -EINVAL;
12397 		}
12398 
12399 		env->insn_idx++;
12400 	}
12401 
12402 	return 0;
12403 }
12404 
12405 static int find_btf_percpu_datasec(struct btf *btf)
12406 {
12407 	const struct btf_type *t;
12408 	const char *tname;
12409 	int i, n;
12410 
12411 	/*
12412 	 * Both vmlinux and module each have their own ".data..percpu"
12413 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12414 	 * types to look at only module's own BTF types.
12415 	 */
12416 	n = btf_nr_types(btf);
12417 	if (btf_is_module(btf))
12418 		i = btf_nr_types(btf_vmlinux);
12419 	else
12420 		i = 1;
12421 
12422 	for(; i < n; i++) {
12423 		t = btf_type_by_id(btf, i);
12424 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12425 			continue;
12426 
12427 		tname = btf_name_by_offset(btf, t->name_off);
12428 		if (!strcmp(tname, ".data..percpu"))
12429 			return i;
12430 	}
12431 
12432 	return -ENOENT;
12433 }
12434 
12435 /* replace pseudo btf_id with kernel symbol address */
12436 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12437 			       struct bpf_insn *insn,
12438 			       struct bpf_insn_aux_data *aux)
12439 {
12440 	const struct btf_var_secinfo *vsi;
12441 	const struct btf_type *datasec;
12442 	struct btf_mod_pair *btf_mod;
12443 	const struct btf_type *t;
12444 	const char *sym_name;
12445 	bool percpu = false;
12446 	u32 type, id = insn->imm;
12447 	struct btf *btf;
12448 	s32 datasec_id;
12449 	u64 addr;
12450 	int i, btf_fd, err;
12451 
12452 	btf_fd = insn[1].imm;
12453 	if (btf_fd) {
12454 		btf = btf_get_by_fd(btf_fd);
12455 		if (IS_ERR(btf)) {
12456 			verbose(env, "invalid module BTF object FD specified.\n");
12457 			return -EINVAL;
12458 		}
12459 	} else {
12460 		if (!btf_vmlinux) {
12461 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12462 			return -EINVAL;
12463 		}
12464 		btf = btf_vmlinux;
12465 		btf_get(btf);
12466 	}
12467 
12468 	t = btf_type_by_id(btf, id);
12469 	if (!t) {
12470 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12471 		err = -ENOENT;
12472 		goto err_put;
12473 	}
12474 
12475 	if (!btf_type_is_var(t)) {
12476 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12477 		err = -EINVAL;
12478 		goto err_put;
12479 	}
12480 
12481 	sym_name = btf_name_by_offset(btf, t->name_off);
12482 	addr = kallsyms_lookup_name(sym_name);
12483 	if (!addr) {
12484 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12485 			sym_name);
12486 		err = -ENOENT;
12487 		goto err_put;
12488 	}
12489 
12490 	datasec_id = find_btf_percpu_datasec(btf);
12491 	if (datasec_id > 0) {
12492 		datasec = btf_type_by_id(btf, datasec_id);
12493 		for_each_vsi(i, datasec, vsi) {
12494 			if (vsi->type == id) {
12495 				percpu = true;
12496 				break;
12497 			}
12498 		}
12499 	}
12500 
12501 	insn[0].imm = (u32)addr;
12502 	insn[1].imm = addr >> 32;
12503 
12504 	type = t->type;
12505 	t = btf_type_skip_modifiers(btf, type, NULL);
12506 	if (percpu) {
12507 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12508 		aux->btf_var.btf = btf;
12509 		aux->btf_var.btf_id = type;
12510 	} else if (!btf_type_is_struct(t)) {
12511 		const struct btf_type *ret;
12512 		const char *tname;
12513 		u32 tsize;
12514 
12515 		/* resolve the type size of ksym. */
12516 		ret = btf_resolve_size(btf, t, &tsize);
12517 		if (IS_ERR(ret)) {
12518 			tname = btf_name_by_offset(btf, t->name_off);
12519 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12520 				tname, PTR_ERR(ret));
12521 			err = -EINVAL;
12522 			goto err_put;
12523 		}
12524 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12525 		aux->btf_var.mem_size = tsize;
12526 	} else {
12527 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12528 		aux->btf_var.btf = btf;
12529 		aux->btf_var.btf_id = type;
12530 	}
12531 
12532 	/* check whether we recorded this BTF (and maybe module) already */
12533 	for (i = 0; i < env->used_btf_cnt; i++) {
12534 		if (env->used_btfs[i].btf == btf) {
12535 			btf_put(btf);
12536 			return 0;
12537 		}
12538 	}
12539 
12540 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12541 		err = -E2BIG;
12542 		goto err_put;
12543 	}
12544 
12545 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12546 	btf_mod->btf = btf;
12547 	btf_mod->module = NULL;
12548 
12549 	/* if we reference variables from kernel module, bump its refcount */
12550 	if (btf_is_module(btf)) {
12551 		btf_mod->module = btf_try_get_module(btf);
12552 		if (!btf_mod->module) {
12553 			err = -ENXIO;
12554 			goto err_put;
12555 		}
12556 	}
12557 
12558 	env->used_btf_cnt++;
12559 
12560 	return 0;
12561 err_put:
12562 	btf_put(btf);
12563 	return err;
12564 }
12565 
12566 static int check_map_prealloc(struct bpf_map *map)
12567 {
12568 	return (map->map_type != BPF_MAP_TYPE_HASH &&
12569 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
12570 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
12571 		!(map->map_flags & BPF_F_NO_PREALLOC);
12572 }
12573 
12574 static bool is_tracing_prog_type(enum bpf_prog_type type)
12575 {
12576 	switch (type) {
12577 	case BPF_PROG_TYPE_KPROBE:
12578 	case BPF_PROG_TYPE_TRACEPOINT:
12579 	case BPF_PROG_TYPE_PERF_EVENT:
12580 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12581 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12582 		return true;
12583 	default:
12584 		return false;
12585 	}
12586 }
12587 
12588 static bool is_preallocated_map(struct bpf_map *map)
12589 {
12590 	if (!check_map_prealloc(map))
12591 		return false;
12592 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
12593 		return false;
12594 	return true;
12595 }
12596 
12597 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12598 					struct bpf_map *map,
12599 					struct bpf_prog *prog)
12600 
12601 {
12602 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12603 	/*
12604 	 * Validate that trace type programs use preallocated hash maps.
12605 	 *
12606 	 * For programs attached to PERF events this is mandatory as the
12607 	 * perf NMI can hit any arbitrary code sequence.
12608 	 *
12609 	 * All other trace types using preallocated hash maps are unsafe as
12610 	 * well because tracepoint or kprobes can be inside locked regions
12611 	 * of the memory allocator or at a place where a recursion into the
12612 	 * memory allocator would see inconsistent state.
12613 	 *
12614 	 * On RT enabled kernels run-time allocation of all trace type
12615 	 * programs is strictly prohibited due to lock type constraints. On
12616 	 * !RT kernels it is allowed for backwards compatibility reasons for
12617 	 * now, but warnings are emitted so developers are made aware of
12618 	 * the unsafety and can fix their programs before this is enforced.
12619 	 */
12620 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
12621 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
12622 			verbose(env, "perf_event programs can only use preallocated hash map\n");
12623 			return -EINVAL;
12624 		}
12625 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
12626 			verbose(env, "trace type programs can only use preallocated hash map\n");
12627 			return -EINVAL;
12628 		}
12629 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
12630 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
12631 	}
12632 
12633 	if (map_value_has_spin_lock(map)) {
12634 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12635 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12636 			return -EINVAL;
12637 		}
12638 
12639 		if (is_tracing_prog_type(prog_type)) {
12640 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12641 			return -EINVAL;
12642 		}
12643 
12644 		if (prog->aux->sleepable) {
12645 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12646 			return -EINVAL;
12647 		}
12648 	}
12649 
12650 	if (map_value_has_timer(map)) {
12651 		if (is_tracing_prog_type(prog_type)) {
12652 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12653 			return -EINVAL;
12654 		}
12655 	}
12656 
12657 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12658 	    !bpf_offload_prog_map_match(prog, map)) {
12659 		verbose(env, "offload device mismatch between prog and map\n");
12660 		return -EINVAL;
12661 	}
12662 
12663 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12664 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12665 		return -EINVAL;
12666 	}
12667 
12668 	if (prog->aux->sleepable)
12669 		switch (map->map_type) {
12670 		case BPF_MAP_TYPE_HASH:
12671 		case BPF_MAP_TYPE_LRU_HASH:
12672 		case BPF_MAP_TYPE_ARRAY:
12673 		case BPF_MAP_TYPE_PERCPU_HASH:
12674 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12675 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12676 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12677 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12678 			if (!is_preallocated_map(map)) {
12679 				verbose(env,
12680 					"Sleepable programs can only use preallocated maps\n");
12681 				return -EINVAL;
12682 			}
12683 			break;
12684 		case BPF_MAP_TYPE_RINGBUF:
12685 		case BPF_MAP_TYPE_INODE_STORAGE:
12686 		case BPF_MAP_TYPE_SK_STORAGE:
12687 		case BPF_MAP_TYPE_TASK_STORAGE:
12688 			break;
12689 		default:
12690 			verbose(env,
12691 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12692 			return -EINVAL;
12693 		}
12694 
12695 	return 0;
12696 }
12697 
12698 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12699 {
12700 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12701 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12702 }
12703 
12704 /* find and rewrite pseudo imm in ld_imm64 instructions:
12705  *
12706  * 1. if it accesses map FD, replace it with actual map pointer.
12707  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12708  *
12709  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12710  */
12711 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12712 {
12713 	struct bpf_insn *insn = env->prog->insnsi;
12714 	int insn_cnt = env->prog->len;
12715 	int i, j, err;
12716 
12717 	err = bpf_prog_calc_tag(env->prog);
12718 	if (err)
12719 		return err;
12720 
12721 	for (i = 0; i < insn_cnt; i++, insn++) {
12722 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12723 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12724 			verbose(env, "BPF_LDX uses reserved fields\n");
12725 			return -EINVAL;
12726 		}
12727 
12728 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12729 			struct bpf_insn_aux_data *aux;
12730 			struct bpf_map *map;
12731 			struct fd f;
12732 			u64 addr;
12733 			u32 fd;
12734 
12735 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12736 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12737 			    insn[1].off != 0) {
12738 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12739 				return -EINVAL;
12740 			}
12741 
12742 			if (insn[0].src_reg == 0)
12743 				/* valid generic load 64-bit imm */
12744 				goto next_insn;
12745 
12746 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12747 				aux = &env->insn_aux_data[i];
12748 				err = check_pseudo_btf_id(env, insn, aux);
12749 				if (err)
12750 					return err;
12751 				goto next_insn;
12752 			}
12753 
12754 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12755 				aux = &env->insn_aux_data[i];
12756 				aux->ptr_type = PTR_TO_FUNC;
12757 				goto next_insn;
12758 			}
12759 
12760 			/* In final convert_pseudo_ld_imm64() step, this is
12761 			 * converted into regular 64-bit imm load insn.
12762 			 */
12763 			switch (insn[0].src_reg) {
12764 			case BPF_PSEUDO_MAP_VALUE:
12765 			case BPF_PSEUDO_MAP_IDX_VALUE:
12766 				break;
12767 			case BPF_PSEUDO_MAP_FD:
12768 			case BPF_PSEUDO_MAP_IDX:
12769 				if (insn[1].imm == 0)
12770 					break;
12771 				fallthrough;
12772 			default:
12773 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12774 				return -EINVAL;
12775 			}
12776 
12777 			switch (insn[0].src_reg) {
12778 			case BPF_PSEUDO_MAP_IDX_VALUE:
12779 			case BPF_PSEUDO_MAP_IDX:
12780 				if (bpfptr_is_null(env->fd_array)) {
12781 					verbose(env, "fd_idx without fd_array is invalid\n");
12782 					return -EPROTO;
12783 				}
12784 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12785 							    insn[0].imm * sizeof(fd),
12786 							    sizeof(fd)))
12787 					return -EFAULT;
12788 				break;
12789 			default:
12790 				fd = insn[0].imm;
12791 				break;
12792 			}
12793 
12794 			f = fdget(fd);
12795 			map = __bpf_map_get(f);
12796 			if (IS_ERR(map)) {
12797 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12798 					insn[0].imm);
12799 				return PTR_ERR(map);
12800 			}
12801 
12802 			err = check_map_prog_compatibility(env, map, env->prog);
12803 			if (err) {
12804 				fdput(f);
12805 				return err;
12806 			}
12807 
12808 			aux = &env->insn_aux_data[i];
12809 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12810 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12811 				addr = (unsigned long)map;
12812 			} else {
12813 				u32 off = insn[1].imm;
12814 
12815 				if (off >= BPF_MAX_VAR_OFF) {
12816 					verbose(env, "direct value offset of %u is not allowed\n", off);
12817 					fdput(f);
12818 					return -EINVAL;
12819 				}
12820 
12821 				if (!map->ops->map_direct_value_addr) {
12822 					verbose(env, "no direct value access support for this map type\n");
12823 					fdput(f);
12824 					return -EINVAL;
12825 				}
12826 
12827 				err = map->ops->map_direct_value_addr(map, &addr, off);
12828 				if (err) {
12829 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12830 						map->value_size, off);
12831 					fdput(f);
12832 					return err;
12833 				}
12834 
12835 				aux->map_off = off;
12836 				addr += off;
12837 			}
12838 
12839 			insn[0].imm = (u32)addr;
12840 			insn[1].imm = addr >> 32;
12841 
12842 			/* check whether we recorded this map already */
12843 			for (j = 0; j < env->used_map_cnt; j++) {
12844 				if (env->used_maps[j] == map) {
12845 					aux->map_index = j;
12846 					fdput(f);
12847 					goto next_insn;
12848 				}
12849 			}
12850 
12851 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12852 				fdput(f);
12853 				return -E2BIG;
12854 			}
12855 
12856 			/* hold the map. If the program is rejected by verifier,
12857 			 * the map will be released by release_maps() or it
12858 			 * will be used by the valid program until it's unloaded
12859 			 * and all maps are released in free_used_maps()
12860 			 */
12861 			bpf_map_inc(map);
12862 
12863 			aux->map_index = env->used_map_cnt;
12864 			env->used_maps[env->used_map_cnt++] = map;
12865 
12866 			if (bpf_map_is_cgroup_storage(map) &&
12867 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12868 				verbose(env, "only one cgroup storage of each type is allowed\n");
12869 				fdput(f);
12870 				return -EBUSY;
12871 			}
12872 
12873 			fdput(f);
12874 next_insn:
12875 			insn++;
12876 			i++;
12877 			continue;
12878 		}
12879 
12880 		/* Basic sanity check before we invest more work here. */
12881 		if (!bpf_opcode_in_insntable(insn->code)) {
12882 			verbose(env, "unknown opcode %02x\n", insn->code);
12883 			return -EINVAL;
12884 		}
12885 	}
12886 
12887 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12888 	 * 'struct bpf_map *' into a register instead of user map_fd.
12889 	 * These pointers will be used later by verifier to validate map access.
12890 	 */
12891 	return 0;
12892 }
12893 
12894 /* drop refcnt of maps used by the rejected program */
12895 static void release_maps(struct bpf_verifier_env *env)
12896 {
12897 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12898 			     env->used_map_cnt);
12899 }
12900 
12901 /* drop refcnt of maps used by the rejected program */
12902 static void release_btfs(struct bpf_verifier_env *env)
12903 {
12904 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12905 			     env->used_btf_cnt);
12906 }
12907 
12908 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12909 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12910 {
12911 	struct bpf_insn *insn = env->prog->insnsi;
12912 	int insn_cnt = env->prog->len;
12913 	int i;
12914 
12915 	for (i = 0; i < insn_cnt; i++, insn++) {
12916 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12917 			continue;
12918 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12919 			continue;
12920 		insn->src_reg = 0;
12921 	}
12922 }
12923 
12924 /* single env->prog->insni[off] instruction was replaced with the range
12925  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12926  * [0, off) and [off, end) to new locations, so the patched range stays zero
12927  */
12928 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12929 				 struct bpf_insn_aux_data *new_data,
12930 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12931 {
12932 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12933 	struct bpf_insn *insn = new_prog->insnsi;
12934 	u32 old_seen = old_data[off].seen;
12935 	u32 prog_len;
12936 	int i;
12937 
12938 	/* aux info at OFF always needs adjustment, no matter fast path
12939 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12940 	 * original insn at old prog.
12941 	 */
12942 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12943 
12944 	if (cnt == 1)
12945 		return;
12946 	prog_len = new_prog->len;
12947 
12948 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12949 	memcpy(new_data + off + cnt - 1, old_data + off,
12950 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12951 	for (i = off; i < off + cnt - 1; i++) {
12952 		/* Expand insni[off]'s seen count to the patched range. */
12953 		new_data[i].seen = old_seen;
12954 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12955 	}
12956 	env->insn_aux_data = new_data;
12957 	vfree(old_data);
12958 }
12959 
12960 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12961 {
12962 	int i;
12963 
12964 	if (len == 1)
12965 		return;
12966 	/* NOTE: fake 'exit' subprog should be updated as well. */
12967 	for (i = 0; i <= env->subprog_cnt; i++) {
12968 		if (env->subprog_info[i].start <= off)
12969 			continue;
12970 		env->subprog_info[i].start += len - 1;
12971 	}
12972 }
12973 
12974 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12975 {
12976 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12977 	int i, sz = prog->aux->size_poke_tab;
12978 	struct bpf_jit_poke_descriptor *desc;
12979 
12980 	for (i = 0; i < sz; i++) {
12981 		desc = &tab[i];
12982 		if (desc->insn_idx <= off)
12983 			continue;
12984 		desc->insn_idx += len - 1;
12985 	}
12986 }
12987 
12988 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12989 					    const struct bpf_insn *patch, u32 len)
12990 {
12991 	struct bpf_prog *new_prog;
12992 	struct bpf_insn_aux_data *new_data = NULL;
12993 
12994 	if (len > 1) {
12995 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12996 					      sizeof(struct bpf_insn_aux_data)));
12997 		if (!new_data)
12998 			return NULL;
12999 	}
13000 
13001 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13002 	if (IS_ERR(new_prog)) {
13003 		if (PTR_ERR(new_prog) == -ERANGE)
13004 			verbose(env,
13005 				"insn %d cannot be patched due to 16-bit range\n",
13006 				env->insn_aux_data[off].orig_idx);
13007 		vfree(new_data);
13008 		return NULL;
13009 	}
13010 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
13011 	adjust_subprog_starts(env, off, len);
13012 	adjust_poke_descs(new_prog, off, len);
13013 	return new_prog;
13014 }
13015 
13016 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13017 					      u32 off, u32 cnt)
13018 {
13019 	int i, j;
13020 
13021 	/* find first prog starting at or after off (first to remove) */
13022 	for (i = 0; i < env->subprog_cnt; i++)
13023 		if (env->subprog_info[i].start >= off)
13024 			break;
13025 	/* find first prog starting at or after off + cnt (first to stay) */
13026 	for (j = i; j < env->subprog_cnt; j++)
13027 		if (env->subprog_info[j].start >= off + cnt)
13028 			break;
13029 	/* if j doesn't start exactly at off + cnt, we are just removing
13030 	 * the front of previous prog
13031 	 */
13032 	if (env->subprog_info[j].start != off + cnt)
13033 		j--;
13034 
13035 	if (j > i) {
13036 		struct bpf_prog_aux *aux = env->prog->aux;
13037 		int move;
13038 
13039 		/* move fake 'exit' subprog as well */
13040 		move = env->subprog_cnt + 1 - j;
13041 
13042 		memmove(env->subprog_info + i,
13043 			env->subprog_info + j,
13044 			sizeof(*env->subprog_info) * move);
13045 		env->subprog_cnt -= j - i;
13046 
13047 		/* remove func_info */
13048 		if (aux->func_info) {
13049 			move = aux->func_info_cnt - j;
13050 
13051 			memmove(aux->func_info + i,
13052 				aux->func_info + j,
13053 				sizeof(*aux->func_info) * move);
13054 			aux->func_info_cnt -= j - i;
13055 			/* func_info->insn_off is set after all code rewrites,
13056 			 * in adjust_btf_func() - no need to adjust
13057 			 */
13058 		}
13059 	} else {
13060 		/* convert i from "first prog to remove" to "first to adjust" */
13061 		if (env->subprog_info[i].start == off)
13062 			i++;
13063 	}
13064 
13065 	/* update fake 'exit' subprog as well */
13066 	for (; i <= env->subprog_cnt; i++)
13067 		env->subprog_info[i].start -= cnt;
13068 
13069 	return 0;
13070 }
13071 
13072 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13073 				      u32 cnt)
13074 {
13075 	struct bpf_prog *prog = env->prog;
13076 	u32 i, l_off, l_cnt, nr_linfo;
13077 	struct bpf_line_info *linfo;
13078 
13079 	nr_linfo = prog->aux->nr_linfo;
13080 	if (!nr_linfo)
13081 		return 0;
13082 
13083 	linfo = prog->aux->linfo;
13084 
13085 	/* find first line info to remove, count lines to be removed */
13086 	for (i = 0; i < nr_linfo; i++)
13087 		if (linfo[i].insn_off >= off)
13088 			break;
13089 
13090 	l_off = i;
13091 	l_cnt = 0;
13092 	for (; i < nr_linfo; i++)
13093 		if (linfo[i].insn_off < off + cnt)
13094 			l_cnt++;
13095 		else
13096 			break;
13097 
13098 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13099 	 * last removed linfo.  prog is already modified, so prog->len == off
13100 	 * means no live instructions after (tail of the program was removed).
13101 	 */
13102 	if (prog->len != off && l_cnt &&
13103 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13104 		l_cnt--;
13105 		linfo[--i].insn_off = off + cnt;
13106 	}
13107 
13108 	/* remove the line info which refer to the removed instructions */
13109 	if (l_cnt) {
13110 		memmove(linfo + l_off, linfo + i,
13111 			sizeof(*linfo) * (nr_linfo - i));
13112 
13113 		prog->aux->nr_linfo -= l_cnt;
13114 		nr_linfo = prog->aux->nr_linfo;
13115 	}
13116 
13117 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13118 	for (i = l_off; i < nr_linfo; i++)
13119 		linfo[i].insn_off -= cnt;
13120 
13121 	/* fix up all subprogs (incl. 'exit') which start >= off */
13122 	for (i = 0; i <= env->subprog_cnt; i++)
13123 		if (env->subprog_info[i].linfo_idx > l_off) {
13124 			/* program may have started in the removed region but
13125 			 * may not be fully removed
13126 			 */
13127 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13128 				env->subprog_info[i].linfo_idx -= l_cnt;
13129 			else
13130 				env->subprog_info[i].linfo_idx = l_off;
13131 		}
13132 
13133 	return 0;
13134 }
13135 
13136 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13137 {
13138 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13139 	unsigned int orig_prog_len = env->prog->len;
13140 	int err;
13141 
13142 	if (bpf_prog_is_dev_bound(env->prog->aux))
13143 		bpf_prog_offload_remove_insns(env, off, cnt);
13144 
13145 	err = bpf_remove_insns(env->prog, off, cnt);
13146 	if (err)
13147 		return err;
13148 
13149 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13150 	if (err)
13151 		return err;
13152 
13153 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13154 	if (err)
13155 		return err;
13156 
13157 	memmove(aux_data + off,	aux_data + off + cnt,
13158 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13159 
13160 	return 0;
13161 }
13162 
13163 /* The verifier does more data flow analysis than llvm and will not
13164  * explore branches that are dead at run time. Malicious programs can
13165  * have dead code too. Therefore replace all dead at-run-time code
13166  * with 'ja -1'.
13167  *
13168  * Just nops are not optimal, e.g. if they would sit at the end of the
13169  * program and through another bug we would manage to jump there, then
13170  * we'd execute beyond program memory otherwise. Returning exception
13171  * code also wouldn't work since we can have subprogs where the dead
13172  * code could be located.
13173  */
13174 static void sanitize_dead_code(struct bpf_verifier_env *env)
13175 {
13176 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13177 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13178 	struct bpf_insn *insn = env->prog->insnsi;
13179 	const int insn_cnt = env->prog->len;
13180 	int i;
13181 
13182 	for (i = 0; i < insn_cnt; i++) {
13183 		if (aux_data[i].seen)
13184 			continue;
13185 		memcpy(insn + i, &trap, sizeof(trap));
13186 		aux_data[i].zext_dst = false;
13187 	}
13188 }
13189 
13190 static bool insn_is_cond_jump(u8 code)
13191 {
13192 	u8 op;
13193 
13194 	if (BPF_CLASS(code) == BPF_JMP32)
13195 		return true;
13196 
13197 	if (BPF_CLASS(code) != BPF_JMP)
13198 		return false;
13199 
13200 	op = BPF_OP(code);
13201 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13202 }
13203 
13204 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13205 {
13206 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13207 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13208 	struct bpf_insn *insn = env->prog->insnsi;
13209 	const int insn_cnt = env->prog->len;
13210 	int i;
13211 
13212 	for (i = 0; i < insn_cnt; i++, insn++) {
13213 		if (!insn_is_cond_jump(insn->code))
13214 			continue;
13215 
13216 		if (!aux_data[i + 1].seen)
13217 			ja.off = insn->off;
13218 		else if (!aux_data[i + 1 + insn->off].seen)
13219 			ja.off = 0;
13220 		else
13221 			continue;
13222 
13223 		if (bpf_prog_is_dev_bound(env->prog->aux))
13224 			bpf_prog_offload_replace_insn(env, i, &ja);
13225 
13226 		memcpy(insn, &ja, sizeof(ja));
13227 	}
13228 }
13229 
13230 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13231 {
13232 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13233 	int insn_cnt = env->prog->len;
13234 	int i, err;
13235 
13236 	for (i = 0; i < insn_cnt; i++) {
13237 		int j;
13238 
13239 		j = 0;
13240 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13241 			j++;
13242 		if (!j)
13243 			continue;
13244 
13245 		err = verifier_remove_insns(env, i, j);
13246 		if (err)
13247 			return err;
13248 		insn_cnt = env->prog->len;
13249 	}
13250 
13251 	return 0;
13252 }
13253 
13254 static int opt_remove_nops(struct bpf_verifier_env *env)
13255 {
13256 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13257 	struct bpf_insn *insn = env->prog->insnsi;
13258 	int insn_cnt = env->prog->len;
13259 	int i, err;
13260 
13261 	for (i = 0; i < insn_cnt; i++) {
13262 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13263 			continue;
13264 
13265 		err = verifier_remove_insns(env, i, 1);
13266 		if (err)
13267 			return err;
13268 		insn_cnt--;
13269 		i--;
13270 	}
13271 
13272 	return 0;
13273 }
13274 
13275 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13276 					 const union bpf_attr *attr)
13277 {
13278 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13279 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13280 	int i, patch_len, delta = 0, len = env->prog->len;
13281 	struct bpf_insn *insns = env->prog->insnsi;
13282 	struct bpf_prog *new_prog;
13283 	bool rnd_hi32;
13284 
13285 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13286 	zext_patch[1] = BPF_ZEXT_REG(0);
13287 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13288 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13289 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13290 	for (i = 0; i < len; i++) {
13291 		int adj_idx = i + delta;
13292 		struct bpf_insn insn;
13293 		int load_reg;
13294 
13295 		insn = insns[adj_idx];
13296 		load_reg = insn_def_regno(&insn);
13297 		if (!aux[adj_idx].zext_dst) {
13298 			u8 code, class;
13299 			u32 imm_rnd;
13300 
13301 			if (!rnd_hi32)
13302 				continue;
13303 
13304 			code = insn.code;
13305 			class = BPF_CLASS(code);
13306 			if (load_reg == -1)
13307 				continue;
13308 
13309 			/* NOTE: arg "reg" (the fourth one) is only used for
13310 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13311 			 *       here.
13312 			 */
13313 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13314 				if (class == BPF_LD &&
13315 				    BPF_MODE(code) == BPF_IMM)
13316 					i++;
13317 				continue;
13318 			}
13319 
13320 			/* ctx load could be transformed into wider load. */
13321 			if (class == BPF_LDX &&
13322 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13323 				continue;
13324 
13325 			imm_rnd = get_random_int();
13326 			rnd_hi32_patch[0] = insn;
13327 			rnd_hi32_patch[1].imm = imm_rnd;
13328 			rnd_hi32_patch[3].dst_reg = load_reg;
13329 			patch = rnd_hi32_patch;
13330 			patch_len = 4;
13331 			goto apply_patch_buffer;
13332 		}
13333 
13334 		/* Add in an zero-extend instruction if a) the JIT has requested
13335 		 * it or b) it's a CMPXCHG.
13336 		 *
13337 		 * The latter is because: BPF_CMPXCHG always loads a value into
13338 		 * R0, therefore always zero-extends. However some archs'
13339 		 * equivalent instruction only does this load when the
13340 		 * comparison is successful. This detail of CMPXCHG is
13341 		 * orthogonal to the general zero-extension behaviour of the
13342 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13343 		 */
13344 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13345 			continue;
13346 
13347 		if (WARN_ON(load_reg == -1)) {
13348 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13349 			return -EFAULT;
13350 		}
13351 
13352 		zext_patch[0] = insn;
13353 		zext_patch[1].dst_reg = load_reg;
13354 		zext_patch[1].src_reg = load_reg;
13355 		patch = zext_patch;
13356 		patch_len = 2;
13357 apply_patch_buffer:
13358 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13359 		if (!new_prog)
13360 			return -ENOMEM;
13361 		env->prog = new_prog;
13362 		insns = new_prog->insnsi;
13363 		aux = env->insn_aux_data;
13364 		delta += patch_len - 1;
13365 	}
13366 
13367 	return 0;
13368 }
13369 
13370 /* convert load instructions that access fields of a context type into a
13371  * sequence of instructions that access fields of the underlying structure:
13372  *     struct __sk_buff    -> struct sk_buff
13373  *     struct bpf_sock_ops -> struct sock
13374  */
13375 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13376 {
13377 	const struct bpf_verifier_ops *ops = env->ops;
13378 	int i, cnt, size, ctx_field_size, delta = 0;
13379 	const int insn_cnt = env->prog->len;
13380 	struct bpf_insn insn_buf[16], *insn;
13381 	u32 target_size, size_default, off;
13382 	struct bpf_prog *new_prog;
13383 	enum bpf_access_type type;
13384 	bool is_narrower_load;
13385 
13386 	if (ops->gen_prologue || env->seen_direct_write) {
13387 		if (!ops->gen_prologue) {
13388 			verbose(env, "bpf verifier is misconfigured\n");
13389 			return -EINVAL;
13390 		}
13391 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13392 					env->prog);
13393 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13394 			verbose(env, "bpf verifier is misconfigured\n");
13395 			return -EINVAL;
13396 		} else if (cnt) {
13397 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13398 			if (!new_prog)
13399 				return -ENOMEM;
13400 
13401 			env->prog = new_prog;
13402 			delta += cnt - 1;
13403 		}
13404 	}
13405 
13406 	if (bpf_prog_is_dev_bound(env->prog->aux))
13407 		return 0;
13408 
13409 	insn = env->prog->insnsi + delta;
13410 
13411 	for (i = 0; i < insn_cnt; i++, insn++) {
13412 		bpf_convert_ctx_access_t convert_ctx_access;
13413 		bool ctx_access;
13414 
13415 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13416 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13417 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13418 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13419 			type = BPF_READ;
13420 			ctx_access = true;
13421 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13422 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13423 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13424 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13425 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13426 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13427 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13428 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13429 			type = BPF_WRITE;
13430 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13431 		} else {
13432 			continue;
13433 		}
13434 
13435 		if (type == BPF_WRITE &&
13436 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13437 			struct bpf_insn patch[] = {
13438 				*insn,
13439 				BPF_ST_NOSPEC(),
13440 			};
13441 
13442 			cnt = ARRAY_SIZE(patch);
13443 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13444 			if (!new_prog)
13445 				return -ENOMEM;
13446 
13447 			delta    += cnt - 1;
13448 			env->prog = new_prog;
13449 			insn      = new_prog->insnsi + i + delta;
13450 			continue;
13451 		}
13452 
13453 		if (!ctx_access)
13454 			continue;
13455 
13456 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13457 		case PTR_TO_CTX:
13458 			if (!ops->convert_ctx_access)
13459 				continue;
13460 			convert_ctx_access = ops->convert_ctx_access;
13461 			break;
13462 		case PTR_TO_SOCKET:
13463 		case PTR_TO_SOCK_COMMON:
13464 			convert_ctx_access = bpf_sock_convert_ctx_access;
13465 			break;
13466 		case PTR_TO_TCP_SOCK:
13467 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13468 			break;
13469 		case PTR_TO_XDP_SOCK:
13470 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13471 			break;
13472 		case PTR_TO_BTF_ID:
13473 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13474 			if (type == BPF_READ) {
13475 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13476 					BPF_SIZE((insn)->code);
13477 				env->prog->aux->num_exentries++;
13478 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
13479 				verbose(env, "Writes through BTF pointers are not allowed\n");
13480 				return -EINVAL;
13481 			}
13482 			continue;
13483 		default:
13484 			continue;
13485 		}
13486 
13487 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13488 		size = BPF_LDST_BYTES(insn);
13489 
13490 		/* If the read access is a narrower load of the field,
13491 		 * convert to a 4/8-byte load, to minimum program type specific
13492 		 * convert_ctx_access changes. If conversion is successful,
13493 		 * we will apply proper mask to the result.
13494 		 */
13495 		is_narrower_load = size < ctx_field_size;
13496 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13497 		off = insn->off;
13498 		if (is_narrower_load) {
13499 			u8 size_code;
13500 
13501 			if (type == BPF_WRITE) {
13502 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13503 				return -EINVAL;
13504 			}
13505 
13506 			size_code = BPF_H;
13507 			if (ctx_field_size == 4)
13508 				size_code = BPF_W;
13509 			else if (ctx_field_size == 8)
13510 				size_code = BPF_DW;
13511 
13512 			insn->off = off & ~(size_default - 1);
13513 			insn->code = BPF_LDX | BPF_MEM | size_code;
13514 		}
13515 
13516 		target_size = 0;
13517 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13518 					 &target_size);
13519 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13520 		    (ctx_field_size && !target_size)) {
13521 			verbose(env, "bpf verifier is misconfigured\n");
13522 			return -EINVAL;
13523 		}
13524 
13525 		if (is_narrower_load && size < target_size) {
13526 			u8 shift = bpf_ctx_narrow_access_offset(
13527 				off, size, size_default) * 8;
13528 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13529 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13530 				return -EINVAL;
13531 			}
13532 			if (ctx_field_size <= 4) {
13533 				if (shift)
13534 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13535 									insn->dst_reg,
13536 									shift);
13537 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13538 								(1 << size * 8) - 1);
13539 			} else {
13540 				if (shift)
13541 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13542 									insn->dst_reg,
13543 									shift);
13544 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13545 								(1ULL << size * 8) - 1);
13546 			}
13547 		}
13548 
13549 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13550 		if (!new_prog)
13551 			return -ENOMEM;
13552 
13553 		delta += cnt - 1;
13554 
13555 		/* keep walking new program and skip insns we just inserted */
13556 		env->prog = new_prog;
13557 		insn      = new_prog->insnsi + i + delta;
13558 	}
13559 
13560 	return 0;
13561 }
13562 
13563 static int jit_subprogs(struct bpf_verifier_env *env)
13564 {
13565 	struct bpf_prog *prog = env->prog, **func, *tmp;
13566 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13567 	struct bpf_map *map_ptr;
13568 	struct bpf_insn *insn;
13569 	void *old_bpf_func;
13570 	int err, num_exentries;
13571 
13572 	if (env->subprog_cnt <= 1)
13573 		return 0;
13574 
13575 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13576 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13577 			continue;
13578 
13579 		/* Upon error here we cannot fall back to interpreter but
13580 		 * need a hard reject of the program. Thus -EFAULT is
13581 		 * propagated in any case.
13582 		 */
13583 		subprog = find_subprog(env, i + insn->imm + 1);
13584 		if (subprog < 0) {
13585 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13586 				  i + insn->imm + 1);
13587 			return -EFAULT;
13588 		}
13589 		/* temporarily remember subprog id inside insn instead of
13590 		 * aux_data, since next loop will split up all insns into funcs
13591 		 */
13592 		insn->off = subprog;
13593 		/* remember original imm in case JIT fails and fallback
13594 		 * to interpreter will be needed
13595 		 */
13596 		env->insn_aux_data[i].call_imm = insn->imm;
13597 		/* point imm to __bpf_call_base+1 from JITs point of view */
13598 		insn->imm = 1;
13599 		if (bpf_pseudo_func(insn))
13600 			/* jit (e.g. x86_64) may emit fewer instructions
13601 			 * if it learns a u32 imm is the same as a u64 imm.
13602 			 * Force a non zero here.
13603 			 */
13604 			insn[1].imm = 1;
13605 	}
13606 
13607 	err = bpf_prog_alloc_jited_linfo(prog);
13608 	if (err)
13609 		goto out_undo_insn;
13610 
13611 	err = -ENOMEM;
13612 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13613 	if (!func)
13614 		goto out_undo_insn;
13615 
13616 	for (i = 0; i < env->subprog_cnt; i++) {
13617 		subprog_start = subprog_end;
13618 		subprog_end = env->subprog_info[i + 1].start;
13619 
13620 		len = subprog_end - subprog_start;
13621 		/* bpf_prog_run() doesn't call subprogs directly,
13622 		 * hence main prog stats include the runtime of subprogs.
13623 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13624 		 * func[i]->stats will never be accessed and stays NULL
13625 		 */
13626 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13627 		if (!func[i])
13628 			goto out_free;
13629 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13630 		       len * sizeof(struct bpf_insn));
13631 		func[i]->type = prog->type;
13632 		func[i]->len = len;
13633 		if (bpf_prog_calc_tag(func[i]))
13634 			goto out_free;
13635 		func[i]->is_func = 1;
13636 		func[i]->aux->func_idx = i;
13637 		/* Below members will be freed only at prog->aux */
13638 		func[i]->aux->btf = prog->aux->btf;
13639 		func[i]->aux->func_info = prog->aux->func_info;
13640 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13641 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13642 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13643 
13644 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13645 			struct bpf_jit_poke_descriptor *poke;
13646 
13647 			poke = &prog->aux->poke_tab[j];
13648 			if (poke->insn_idx < subprog_end &&
13649 			    poke->insn_idx >= subprog_start)
13650 				poke->aux = func[i]->aux;
13651 		}
13652 
13653 		func[i]->aux->name[0] = 'F';
13654 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13655 		func[i]->jit_requested = 1;
13656 		func[i]->blinding_requested = prog->blinding_requested;
13657 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13658 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13659 		func[i]->aux->linfo = prog->aux->linfo;
13660 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13661 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13662 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13663 		num_exentries = 0;
13664 		insn = func[i]->insnsi;
13665 		for (j = 0; j < func[i]->len; j++, insn++) {
13666 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13667 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13668 				num_exentries++;
13669 		}
13670 		func[i]->aux->num_exentries = num_exentries;
13671 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13672 		func[i] = bpf_int_jit_compile(func[i]);
13673 		if (!func[i]->jited) {
13674 			err = -ENOTSUPP;
13675 			goto out_free;
13676 		}
13677 		cond_resched();
13678 	}
13679 
13680 	/* at this point all bpf functions were successfully JITed
13681 	 * now populate all bpf_calls with correct addresses and
13682 	 * run last pass of JIT
13683 	 */
13684 	for (i = 0; i < env->subprog_cnt; i++) {
13685 		insn = func[i]->insnsi;
13686 		for (j = 0; j < func[i]->len; j++, insn++) {
13687 			if (bpf_pseudo_func(insn)) {
13688 				subprog = insn->off;
13689 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13690 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13691 				continue;
13692 			}
13693 			if (!bpf_pseudo_call(insn))
13694 				continue;
13695 			subprog = insn->off;
13696 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13697 		}
13698 
13699 		/* we use the aux data to keep a list of the start addresses
13700 		 * of the JITed images for each function in the program
13701 		 *
13702 		 * for some architectures, such as powerpc64, the imm field
13703 		 * might not be large enough to hold the offset of the start
13704 		 * address of the callee's JITed image from __bpf_call_base
13705 		 *
13706 		 * in such cases, we can lookup the start address of a callee
13707 		 * by using its subprog id, available from the off field of
13708 		 * the call instruction, as an index for this list
13709 		 */
13710 		func[i]->aux->func = func;
13711 		func[i]->aux->func_cnt = env->subprog_cnt;
13712 	}
13713 	for (i = 0; i < env->subprog_cnt; i++) {
13714 		old_bpf_func = func[i]->bpf_func;
13715 		tmp = bpf_int_jit_compile(func[i]);
13716 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13717 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13718 			err = -ENOTSUPP;
13719 			goto out_free;
13720 		}
13721 		cond_resched();
13722 	}
13723 
13724 	/* finally lock prog and jit images for all functions and
13725 	 * populate kallsysm
13726 	 */
13727 	for (i = 0; i < env->subprog_cnt; i++) {
13728 		bpf_prog_lock_ro(func[i]);
13729 		bpf_prog_kallsyms_add(func[i]);
13730 	}
13731 
13732 	/* Last step: make now unused interpreter insns from main
13733 	 * prog consistent for later dump requests, so they can
13734 	 * later look the same as if they were interpreted only.
13735 	 */
13736 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13737 		if (bpf_pseudo_func(insn)) {
13738 			insn[0].imm = env->insn_aux_data[i].call_imm;
13739 			insn[1].imm = insn->off;
13740 			insn->off = 0;
13741 			continue;
13742 		}
13743 		if (!bpf_pseudo_call(insn))
13744 			continue;
13745 		insn->off = env->insn_aux_data[i].call_imm;
13746 		subprog = find_subprog(env, i + insn->off + 1);
13747 		insn->imm = subprog;
13748 	}
13749 
13750 	prog->jited = 1;
13751 	prog->bpf_func = func[0]->bpf_func;
13752 	prog->jited_len = func[0]->jited_len;
13753 	prog->aux->func = func;
13754 	prog->aux->func_cnt = env->subprog_cnt;
13755 	bpf_prog_jit_attempt_done(prog);
13756 	return 0;
13757 out_free:
13758 	/* We failed JIT'ing, so at this point we need to unregister poke
13759 	 * descriptors from subprogs, so that kernel is not attempting to
13760 	 * patch it anymore as we're freeing the subprog JIT memory.
13761 	 */
13762 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13763 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13764 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13765 	}
13766 	/* At this point we're guaranteed that poke descriptors are not
13767 	 * live anymore. We can just unlink its descriptor table as it's
13768 	 * released with the main prog.
13769 	 */
13770 	for (i = 0; i < env->subprog_cnt; i++) {
13771 		if (!func[i])
13772 			continue;
13773 		func[i]->aux->poke_tab = NULL;
13774 		bpf_jit_free(func[i]);
13775 	}
13776 	kfree(func);
13777 out_undo_insn:
13778 	/* cleanup main prog to be interpreted */
13779 	prog->jit_requested = 0;
13780 	prog->blinding_requested = 0;
13781 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13782 		if (!bpf_pseudo_call(insn))
13783 			continue;
13784 		insn->off = 0;
13785 		insn->imm = env->insn_aux_data[i].call_imm;
13786 	}
13787 	bpf_prog_jit_attempt_done(prog);
13788 	return err;
13789 }
13790 
13791 static int fixup_call_args(struct bpf_verifier_env *env)
13792 {
13793 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13794 	struct bpf_prog *prog = env->prog;
13795 	struct bpf_insn *insn = prog->insnsi;
13796 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13797 	int i, depth;
13798 #endif
13799 	int err = 0;
13800 
13801 	if (env->prog->jit_requested &&
13802 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13803 		err = jit_subprogs(env);
13804 		if (err == 0)
13805 			return 0;
13806 		if (err == -EFAULT)
13807 			return err;
13808 	}
13809 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13810 	if (has_kfunc_call) {
13811 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13812 		return -EINVAL;
13813 	}
13814 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13815 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13816 		 * have to be rejected, since interpreter doesn't support them yet.
13817 		 */
13818 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13819 		return -EINVAL;
13820 	}
13821 	for (i = 0; i < prog->len; i++, insn++) {
13822 		if (bpf_pseudo_func(insn)) {
13823 			/* When JIT fails the progs with callback calls
13824 			 * have to be rejected, since interpreter doesn't support them yet.
13825 			 */
13826 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13827 			return -EINVAL;
13828 		}
13829 
13830 		if (!bpf_pseudo_call(insn))
13831 			continue;
13832 		depth = get_callee_stack_depth(env, insn, i);
13833 		if (depth < 0)
13834 			return depth;
13835 		bpf_patch_call_args(insn, depth);
13836 	}
13837 	err = 0;
13838 #endif
13839 	return err;
13840 }
13841 
13842 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13843 			    struct bpf_insn *insn)
13844 {
13845 	const struct bpf_kfunc_desc *desc;
13846 
13847 	if (!insn->imm) {
13848 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13849 		return -EINVAL;
13850 	}
13851 
13852 	/* insn->imm has the btf func_id. Replace it with
13853 	 * an address (relative to __bpf_base_call).
13854 	 */
13855 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13856 	if (!desc) {
13857 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13858 			insn->imm);
13859 		return -EFAULT;
13860 	}
13861 
13862 	insn->imm = desc->imm;
13863 
13864 	return 0;
13865 }
13866 
13867 /* Do various post-verification rewrites in a single program pass.
13868  * These rewrites simplify JIT and interpreter implementations.
13869  */
13870 static int do_misc_fixups(struct bpf_verifier_env *env)
13871 {
13872 	struct bpf_prog *prog = env->prog;
13873 	enum bpf_attach_type eatype = prog->expected_attach_type;
13874 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13875 	struct bpf_insn *insn = prog->insnsi;
13876 	const struct bpf_func_proto *fn;
13877 	const int insn_cnt = prog->len;
13878 	const struct bpf_map_ops *ops;
13879 	struct bpf_insn_aux_data *aux;
13880 	struct bpf_insn insn_buf[16];
13881 	struct bpf_prog *new_prog;
13882 	struct bpf_map *map_ptr;
13883 	int i, ret, cnt, delta = 0;
13884 
13885 	for (i = 0; i < insn_cnt; i++, insn++) {
13886 		/* Make divide-by-zero exceptions impossible. */
13887 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13888 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13889 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13890 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13891 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13892 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13893 			struct bpf_insn *patchlet;
13894 			struct bpf_insn chk_and_div[] = {
13895 				/* [R,W]x div 0 -> 0 */
13896 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13897 					     BPF_JNE | BPF_K, insn->src_reg,
13898 					     0, 2, 0),
13899 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13900 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13901 				*insn,
13902 			};
13903 			struct bpf_insn chk_and_mod[] = {
13904 				/* [R,W]x mod 0 -> [R,W]x */
13905 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13906 					     BPF_JEQ | BPF_K, insn->src_reg,
13907 					     0, 1 + (is64 ? 0 : 1), 0),
13908 				*insn,
13909 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13910 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13911 			};
13912 
13913 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13914 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13915 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13916 
13917 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13918 			if (!new_prog)
13919 				return -ENOMEM;
13920 
13921 			delta    += cnt - 1;
13922 			env->prog = prog = new_prog;
13923 			insn      = new_prog->insnsi + i + delta;
13924 			continue;
13925 		}
13926 
13927 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13928 		if (BPF_CLASS(insn->code) == BPF_LD &&
13929 		    (BPF_MODE(insn->code) == BPF_ABS ||
13930 		     BPF_MODE(insn->code) == BPF_IND)) {
13931 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13932 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13933 				verbose(env, "bpf verifier is misconfigured\n");
13934 				return -EINVAL;
13935 			}
13936 
13937 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13938 			if (!new_prog)
13939 				return -ENOMEM;
13940 
13941 			delta    += cnt - 1;
13942 			env->prog = prog = new_prog;
13943 			insn      = new_prog->insnsi + i + delta;
13944 			continue;
13945 		}
13946 
13947 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
13948 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13949 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13950 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13951 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13952 			struct bpf_insn *patch = &insn_buf[0];
13953 			bool issrc, isneg, isimm;
13954 			u32 off_reg;
13955 
13956 			aux = &env->insn_aux_data[i + delta];
13957 			if (!aux->alu_state ||
13958 			    aux->alu_state == BPF_ALU_NON_POINTER)
13959 				continue;
13960 
13961 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13962 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13963 				BPF_ALU_SANITIZE_SRC;
13964 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13965 
13966 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13967 			if (isimm) {
13968 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13969 			} else {
13970 				if (isneg)
13971 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13972 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13973 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13974 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13975 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13976 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13977 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13978 			}
13979 			if (!issrc)
13980 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13981 			insn->src_reg = BPF_REG_AX;
13982 			if (isneg)
13983 				insn->code = insn->code == code_add ?
13984 					     code_sub : code_add;
13985 			*patch++ = *insn;
13986 			if (issrc && isneg && !isimm)
13987 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13988 			cnt = patch - insn_buf;
13989 
13990 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13991 			if (!new_prog)
13992 				return -ENOMEM;
13993 
13994 			delta    += cnt - 1;
13995 			env->prog = prog = new_prog;
13996 			insn      = new_prog->insnsi + i + delta;
13997 			continue;
13998 		}
13999 
14000 		if (insn->code != (BPF_JMP | BPF_CALL))
14001 			continue;
14002 		if (insn->src_reg == BPF_PSEUDO_CALL)
14003 			continue;
14004 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14005 			ret = fixup_kfunc_call(env, insn);
14006 			if (ret)
14007 				return ret;
14008 			continue;
14009 		}
14010 
14011 		if (insn->imm == BPF_FUNC_get_route_realm)
14012 			prog->dst_needed = 1;
14013 		if (insn->imm == BPF_FUNC_get_prandom_u32)
14014 			bpf_user_rnd_init_once();
14015 		if (insn->imm == BPF_FUNC_override_return)
14016 			prog->kprobe_override = 1;
14017 		if (insn->imm == BPF_FUNC_tail_call) {
14018 			/* If we tail call into other programs, we
14019 			 * cannot make any assumptions since they can
14020 			 * be replaced dynamically during runtime in
14021 			 * the program array.
14022 			 */
14023 			prog->cb_access = 1;
14024 			if (!allow_tail_call_in_subprogs(env))
14025 				prog->aux->stack_depth = MAX_BPF_STACK;
14026 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14027 
14028 			/* mark bpf_tail_call as different opcode to avoid
14029 			 * conditional branch in the interpreter for every normal
14030 			 * call and to prevent accidental JITing by JIT compiler
14031 			 * that doesn't support bpf_tail_call yet
14032 			 */
14033 			insn->imm = 0;
14034 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14035 
14036 			aux = &env->insn_aux_data[i + delta];
14037 			if (env->bpf_capable && !prog->blinding_requested &&
14038 			    prog->jit_requested &&
14039 			    !bpf_map_key_poisoned(aux) &&
14040 			    !bpf_map_ptr_poisoned(aux) &&
14041 			    !bpf_map_ptr_unpriv(aux)) {
14042 				struct bpf_jit_poke_descriptor desc = {
14043 					.reason = BPF_POKE_REASON_TAIL_CALL,
14044 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14045 					.tail_call.key = bpf_map_key_immediate(aux),
14046 					.insn_idx = i + delta,
14047 				};
14048 
14049 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14050 				if (ret < 0) {
14051 					verbose(env, "adding tail call poke descriptor failed\n");
14052 					return ret;
14053 				}
14054 
14055 				insn->imm = ret + 1;
14056 				continue;
14057 			}
14058 
14059 			if (!bpf_map_ptr_unpriv(aux))
14060 				continue;
14061 
14062 			/* instead of changing every JIT dealing with tail_call
14063 			 * emit two extra insns:
14064 			 * if (index >= max_entries) goto out;
14065 			 * index &= array->index_mask;
14066 			 * to avoid out-of-bounds cpu speculation
14067 			 */
14068 			if (bpf_map_ptr_poisoned(aux)) {
14069 				verbose(env, "tail_call abusing map_ptr\n");
14070 				return -EINVAL;
14071 			}
14072 
14073 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14074 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14075 						  map_ptr->max_entries, 2);
14076 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14077 						    container_of(map_ptr,
14078 								 struct bpf_array,
14079 								 map)->index_mask);
14080 			insn_buf[2] = *insn;
14081 			cnt = 3;
14082 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14083 			if (!new_prog)
14084 				return -ENOMEM;
14085 
14086 			delta    += cnt - 1;
14087 			env->prog = prog = new_prog;
14088 			insn      = new_prog->insnsi + i + delta;
14089 			continue;
14090 		}
14091 
14092 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14093 			/* The verifier will process callback_fn as many times as necessary
14094 			 * with different maps and the register states prepared by
14095 			 * set_timer_callback_state will be accurate.
14096 			 *
14097 			 * The following use case is valid:
14098 			 *   map1 is shared by prog1, prog2, prog3.
14099 			 *   prog1 calls bpf_timer_init for some map1 elements
14100 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14101 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14102 			 *   prog3 calls bpf_timer_start for some map1 elements.
14103 			 *     Those that were not both bpf_timer_init-ed and
14104 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14105 			 */
14106 			struct bpf_insn ld_addrs[2] = {
14107 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14108 			};
14109 
14110 			insn_buf[0] = ld_addrs[0];
14111 			insn_buf[1] = ld_addrs[1];
14112 			insn_buf[2] = *insn;
14113 			cnt = 3;
14114 
14115 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14116 			if (!new_prog)
14117 				return -ENOMEM;
14118 
14119 			delta    += cnt - 1;
14120 			env->prog = prog = new_prog;
14121 			insn      = new_prog->insnsi + i + delta;
14122 			goto patch_call_imm;
14123 		}
14124 
14125 		if (insn->imm == BPF_FUNC_task_storage_get ||
14126 		    insn->imm == BPF_FUNC_sk_storage_get ||
14127 		    insn->imm == BPF_FUNC_inode_storage_get) {
14128 			if (env->prog->aux->sleepable)
14129 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14130 			else
14131 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14132 			insn_buf[1] = *insn;
14133 			cnt = 2;
14134 
14135 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14136 			if (!new_prog)
14137 				return -ENOMEM;
14138 
14139 			delta += cnt - 1;
14140 			env->prog = prog = new_prog;
14141 			insn = new_prog->insnsi + i + delta;
14142 			goto patch_call_imm;
14143 		}
14144 
14145 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14146 		 * and other inlining handlers are currently limited to 64 bit
14147 		 * only.
14148 		 */
14149 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14150 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14151 		     insn->imm == BPF_FUNC_map_update_elem ||
14152 		     insn->imm == BPF_FUNC_map_delete_elem ||
14153 		     insn->imm == BPF_FUNC_map_push_elem   ||
14154 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14155 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14156 		     insn->imm == BPF_FUNC_redirect_map    ||
14157 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14158 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14159 			aux = &env->insn_aux_data[i + delta];
14160 			if (bpf_map_ptr_poisoned(aux))
14161 				goto patch_call_imm;
14162 
14163 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14164 			ops = map_ptr->ops;
14165 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14166 			    ops->map_gen_lookup) {
14167 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14168 				if (cnt == -EOPNOTSUPP)
14169 					goto patch_map_ops_generic;
14170 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14171 					verbose(env, "bpf verifier is misconfigured\n");
14172 					return -EINVAL;
14173 				}
14174 
14175 				new_prog = bpf_patch_insn_data(env, i + delta,
14176 							       insn_buf, cnt);
14177 				if (!new_prog)
14178 					return -ENOMEM;
14179 
14180 				delta    += cnt - 1;
14181 				env->prog = prog = new_prog;
14182 				insn      = new_prog->insnsi + i + delta;
14183 				continue;
14184 			}
14185 
14186 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14187 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14188 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14189 				     (int (*)(struct bpf_map *map, void *key))NULL));
14190 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14191 				     (int (*)(struct bpf_map *map, void *key, void *value,
14192 					      u64 flags))NULL));
14193 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14194 				     (int (*)(struct bpf_map *map, void *value,
14195 					      u64 flags))NULL));
14196 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14197 				     (int (*)(struct bpf_map *map, void *value))NULL));
14198 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14199 				     (int (*)(struct bpf_map *map, void *value))NULL));
14200 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14201 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14202 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14203 				     (int (*)(struct bpf_map *map,
14204 					      bpf_callback_t callback_fn,
14205 					      void *callback_ctx,
14206 					      u64 flags))NULL));
14207 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14208 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14209 
14210 patch_map_ops_generic:
14211 			switch (insn->imm) {
14212 			case BPF_FUNC_map_lookup_elem:
14213 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14214 				continue;
14215 			case BPF_FUNC_map_update_elem:
14216 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14217 				continue;
14218 			case BPF_FUNC_map_delete_elem:
14219 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14220 				continue;
14221 			case BPF_FUNC_map_push_elem:
14222 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14223 				continue;
14224 			case BPF_FUNC_map_pop_elem:
14225 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14226 				continue;
14227 			case BPF_FUNC_map_peek_elem:
14228 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14229 				continue;
14230 			case BPF_FUNC_redirect_map:
14231 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14232 				continue;
14233 			case BPF_FUNC_for_each_map_elem:
14234 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14235 				continue;
14236 			case BPF_FUNC_map_lookup_percpu_elem:
14237 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14238 				continue;
14239 			}
14240 
14241 			goto patch_call_imm;
14242 		}
14243 
14244 		/* Implement bpf_jiffies64 inline. */
14245 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14246 		    insn->imm == BPF_FUNC_jiffies64) {
14247 			struct bpf_insn ld_jiffies_addr[2] = {
14248 				BPF_LD_IMM64(BPF_REG_0,
14249 					     (unsigned long)&jiffies),
14250 			};
14251 
14252 			insn_buf[0] = ld_jiffies_addr[0];
14253 			insn_buf[1] = ld_jiffies_addr[1];
14254 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14255 						  BPF_REG_0, 0);
14256 			cnt = 3;
14257 
14258 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14259 						       cnt);
14260 			if (!new_prog)
14261 				return -ENOMEM;
14262 
14263 			delta    += cnt - 1;
14264 			env->prog = prog = new_prog;
14265 			insn      = new_prog->insnsi + i + delta;
14266 			continue;
14267 		}
14268 
14269 		/* Implement bpf_get_func_arg inline. */
14270 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14271 		    insn->imm == BPF_FUNC_get_func_arg) {
14272 			/* Load nr_args from ctx - 8 */
14273 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14274 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14275 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14276 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14277 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14278 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14279 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14280 			insn_buf[7] = BPF_JMP_A(1);
14281 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14282 			cnt = 9;
14283 
14284 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14285 			if (!new_prog)
14286 				return -ENOMEM;
14287 
14288 			delta    += cnt - 1;
14289 			env->prog = prog = new_prog;
14290 			insn      = new_prog->insnsi + i + delta;
14291 			continue;
14292 		}
14293 
14294 		/* Implement bpf_get_func_ret inline. */
14295 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14296 		    insn->imm == BPF_FUNC_get_func_ret) {
14297 			if (eatype == BPF_TRACE_FEXIT ||
14298 			    eatype == BPF_MODIFY_RETURN) {
14299 				/* Load nr_args from ctx - 8 */
14300 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14301 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14302 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14303 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14304 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14305 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14306 				cnt = 6;
14307 			} else {
14308 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14309 				cnt = 1;
14310 			}
14311 
14312 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14313 			if (!new_prog)
14314 				return -ENOMEM;
14315 
14316 			delta    += cnt - 1;
14317 			env->prog = prog = new_prog;
14318 			insn      = new_prog->insnsi + i + delta;
14319 			continue;
14320 		}
14321 
14322 		/* Implement get_func_arg_cnt inline. */
14323 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14324 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14325 			/* Load nr_args from ctx - 8 */
14326 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14327 
14328 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14329 			if (!new_prog)
14330 				return -ENOMEM;
14331 
14332 			env->prog = prog = new_prog;
14333 			insn      = new_prog->insnsi + i + delta;
14334 			continue;
14335 		}
14336 
14337 		/* Implement bpf_get_func_ip inline. */
14338 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14339 		    insn->imm == BPF_FUNC_get_func_ip) {
14340 			/* Load IP address from ctx - 16 */
14341 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14342 
14343 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14344 			if (!new_prog)
14345 				return -ENOMEM;
14346 
14347 			env->prog = prog = new_prog;
14348 			insn      = new_prog->insnsi + i + delta;
14349 			continue;
14350 		}
14351 
14352 patch_call_imm:
14353 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14354 		/* all functions that have prototype and verifier allowed
14355 		 * programs to call them, must be real in-kernel functions
14356 		 */
14357 		if (!fn->func) {
14358 			verbose(env,
14359 				"kernel subsystem misconfigured func %s#%d\n",
14360 				func_id_name(insn->imm), insn->imm);
14361 			return -EFAULT;
14362 		}
14363 		insn->imm = fn->func - __bpf_call_base;
14364 	}
14365 
14366 	/* Since poke tab is now finalized, publish aux to tracker. */
14367 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14368 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14369 		if (!map_ptr->ops->map_poke_track ||
14370 		    !map_ptr->ops->map_poke_untrack ||
14371 		    !map_ptr->ops->map_poke_run) {
14372 			verbose(env, "bpf verifier is misconfigured\n");
14373 			return -EINVAL;
14374 		}
14375 
14376 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14377 		if (ret < 0) {
14378 			verbose(env, "tracking tail call prog failed\n");
14379 			return ret;
14380 		}
14381 	}
14382 
14383 	sort_kfunc_descs_by_imm(env->prog);
14384 
14385 	return 0;
14386 }
14387 
14388 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14389 					int position,
14390 					s32 stack_base,
14391 					u32 callback_subprogno,
14392 					u32 *cnt)
14393 {
14394 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14395 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14396 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14397 	int reg_loop_max = BPF_REG_6;
14398 	int reg_loop_cnt = BPF_REG_7;
14399 	int reg_loop_ctx = BPF_REG_8;
14400 
14401 	struct bpf_prog *new_prog;
14402 	u32 callback_start;
14403 	u32 call_insn_offset;
14404 	s32 callback_offset;
14405 
14406 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14407 	 * be careful to modify this code in sync.
14408 	 */
14409 	struct bpf_insn insn_buf[] = {
14410 		/* Return error and jump to the end of the patch if
14411 		 * expected number of iterations is too big.
14412 		 */
14413 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14414 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14415 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14416 		/* spill R6, R7, R8 to use these as loop vars */
14417 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14418 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14419 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14420 		/* initialize loop vars */
14421 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14422 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14423 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14424 		/* loop header,
14425 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14426 		 */
14427 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14428 		/* callback call,
14429 		 * correct callback offset would be set after patching
14430 		 */
14431 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14432 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14433 		BPF_CALL_REL(0),
14434 		/* increment loop counter */
14435 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14436 		/* jump to loop header if callback returned 0 */
14437 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14438 		/* return value of bpf_loop,
14439 		 * set R0 to the number of iterations
14440 		 */
14441 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14442 		/* restore original values of R6, R7, R8 */
14443 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14444 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14445 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14446 	};
14447 
14448 	*cnt = ARRAY_SIZE(insn_buf);
14449 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14450 	if (!new_prog)
14451 		return new_prog;
14452 
14453 	/* callback start is known only after patching */
14454 	callback_start = env->subprog_info[callback_subprogno].start;
14455 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14456 	call_insn_offset = position + 12;
14457 	callback_offset = callback_start - call_insn_offset - 1;
14458 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14459 
14460 	return new_prog;
14461 }
14462 
14463 static bool is_bpf_loop_call(struct bpf_insn *insn)
14464 {
14465 	return insn->code == (BPF_JMP | BPF_CALL) &&
14466 		insn->src_reg == 0 &&
14467 		insn->imm == BPF_FUNC_loop;
14468 }
14469 
14470 /* For all sub-programs in the program (including main) check
14471  * insn_aux_data to see if there are bpf_loop calls that require
14472  * inlining. If such calls are found the calls are replaced with a
14473  * sequence of instructions produced by `inline_bpf_loop` function and
14474  * subprog stack_depth is increased by the size of 3 registers.
14475  * This stack space is used to spill values of the R6, R7, R8.  These
14476  * registers are used to store the loop bound, counter and context
14477  * variables.
14478  */
14479 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14480 {
14481 	struct bpf_subprog_info *subprogs = env->subprog_info;
14482 	int i, cur_subprog = 0, cnt, delta = 0;
14483 	struct bpf_insn *insn = env->prog->insnsi;
14484 	int insn_cnt = env->prog->len;
14485 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14486 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14487 	u16 stack_depth_extra = 0;
14488 
14489 	for (i = 0; i < insn_cnt; i++, insn++) {
14490 		struct bpf_loop_inline_state *inline_state =
14491 			&env->insn_aux_data[i + delta].loop_inline_state;
14492 
14493 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14494 			struct bpf_prog *new_prog;
14495 
14496 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14497 			new_prog = inline_bpf_loop(env,
14498 						   i + delta,
14499 						   -(stack_depth + stack_depth_extra),
14500 						   inline_state->callback_subprogno,
14501 						   &cnt);
14502 			if (!new_prog)
14503 				return -ENOMEM;
14504 
14505 			delta     += cnt - 1;
14506 			env->prog  = new_prog;
14507 			insn       = new_prog->insnsi + i + delta;
14508 		}
14509 
14510 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14511 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14512 			cur_subprog++;
14513 			stack_depth = subprogs[cur_subprog].stack_depth;
14514 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14515 			stack_depth_extra = 0;
14516 		}
14517 	}
14518 
14519 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14520 
14521 	return 0;
14522 }
14523 
14524 static void free_states(struct bpf_verifier_env *env)
14525 {
14526 	struct bpf_verifier_state_list *sl, *sln;
14527 	int i;
14528 
14529 	sl = env->free_list;
14530 	while (sl) {
14531 		sln = sl->next;
14532 		free_verifier_state(&sl->state, false);
14533 		kfree(sl);
14534 		sl = sln;
14535 	}
14536 	env->free_list = NULL;
14537 
14538 	if (!env->explored_states)
14539 		return;
14540 
14541 	for (i = 0; i < state_htab_size(env); i++) {
14542 		sl = env->explored_states[i];
14543 
14544 		while (sl) {
14545 			sln = sl->next;
14546 			free_verifier_state(&sl->state, false);
14547 			kfree(sl);
14548 			sl = sln;
14549 		}
14550 		env->explored_states[i] = NULL;
14551 	}
14552 }
14553 
14554 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14555 {
14556 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14557 	struct bpf_verifier_state *state;
14558 	struct bpf_reg_state *regs;
14559 	int ret, i;
14560 
14561 	env->prev_linfo = NULL;
14562 	env->pass_cnt++;
14563 
14564 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14565 	if (!state)
14566 		return -ENOMEM;
14567 	state->curframe = 0;
14568 	state->speculative = false;
14569 	state->branches = 1;
14570 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14571 	if (!state->frame[0]) {
14572 		kfree(state);
14573 		return -ENOMEM;
14574 	}
14575 	env->cur_state = state;
14576 	init_func_state(env, state->frame[0],
14577 			BPF_MAIN_FUNC /* callsite */,
14578 			0 /* frameno */,
14579 			subprog);
14580 
14581 	regs = state->frame[state->curframe]->regs;
14582 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14583 		ret = btf_prepare_func_args(env, subprog, regs);
14584 		if (ret)
14585 			goto out;
14586 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14587 			if (regs[i].type == PTR_TO_CTX)
14588 				mark_reg_known_zero(env, regs, i);
14589 			else if (regs[i].type == SCALAR_VALUE)
14590 				mark_reg_unknown(env, regs, i);
14591 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14592 				const u32 mem_size = regs[i].mem_size;
14593 
14594 				mark_reg_known_zero(env, regs, i);
14595 				regs[i].mem_size = mem_size;
14596 				regs[i].id = ++env->id_gen;
14597 			}
14598 		}
14599 	} else {
14600 		/* 1st arg to a function */
14601 		regs[BPF_REG_1].type = PTR_TO_CTX;
14602 		mark_reg_known_zero(env, regs, BPF_REG_1);
14603 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14604 		if (ret == -EFAULT)
14605 			/* unlikely verifier bug. abort.
14606 			 * ret == 0 and ret < 0 are sadly acceptable for
14607 			 * main() function due to backward compatibility.
14608 			 * Like socket filter program may be written as:
14609 			 * int bpf_prog(struct pt_regs *ctx)
14610 			 * and never dereference that ctx in the program.
14611 			 * 'struct pt_regs' is a type mismatch for socket
14612 			 * filter that should be using 'struct __sk_buff'.
14613 			 */
14614 			goto out;
14615 	}
14616 
14617 	ret = do_check(env);
14618 out:
14619 	/* check for NULL is necessary, since cur_state can be freed inside
14620 	 * do_check() under memory pressure.
14621 	 */
14622 	if (env->cur_state) {
14623 		free_verifier_state(env->cur_state, true);
14624 		env->cur_state = NULL;
14625 	}
14626 	while (!pop_stack(env, NULL, NULL, false));
14627 	if (!ret && pop_log)
14628 		bpf_vlog_reset(&env->log, 0);
14629 	free_states(env);
14630 	return ret;
14631 }
14632 
14633 /* Verify all global functions in a BPF program one by one based on their BTF.
14634  * All global functions must pass verification. Otherwise the whole program is rejected.
14635  * Consider:
14636  * int bar(int);
14637  * int foo(int f)
14638  * {
14639  *    return bar(f);
14640  * }
14641  * int bar(int b)
14642  * {
14643  *    ...
14644  * }
14645  * foo() will be verified first for R1=any_scalar_value. During verification it
14646  * will be assumed that bar() already verified successfully and call to bar()
14647  * from foo() will be checked for type match only. Later bar() will be verified
14648  * independently to check that it's safe for R1=any_scalar_value.
14649  */
14650 static int do_check_subprogs(struct bpf_verifier_env *env)
14651 {
14652 	struct bpf_prog_aux *aux = env->prog->aux;
14653 	int i, ret;
14654 
14655 	if (!aux->func_info)
14656 		return 0;
14657 
14658 	for (i = 1; i < env->subprog_cnt; i++) {
14659 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14660 			continue;
14661 		env->insn_idx = env->subprog_info[i].start;
14662 		WARN_ON_ONCE(env->insn_idx == 0);
14663 		ret = do_check_common(env, i);
14664 		if (ret) {
14665 			return ret;
14666 		} else if (env->log.level & BPF_LOG_LEVEL) {
14667 			verbose(env,
14668 				"Func#%d is safe for any args that match its prototype\n",
14669 				i);
14670 		}
14671 	}
14672 	return 0;
14673 }
14674 
14675 static int do_check_main(struct bpf_verifier_env *env)
14676 {
14677 	int ret;
14678 
14679 	env->insn_idx = 0;
14680 	ret = do_check_common(env, 0);
14681 	if (!ret)
14682 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14683 	return ret;
14684 }
14685 
14686 
14687 static void print_verification_stats(struct bpf_verifier_env *env)
14688 {
14689 	int i;
14690 
14691 	if (env->log.level & BPF_LOG_STATS) {
14692 		verbose(env, "verification time %lld usec\n",
14693 			div_u64(env->verification_time, 1000));
14694 		verbose(env, "stack depth ");
14695 		for (i = 0; i < env->subprog_cnt; i++) {
14696 			u32 depth = env->subprog_info[i].stack_depth;
14697 
14698 			verbose(env, "%d", depth);
14699 			if (i + 1 < env->subprog_cnt)
14700 				verbose(env, "+");
14701 		}
14702 		verbose(env, "\n");
14703 	}
14704 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14705 		"total_states %d peak_states %d mark_read %d\n",
14706 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14707 		env->max_states_per_insn, env->total_states,
14708 		env->peak_states, env->longest_mark_read_walk);
14709 }
14710 
14711 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14712 {
14713 	const struct btf_type *t, *func_proto;
14714 	const struct bpf_struct_ops *st_ops;
14715 	const struct btf_member *member;
14716 	struct bpf_prog *prog = env->prog;
14717 	u32 btf_id, member_idx;
14718 	const char *mname;
14719 
14720 	if (!prog->gpl_compatible) {
14721 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14722 		return -EINVAL;
14723 	}
14724 
14725 	btf_id = prog->aux->attach_btf_id;
14726 	st_ops = bpf_struct_ops_find(btf_id);
14727 	if (!st_ops) {
14728 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14729 			btf_id);
14730 		return -ENOTSUPP;
14731 	}
14732 
14733 	t = st_ops->type;
14734 	member_idx = prog->expected_attach_type;
14735 	if (member_idx >= btf_type_vlen(t)) {
14736 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14737 			member_idx, st_ops->name);
14738 		return -EINVAL;
14739 	}
14740 
14741 	member = &btf_type_member(t)[member_idx];
14742 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14743 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14744 					       NULL);
14745 	if (!func_proto) {
14746 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14747 			mname, member_idx, st_ops->name);
14748 		return -EINVAL;
14749 	}
14750 
14751 	if (st_ops->check_member) {
14752 		int err = st_ops->check_member(t, member);
14753 
14754 		if (err) {
14755 			verbose(env, "attach to unsupported member %s of struct %s\n",
14756 				mname, st_ops->name);
14757 			return err;
14758 		}
14759 	}
14760 
14761 	prog->aux->attach_func_proto = func_proto;
14762 	prog->aux->attach_func_name = mname;
14763 	env->ops = st_ops->verifier_ops;
14764 
14765 	return 0;
14766 }
14767 #define SECURITY_PREFIX "security_"
14768 
14769 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14770 {
14771 	if (within_error_injection_list(addr) ||
14772 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14773 		return 0;
14774 
14775 	return -EINVAL;
14776 }
14777 
14778 /* list of non-sleepable functions that are otherwise on
14779  * ALLOW_ERROR_INJECTION list
14780  */
14781 BTF_SET_START(btf_non_sleepable_error_inject)
14782 /* Three functions below can be called from sleepable and non-sleepable context.
14783  * Assume non-sleepable from bpf safety point of view.
14784  */
14785 BTF_ID(func, __filemap_add_folio)
14786 BTF_ID(func, should_fail_alloc_page)
14787 BTF_ID(func, should_failslab)
14788 BTF_SET_END(btf_non_sleepable_error_inject)
14789 
14790 static int check_non_sleepable_error_inject(u32 btf_id)
14791 {
14792 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14793 }
14794 
14795 int bpf_check_attach_target(struct bpf_verifier_log *log,
14796 			    const struct bpf_prog *prog,
14797 			    const struct bpf_prog *tgt_prog,
14798 			    u32 btf_id,
14799 			    struct bpf_attach_target_info *tgt_info)
14800 {
14801 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14802 	const char prefix[] = "btf_trace_";
14803 	int ret = 0, subprog = -1, i;
14804 	const struct btf_type *t;
14805 	bool conservative = true;
14806 	const char *tname;
14807 	struct btf *btf;
14808 	long addr = 0;
14809 
14810 	if (!btf_id) {
14811 		bpf_log(log, "Tracing programs must provide btf_id\n");
14812 		return -EINVAL;
14813 	}
14814 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14815 	if (!btf) {
14816 		bpf_log(log,
14817 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14818 		return -EINVAL;
14819 	}
14820 	t = btf_type_by_id(btf, btf_id);
14821 	if (!t) {
14822 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14823 		return -EINVAL;
14824 	}
14825 	tname = btf_name_by_offset(btf, t->name_off);
14826 	if (!tname) {
14827 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14828 		return -EINVAL;
14829 	}
14830 	if (tgt_prog) {
14831 		struct bpf_prog_aux *aux = tgt_prog->aux;
14832 
14833 		for (i = 0; i < aux->func_info_cnt; i++)
14834 			if (aux->func_info[i].type_id == btf_id) {
14835 				subprog = i;
14836 				break;
14837 			}
14838 		if (subprog == -1) {
14839 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
14840 			return -EINVAL;
14841 		}
14842 		conservative = aux->func_info_aux[subprog].unreliable;
14843 		if (prog_extension) {
14844 			if (conservative) {
14845 				bpf_log(log,
14846 					"Cannot replace static functions\n");
14847 				return -EINVAL;
14848 			}
14849 			if (!prog->jit_requested) {
14850 				bpf_log(log,
14851 					"Extension programs should be JITed\n");
14852 				return -EINVAL;
14853 			}
14854 		}
14855 		if (!tgt_prog->jited) {
14856 			bpf_log(log, "Can attach to only JITed progs\n");
14857 			return -EINVAL;
14858 		}
14859 		if (tgt_prog->type == prog->type) {
14860 			/* Cannot fentry/fexit another fentry/fexit program.
14861 			 * Cannot attach program extension to another extension.
14862 			 * It's ok to attach fentry/fexit to extension program.
14863 			 */
14864 			bpf_log(log, "Cannot recursively attach\n");
14865 			return -EINVAL;
14866 		}
14867 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14868 		    prog_extension &&
14869 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14870 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14871 			/* Program extensions can extend all program types
14872 			 * except fentry/fexit. The reason is the following.
14873 			 * The fentry/fexit programs are used for performance
14874 			 * analysis, stats and can be attached to any program
14875 			 * type except themselves. When extension program is
14876 			 * replacing XDP function it is necessary to allow
14877 			 * performance analysis of all functions. Both original
14878 			 * XDP program and its program extension. Hence
14879 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14880 			 * allowed. If extending of fentry/fexit was allowed it
14881 			 * would be possible to create long call chain
14882 			 * fentry->extension->fentry->extension beyond
14883 			 * reasonable stack size. Hence extending fentry is not
14884 			 * allowed.
14885 			 */
14886 			bpf_log(log, "Cannot extend fentry/fexit\n");
14887 			return -EINVAL;
14888 		}
14889 	} else {
14890 		if (prog_extension) {
14891 			bpf_log(log, "Cannot replace kernel functions\n");
14892 			return -EINVAL;
14893 		}
14894 	}
14895 
14896 	switch (prog->expected_attach_type) {
14897 	case BPF_TRACE_RAW_TP:
14898 		if (tgt_prog) {
14899 			bpf_log(log,
14900 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14901 			return -EINVAL;
14902 		}
14903 		if (!btf_type_is_typedef(t)) {
14904 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
14905 				btf_id);
14906 			return -EINVAL;
14907 		}
14908 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14909 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14910 				btf_id, tname);
14911 			return -EINVAL;
14912 		}
14913 		tname += sizeof(prefix) - 1;
14914 		t = btf_type_by_id(btf, t->type);
14915 		if (!btf_type_is_ptr(t))
14916 			/* should never happen in valid vmlinux build */
14917 			return -EINVAL;
14918 		t = btf_type_by_id(btf, t->type);
14919 		if (!btf_type_is_func_proto(t))
14920 			/* should never happen in valid vmlinux build */
14921 			return -EINVAL;
14922 
14923 		break;
14924 	case BPF_TRACE_ITER:
14925 		if (!btf_type_is_func(t)) {
14926 			bpf_log(log, "attach_btf_id %u is not a function\n",
14927 				btf_id);
14928 			return -EINVAL;
14929 		}
14930 		t = btf_type_by_id(btf, t->type);
14931 		if (!btf_type_is_func_proto(t))
14932 			return -EINVAL;
14933 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14934 		if (ret)
14935 			return ret;
14936 		break;
14937 	default:
14938 		if (!prog_extension)
14939 			return -EINVAL;
14940 		fallthrough;
14941 	case BPF_MODIFY_RETURN:
14942 	case BPF_LSM_MAC:
14943 	case BPF_LSM_CGROUP:
14944 	case BPF_TRACE_FENTRY:
14945 	case BPF_TRACE_FEXIT:
14946 		if (!btf_type_is_func(t)) {
14947 			bpf_log(log, "attach_btf_id %u is not a function\n",
14948 				btf_id);
14949 			return -EINVAL;
14950 		}
14951 		if (prog_extension &&
14952 		    btf_check_type_match(log, prog, btf, t))
14953 			return -EINVAL;
14954 		t = btf_type_by_id(btf, t->type);
14955 		if (!btf_type_is_func_proto(t))
14956 			return -EINVAL;
14957 
14958 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14959 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14960 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14961 			return -EINVAL;
14962 
14963 		if (tgt_prog && conservative)
14964 			t = NULL;
14965 
14966 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14967 		if (ret < 0)
14968 			return ret;
14969 
14970 		if (tgt_prog) {
14971 			if (subprog == 0)
14972 				addr = (long) tgt_prog->bpf_func;
14973 			else
14974 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14975 		} else {
14976 			addr = kallsyms_lookup_name(tname);
14977 			if (!addr) {
14978 				bpf_log(log,
14979 					"The address of function %s cannot be found\n",
14980 					tname);
14981 				return -ENOENT;
14982 			}
14983 		}
14984 
14985 		if (prog->aux->sleepable) {
14986 			ret = -EINVAL;
14987 			switch (prog->type) {
14988 			case BPF_PROG_TYPE_TRACING:
14989 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
14990 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14991 				 */
14992 				if (!check_non_sleepable_error_inject(btf_id) &&
14993 				    within_error_injection_list(addr))
14994 					ret = 0;
14995 				break;
14996 			case BPF_PROG_TYPE_LSM:
14997 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
14998 				 * Only some of them are sleepable.
14999 				 */
15000 				if (bpf_lsm_is_sleepable_hook(btf_id))
15001 					ret = 0;
15002 				break;
15003 			default:
15004 				break;
15005 			}
15006 			if (ret) {
15007 				bpf_log(log, "%s is not sleepable\n", tname);
15008 				return ret;
15009 			}
15010 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15011 			if (tgt_prog) {
15012 				bpf_log(log, "can't modify return codes of BPF programs\n");
15013 				return -EINVAL;
15014 			}
15015 			ret = check_attach_modify_return(addr, tname);
15016 			if (ret) {
15017 				bpf_log(log, "%s() is not modifiable\n", tname);
15018 				return ret;
15019 			}
15020 		}
15021 
15022 		break;
15023 	}
15024 	tgt_info->tgt_addr = addr;
15025 	tgt_info->tgt_name = tname;
15026 	tgt_info->tgt_type = t;
15027 	return 0;
15028 }
15029 
15030 BTF_SET_START(btf_id_deny)
15031 BTF_ID_UNUSED
15032 #ifdef CONFIG_SMP
15033 BTF_ID(func, migrate_disable)
15034 BTF_ID(func, migrate_enable)
15035 #endif
15036 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15037 BTF_ID(func, rcu_read_unlock_strict)
15038 #endif
15039 BTF_SET_END(btf_id_deny)
15040 
15041 static int check_attach_btf_id(struct bpf_verifier_env *env)
15042 {
15043 	struct bpf_prog *prog = env->prog;
15044 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15045 	struct bpf_attach_target_info tgt_info = {};
15046 	u32 btf_id = prog->aux->attach_btf_id;
15047 	struct bpf_trampoline *tr;
15048 	int ret;
15049 	u64 key;
15050 
15051 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15052 		if (prog->aux->sleepable)
15053 			/* attach_btf_id checked to be zero already */
15054 			return 0;
15055 		verbose(env, "Syscall programs can only be sleepable\n");
15056 		return -EINVAL;
15057 	}
15058 
15059 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15060 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15061 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15062 		return -EINVAL;
15063 	}
15064 
15065 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15066 		return check_struct_ops_btf_id(env);
15067 
15068 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15069 	    prog->type != BPF_PROG_TYPE_LSM &&
15070 	    prog->type != BPF_PROG_TYPE_EXT)
15071 		return 0;
15072 
15073 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15074 	if (ret)
15075 		return ret;
15076 
15077 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15078 		/* to make freplace equivalent to their targets, they need to
15079 		 * inherit env->ops and expected_attach_type for the rest of the
15080 		 * verification
15081 		 */
15082 		env->ops = bpf_verifier_ops[tgt_prog->type];
15083 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15084 	}
15085 
15086 	/* store info about the attachment target that will be used later */
15087 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15088 	prog->aux->attach_func_name = tgt_info.tgt_name;
15089 
15090 	if (tgt_prog) {
15091 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15092 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15093 	}
15094 
15095 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15096 		prog->aux->attach_btf_trace = true;
15097 		return 0;
15098 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15099 		if (!bpf_iter_prog_supported(prog))
15100 			return -EINVAL;
15101 		return 0;
15102 	}
15103 
15104 	if (prog->type == BPF_PROG_TYPE_LSM) {
15105 		ret = bpf_lsm_verify_prog(&env->log, prog);
15106 		if (ret < 0)
15107 			return ret;
15108 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15109 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15110 		return -EINVAL;
15111 	}
15112 
15113 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15114 	tr = bpf_trampoline_get(key, &tgt_info);
15115 	if (!tr)
15116 		return -ENOMEM;
15117 
15118 	prog->aux->dst_trampoline = tr;
15119 	return 0;
15120 }
15121 
15122 struct btf *bpf_get_btf_vmlinux(void)
15123 {
15124 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15125 		mutex_lock(&bpf_verifier_lock);
15126 		if (!btf_vmlinux)
15127 			btf_vmlinux = btf_parse_vmlinux();
15128 		mutex_unlock(&bpf_verifier_lock);
15129 	}
15130 	return btf_vmlinux;
15131 }
15132 
15133 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15134 {
15135 	u64 start_time = ktime_get_ns();
15136 	struct bpf_verifier_env *env;
15137 	struct bpf_verifier_log *log;
15138 	int i, len, ret = -EINVAL;
15139 	bool is_priv;
15140 
15141 	/* no program is valid */
15142 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15143 		return -EINVAL;
15144 
15145 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15146 	 * allocate/free it every time bpf_check() is called
15147 	 */
15148 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15149 	if (!env)
15150 		return -ENOMEM;
15151 	log = &env->log;
15152 
15153 	len = (*prog)->len;
15154 	env->insn_aux_data =
15155 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15156 	ret = -ENOMEM;
15157 	if (!env->insn_aux_data)
15158 		goto err_free_env;
15159 	for (i = 0; i < len; i++)
15160 		env->insn_aux_data[i].orig_idx = i;
15161 	env->prog = *prog;
15162 	env->ops = bpf_verifier_ops[env->prog->type];
15163 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15164 	is_priv = bpf_capable();
15165 
15166 	bpf_get_btf_vmlinux();
15167 
15168 	/* grab the mutex to protect few globals used by verifier */
15169 	if (!is_priv)
15170 		mutex_lock(&bpf_verifier_lock);
15171 
15172 	if (attr->log_level || attr->log_buf || attr->log_size) {
15173 		/* user requested verbose verifier output
15174 		 * and supplied buffer to store the verification trace
15175 		 */
15176 		log->level = attr->log_level;
15177 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15178 		log->len_total = attr->log_size;
15179 
15180 		/* log attributes have to be sane */
15181 		if (!bpf_verifier_log_attr_valid(log)) {
15182 			ret = -EINVAL;
15183 			goto err_unlock;
15184 		}
15185 	}
15186 
15187 	mark_verifier_state_clean(env);
15188 
15189 	if (IS_ERR(btf_vmlinux)) {
15190 		/* Either gcc or pahole or kernel are broken. */
15191 		verbose(env, "in-kernel BTF is malformed\n");
15192 		ret = PTR_ERR(btf_vmlinux);
15193 		goto skip_full_check;
15194 	}
15195 
15196 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15197 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15198 		env->strict_alignment = true;
15199 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15200 		env->strict_alignment = false;
15201 
15202 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15203 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15204 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15205 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15206 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15207 	env->bpf_capable = bpf_capable();
15208 
15209 	if (is_priv)
15210 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15211 
15212 	env->explored_states = kvcalloc(state_htab_size(env),
15213 				       sizeof(struct bpf_verifier_state_list *),
15214 				       GFP_USER);
15215 	ret = -ENOMEM;
15216 	if (!env->explored_states)
15217 		goto skip_full_check;
15218 
15219 	ret = add_subprog_and_kfunc(env);
15220 	if (ret < 0)
15221 		goto skip_full_check;
15222 
15223 	ret = check_subprogs(env);
15224 	if (ret < 0)
15225 		goto skip_full_check;
15226 
15227 	ret = check_btf_info(env, attr, uattr);
15228 	if (ret < 0)
15229 		goto skip_full_check;
15230 
15231 	ret = check_attach_btf_id(env);
15232 	if (ret)
15233 		goto skip_full_check;
15234 
15235 	ret = resolve_pseudo_ldimm64(env);
15236 	if (ret < 0)
15237 		goto skip_full_check;
15238 
15239 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15240 		ret = bpf_prog_offload_verifier_prep(env->prog);
15241 		if (ret)
15242 			goto skip_full_check;
15243 	}
15244 
15245 	ret = check_cfg(env);
15246 	if (ret < 0)
15247 		goto skip_full_check;
15248 
15249 	ret = do_check_subprogs(env);
15250 	ret = ret ?: do_check_main(env);
15251 
15252 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15253 		ret = bpf_prog_offload_finalize(env);
15254 
15255 skip_full_check:
15256 	kvfree(env->explored_states);
15257 
15258 	if (ret == 0)
15259 		ret = check_max_stack_depth(env);
15260 
15261 	/* instruction rewrites happen after this point */
15262 	if (ret == 0)
15263 		ret = optimize_bpf_loop(env);
15264 
15265 	if (is_priv) {
15266 		if (ret == 0)
15267 			opt_hard_wire_dead_code_branches(env);
15268 		if (ret == 0)
15269 			ret = opt_remove_dead_code(env);
15270 		if (ret == 0)
15271 			ret = opt_remove_nops(env);
15272 	} else {
15273 		if (ret == 0)
15274 			sanitize_dead_code(env);
15275 	}
15276 
15277 	if (ret == 0)
15278 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15279 		ret = convert_ctx_accesses(env);
15280 
15281 	if (ret == 0)
15282 		ret = do_misc_fixups(env);
15283 
15284 	/* do 32-bit optimization after insn patching has done so those patched
15285 	 * insns could be handled correctly.
15286 	 */
15287 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15288 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15289 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15290 								     : false;
15291 	}
15292 
15293 	if (ret == 0)
15294 		ret = fixup_call_args(env);
15295 
15296 	env->verification_time = ktime_get_ns() - start_time;
15297 	print_verification_stats(env);
15298 	env->prog->aux->verified_insns = env->insn_processed;
15299 
15300 	if (log->level && bpf_verifier_log_full(log))
15301 		ret = -ENOSPC;
15302 	if (log->level && !log->ubuf) {
15303 		ret = -EFAULT;
15304 		goto err_release_maps;
15305 	}
15306 
15307 	if (ret)
15308 		goto err_release_maps;
15309 
15310 	if (env->used_map_cnt) {
15311 		/* if program passed verifier, update used_maps in bpf_prog_info */
15312 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15313 							  sizeof(env->used_maps[0]),
15314 							  GFP_KERNEL);
15315 
15316 		if (!env->prog->aux->used_maps) {
15317 			ret = -ENOMEM;
15318 			goto err_release_maps;
15319 		}
15320 
15321 		memcpy(env->prog->aux->used_maps, env->used_maps,
15322 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15323 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15324 	}
15325 	if (env->used_btf_cnt) {
15326 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15327 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15328 							  sizeof(env->used_btfs[0]),
15329 							  GFP_KERNEL);
15330 		if (!env->prog->aux->used_btfs) {
15331 			ret = -ENOMEM;
15332 			goto err_release_maps;
15333 		}
15334 
15335 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15336 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15337 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15338 	}
15339 	if (env->used_map_cnt || env->used_btf_cnt) {
15340 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15341 		 * bpf_ld_imm64 instructions
15342 		 */
15343 		convert_pseudo_ld_imm64(env);
15344 	}
15345 
15346 	adjust_btf_func(env);
15347 
15348 err_release_maps:
15349 	if (!env->prog->aux->used_maps)
15350 		/* if we didn't copy map pointers into bpf_prog_info, release
15351 		 * them now. Otherwise free_used_maps() will release them.
15352 		 */
15353 		release_maps(env);
15354 	if (!env->prog->aux->used_btfs)
15355 		release_btfs(env);
15356 
15357 	/* extension progs temporarily inherit the attach_type of their targets
15358 	   for verification purposes, so set it back to zero before returning
15359 	 */
15360 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15361 		env->prog->expected_attach_type = 0;
15362 
15363 	*prog = env->prog;
15364 err_unlock:
15365 	if (!is_priv)
15366 		mutex_unlock(&bpf_verifier_lock);
15367 	vfree(env->insn_aux_data);
15368 err_free_env:
15369 	kfree(env);
15370 	return ret;
15371 }
15372