xref: /openbmc/linux/kernel/bpf/verifier.c (revision 0bcc4025)
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 #include <linux/poison.h>
27 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
195 static int ref_set_non_owning(struct bpf_verifier_env *env,
196 			      struct bpf_reg_state *reg);
197 
198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
199 {
200 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
201 }
202 
203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
204 {
205 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
206 }
207 
208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
209 			      const struct bpf_map *map, bool unpriv)
210 {
211 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
212 	unpriv |= bpf_map_ptr_unpriv(aux);
213 	aux->map_ptr_state = (unsigned long)map |
214 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
215 }
216 
217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
218 {
219 	return aux->map_key_state & BPF_MAP_KEY_POISON;
220 }
221 
222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
223 {
224 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
225 }
226 
227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
230 }
231 
232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
233 {
234 	bool poisoned = bpf_map_key_poisoned(aux);
235 
236 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
237 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
238 }
239 
240 static bool bpf_pseudo_call(const struct bpf_insn *insn)
241 {
242 	return insn->code == (BPF_JMP | BPF_CALL) &&
243 	       insn->src_reg == BPF_PSEUDO_CALL;
244 }
245 
246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
250 }
251 
252 struct bpf_call_arg_meta {
253 	struct bpf_map *map_ptr;
254 	bool raw_mode;
255 	bool pkt_access;
256 	u8 release_regno;
257 	int regno;
258 	int access_size;
259 	int mem_size;
260 	u64 msize_max_value;
261 	int ref_obj_id;
262 	int dynptr_id;
263 	int map_uid;
264 	int func_id;
265 	struct btf *btf;
266 	u32 btf_id;
267 	struct btf *ret_btf;
268 	u32 ret_btf_id;
269 	u32 subprogno;
270 	struct btf_field *kptr_field;
271 	u8 uninit_dynptr_regno;
272 };
273 
274 struct btf *btf_vmlinux;
275 
276 static DEFINE_MUTEX(bpf_verifier_lock);
277 
278 static const struct bpf_line_info *
279 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
280 {
281 	const struct bpf_line_info *linfo;
282 	const struct bpf_prog *prog;
283 	u32 i, nr_linfo;
284 
285 	prog = env->prog;
286 	nr_linfo = prog->aux->nr_linfo;
287 
288 	if (!nr_linfo || insn_off >= prog->len)
289 		return NULL;
290 
291 	linfo = prog->aux->linfo;
292 	for (i = 1; i < nr_linfo; i++)
293 		if (insn_off < linfo[i].insn_off)
294 			break;
295 
296 	return &linfo[i - 1];
297 }
298 
299 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
300 		       va_list args)
301 {
302 	unsigned int n;
303 
304 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
305 
306 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
307 		  "verifier log line truncated - local buffer too short\n");
308 
309 	if (log->level == BPF_LOG_KERNEL) {
310 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
311 
312 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
313 		return;
314 	}
315 
316 	n = min(log->len_total - log->len_used - 1, n);
317 	log->kbuf[n] = '\0';
318 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
319 		log->len_used += n;
320 	else
321 		log->ubuf = NULL;
322 }
323 
324 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
325 {
326 	char zero = 0;
327 
328 	if (!bpf_verifier_log_needed(log))
329 		return;
330 
331 	log->len_used = new_pos;
332 	if (put_user(zero, log->ubuf + new_pos))
333 		log->ubuf = NULL;
334 }
335 
336 /* log_level controls verbosity level of eBPF verifier.
337  * bpf_verifier_log_write() is used to dump the verification trace to the log,
338  * so the user can figure out what's wrong with the program
339  */
340 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
341 					   const char *fmt, ...)
342 {
343 	va_list args;
344 
345 	if (!bpf_verifier_log_needed(&env->log))
346 		return;
347 
348 	va_start(args, fmt);
349 	bpf_verifier_vlog(&env->log, fmt, args);
350 	va_end(args);
351 }
352 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
353 
354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
355 {
356 	struct bpf_verifier_env *env = private_data;
357 	va_list args;
358 
359 	if (!bpf_verifier_log_needed(&env->log))
360 		return;
361 
362 	va_start(args, fmt);
363 	bpf_verifier_vlog(&env->log, fmt, args);
364 	va_end(args);
365 }
366 
367 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
368 			    const char *fmt, ...)
369 {
370 	va_list args;
371 
372 	if (!bpf_verifier_log_needed(log))
373 		return;
374 
375 	va_start(args, fmt);
376 	bpf_verifier_vlog(log, fmt, args);
377 	va_end(args);
378 }
379 EXPORT_SYMBOL_GPL(bpf_log);
380 
381 static const char *ltrim(const char *s)
382 {
383 	while (isspace(*s))
384 		s++;
385 
386 	return s;
387 }
388 
389 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
390 					 u32 insn_off,
391 					 const char *prefix_fmt, ...)
392 {
393 	const struct bpf_line_info *linfo;
394 
395 	if (!bpf_verifier_log_needed(&env->log))
396 		return;
397 
398 	linfo = find_linfo(env, insn_off);
399 	if (!linfo || linfo == env->prev_linfo)
400 		return;
401 
402 	if (prefix_fmt) {
403 		va_list args;
404 
405 		va_start(args, prefix_fmt);
406 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
407 		va_end(args);
408 	}
409 
410 	verbose(env, "%s\n",
411 		ltrim(btf_name_by_offset(env->prog->aux->btf,
412 					 linfo->line_off)));
413 
414 	env->prev_linfo = linfo;
415 }
416 
417 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
418 				   struct bpf_reg_state *reg,
419 				   struct tnum *range, const char *ctx,
420 				   const char *reg_name)
421 {
422 	char tn_buf[48];
423 
424 	verbose(env, "At %s the register %s ", ctx, reg_name);
425 	if (!tnum_is_unknown(reg->var_off)) {
426 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
427 		verbose(env, "has value %s", tn_buf);
428 	} else {
429 		verbose(env, "has unknown scalar value");
430 	}
431 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
432 	verbose(env, " should have been in %s\n", tn_buf);
433 }
434 
435 static bool type_is_pkt_pointer(enum bpf_reg_type type)
436 {
437 	type = base_type(type);
438 	return type == PTR_TO_PACKET ||
439 	       type == PTR_TO_PACKET_META;
440 }
441 
442 static bool type_is_sk_pointer(enum bpf_reg_type type)
443 {
444 	return type == PTR_TO_SOCKET ||
445 		type == PTR_TO_SOCK_COMMON ||
446 		type == PTR_TO_TCP_SOCK ||
447 		type == PTR_TO_XDP_SOCK;
448 }
449 
450 static bool reg_type_not_null(enum bpf_reg_type type)
451 {
452 	return type == PTR_TO_SOCKET ||
453 		type == PTR_TO_TCP_SOCK ||
454 		type == PTR_TO_MAP_VALUE ||
455 		type == PTR_TO_MAP_KEY ||
456 		type == PTR_TO_SOCK_COMMON;
457 }
458 
459 static bool type_is_ptr_alloc_obj(u32 type)
460 {
461 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
462 }
463 
464 static bool type_is_non_owning_ref(u32 type)
465 {
466 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
467 }
468 
469 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
470 {
471 	struct btf_record *rec = NULL;
472 	struct btf_struct_meta *meta;
473 
474 	if (reg->type == PTR_TO_MAP_VALUE) {
475 		rec = reg->map_ptr->record;
476 	} else if (type_is_ptr_alloc_obj(reg->type)) {
477 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
478 		if (meta)
479 			rec = meta->record;
480 	}
481 	return rec;
482 }
483 
484 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
485 {
486 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
487 }
488 
489 static bool type_is_rdonly_mem(u32 type)
490 {
491 	return type & MEM_RDONLY;
492 }
493 
494 static bool type_may_be_null(u32 type)
495 {
496 	return type & PTR_MAYBE_NULL;
497 }
498 
499 static bool is_acquire_function(enum bpf_func_id func_id,
500 				const struct bpf_map *map)
501 {
502 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
503 
504 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
505 	    func_id == BPF_FUNC_sk_lookup_udp ||
506 	    func_id == BPF_FUNC_skc_lookup_tcp ||
507 	    func_id == BPF_FUNC_ringbuf_reserve ||
508 	    func_id == BPF_FUNC_kptr_xchg)
509 		return true;
510 
511 	if (func_id == BPF_FUNC_map_lookup_elem &&
512 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
513 	     map_type == BPF_MAP_TYPE_SOCKHASH))
514 		return true;
515 
516 	return false;
517 }
518 
519 static bool is_ptr_cast_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_tcp_sock ||
522 		func_id == BPF_FUNC_sk_fullsock ||
523 		func_id == BPF_FUNC_skc_to_tcp_sock ||
524 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
525 		func_id == BPF_FUNC_skc_to_udp6_sock ||
526 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
527 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
528 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
529 }
530 
531 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
532 {
533 	return func_id == BPF_FUNC_dynptr_data;
534 }
535 
536 static bool is_callback_calling_function(enum bpf_func_id func_id)
537 {
538 	return func_id == BPF_FUNC_for_each_map_elem ||
539 	       func_id == BPF_FUNC_timer_set_callback ||
540 	       func_id == BPF_FUNC_find_vma ||
541 	       func_id == BPF_FUNC_loop ||
542 	       func_id == BPF_FUNC_user_ringbuf_drain;
543 }
544 
545 static bool is_storage_get_function(enum bpf_func_id func_id)
546 {
547 	return func_id == BPF_FUNC_sk_storage_get ||
548 	       func_id == BPF_FUNC_inode_storage_get ||
549 	       func_id == BPF_FUNC_task_storage_get ||
550 	       func_id == BPF_FUNC_cgrp_storage_get;
551 }
552 
553 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
554 					const struct bpf_map *map)
555 {
556 	int ref_obj_uses = 0;
557 
558 	if (is_ptr_cast_function(func_id))
559 		ref_obj_uses++;
560 	if (is_acquire_function(func_id, map))
561 		ref_obj_uses++;
562 	if (is_dynptr_ref_function(func_id))
563 		ref_obj_uses++;
564 
565 	return ref_obj_uses > 1;
566 }
567 
568 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
569 {
570 	return BPF_CLASS(insn->code) == BPF_STX &&
571 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
572 	       insn->imm == BPF_CMPXCHG;
573 }
574 
575 /* string representation of 'enum bpf_reg_type'
576  *
577  * Note that reg_type_str() can not appear more than once in a single verbose()
578  * statement.
579  */
580 static const char *reg_type_str(struct bpf_verifier_env *env,
581 				enum bpf_reg_type type)
582 {
583 	char postfix[16] = {0}, prefix[64] = {0};
584 	static const char * const str[] = {
585 		[NOT_INIT]		= "?",
586 		[SCALAR_VALUE]		= "scalar",
587 		[PTR_TO_CTX]		= "ctx",
588 		[CONST_PTR_TO_MAP]	= "map_ptr",
589 		[PTR_TO_MAP_VALUE]	= "map_value",
590 		[PTR_TO_STACK]		= "fp",
591 		[PTR_TO_PACKET]		= "pkt",
592 		[PTR_TO_PACKET_META]	= "pkt_meta",
593 		[PTR_TO_PACKET_END]	= "pkt_end",
594 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
595 		[PTR_TO_SOCKET]		= "sock",
596 		[PTR_TO_SOCK_COMMON]	= "sock_common",
597 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
598 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
599 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
600 		[PTR_TO_BTF_ID]		= "ptr_",
601 		[PTR_TO_MEM]		= "mem",
602 		[PTR_TO_BUF]		= "buf",
603 		[PTR_TO_FUNC]		= "func",
604 		[PTR_TO_MAP_KEY]	= "map_key",
605 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
606 	};
607 
608 	if (type & PTR_MAYBE_NULL) {
609 		if (base_type(type) == PTR_TO_BTF_ID)
610 			strncpy(postfix, "or_null_", 16);
611 		else
612 			strncpy(postfix, "_or_null", 16);
613 	}
614 
615 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
616 		 type & MEM_RDONLY ? "rdonly_" : "",
617 		 type & MEM_RINGBUF ? "ringbuf_" : "",
618 		 type & MEM_USER ? "user_" : "",
619 		 type & MEM_PERCPU ? "percpu_" : "",
620 		 type & MEM_RCU ? "rcu_" : "",
621 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
622 		 type & PTR_TRUSTED ? "trusted_" : ""
623 	);
624 
625 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
626 		 prefix, str[base_type(type)], postfix);
627 	return env->type_str_buf;
628 }
629 
630 static char slot_type_char[] = {
631 	[STACK_INVALID]	= '?',
632 	[STACK_SPILL]	= 'r',
633 	[STACK_MISC]	= 'm',
634 	[STACK_ZERO]	= '0',
635 	[STACK_DYNPTR]	= 'd',
636 };
637 
638 static void print_liveness(struct bpf_verifier_env *env,
639 			   enum bpf_reg_liveness live)
640 {
641 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
642 	    verbose(env, "_");
643 	if (live & REG_LIVE_READ)
644 		verbose(env, "r");
645 	if (live & REG_LIVE_WRITTEN)
646 		verbose(env, "w");
647 	if (live & REG_LIVE_DONE)
648 		verbose(env, "D");
649 }
650 
651 static int __get_spi(s32 off)
652 {
653 	return (-off - 1) / BPF_REG_SIZE;
654 }
655 
656 static struct bpf_func_state *func(struct bpf_verifier_env *env,
657 				   const struct bpf_reg_state *reg)
658 {
659 	struct bpf_verifier_state *cur = env->cur_state;
660 
661 	return cur->frame[reg->frameno];
662 }
663 
664 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
665 {
666        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
667 
668        /* We need to check that slots between [spi - nr_slots + 1, spi] are
669 	* within [0, allocated_stack).
670 	*
671 	* Please note that the spi grows downwards. For example, a dynptr
672 	* takes the size of two stack slots; the first slot will be at
673 	* spi and the second slot will be at spi - 1.
674 	*/
675        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
676 }
677 
678 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
679 {
680 	int off, spi;
681 
682 	if (!tnum_is_const(reg->var_off)) {
683 		verbose(env, "dynptr has to be at a constant offset\n");
684 		return -EINVAL;
685 	}
686 
687 	off = reg->off + reg->var_off.value;
688 	if (off % BPF_REG_SIZE) {
689 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
690 		return -EINVAL;
691 	}
692 
693 	spi = __get_spi(off);
694 	if (spi < 1) {
695 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
696 		return -EINVAL;
697 	}
698 
699 	if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS))
700 		return -ERANGE;
701 	return spi;
702 }
703 
704 static const char *kernel_type_name(const struct btf* btf, u32 id)
705 {
706 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
707 }
708 
709 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
710 {
711 	env->scratched_regs |= 1U << regno;
712 }
713 
714 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
715 {
716 	env->scratched_stack_slots |= 1ULL << spi;
717 }
718 
719 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
720 {
721 	return (env->scratched_regs >> regno) & 1;
722 }
723 
724 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
725 {
726 	return (env->scratched_stack_slots >> regno) & 1;
727 }
728 
729 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
730 {
731 	return env->scratched_regs || env->scratched_stack_slots;
732 }
733 
734 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
735 {
736 	env->scratched_regs = 0U;
737 	env->scratched_stack_slots = 0ULL;
738 }
739 
740 /* Used for printing the entire verifier state. */
741 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
742 {
743 	env->scratched_regs = ~0U;
744 	env->scratched_stack_slots = ~0ULL;
745 }
746 
747 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
748 {
749 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
750 	case DYNPTR_TYPE_LOCAL:
751 		return BPF_DYNPTR_TYPE_LOCAL;
752 	case DYNPTR_TYPE_RINGBUF:
753 		return BPF_DYNPTR_TYPE_RINGBUF;
754 	default:
755 		return BPF_DYNPTR_TYPE_INVALID;
756 	}
757 }
758 
759 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
760 {
761 	return type == BPF_DYNPTR_TYPE_RINGBUF;
762 }
763 
764 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
765 			      enum bpf_dynptr_type type,
766 			      bool first_slot, int dynptr_id);
767 
768 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
769 				struct bpf_reg_state *reg);
770 
771 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
772 				   struct bpf_reg_state *sreg1,
773 				   struct bpf_reg_state *sreg2,
774 				   enum bpf_dynptr_type type)
775 {
776 	int id = ++env->id_gen;
777 
778 	__mark_dynptr_reg(sreg1, type, true, id);
779 	__mark_dynptr_reg(sreg2, type, false, id);
780 }
781 
782 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
783 			       struct bpf_reg_state *reg,
784 			       enum bpf_dynptr_type type)
785 {
786 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
787 }
788 
789 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
790 				        struct bpf_func_state *state, int spi);
791 
792 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
793 				   enum bpf_arg_type arg_type, int insn_idx)
794 {
795 	struct bpf_func_state *state = func(env, reg);
796 	enum bpf_dynptr_type type;
797 	int spi, i, id, err;
798 
799 	spi = dynptr_get_spi(env, reg);
800 	if (spi < 0)
801 		return spi;
802 
803 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
804 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
805 	 * to ensure that for the following example:
806 	 *	[d1][d1][d2][d2]
807 	 * spi    3   2   1   0
808 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
809 	 * case they do belong to same dynptr, second call won't see slot_type
810 	 * as STACK_DYNPTR and will simply skip destruction.
811 	 */
812 	err = destroy_if_dynptr_stack_slot(env, state, spi);
813 	if (err)
814 		return err;
815 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
816 	if (err)
817 		return err;
818 
819 	for (i = 0; i < BPF_REG_SIZE; i++) {
820 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
821 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
822 	}
823 
824 	type = arg_to_dynptr_type(arg_type);
825 	if (type == BPF_DYNPTR_TYPE_INVALID)
826 		return -EINVAL;
827 
828 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
829 			       &state->stack[spi - 1].spilled_ptr, type);
830 
831 	if (dynptr_type_refcounted(type)) {
832 		/* The id is used to track proper releasing */
833 		id = acquire_reference_state(env, insn_idx);
834 		if (id < 0)
835 			return id;
836 
837 		state->stack[spi].spilled_ptr.ref_obj_id = id;
838 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
839 	}
840 
841 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
842 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
843 
844 	return 0;
845 }
846 
847 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
848 {
849 	struct bpf_func_state *state = func(env, reg);
850 	int spi, i;
851 
852 	spi = dynptr_get_spi(env, reg);
853 	if (spi < 0)
854 		return spi;
855 
856 	for (i = 0; i < BPF_REG_SIZE; i++) {
857 		state->stack[spi].slot_type[i] = STACK_INVALID;
858 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
859 	}
860 
861 	/* Invalidate any slices associated with this dynptr */
862 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
863 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
864 
865 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
866 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
867 
868 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
869 	 *
870 	 * While we don't allow reading STACK_INVALID, it is still possible to
871 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
872 	 * helpers or insns can do partial read of that part without failing,
873 	 * but check_stack_range_initialized, check_stack_read_var_off, and
874 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
875 	 * the slot conservatively. Hence we need to prevent those liveness
876 	 * marking walks.
877 	 *
878 	 * This was not a problem before because STACK_INVALID is only set by
879 	 * default (where the default reg state has its reg->parent as NULL), or
880 	 * in clean_live_states after REG_LIVE_DONE (at which point
881 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
882 	 * verifier state exploration (like we did above). Hence, for our case
883 	 * parentage chain will still be live (i.e. reg->parent may be
884 	 * non-NULL), while earlier reg->parent was NULL, so we need
885 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
886 	 * done later on reads or by mark_dynptr_read as well to unnecessary
887 	 * mark registers in verifier state.
888 	 */
889 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
890 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
891 
892 	return 0;
893 }
894 
895 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
896 			       struct bpf_reg_state *reg);
897 
898 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
899 				        struct bpf_func_state *state, int spi)
900 {
901 	struct bpf_func_state *fstate;
902 	struct bpf_reg_state *dreg;
903 	int i, dynptr_id;
904 
905 	/* We always ensure that STACK_DYNPTR is never set partially,
906 	 * hence just checking for slot_type[0] is enough. This is
907 	 * different for STACK_SPILL, where it may be only set for
908 	 * 1 byte, so code has to use is_spilled_reg.
909 	 */
910 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
911 		return 0;
912 
913 	/* Reposition spi to first slot */
914 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
915 		spi = spi + 1;
916 
917 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
918 		verbose(env, "cannot overwrite referenced dynptr\n");
919 		return -EINVAL;
920 	}
921 
922 	mark_stack_slot_scratched(env, spi);
923 	mark_stack_slot_scratched(env, spi - 1);
924 
925 	/* Writing partially to one dynptr stack slot destroys both. */
926 	for (i = 0; i < BPF_REG_SIZE; i++) {
927 		state->stack[spi].slot_type[i] = STACK_INVALID;
928 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
929 	}
930 
931 	dynptr_id = state->stack[spi].spilled_ptr.id;
932 	/* Invalidate any slices associated with this dynptr */
933 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
934 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
935 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
936 			continue;
937 		if (dreg->dynptr_id == dynptr_id) {
938 			if (!env->allow_ptr_leaks)
939 				__mark_reg_not_init(env, dreg);
940 			else
941 				__mark_reg_unknown(env, dreg);
942 		}
943 	}));
944 
945 	/* Do not release reference state, we are destroying dynptr on stack,
946 	 * not using some helper to release it. Just reset register.
947 	 */
948 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
949 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
950 
951 	/* Same reason as unmark_stack_slots_dynptr above */
952 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
953 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
954 
955 	return 0;
956 }
957 
958 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959 				       int spi)
960 {
961 	if (reg->type == CONST_PTR_TO_DYNPTR)
962 		return false;
963 
964 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
965 	 * will do check_mem_access to check and update stack bounds later, so
966 	 * return true for that case.
967 	 */
968 	if (spi < 0)
969 		return spi == -ERANGE;
970 	/* We allow overwriting existing unreferenced STACK_DYNPTR slots, see
971 	 * mark_stack_slots_dynptr which calls destroy_if_dynptr_stack_slot to
972 	 * ensure dynptr objects at the slots we are touching are completely
973 	 * destructed before we reinitialize them for a new one. For referenced
974 	 * ones, destroy_if_dynptr_stack_slot returns an error early instead of
975 	 * delaying it until the end where the user will get "Unreleased
976 	 * reference" error.
977 	 */
978 	return true;
979 }
980 
981 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
982 				     int spi)
983 {
984 	struct bpf_func_state *state = func(env, reg);
985 	int i;
986 
987 	/* This already represents first slot of initialized bpf_dynptr */
988 	if (reg->type == CONST_PTR_TO_DYNPTR)
989 		return true;
990 
991 	if (spi < 0)
992 		return false;
993 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
994 		return false;
995 
996 	for (i = 0; i < BPF_REG_SIZE; i++) {
997 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
998 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
999 			return false;
1000 	}
1001 
1002 	return true;
1003 }
1004 
1005 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1006 				    enum bpf_arg_type arg_type)
1007 {
1008 	struct bpf_func_state *state = func(env, reg);
1009 	enum bpf_dynptr_type dynptr_type;
1010 	int spi;
1011 
1012 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1013 	if (arg_type == ARG_PTR_TO_DYNPTR)
1014 		return true;
1015 
1016 	dynptr_type = arg_to_dynptr_type(arg_type);
1017 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1018 		return reg->dynptr.type == dynptr_type;
1019 	} else {
1020 		spi = dynptr_get_spi(env, reg);
1021 		if (spi < 0)
1022 			return false;
1023 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1024 	}
1025 }
1026 
1027 /* The reg state of a pointer or a bounded scalar was saved when
1028  * it was spilled to the stack.
1029  */
1030 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1031 {
1032 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1033 }
1034 
1035 static void scrub_spilled_slot(u8 *stype)
1036 {
1037 	if (*stype != STACK_INVALID)
1038 		*stype = STACK_MISC;
1039 }
1040 
1041 static void print_verifier_state(struct bpf_verifier_env *env,
1042 				 const struct bpf_func_state *state,
1043 				 bool print_all)
1044 {
1045 	const struct bpf_reg_state *reg;
1046 	enum bpf_reg_type t;
1047 	int i;
1048 
1049 	if (state->frameno)
1050 		verbose(env, " frame%d:", state->frameno);
1051 	for (i = 0; i < MAX_BPF_REG; i++) {
1052 		reg = &state->regs[i];
1053 		t = reg->type;
1054 		if (t == NOT_INIT)
1055 			continue;
1056 		if (!print_all && !reg_scratched(env, i))
1057 			continue;
1058 		verbose(env, " R%d", i);
1059 		print_liveness(env, reg->live);
1060 		verbose(env, "=");
1061 		if (t == SCALAR_VALUE && reg->precise)
1062 			verbose(env, "P");
1063 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1064 		    tnum_is_const(reg->var_off)) {
1065 			/* reg->off should be 0 for SCALAR_VALUE */
1066 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1067 			verbose(env, "%lld", reg->var_off.value + reg->off);
1068 		} else {
1069 			const char *sep = "";
1070 
1071 			verbose(env, "%s", reg_type_str(env, t));
1072 			if (base_type(t) == PTR_TO_BTF_ID)
1073 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1074 			verbose(env, "(");
1075 /*
1076  * _a stands for append, was shortened to avoid multiline statements below.
1077  * This macro is used to output a comma separated list of attributes.
1078  */
1079 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1080 
1081 			if (reg->id)
1082 				verbose_a("id=%d", reg->id);
1083 			if (reg->ref_obj_id)
1084 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1085 			if (type_is_non_owning_ref(reg->type))
1086 				verbose_a("%s", "non_own_ref");
1087 			if (t != SCALAR_VALUE)
1088 				verbose_a("off=%d", reg->off);
1089 			if (type_is_pkt_pointer(t))
1090 				verbose_a("r=%d", reg->range);
1091 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1092 				 base_type(t) == PTR_TO_MAP_KEY ||
1093 				 base_type(t) == PTR_TO_MAP_VALUE)
1094 				verbose_a("ks=%d,vs=%d",
1095 					  reg->map_ptr->key_size,
1096 					  reg->map_ptr->value_size);
1097 			if (tnum_is_const(reg->var_off)) {
1098 				/* Typically an immediate SCALAR_VALUE, but
1099 				 * could be a pointer whose offset is too big
1100 				 * for reg->off
1101 				 */
1102 				verbose_a("imm=%llx", reg->var_off.value);
1103 			} else {
1104 				if (reg->smin_value != reg->umin_value &&
1105 				    reg->smin_value != S64_MIN)
1106 					verbose_a("smin=%lld", (long long)reg->smin_value);
1107 				if (reg->smax_value != reg->umax_value &&
1108 				    reg->smax_value != S64_MAX)
1109 					verbose_a("smax=%lld", (long long)reg->smax_value);
1110 				if (reg->umin_value != 0)
1111 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1112 				if (reg->umax_value != U64_MAX)
1113 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1114 				if (!tnum_is_unknown(reg->var_off)) {
1115 					char tn_buf[48];
1116 
1117 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1118 					verbose_a("var_off=%s", tn_buf);
1119 				}
1120 				if (reg->s32_min_value != reg->smin_value &&
1121 				    reg->s32_min_value != S32_MIN)
1122 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1123 				if (reg->s32_max_value != reg->smax_value &&
1124 				    reg->s32_max_value != S32_MAX)
1125 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1126 				if (reg->u32_min_value != reg->umin_value &&
1127 				    reg->u32_min_value != U32_MIN)
1128 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1129 				if (reg->u32_max_value != reg->umax_value &&
1130 				    reg->u32_max_value != U32_MAX)
1131 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1132 			}
1133 #undef verbose_a
1134 
1135 			verbose(env, ")");
1136 		}
1137 	}
1138 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1139 		char types_buf[BPF_REG_SIZE + 1];
1140 		bool valid = false;
1141 		int j;
1142 
1143 		for (j = 0; j < BPF_REG_SIZE; j++) {
1144 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1145 				valid = true;
1146 			types_buf[j] = slot_type_char[
1147 					state->stack[i].slot_type[j]];
1148 		}
1149 		types_buf[BPF_REG_SIZE] = 0;
1150 		if (!valid)
1151 			continue;
1152 		if (!print_all && !stack_slot_scratched(env, i))
1153 			continue;
1154 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1155 		print_liveness(env, state->stack[i].spilled_ptr.live);
1156 		if (is_spilled_reg(&state->stack[i])) {
1157 			reg = &state->stack[i].spilled_ptr;
1158 			t = reg->type;
1159 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1160 			if (t == SCALAR_VALUE && reg->precise)
1161 				verbose(env, "P");
1162 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1163 				verbose(env, "%lld", reg->var_off.value + reg->off);
1164 		} else {
1165 			verbose(env, "=%s", types_buf);
1166 		}
1167 	}
1168 	if (state->acquired_refs && state->refs[0].id) {
1169 		verbose(env, " refs=%d", state->refs[0].id);
1170 		for (i = 1; i < state->acquired_refs; i++)
1171 			if (state->refs[i].id)
1172 				verbose(env, ",%d", state->refs[i].id);
1173 	}
1174 	if (state->in_callback_fn)
1175 		verbose(env, " cb");
1176 	if (state->in_async_callback_fn)
1177 		verbose(env, " async_cb");
1178 	verbose(env, "\n");
1179 	mark_verifier_state_clean(env);
1180 }
1181 
1182 static inline u32 vlog_alignment(u32 pos)
1183 {
1184 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1185 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1186 }
1187 
1188 static void print_insn_state(struct bpf_verifier_env *env,
1189 			     const struct bpf_func_state *state)
1190 {
1191 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1192 		/* remove new line character */
1193 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1194 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1195 	} else {
1196 		verbose(env, "%d:", env->insn_idx);
1197 	}
1198 	print_verifier_state(env, state, false);
1199 }
1200 
1201 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1202  * small to hold src. This is different from krealloc since we don't want to preserve
1203  * the contents of dst.
1204  *
1205  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1206  * not be allocated.
1207  */
1208 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1209 {
1210 	size_t alloc_bytes;
1211 	void *orig = dst;
1212 	size_t bytes;
1213 
1214 	if (ZERO_OR_NULL_PTR(src))
1215 		goto out;
1216 
1217 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1218 		return NULL;
1219 
1220 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1221 	dst = krealloc(orig, alloc_bytes, flags);
1222 	if (!dst) {
1223 		kfree(orig);
1224 		return NULL;
1225 	}
1226 
1227 	memcpy(dst, src, bytes);
1228 out:
1229 	return dst ? dst : ZERO_SIZE_PTR;
1230 }
1231 
1232 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1233  * small to hold new_n items. new items are zeroed out if the array grows.
1234  *
1235  * Contrary to krealloc_array, does not free arr if new_n is zero.
1236  */
1237 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1238 {
1239 	size_t alloc_size;
1240 	void *new_arr;
1241 
1242 	if (!new_n || old_n == new_n)
1243 		goto out;
1244 
1245 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1246 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1247 	if (!new_arr) {
1248 		kfree(arr);
1249 		return NULL;
1250 	}
1251 	arr = new_arr;
1252 
1253 	if (new_n > old_n)
1254 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1255 
1256 out:
1257 	return arr ? arr : ZERO_SIZE_PTR;
1258 }
1259 
1260 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1261 {
1262 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1263 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1264 	if (!dst->refs)
1265 		return -ENOMEM;
1266 
1267 	dst->acquired_refs = src->acquired_refs;
1268 	return 0;
1269 }
1270 
1271 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1272 {
1273 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1274 
1275 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1276 				GFP_KERNEL);
1277 	if (!dst->stack)
1278 		return -ENOMEM;
1279 
1280 	dst->allocated_stack = src->allocated_stack;
1281 	return 0;
1282 }
1283 
1284 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1285 {
1286 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1287 				    sizeof(struct bpf_reference_state));
1288 	if (!state->refs)
1289 		return -ENOMEM;
1290 
1291 	state->acquired_refs = n;
1292 	return 0;
1293 }
1294 
1295 static int grow_stack_state(struct bpf_func_state *state, int size)
1296 {
1297 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1298 
1299 	if (old_n >= n)
1300 		return 0;
1301 
1302 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1303 	if (!state->stack)
1304 		return -ENOMEM;
1305 
1306 	state->allocated_stack = size;
1307 	return 0;
1308 }
1309 
1310 /* Acquire a pointer id from the env and update the state->refs to include
1311  * this new pointer reference.
1312  * On success, returns a valid pointer id to associate with the register
1313  * On failure, returns a negative errno.
1314  */
1315 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1316 {
1317 	struct bpf_func_state *state = cur_func(env);
1318 	int new_ofs = state->acquired_refs;
1319 	int id, err;
1320 
1321 	err = resize_reference_state(state, state->acquired_refs + 1);
1322 	if (err)
1323 		return err;
1324 	id = ++env->id_gen;
1325 	state->refs[new_ofs].id = id;
1326 	state->refs[new_ofs].insn_idx = insn_idx;
1327 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1328 
1329 	return id;
1330 }
1331 
1332 /* release function corresponding to acquire_reference_state(). Idempotent. */
1333 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1334 {
1335 	int i, last_idx;
1336 
1337 	last_idx = state->acquired_refs - 1;
1338 	for (i = 0; i < state->acquired_refs; i++) {
1339 		if (state->refs[i].id == ptr_id) {
1340 			/* Cannot release caller references in callbacks */
1341 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1342 				return -EINVAL;
1343 			if (last_idx && i != last_idx)
1344 				memcpy(&state->refs[i], &state->refs[last_idx],
1345 				       sizeof(*state->refs));
1346 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1347 			state->acquired_refs--;
1348 			return 0;
1349 		}
1350 	}
1351 	return -EINVAL;
1352 }
1353 
1354 static void free_func_state(struct bpf_func_state *state)
1355 {
1356 	if (!state)
1357 		return;
1358 	kfree(state->refs);
1359 	kfree(state->stack);
1360 	kfree(state);
1361 }
1362 
1363 static void clear_jmp_history(struct bpf_verifier_state *state)
1364 {
1365 	kfree(state->jmp_history);
1366 	state->jmp_history = NULL;
1367 	state->jmp_history_cnt = 0;
1368 }
1369 
1370 static void free_verifier_state(struct bpf_verifier_state *state,
1371 				bool free_self)
1372 {
1373 	int i;
1374 
1375 	for (i = 0; i <= state->curframe; i++) {
1376 		free_func_state(state->frame[i]);
1377 		state->frame[i] = NULL;
1378 	}
1379 	clear_jmp_history(state);
1380 	if (free_self)
1381 		kfree(state);
1382 }
1383 
1384 /* copy verifier state from src to dst growing dst stack space
1385  * when necessary to accommodate larger src stack
1386  */
1387 static int copy_func_state(struct bpf_func_state *dst,
1388 			   const struct bpf_func_state *src)
1389 {
1390 	int err;
1391 
1392 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1393 	err = copy_reference_state(dst, src);
1394 	if (err)
1395 		return err;
1396 	return copy_stack_state(dst, src);
1397 }
1398 
1399 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1400 			       const struct bpf_verifier_state *src)
1401 {
1402 	struct bpf_func_state *dst;
1403 	int i, err;
1404 
1405 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1406 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1407 					    GFP_USER);
1408 	if (!dst_state->jmp_history)
1409 		return -ENOMEM;
1410 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1411 
1412 	/* if dst has more stack frames then src frame, free them */
1413 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1414 		free_func_state(dst_state->frame[i]);
1415 		dst_state->frame[i] = NULL;
1416 	}
1417 	dst_state->speculative = src->speculative;
1418 	dst_state->active_rcu_lock = src->active_rcu_lock;
1419 	dst_state->curframe = src->curframe;
1420 	dst_state->active_lock.ptr = src->active_lock.ptr;
1421 	dst_state->active_lock.id = src->active_lock.id;
1422 	dst_state->branches = src->branches;
1423 	dst_state->parent = src->parent;
1424 	dst_state->first_insn_idx = src->first_insn_idx;
1425 	dst_state->last_insn_idx = src->last_insn_idx;
1426 	for (i = 0; i <= src->curframe; i++) {
1427 		dst = dst_state->frame[i];
1428 		if (!dst) {
1429 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1430 			if (!dst)
1431 				return -ENOMEM;
1432 			dst_state->frame[i] = dst;
1433 		}
1434 		err = copy_func_state(dst, src->frame[i]);
1435 		if (err)
1436 			return err;
1437 	}
1438 	return 0;
1439 }
1440 
1441 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1442 {
1443 	while (st) {
1444 		u32 br = --st->branches;
1445 
1446 		/* WARN_ON(br > 1) technically makes sense here,
1447 		 * but see comment in push_stack(), hence:
1448 		 */
1449 		WARN_ONCE((int)br < 0,
1450 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1451 			  br);
1452 		if (br)
1453 			break;
1454 		st = st->parent;
1455 	}
1456 }
1457 
1458 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1459 		     int *insn_idx, bool pop_log)
1460 {
1461 	struct bpf_verifier_state *cur = env->cur_state;
1462 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1463 	int err;
1464 
1465 	if (env->head == NULL)
1466 		return -ENOENT;
1467 
1468 	if (cur) {
1469 		err = copy_verifier_state(cur, &head->st);
1470 		if (err)
1471 			return err;
1472 	}
1473 	if (pop_log)
1474 		bpf_vlog_reset(&env->log, head->log_pos);
1475 	if (insn_idx)
1476 		*insn_idx = head->insn_idx;
1477 	if (prev_insn_idx)
1478 		*prev_insn_idx = head->prev_insn_idx;
1479 	elem = head->next;
1480 	free_verifier_state(&head->st, false);
1481 	kfree(head);
1482 	env->head = elem;
1483 	env->stack_size--;
1484 	return 0;
1485 }
1486 
1487 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1488 					     int insn_idx, int prev_insn_idx,
1489 					     bool speculative)
1490 {
1491 	struct bpf_verifier_state *cur = env->cur_state;
1492 	struct bpf_verifier_stack_elem *elem;
1493 	int err;
1494 
1495 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1496 	if (!elem)
1497 		goto err;
1498 
1499 	elem->insn_idx = insn_idx;
1500 	elem->prev_insn_idx = prev_insn_idx;
1501 	elem->next = env->head;
1502 	elem->log_pos = env->log.len_used;
1503 	env->head = elem;
1504 	env->stack_size++;
1505 	err = copy_verifier_state(&elem->st, cur);
1506 	if (err)
1507 		goto err;
1508 	elem->st.speculative |= speculative;
1509 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1510 		verbose(env, "The sequence of %d jumps is too complex.\n",
1511 			env->stack_size);
1512 		goto err;
1513 	}
1514 	if (elem->st.parent) {
1515 		++elem->st.parent->branches;
1516 		/* WARN_ON(branches > 2) technically makes sense here,
1517 		 * but
1518 		 * 1. speculative states will bump 'branches' for non-branch
1519 		 * instructions
1520 		 * 2. is_state_visited() heuristics may decide not to create
1521 		 * a new state for a sequence of branches and all such current
1522 		 * and cloned states will be pointing to a single parent state
1523 		 * which might have large 'branches' count.
1524 		 */
1525 	}
1526 	return &elem->st;
1527 err:
1528 	free_verifier_state(env->cur_state, true);
1529 	env->cur_state = NULL;
1530 	/* pop all elements and return */
1531 	while (!pop_stack(env, NULL, NULL, false));
1532 	return NULL;
1533 }
1534 
1535 #define CALLER_SAVED_REGS 6
1536 static const int caller_saved[CALLER_SAVED_REGS] = {
1537 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1538 };
1539 
1540 /* This helper doesn't clear reg->id */
1541 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1542 {
1543 	reg->var_off = tnum_const(imm);
1544 	reg->smin_value = (s64)imm;
1545 	reg->smax_value = (s64)imm;
1546 	reg->umin_value = imm;
1547 	reg->umax_value = imm;
1548 
1549 	reg->s32_min_value = (s32)imm;
1550 	reg->s32_max_value = (s32)imm;
1551 	reg->u32_min_value = (u32)imm;
1552 	reg->u32_max_value = (u32)imm;
1553 }
1554 
1555 /* Mark the unknown part of a register (variable offset or scalar value) as
1556  * known to have the value @imm.
1557  */
1558 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1559 {
1560 	/* Clear off and union(map_ptr, range) */
1561 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1562 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1563 	reg->id = 0;
1564 	reg->ref_obj_id = 0;
1565 	___mark_reg_known(reg, imm);
1566 }
1567 
1568 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1569 {
1570 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1571 	reg->s32_min_value = (s32)imm;
1572 	reg->s32_max_value = (s32)imm;
1573 	reg->u32_min_value = (u32)imm;
1574 	reg->u32_max_value = (u32)imm;
1575 }
1576 
1577 /* Mark the 'variable offset' part of a register as zero.  This should be
1578  * used only on registers holding a pointer type.
1579  */
1580 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1581 {
1582 	__mark_reg_known(reg, 0);
1583 }
1584 
1585 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1586 {
1587 	__mark_reg_known(reg, 0);
1588 	reg->type = SCALAR_VALUE;
1589 }
1590 
1591 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1592 				struct bpf_reg_state *regs, u32 regno)
1593 {
1594 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1595 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1596 		/* Something bad happened, let's kill all regs */
1597 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1598 			__mark_reg_not_init(env, regs + regno);
1599 		return;
1600 	}
1601 	__mark_reg_known_zero(regs + regno);
1602 }
1603 
1604 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1605 			      bool first_slot, int dynptr_id)
1606 {
1607 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1608 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1609 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1610 	 */
1611 	__mark_reg_known_zero(reg);
1612 	reg->type = CONST_PTR_TO_DYNPTR;
1613 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1614 	reg->id = dynptr_id;
1615 	reg->dynptr.type = type;
1616 	reg->dynptr.first_slot = first_slot;
1617 }
1618 
1619 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1620 {
1621 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1622 		const struct bpf_map *map = reg->map_ptr;
1623 
1624 		if (map->inner_map_meta) {
1625 			reg->type = CONST_PTR_TO_MAP;
1626 			reg->map_ptr = map->inner_map_meta;
1627 			/* transfer reg's id which is unique for every map_lookup_elem
1628 			 * as UID of the inner map.
1629 			 */
1630 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1631 				reg->map_uid = reg->id;
1632 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1633 			reg->type = PTR_TO_XDP_SOCK;
1634 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1635 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1636 			reg->type = PTR_TO_SOCKET;
1637 		} else {
1638 			reg->type = PTR_TO_MAP_VALUE;
1639 		}
1640 		return;
1641 	}
1642 
1643 	reg->type &= ~PTR_MAYBE_NULL;
1644 }
1645 
1646 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1647 				struct btf_field_graph_root *ds_head)
1648 {
1649 	__mark_reg_known_zero(&regs[regno]);
1650 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1651 	regs[regno].btf = ds_head->btf;
1652 	regs[regno].btf_id = ds_head->value_btf_id;
1653 	regs[regno].off = ds_head->node_offset;
1654 }
1655 
1656 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1657 {
1658 	return type_is_pkt_pointer(reg->type);
1659 }
1660 
1661 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1662 {
1663 	return reg_is_pkt_pointer(reg) ||
1664 	       reg->type == PTR_TO_PACKET_END;
1665 }
1666 
1667 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1668 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1669 				    enum bpf_reg_type which)
1670 {
1671 	/* The register can already have a range from prior markings.
1672 	 * This is fine as long as it hasn't been advanced from its
1673 	 * origin.
1674 	 */
1675 	return reg->type == which &&
1676 	       reg->id == 0 &&
1677 	       reg->off == 0 &&
1678 	       tnum_equals_const(reg->var_off, 0);
1679 }
1680 
1681 /* Reset the min/max bounds of a register */
1682 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1683 {
1684 	reg->smin_value = S64_MIN;
1685 	reg->smax_value = S64_MAX;
1686 	reg->umin_value = 0;
1687 	reg->umax_value = U64_MAX;
1688 
1689 	reg->s32_min_value = S32_MIN;
1690 	reg->s32_max_value = S32_MAX;
1691 	reg->u32_min_value = 0;
1692 	reg->u32_max_value = U32_MAX;
1693 }
1694 
1695 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1696 {
1697 	reg->smin_value = S64_MIN;
1698 	reg->smax_value = S64_MAX;
1699 	reg->umin_value = 0;
1700 	reg->umax_value = U64_MAX;
1701 }
1702 
1703 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1704 {
1705 	reg->s32_min_value = S32_MIN;
1706 	reg->s32_max_value = S32_MAX;
1707 	reg->u32_min_value = 0;
1708 	reg->u32_max_value = U32_MAX;
1709 }
1710 
1711 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1712 {
1713 	struct tnum var32_off = tnum_subreg(reg->var_off);
1714 
1715 	/* min signed is max(sign bit) | min(other bits) */
1716 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1717 			var32_off.value | (var32_off.mask & S32_MIN));
1718 	/* max signed is min(sign bit) | max(other bits) */
1719 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1720 			var32_off.value | (var32_off.mask & S32_MAX));
1721 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1722 	reg->u32_max_value = min(reg->u32_max_value,
1723 				 (u32)(var32_off.value | var32_off.mask));
1724 }
1725 
1726 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1727 {
1728 	/* min signed is max(sign bit) | min(other bits) */
1729 	reg->smin_value = max_t(s64, reg->smin_value,
1730 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1731 	/* max signed is min(sign bit) | max(other bits) */
1732 	reg->smax_value = min_t(s64, reg->smax_value,
1733 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1734 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1735 	reg->umax_value = min(reg->umax_value,
1736 			      reg->var_off.value | reg->var_off.mask);
1737 }
1738 
1739 static void __update_reg_bounds(struct bpf_reg_state *reg)
1740 {
1741 	__update_reg32_bounds(reg);
1742 	__update_reg64_bounds(reg);
1743 }
1744 
1745 /* Uses signed min/max values to inform unsigned, and vice-versa */
1746 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1747 {
1748 	/* Learn sign from signed bounds.
1749 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1750 	 * are the same, so combine.  This works even in the negative case, e.g.
1751 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1752 	 */
1753 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1754 		reg->s32_min_value = reg->u32_min_value =
1755 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1756 		reg->s32_max_value = reg->u32_max_value =
1757 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1758 		return;
1759 	}
1760 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1761 	 * boundary, so we must be careful.
1762 	 */
1763 	if ((s32)reg->u32_max_value >= 0) {
1764 		/* Positive.  We can't learn anything from the smin, but smax
1765 		 * is positive, hence safe.
1766 		 */
1767 		reg->s32_min_value = reg->u32_min_value;
1768 		reg->s32_max_value = reg->u32_max_value =
1769 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1770 	} else if ((s32)reg->u32_min_value < 0) {
1771 		/* Negative.  We can't learn anything from the smax, but smin
1772 		 * is negative, hence safe.
1773 		 */
1774 		reg->s32_min_value = reg->u32_min_value =
1775 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1776 		reg->s32_max_value = reg->u32_max_value;
1777 	}
1778 }
1779 
1780 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1781 {
1782 	/* Learn sign from signed bounds.
1783 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1784 	 * are the same, so combine.  This works even in the negative case, e.g.
1785 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1786 	 */
1787 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1788 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1789 							  reg->umin_value);
1790 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1791 							  reg->umax_value);
1792 		return;
1793 	}
1794 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1795 	 * boundary, so we must be careful.
1796 	 */
1797 	if ((s64)reg->umax_value >= 0) {
1798 		/* Positive.  We can't learn anything from the smin, but smax
1799 		 * is positive, hence safe.
1800 		 */
1801 		reg->smin_value = reg->umin_value;
1802 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1803 							  reg->umax_value);
1804 	} else if ((s64)reg->umin_value < 0) {
1805 		/* Negative.  We can't learn anything from the smax, but smin
1806 		 * is negative, hence safe.
1807 		 */
1808 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1809 							  reg->umin_value);
1810 		reg->smax_value = reg->umax_value;
1811 	}
1812 }
1813 
1814 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1815 {
1816 	__reg32_deduce_bounds(reg);
1817 	__reg64_deduce_bounds(reg);
1818 }
1819 
1820 /* Attempts to improve var_off based on unsigned min/max information */
1821 static void __reg_bound_offset(struct bpf_reg_state *reg)
1822 {
1823 	struct tnum var64_off = tnum_intersect(reg->var_off,
1824 					       tnum_range(reg->umin_value,
1825 							  reg->umax_value));
1826 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1827 						tnum_range(reg->u32_min_value,
1828 							   reg->u32_max_value));
1829 
1830 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1831 }
1832 
1833 static void reg_bounds_sync(struct bpf_reg_state *reg)
1834 {
1835 	/* We might have learned new bounds from the var_off. */
1836 	__update_reg_bounds(reg);
1837 	/* We might have learned something about the sign bit. */
1838 	__reg_deduce_bounds(reg);
1839 	/* We might have learned some bits from the bounds. */
1840 	__reg_bound_offset(reg);
1841 	/* Intersecting with the old var_off might have improved our bounds
1842 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1843 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1844 	 */
1845 	__update_reg_bounds(reg);
1846 }
1847 
1848 static bool __reg32_bound_s64(s32 a)
1849 {
1850 	return a >= 0 && a <= S32_MAX;
1851 }
1852 
1853 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1854 {
1855 	reg->umin_value = reg->u32_min_value;
1856 	reg->umax_value = reg->u32_max_value;
1857 
1858 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1859 	 * be positive otherwise set to worse case bounds and refine later
1860 	 * from tnum.
1861 	 */
1862 	if (__reg32_bound_s64(reg->s32_min_value) &&
1863 	    __reg32_bound_s64(reg->s32_max_value)) {
1864 		reg->smin_value = reg->s32_min_value;
1865 		reg->smax_value = reg->s32_max_value;
1866 	} else {
1867 		reg->smin_value = 0;
1868 		reg->smax_value = U32_MAX;
1869 	}
1870 }
1871 
1872 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1873 {
1874 	/* special case when 64-bit register has upper 32-bit register
1875 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1876 	 * allowing us to use 32-bit bounds directly,
1877 	 */
1878 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1879 		__reg_assign_32_into_64(reg);
1880 	} else {
1881 		/* Otherwise the best we can do is push lower 32bit known and
1882 		 * unknown bits into register (var_off set from jmp logic)
1883 		 * then learn as much as possible from the 64-bit tnum
1884 		 * known and unknown bits. The previous smin/smax bounds are
1885 		 * invalid here because of jmp32 compare so mark them unknown
1886 		 * so they do not impact tnum bounds calculation.
1887 		 */
1888 		__mark_reg64_unbounded(reg);
1889 	}
1890 	reg_bounds_sync(reg);
1891 }
1892 
1893 static bool __reg64_bound_s32(s64 a)
1894 {
1895 	return a >= S32_MIN && a <= S32_MAX;
1896 }
1897 
1898 static bool __reg64_bound_u32(u64 a)
1899 {
1900 	return a >= U32_MIN && a <= U32_MAX;
1901 }
1902 
1903 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1904 {
1905 	__mark_reg32_unbounded(reg);
1906 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1907 		reg->s32_min_value = (s32)reg->smin_value;
1908 		reg->s32_max_value = (s32)reg->smax_value;
1909 	}
1910 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1911 		reg->u32_min_value = (u32)reg->umin_value;
1912 		reg->u32_max_value = (u32)reg->umax_value;
1913 	}
1914 	reg_bounds_sync(reg);
1915 }
1916 
1917 /* Mark a register as having a completely unknown (scalar) value. */
1918 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1919 			       struct bpf_reg_state *reg)
1920 {
1921 	/*
1922 	 * Clear type, off, and union(map_ptr, range) and
1923 	 * padding between 'type' and union
1924 	 */
1925 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1926 	reg->type = SCALAR_VALUE;
1927 	reg->id = 0;
1928 	reg->ref_obj_id = 0;
1929 	reg->var_off = tnum_unknown;
1930 	reg->frameno = 0;
1931 	reg->precise = !env->bpf_capable;
1932 	__mark_reg_unbounded(reg);
1933 }
1934 
1935 static void mark_reg_unknown(struct bpf_verifier_env *env,
1936 			     struct bpf_reg_state *regs, u32 regno)
1937 {
1938 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1939 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1940 		/* Something bad happened, let's kill all regs except FP */
1941 		for (regno = 0; regno < BPF_REG_FP; regno++)
1942 			__mark_reg_not_init(env, regs + regno);
1943 		return;
1944 	}
1945 	__mark_reg_unknown(env, regs + regno);
1946 }
1947 
1948 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1949 				struct bpf_reg_state *reg)
1950 {
1951 	__mark_reg_unknown(env, reg);
1952 	reg->type = NOT_INIT;
1953 }
1954 
1955 static void mark_reg_not_init(struct bpf_verifier_env *env,
1956 			      struct bpf_reg_state *regs, u32 regno)
1957 {
1958 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1959 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1960 		/* Something bad happened, let's kill all regs except FP */
1961 		for (regno = 0; regno < BPF_REG_FP; regno++)
1962 			__mark_reg_not_init(env, regs + regno);
1963 		return;
1964 	}
1965 	__mark_reg_not_init(env, regs + regno);
1966 }
1967 
1968 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1969 			    struct bpf_reg_state *regs, u32 regno,
1970 			    enum bpf_reg_type reg_type,
1971 			    struct btf *btf, u32 btf_id,
1972 			    enum bpf_type_flag flag)
1973 {
1974 	if (reg_type == SCALAR_VALUE) {
1975 		mark_reg_unknown(env, regs, regno);
1976 		return;
1977 	}
1978 	mark_reg_known_zero(env, regs, regno);
1979 	regs[regno].type = PTR_TO_BTF_ID | flag;
1980 	regs[regno].btf = btf;
1981 	regs[regno].btf_id = btf_id;
1982 }
1983 
1984 #define DEF_NOT_SUBREG	(0)
1985 static void init_reg_state(struct bpf_verifier_env *env,
1986 			   struct bpf_func_state *state)
1987 {
1988 	struct bpf_reg_state *regs = state->regs;
1989 	int i;
1990 
1991 	for (i = 0; i < MAX_BPF_REG; i++) {
1992 		mark_reg_not_init(env, regs, i);
1993 		regs[i].live = REG_LIVE_NONE;
1994 		regs[i].parent = NULL;
1995 		regs[i].subreg_def = DEF_NOT_SUBREG;
1996 	}
1997 
1998 	/* frame pointer */
1999 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2000 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2001 	regs[BPF_REG_FP].frameno = state->frameno;
2002 }
2003 
2004 #define BPF_MAIN_FUNC (-1)
2005 static void init_func_state(struct bpf_verifier_env *env,
2006 			    struct bpf_func_state *state,
2007 			    int callsite, int frameno, int subprogno)
2008 {
2009 	state->callsite = callsite;
2010 	state->frameno = frameno;
2011 	state->subprogno = subprogno;
2012 	state->callback_ret_range = tnum_range(0, 0);
2013 	init_reg_state(env, state);
2014 	mark_verifier_state_scratched(env);
2015 }
2016 
2017 /* Similar to push_stack(), but for async callbacks */
2018 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2019 						int insn_idx, int prev_insn_idx,
2020 						int subprog)
2021 {
2022 	struct bpf_verifier_stack_elem *elem;
2023 	struct bpf_func_state *frame;
2024 
2025 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2026 	if (!elem)
2027 		goto err;
2028 
2029 	elem->insn_idx = insn_idx;
2030 	elem->prev_insn_idx = prev_insn_idx;
2031 	elem->next = env->head;
2032 	elem->log_pos = env->log.len_used;
2033 	env->head = elem;
2034 	env->stack_size++;
2035 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2036 		verbose(env,
2037 			"The sequence of %d jumps is too complex for async cb.\n",
2038 			env->stack_size);
2039 		goto err;
2040 	}
2041 	/* Unlike push_stack() do not copy_verifier_state().
2042 	 * The caller state doesn't matter.
2043 	 * This is async callback. It starts in a fresh stack.
2044 	 * Initialize it similar to do_check_common().
2045 	 */
2046 	elem->st.branches = 1;
2047 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2048 	if (!frame)
2049 		goto err;
2050 	init_func_state(env, frame,
2051 			BPF_MAIN_FUNC /* callsite */,
2052 			0 /* frameno within this callchain */,
2053 			subprog /* subprog number within this prog */);
2054 	elem->st.frame[0] = frame;
2055 	return &elem->st;
2056 err:
2057 	free_verifier_state(env->cur_state, true);
2058 	env->cur_state = NULL;
2059 	/* pop all elements and return */
2060 	while (!pop_stack(env, NULL, NULL, false));
2061 	return NULL;
2062 }
2063 
2064 
2065 enum reg_arg_type {
2066 	SRC_OP,		/* register is used as source operand */
2067 	DST_OP,		/* register is used as destination operand */
2068 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2069 };
2070 
2071 static int cmp_subprogs(const void *a, const void *b)
2072 {
2073 	return ((struct bpf_subprog_info *)a)->start -
2074 	       ((struct bpf_subprog_info *)b)->start;
2075 }
2076 
2077 static int find_subprog(struct bpf_verifier_env *env, int off)
2078 {
2079 	struct bpf_subprog_info *p;
2080 
2081 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2082 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2083 	if (!p)
2084 		return -ENOENT;
2085 	return p - env->subprog_info;
2086 
2087 }
2088 
2089 static int add_subprog(struct bpf_verifier_env *env, int off)
2090 {
2091 	int insn_cnt = env->prog->len;
2092 	int ret;
2093 
2094 	if (off >= insn_cnt || off < 0) {
2095 		verbose(env, "call to invalid destination\n");
2096 		return -EINVAL;
2097 	}
2098 	ret = find_subprog(env, off);
2099 	if (ret >= 0)
2100 		return ret;
2101 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2102 		verbose(env, "too many subprograms\n");
2103 		return -E2BIG;
2104 	}
2105 	/* determine subprog starts. The end is one before the next starts */
2106 	env->subprog_info[env->subprog_cnt++].start = off;
2107 	sort(env->subprog_info, env->subprog_cnt,
2108 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2109 	return env->subprog_cnt - 1;
2110 }
2111 
2112 #define MAX_KFUNC_DESCS 256
2113 #define MAX_KFUNC_BTFS	256
2114 
2115 struct bpf_kfunc_desc {
2116 	struct btf_func_model func_model;
2117 	u32 func_id;
2118 	s32 imm;
2119 	u16 offset;
2120 };
2121 
2122 struct bpf_kfunc_btf {
2123 	struct btf *btf;
2124 	struct module *module;
2125 	u16 offset;
2126 };
2127 
2128 struct bpf_kfunc_desc_tab {
2129 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2130 	u32 nr_descs;
2131 };
2132 
2133 struct bpf_kfunc_btf_tab {
2134 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2135 	u32 nr_descs;
2136 };
2137 
2138 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2139 {
2140 	const struct bpf_kfunc_desc *d0 = a;
2141 	const struct bpf_kfunc_desc *d1 = b;
2142 
2143 	/* func_id is not greater than BTF_MAX_TYPE */
2144 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2145 }
2146 
2147 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2148 {
2149 	const struct bpf_kfunc_btf *d0 = a;
2150 	const struct bpf_kfunc_btf *d1 = b;
2151 
2152 	return d0->offset - d1->offset;
2153 }
2154 
2155 static const struct bpf_kfunc_desc *
2156 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2157 {
2158 	struct bpf_kfunc_desc desc = {
2159 		.func_id = func_id,
2160 		.offset = offset,
2161 	};
2162 	struct bpf_kfunc_desc_tab *tab;
2163 
2164 	tab = prog->aux->kfunc_tab;
2165 	return bsearch(&desc, tab->descs, tab->nr_descs,
2166 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2167 }
2168 
2169 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2170 					 s16 offset)
2171 {
2172 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2173 	struct bpf_kfunc_btf_tab *tab;
2174 	struct bpf_kfunc_btf *b;
2175 	struct module *mod;
2176 	struct btf *btf;
2177 	int btf_fd;
2178 
2179 	tab = env->prog->aux->kfunc_btf_tab;
2180 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2181 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2182 	if (!b) {
2183 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2184 			verbose(env, "too many different module BTFs\n");
2185 			return ERR_PTR(-E2BIG);
2186 		}
2187 
2188 		if (bpfptr_is_null(env->fd_array)) {
2189 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2190 			return ERR_PTR(-EPROTO);
2191 		}
2192 
2193 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2194 					    offset * sizeof(btf_fd),
2195 					    sizeof(btf_fd)))
2196 			return ERR_PTR(-EFAULT);
2197 
2198 		btf = btf_get_by_fd(btf_fd);
2199 		if (IS_ERR(btf)) {
2200 			verbose(env, "invalid module BTF fd specified\n");
2201 			return btf;
2202 		}
2203 
2204 		if (!btf_is_module(btf)) {
2205 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2206 			btf_put(btf);
2207 			return ERR_PTR(-EINVAL);
2208 		}
2209 
2210 		mod = btf_try_get_module(btf);
2211 		if (!mod) {
2212 			btf_put(btf);
2213 			return ERR_PTR(-ENXIO);
2214 		}
2215 
2216 		b = &tab->descs[tab->nr_descs++];
2217 		b->btf = btf;
2218 		b->module = mod;
2219 		b->offset = offset;
2220 
2221 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2222 		     kfunc_btf_cmp_by_off, NULL);
2223 	}
2224 	return b->btf;
2225 }
2226 
2227 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2228 {
2229 	if (!tab)
2230 		return;
2231 
2232 	while (tab->nr_descs--) {
2233 		module_put(tab->descs[tab->nr_descs].module);
2234 		btf_put(tab->descs[tab->nr_descs].btf);
2235 	}
2236 	kfree(tab);
2237 }
2238 
2239 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2240 {
2241 	if (offset) {
2242 		if (offset < 0) {
2243 			/* In the future, this can be allowed to increase limit
2244 			 * of fd index into fd_array, interpreted as u16.
2245 			 */
2246 			verbose(env, "negative offset disallowed for kernel module function call\n");
2247 			return ERR_PTR(-EINVAL);
2248 		}
2249 
2250 		return __find_kfunc_desc_btf(env, offset);
2251 	}
2252 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2253 }
2254 
2255 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2256 {
2257 	const struct btf_type *func, *func_proto;
2258 	struct bpf_kfunc_btf_tab *btf_tab;
2259 	struct bpf_kfunc_desc_tab *tab;
2260 	struct bpf_prog_aux *prog_aux;
2261 	struct bpf_kfunc_desc *desc;
2262 	const char *func_name;
2263 	struct btf *desc_btf;
2264 	unsigned long call_imm;
2265 	unsigned long addr;
2266 	int err;
2267 
2268 	prog_aux = env->prog->aux;
2269 	tab = prog_aux->kfunc_tab;
2270 	btf_tab = prog_aux->kfunc_btf_tab;
2271 	if (!tab) {
2272 		if (!btf_vmlinux) {
2273 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2274 			return -ENOTSUPP;
2275 		}
2276 
2277 		if (!env->prog->jit_requested) {
2278 			verbose(env, "JIT is required for calling kernel function\n");
2279 			return -ENOTSUPP;
2280 		}
2281 
2282 		if (!bpf_jit_supports_kfunc_call()) {
2283 			verbose(env, "JIT does not support calling kernel function\n");
2284 			return -ENOTSUPP;
2285 		}
2286 
2287 		if (!env->prog->gpl_compatible) {
2288 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2289 			return -EINVAL;
2290 		}
2291 
2292 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2293 		if (!tab)
2294 			return -ENOMEM;
2295 		prog_aux->kfunc_tab = tab;
2296 	}
2297 
2298 	/* func_id == 0 is always invalid, but instead of returning an error, be
2299 	 * conservative and wait until the code elimination pass before returning
2300 	 * error, so that invalid calls that get pruned out can be in BPF programs
2301 	 * loaded from userspace.  It is also required that offset be untouched
2302 	 * for such calls.
2303 	 */
2304 	if (!func_id && !offset)
2305 		return 0;
2306 
2307 	if (!btf_tab && offset) {
2308 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2309 		if (!btf_tab)
2310 			return -ENOMEM;
2311 		prog_aux->kfunc_btf_tab = btf_tab;
2312 	}
2313 
2314 	desc_btf = find_kfunc_desc_btf(env, offset);
2315 	if (IS_ERR(desc_btf)) {
2316 		verbose(env, "failed to find BTF for kernel function\n");
2317 		return PTR_ERR(desc_btf);
2318 	}
2319 
2320 	if (find_kfunc_desc(env->prog, func_id, offset))
2321 		return 0;
2322 
2323 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2324 		verbose(env, "too many different kernel function calls\n");
2325 		return -E2BIG;
2326 	}
2327 
2328 	func = btf_type_by_id(desc_btf, func_id);
2329 	if (!func || !btf_type_is_func(func)) {
2330 		verbose(env, "kernel btf_id %u is not a function\n",
2331 			func_id);
2332 		return -EINVAL;
2333 	}
2334 	func_proto = btf_type_by_id(desc_btf, func->type);
2335 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2336 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2337 			func_id);
2338 		return -EINVAL;
2339 	}
2340 
2341 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2342 	addr = kallsyms_lookup_name(func_name);
2343 	if (!addr) {
2344 		verbose(env, "cannot find address for kernel function %s\n",
2345 			func_name);
2346 		return -EINVAL;
2347 	}
2348 
2349 	call_imm = BPF_CALL_IMM(addr);
2350 	/* Check whether or not the relative offset overflows desc->imm */
2351 	if ((unsigned long)(s32)call_imm != call_imm) {
2352 		verbose(env, "address of kernel function %s is out of range\n",
2353 			func_name);
2354 		return -EINVAL;
2355 	}
2356 
2357 	if (bpf_dev_bound_kfunc_id(func_id)) {
2358 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2359 		if (err)
2360 			return err;
2361 	}
2362 
2363 	desc = &tab->descs[tab->nr_descs++];
2364 	desc->func_id = func_id;
2365 	desc->imm = call_imm;
2366 	desc->offset = offset;
2367 	err = btf_distill_func_proto(&env->log, desc_btf,
2368 				     func_proto, func_name,
2369 				     &desc->func_model);
2370 	if (!err)
2371 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2372 		     kfunc_desc_cmp_by_id_off, NULL);
2373 	return err;
2374 }
2375 
2376 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2377 {
2378 	const struct bpf_kfunc_desc *d0 = a;
2379 	const struct bpf_kfunc_desc *d1 = b;
2380 
2381 	if (d0->imm > d1->imm)
2382 		return 1;
2383 	else if (d0->imm < d1->imm)
2384 		return -1;
2385 	return 0;
2386 }
2387 
2388 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2389 {
2390 	struct bpf_kfunc_desc_tab *tab;
2391 
2392 	tab = prog->aux->kfunc_tab;
2393 	if (!tab)
2394 		return;
2395 
2396 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2397 	     kfunc_desc_cmp_by_imm, NULL);
2398 }
2399 
2400 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2401 {
2402 	return !!prog->aux->kfunc_tab;
2403 }
2404 
2405 const struct btf_func_model *
2406 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2407 			 const struct bpf_insn *insn)
2408 {
2409 	const struct bpf_kfunc_desc desc = {
2410 		.imm = insn->imm,
2411 	};
2412 	const struct bpf_kfunc_desc *res;
2413 	struct bpf_kfunc_desc_tab *tab;
2414 
2415 	tab = prog->aux->kfunc_tab;
2416 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2417 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2418 
2419 	return res ? &res->func_model : NULL;
2420 }
2421 
2422 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2423 {
2424 	struct bpf_subprog_info *subprog = env->subprog_info;
2425 	struct bpf_insn *insn = env->prog->insnsi;
2426 	int i, ret, insn_cnt = env->prog->len;
2427 
2428 	/* Add entry function. */
2429 	ret = add_subprog(env, 0);
2430 	if (ret)
2431 		return ret;
2432 
2433 	for (i = 0; i < insn_cnt; i++, insn++) {
2434 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2435 		    !bpf_pseudo_kfunc_call(insn))
2436 			continue;
2437 
2438 		if (!env->bpf_capable) {
2439 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2440 			return -EPERM;
2441 		}
2442 
2443 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2444 			ret = add_subprog(env, i + insn->imm + 1);
2445 		else
2446 			ret = add_kfunc_call(env, insn->imm, insn->off);
2447 
2448 		if (ret < 0)
2449 			return ret;
2450 	}
2451 
2452 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2453 	 * logic. 'subprog_cnt' should not be increased.
2454 	 */
2455 	subprog[env->subprog_cnt].start = insn_cnt;
2456 
2457 	if (env->log.level & BPF_LOG_LEVEL2)
2458 		for (i = 0; i < env->subprog_cnt; i++)
2459 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2460 
2461 	return 0;
2462 }
2463 
2464 static int check_subprogs(struct bpf_verifier_env *env)
2465 {
2466 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2467 	struct bpf_subprog_info *subprog = env->subprog_info;
2468 	struct bpf_insn *insn = env->prog->insnsi;
2469 	int insn_cnt = env->prog->len;
2470 
2471 	/* now check that all jumps are within the same subprog */
2472 	subprog_start = subprog[cur_subprog].start;
2473 	subprog_end = subprog[cur_subprog + 1].start;
2474 	for (i = 0; i < insn_cnt; i++) {
2475 		u8 code = insn[i].code;
2476 
2477 		if (code == (BPF_JMP | BPF_CALL) &&
2478 		    insn[i].imm == BPF_FUNC_tail_call &&
2479 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2480 			subprog[cur_subprog].has_tail_call = true;
2481 		if (BPF_CLASS(code) == BPF_LD &&
2482 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2483 			subprog[cur_subprog].has_ld_abs = true;
2484 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2485 			goto next;
2486 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2487 			goto next;
2488 		off = i + insn[i].off + 1;
2489 		if (off < subprog_start || off >= subprog_end) {
2490 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2491 			return -EINVAL;
2492 		}
2493 next:
2494 		if (i == subprog_end - 1) {
2495 			/* to avoid fall-through from one subprog into another
2496 			 * the last insn of the subprog should be either exit
2497 			 * or unconditional jump back
2498 			 */
2499 			if (code != (BPF_JMP | BPF_EXIT) &&
2500 			    code != (BPF_JMP | BPF_JA)) {
2501 				verbose(env, "last insn is not an exit or jmp\n");
2502 				return -EINVAL;
2503 			}
2504 			subprog_start = subprog_end;
2505 			cur_subprog++;
2506 			if (cur_subprog < env->subprog_cnt)
2507 				subprog_end = subprog[cur_subprog + 1].start;
2508 		}
2509 	}
2510 	return 0;
2511 }
2512 
2513 /* Parentage chain of this register (or stack slot) should take care of all
2514  * issues like callee-saved registers, stack slot allocation time, etc.
2515  */
2516 static int mark_reg_read(struct bpf_verifier_env *env,
2517 			 const struct bpf_reg_state *state,
2518 			 struct bpf_reg_state *parent, u8 flag)
2519 {
2520 	bool writes = parent == state->parent; /* Observe write marks */
2521 	int cnt = 0;
2522 
2523 	while (parent) {
2524 		/* if read wasn't screened by an earlier write ... */
2525 		if (writes && state->live & REG_LIVE_WRITTEN)
2526 			break;
2527 		if (parent->live & REG_LIVE_DONE) {
2528 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2529 				reg_type_str(env, parent->type),
2530 				parent->var_off.value, parent->off);
2531 			return -EFAULT;
2532 		}
2533 		/* The first condition is more likely to be true than the
2534 		 * second, checked it first.
2535 		 */
2536 		if ((parent->live & REG_LIVE_READ) == flag ||
2537 		    parent->live & REG_LIVE_READ64)
2538 			/* The parentage chain never changes and
2539 			 * this parent was already marked as LIVE_READ.
2540 			 * There is no need to keep walking the chain again and
2541 			 * keep re-marking all parents as LIVE_READ.
2542 			 * This case happens when the same register is read
2543 			 * multiple times without writes into it in-between.
2544 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2545 			 * then no need to set the weak REG_LIVE_READ32.
2546 			 */
2547 			break;
2548 		/* ... then we depend on parent's value */
2549 		parent->live |= flag;
2550 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2551 		if (flag == REG_LIVE_READ64)
2552 			parent->live &= ~REG_LIVE_READ32;
2553 		state = parent;
2554 		parent = state->parent;
2555 		writes = true;
2556 		cnt++;
2557 	}
2558 
2559 	if (env->longest_mark_read_walk < cnt)
2560 		env->longest_mark_read_walk = cnt;
2561 	return 0;
2562 }
2563 
2564 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2565 {
2566 	struct bpf_func_state *state = func(env, reg);
2567 	int spi, ret;
2568 
2569 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2570 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2571 	 * check_kfunc_call.
2572 	 */
2573 	if (reg->type == CONST_PTR_TO_DYNPTR)
2574 		return 0;
2575 	spi = dynptr_get_spi(env, reg);
2576 	if (spi < 0)
2577 		return spi;
2578 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2579 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2580 	 * read.
2581 	 */
2582 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2583 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2584 	if (ret)
2585 		return ret;
2586 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2587 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2588 }
2589 
2590 /* This function is supposed to be used by the following 32-bit optimization
2591  * code only. It returns TRUE if the source or destination register operates
2592  * on 64-bit, otherwise return FALSE.
2593  */
2594 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2595 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2596 {
2597 	u8 code, class, op;
2598 
2599 	code = insn->code;
2600 	class = BPF_CLASS(code);
2601 	op = BPF_OP(code);
2602 	if (class == BPF_JMP) {
2603 		/* BPF_EXIT for "main" will reach here. Return TRUE
2604 		 * conservatively.
2605 		 */
2606 		if (op == BPF_EXIT)
2607 			return true;
2608 		if (op == BPF_CALL) {
2609 			/* BPF to BPF call will reach here because of marking
2610 			 * caller saved clobber with DST_OP_NO_MARK for which we
2611 			 * don't care the register def because they are anyway
2612 			 * marked as NOT_INIT already.
2613 			 */
2614 			if (insn->src_reg == BPF_PSEUDO_CALL)
2615 				return false;
2616 			/* Helper call will reach here because of arg type
2617 			 * check, conservatively return TRUE.
2618 			 */
2619 			if (t == SRC_OP)
2620 				return true;
2621 
2622 			return false;
2623 		}
2624 	}
2625 
2626 	if (class == BPF_ALU64 || class == BPF_JMP ||
2627 	    /* BPF_END always use BPF_ALU class. */
2628 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2629 		return true;
2630 
2631 	if (class == BPF_ALU || class == BPF_JMP32)
2632 		return false;
2633 
2634 	if (class == BPF_LDX) {
2635 		if (t != SRC_OP)
2636 			return BPF_SIZE(code) == BPF_DW;
2637 		/* LDX source must be ptr. */
2638 		return true;
2639 	}
2640 
2641 	if (class == BPF_STX) {
2642 		/* BPF_STX (including atomic variants) has multiple source
2643 		 * operands, one of which is a ptr. Check whether the caller is
2644 		 * asking about it.
2645 		 */
2646 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2647 			return true;
2648 		return BPF_SIZE(code) == BPF_DW;
2649 	}
2650 
2651 	if (class == BPF_LD) {
2652 		u8 mode = BPF_MODE(code);
2653 
2654 		/* LD_IMM64 */
2655 		if (mode == BPF_IMM)
2656 			return true;
2657 
2658 		/* Both LD_IND and LD_ABS return 32-bit data. */
2659 		if (t != SRC_OP)
2660 			return  false;
2661 
2662 		/* Implicit ctx ptr. */
2663 		if (regno == BPF_REG_6)
2664 			return true;
2665 
2666 		/* Explicit source could be any width. */
2667 		return true;
2668 	}
2669 
2670 	if (class == BPF_ST)
2671 		/* The only source register for BPF_ST is a ptr. */
2672 		return true;
2673 
2674 	/* Conservatively return true at default. */
2675 	return true;
2676 }
2677 
2678 /* Return the regno defined by the insn, or -1. */
2679 static int insn_def_regno(const struct bpf_insn *insn)
2680 {
2681 	switch (BPF_CLASS(insn->code)) {
2682 	case BPF_JMP:
2683 	case BPF_JMP32:
2684 	case BPF_ST:
2685 		return -1;
2686 	case BPF_STX:
2687 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2688 		    (insn->imm & BPF_FETCH)) {
2689 			if (insn->imm == BPF_CMPXCHG)
2690 				return BPF_REG_0;
2691 			else
2692 				return insn->src_reg;
2693 		} else {
2694 			return -1;
2695 		}
2696 	default:
2697 		return insn->dst_reg;
2698 	}
2699 }
2700 
2701 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2702 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2703 {
2704 	int dst_reg = insn_def_regno(insn);
2705 
2706 	if (dst_reg == -1)
2707 		return false;
2708 
2709 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2710 }
2711 
2712 static void mark_insn_zext(struct bpf_verifier_env *env,
2713 			   struct bpf_reg_state *reg)
2714 {
2715 	s32 def_idx = reg->subreg_def;
2716 
2717 	if (def_idx == DEF_NOT_SUBREG)
2718 		return;
2719 
2720 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2721 	/* The dst will be zero extended, so won't be sub-register anymore. */
2722 	reg->subreg_def = DEF_NOT_SUBREG;
2723 }
2724 
2725 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2726 			 enum reg_arg_type t)
2727 {
2728 	struct bpf_verifier_state *vstate = env->cur_state;
2729 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2730 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2731 	struct bpf_reg_state *reg, *regs = state->regs;
2732 	bool rw64;
2733 
2734 	if (regno >= MAX_BPF_REG) {
2735 		verbose(env, "R%d is invalid\n", regno);
2736 		return -EINVAL;
2737 	}
2738 
2739 	mark_reg_scratched(env, regno);
2740 
2741 	reg = &regs[regno];
2742 	rw64 = is_reg64(env, insn, regno, reg, t);
2743 	if (t == SRC_OP) {
2744 		/* check whether register used as source operand can be read */
2745 		if (reg->type == NOT_INIT) {
2746 			verbose(env, "R%d !read_ok\n", regno);
2747 			return -EACCES;
2748 		}
2749 		/* We don't need to worry about FP liveness because it's read-only */
2750 		if (regno == BPF_REG_FP)
2751 			return 0;
2752 
2753 		if (rw64)
2754 			mark_insn_zext(env, reg);
2755 
2756 		return mark_reg_read(env, reg, reg->parent,
2757 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2758 	} else {
2759 		/* check whether register used as dest operand can be written to */
2760 		if (regno == BPF_REG_FP) {
2761 			verbose(env, "frame pointer is read only\n");
2762 			return -EACCES;
2763 		}
2764 		reg->live |= REG_LIVE_WRITTEN;
2765 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2766 		if (t == DST_OP)
2767 			mark_reg_unknown(env, regs, regno);
2768 	}
2769 	return 0;
2770 }
2771 
2772 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2773 {
2774 	env->insn_aux_data[idx].jmp_point = true;
2775 }
2776 
2777 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2778 {
2779 	return env->insn_aux_data[insn_idx].jmp_point;
2780 }
2781 
2782 /* for any branch, call, exit record the history of jmps in the given state */
2783 static int push_jmp_history(struct bpf_verifier_env *env,
2784 			    struct bpf_verifier_state *cur)
2785 {
2786 	u32 cnt = cur->jmp_history_cnt;
2787 	struct bpf_idx_pair *p;
2788 	size_t alloc_size;
2789 
2790 	if (!is_jmp_point(env, env->insn_idx))
2791 		return 0;
2792 
2793 	cnt++;
2794 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2795 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2796 	if (!p)
2797 		return -ENOMEM;
2798 	p[cnt - 1].idx = env->insn_idx;
2799 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2800 	cur->jmp_history = p;
2801 	cur->jmp_history_cnt = cnt;
2802 	return 0;
2803 }
2804 
2805 /* Backtrack one insn at a time. If idx is not at the top of recorded
2806  * history then previous instruction came from straight line execution.
2807  */
2808 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2809 			     u32 *history)
2810 {
2811 	u32 cnt = *history;
2812 
2813 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2814 		i = st->jmp_history[cnt - 1].prev_idx;
2815 		(*history)--;
2816 	} else {
2817 		i--;
2818 	}
2819 	return i;
2820 }
2821 
2822 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2823 {
2824 	const struct btf_type *func;
2825 	struct btf *desc_btf;
2826 
2827 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2828 		return NULL;
2829 
2830 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2831 	if (IS_ERR(desc_btf))
2832 		return "<error>";
2833 
2834 	func = btf_type_by_id(desc_btf, insn->imm);
2835 	return btf_name_by_offset(desc_btf, func->name_off);
2836 }
2837 
2838 /* For given verifier state backtrack_insn() is called from the last insn to
2839  * the first insn. Its purpose is to compute a bitmask of registers and
2840  * stack slots that needs precision in the parent verifier state.
2841  */
2842 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2843 			  u32 *reg_mask, u64 *stack_mask)
2844 {
2845 	const struct bpf_insn_cbs cbs = {
2846 		.cb_call	= disasm_kfunc_name,
2847 		.cb_print	= verbose,
2848 		.private_data	= env,
2849 	};
2850 	struct bpf_insn *insn = env->prog->insnsi + idx;
2851 	u8 class = BPF_CLASS(insn->code);
2852 	u8 opcode = BPF_OP(insn->code);
2853 	u8 mode = BPF_MODE(insn->code);
2854 	u32 dreg = 1u << insn->dst_reg;
2855 	u32 sreg = 1u << insn->src_reg;
2856 	u32 spi;
2857 
2858 	if (insn->code == 0)
2859 		return 0;
2860 	if (env->log.level & BPF_LOG_LEVEL2) {
2861 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2862 		verbose(env, "%d: ", idx);
2863 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2864 	}
2865 
2866 	if (class == BPF_ALU || class == BPF_ALU64) {
2867 		if (!(*reg_mask & dreg))
2868 			return 0;
2869 		if (opcode == BPF_MOV) {
2870 			if (BPF_SRC(insn->code) == BPF_X) {
2871 				/* dreg = sreg
2872 				 * dreg needs precision after this insn
2873 				 * sreg needs precision before this insn
2874 				 */
2875 				*reg_mask &= ~dreg;
2876 				*reg_mask |= sreg;
2877 			} else {
2878 				/* dreg = K
2879 				 * dreg needs precision after this insn.
2880 				 * Corresponding register is already marked
2881 				 * as precise=true in this verifier state.
2882 				 * No further markings in parent are necessary
2883 				 */
2884 				*reg_mask &= ~dreg;
2885 			}
2886 		} else {
2887 			if (BPF_SRC(insn->code) == BPF_X) {
2888 				/* dreg += sreg
2889 				 * both dreg and sreg need precision
2890 				 * before this insn
2891 				 */
2892 				*reg_mask |= sreg;
2893 			} /* else dreg += K
2894 			   * dreg still needs precision before this insn
2895 			   */
2896 		}
2897 	} else if (class == BPF_LDX) {
2898 		if (!(*reg_mask & dreg))
2899 			return 0;
2900 		*reg_mask &= ~dreg;
2901 
2902 		/* scalars can only be spilled into stack w/o losing precision.
2903 		 * Load from any other memory can be zero extended.
2904 		 * The desire to keep that precision is already indicated
2905 		 * by 'precise' mark in corresponding register of this state.
2906 		 * No further tracking necessary.
2907 		 */
2908 		if (insn->src_reg != BPF_REG_FP)
2909 			return 0;
2910 
2911 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2912 		 * that [fp - off] slot contains scalar that needs to be
2913 		 * tracked with precision
2914 		 */
2915 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2916 		if (spi >= 64) {
2917 			verbose(env, "BUG spi %d\n", spi);
2918 			WARN_ONCE(1, "verifier backtracking bug");
2919 			return -EFAULT;
2920 		}
2921 		*stack_mask |= 1ull << spi;
2922 	} else if (class == BPF_STX || class == BPF_ST) {
2923 		if (*reg_mask & dreg)
2924 			/* stx & st shouldn't be using _scalar_ dst_reg
2925 			 * to access memory. It means backtracking
2926 			 * encountered a case of pointer subtraction.
2927 			 */
2928 			return -ENOTSUPP;
2929 		/* scalars can only be spilled into stack */
2930 		if (insn->dst_reg != BPF_REG_FP)
2931 			return 0;
2932 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2933 		if (spi >= 64) {
2934 			verbose(env, "BUG spi %d\n", spi);
2935 			WARN_ONCE(1, "verifier backtracking bug");
2936 			return -EFAULT;
2937 		}
2938 		if (!(*stack_mask & (1ull << spi)))
2939 			return 0;
2940 		*stack_mask &= ~(1ull << spi);
2941 		if (class == BPF_STX)
2942 			*reg_mask |= sreg;
2943 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2944 		if (opcode == BPF_CALL) {
2945 			if (insn->src_reg == BPF_PSEUDO_CALL)
2946 				return -ENOTSUPP;
2947 			/* BPF helpers that invoke callback subprogs are
2948 			 * equivalent to BPF_PSEUDO_CALL above
2949 			 */
2950 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2951 				return -ENOTSUPP;
2952 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2953 			 * catch this error later. Make backtracking conservative
2954 			 * with ENOTSUPP.
2955 			 */
2956 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2957 				return -ENOTSUPP;
2958 			/* regular helper call sets R0 */
2959 			*reg_mask &= ~1;
2960 			if (*reg_mask & 0x3f) {
2961 				/* if backtracing was looking for registers R1-R5
2962 				 * they should have been found already.
2963 				 */
2964 				verbose(env, "BUG regs %x\n", *reg_mask);
2965 				WARN_ONCE(1, "verifier backtracking bug");
2966 				return -EFAULT;
2967 			}
2968 		} else if (opcode == BPF_EXIT) {
2969 			return -ENOTSUPP;
2970 		}
2971 	} else if (class == BPF_LD) {
2972 		if (!(*reg_mask & dreg))
2973 			return 0;
2974 		*reg_mask &= ~dreg;
2975 		/* It's ld_imm64 or ld_abs or ld_ind.
2976 		 * For ld_imm64 no further tracking of precision
2977 		 * into parent is necessary
2978 		 */
2979 		if (mode == BPF_IND || mode == BPF_ABS)
2980 			/* to be analyzed */
2981 			return -ENOTSUPP;
2982 	}
2983 	return 0;
2984 }
2985 
2986 /* the scalar precision tracking algorithm:
2987  * . at the start all registers have precise=false.
2988  * . scalar ranges are tracked as normal through alu and jmp insns.
2989  * . once precise value of the scalar register is used in:
2990  *   .  ptr + scalar alu
2991  *   . if (scalar cond K|scalar)
2992  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2993  *   backtrack through the verifier states and mark all registers and
2994  *   stack slots with spilled constants that these scalar regisers
2995  *   should be precise.
2996  * . during state pruning two registers (or spilled stack slots)
2997  *   are equivalent if both are not precise.
2998  *
2999  * Note the verifier cannot simply walk register parentage chain,
3000  * since many different registers and stack slots could have been
3001  * used to compute single precise scalar.
3002  *
3003  * The approach of starting with precise=true for all registers and then
3004  * backtrack to mark a register as not precise when the verifier detects
3005  * that program doesn't care about specific value (e.g., when helper
3006  * takes register as ARG_ANYTHING parameter) is not safe.
3007  *
3008  * It's ok to walk single parentage chain of the verifier states.
3009  * It's possible that this backtracking will go all the way till 1st insn.
3010  * All other branches will be explored for needing precision later.
3011  *
3012  * The backtracking needs to deal with cases like:
3013  *   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)
3014  * r9 -= r8
3015  * r5 = r9
3016  * if r5 > 0x79f goto pc+7
3017  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3018  * r5 += 1
3019  * ...
3020  * call bpf_perf_event_output#25
3021  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3022  *
3023  * and this case:
3024  * r6 = 1
3025  * call foo // uses callee's r6 inside to compute r0
3026  * r0 += r6
3027  * if r0 == 0 goto
3028  *
3029  * to track above reg_mask/stack_mask needs to be independent for each frame.
3030  *
3031  * Also if parent's curframe > frame where backtracking started,
3032  * the verifier need to mark registers in both frames, otherwise callees
3033  * may incorrectly prune callers. This is similar to
3034  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3035  *
3036  * For now backtracking falls back into conservative marking.
3037  */
3038 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3039 				     struct bpf_verifier_state *st)
3040 {
3041 	struct bpf_func_state *func;
3042 	struct bpf_reg_state *reg;
3043 	int i, j;
3044 
3045 	/* big hammer: mark all scalars precise in this path.
3046 	 * pop_stack may still get !precise scalars.
3047 	 * We also skip current state and go straight to first parent state,
3048 	 * because precision markings in current non-checkpointed state are
3049 	 * not needed. See why in the comment in __mark_chain_precision below.
3050 	 */
3051 	for (st = st->parent; st; st = st->parent) {
3052 		for (i = 0; i <= st->curframe; i++) {
3053 			func = st->frame[i];
3054 			for (j = 0; j < BPF_REG_FP; j++) {
3055 				reg = &func->regs[j];
3056 				if (reg->type != SCALAR_VALUE)
3057 					continue;
3058 				reg->precise = true;
3059 			}
3060 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3061 				if (!is_spilled_reg(&func->stack[j]))
3062 					continue;
3063 				reg = &func->stack[j].spilled_ptr;
3064 				if (reg->type != SCALAR_VALUE)
3065 					continue;
3066 				reg->precise = true;
3067 			}
3068 		}
3069 	}
3070 }
3071 
3072 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3073 {
3074 	struct bpf_func_state *func;
3075 	struct bpf_reg_state *reg;
3076 	int i, j;
3077 
3078 	for (i = 0; i <= st->curframe; i++) {
3079 		func = st->frame[i];
3080 		for (j = 0; j < BPF_REG_FP; j++) {
3081 			reg = &func->regs[j];
3082 			if (reg->type != SCALAR_VALUE)
3083 				continue;
3084 			reg->precise = false;
3085 		}
3086 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3087 			if (!is_spilled_reg(&func->stack[j]))
3088 				continue;
3089 			reg = &func->stack[j].spilled_ptr;
3090 			if (reg->type != SCALAR_VALUE)
3091 				continue;
3092 			reg->precise = false;
3093 		}
3094 	}
3095 }
3096 
3097 /*
3098  * __mark_chain_precision() backtracks BPF program instruction sequence and
3099  * chain of verifier states making sure that register *regno* (if regno >= 0)
3100  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3101  * SCALARS, as well as any other registers and slots that contribute to
3102  * a tracked state of given registers/stack slots, depending on specific BPF
3103  * assembly instructions (see backtrack_insns() for exact instruction handling
3104  * logic). This backtracking relies on recorded jmp_history and is able to
3105  * traverse entire chain of parent states. This process ends only when all the
3106  * necessary registers/slots and their transitive dependencies are marked as
3107  * precise.
3108  *
3109  * One important and subtle aspect is that precise marks *do not matter* in
3110  * the currently verified state (current state). It is important to understand
3111  * why this is the case.
3112  *
3113  * First, note that current state is the state that is not yet "checkpointed",
3114  * i.e., it is not yet put into env->explored_states, and it has no children
3115  * states as well. It's ephemeral, and can end up either a) being discarded if
3116  * compatible explored state is found at some point or BPF_EXIT instruction is
3117  * reached or b) checkpointed and put into env->explored_states, branching out
3118  * into one or more children states.
3119  *
3120  * In the former case, precise markings in current state are completely
3121  * ignored by state comparison code (see regsafe() for details). Only
3122  * checkpointed ("old") state precise markings are important, and if old
3123  * state's register/slot is precise, regsafe() assumes current state's
3124  * register/slot as precise and checks value ranges exactly and precisely. If
3125  * states turn out to be compatible, current state's necessary precise
3126  * markings and any required parent states' precise markings are enforced
3127  * after the fact with propagate_precision() logic, after the fact. But it's
3128  * important to realize that in this case, even after marking current state
3129  * registers/slots as precise, we immediately discard current state. So what
3130  * actually matters is any of the precise markings propagated into current
3131  * state's parent states, which are always checkpointed (due to b) case above).
3132  * As such, for scenario a) it doesn't matter if current state has precise
3133  * markings set or not.
3134  *
3135  * Now, for the scenario b), checkpointing and forking into child(ren)
3136  * state(s). Note that before current state gets to checkpointing step, any
3137  * processed instruction always assumes precise SCALAR register/slot
3138  * knowledge: if precise value or range is useful to prune jump branch, BPF
3139  * verifier takes this opportunity enthusiastically. Similarly, when
3140  * register's value is used to calculate offset or memory address, exact
3141  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3142  * what we mentioned above about state comparison ignoring precise markings
3143  * during state comparison, BPF verifier ignores and also assumes precise
3144  * markings *at will* during instruction verification process. But as verifier
3145  * assumes precision, it also propagates any precision dependencies across
3146  * parent states, which are not yet finalized, so can be further restricted
3147  * based on new knowledge gained from restrictions enforced by their children
3148  * states. This is so that once those parent states are finalized, i.e., when
3149  * they have no more active children state, state comparison logic in
3150  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3151  * required for correctness.
3152  *
3153  * To build a bit more intuition, note also that once a state is checkpointed,
3154  * the path we took to get to that state is not important. This is crucial
3155  * property for state pruning. When state is checkpointed and finalized at
3156  * some instruction index, it can be correctly and safely used to "short
3157  * circuit" any *compatible* state that reaches exactly the same instruction
3158  * index. I.e., if we jumped to that instruction from a completely different
3159  * code path than original finalized state was derived from, it doesn't
3160  * matter, current state can be discarded because from that instruction
3161  * forward having a compatible state will ensure we will safely reach the
3162  * exit. States describe preconditions for further exploration, but completely
3163  * forget the history of how we got here.
3164  *
3165  * This also means that even if we needed precise SCALAR range to get to
3166  * finalized state, but from that point forward *that same* SCALAR register is
3167  * never used in a precise context (i.e., it's precise value is not needed for
3168  * correctness), it's correct and safe to mark such register as "imprecise"
3169  * (i.e., precise marking set to false). This is what we rely on when we do
3170  * not set precise marking in current state. If no child state requires
3171  * precision for any given SCALAR register, it's safe to dictate that it can
3172  * be imprecise. If any child state does require this register to be precise,
3173  * we'll mark it precise later retroactively during precise markings
3174  * propagation from child state to parent states.
3175  *
3176  * Skipping precise marking setting in current state is a mild version of
3177  * relying on the above observation. But we can utilize this property even
3178  * more aggressively by proactively forgetting any precise marking in the
3179  * current state (which we inherited from the parent state), right before we
3180  * checkpoint it and branch off into new child state. This is done by
3181  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3182  * finalized states which help in short circuiting more future states.
3183  */
3184 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3185 				  int spi)
3186 {
3187 	struct bpf_verifier_state *st = env->cur_state;
3188 	int first_idx = st->first_insn_idx;
3189 	int last_idx = env->insn_idx;
3190 	struct bpf_func_state *func;
3191 	struct bpf_reg_state *reg;
3192 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3193 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3194 	bool skip_first = true;
3195 	bool new_marks = false;
3196 	int i, err;
3197 
3198 	if (!env->bpf_capable)
3199 		return 0;
3200 
3201 	/* Do sanity checks against current state of register and/or stack
3202 	 * slot, but don't set precise flag in current state, as precision
3203 	 * tracking in the current state is unnecessary.
3204 	 */
3205 	func = st->frame[frame];
3206 	if (regno >= 0) {
3207 		reg = &func->regs[regno];
3208 		if (reg->type != SCALAR_VALUE) {
3209 			WARN_ONCE(1, "backtracing misuse");
3210 			return -EFAULT;
3211 		}
3212 		new_marks = true;
3213 	}
3214 
3215 	while (spi >= 0) {
3216 		if (!is_spilled_reg(&func->stack[spi])) {
3217 			stack_mask = 0;
3218 			break;
3219 		}
3220 		reg = &func->stack[spi].spilled_ptr;
3221 		if (reg->type != SCALAR_VALUE) {
3222 			stack_mask = 0;
3223 			break;
3224 		}
3225 		new_marks = true;
3226 		break;
3227 	}
3228 
3229 	if (!new_marks)
3230 		return 0;
3231 	if (!reg_mask && !stack_mask)
3232 		return 0;
3233 
3234 	for (;;) {
3235 		DECLARE_BITMAP(mask, 64);
3236 		u32 history = st->jmp_history_cnt;
3237 
3238 		if (env->log.level & BPF_LOG_LEVEL2)
3239 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3240 
3241 		if (last_idx < 0) {
3242 			/* we are at the entry into subprog, which
3243 			 * is expected for global funcs, but only if
3244 			 * requested precise registers are R1-R5
3245 			 * (which are global func's input arguments)
3246 			 */
3247 			if (st->curframe == 0 &&
3248 			    st->frame[0]->subprogno > 0 &&
3249 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3250 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3251 				bitmap_from_u64(mask, reg_mask);
3252 				for_each_set_bit(i, mask, 32) {
3253 					reg = &st->frame[0]->regs[i];
3254 					if (reg->type != SCALAR_VALUE) {
3255 						reg_mask &= ~(1u << i);
3256 						continue;
3257 					}
3258 					reg->precise = true;
3259 				}
3260 				return 0;
3261 			}
3262 
3263 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3264 				st->frame[0]->subprogno, reg_mask, stack_mask);
3265 			WARN_ONCE(1, "verifier backtracking bug");
3266 			return -EFAULT;
3267 		}
3268 
3269 		for (i = last_idx;;) {
3270 			if (skip_first) {
3271 				err = 0;
3272 				skip_first = false;
3273 			} else {
3274 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3275 			}
3276 			if (err == -ENOTSUPP) {
3277 				mark_all_scalars_precise(env, st);
3278 				return 0;
3279 			} else if (err) {
3280 				return err;
3281 			}
3282 			if (!reg_mask && !stack_mask)
3283 				/* Found assignment(s) into tracked register in this state.
3284 				 * Since this state is already marked, just return.
3285 				 * Nothing to be tracked further in the parent state.
3286 				 */
3287 				return 0;
3288 			if (i == first_idx)
3289 				break;
3290 			i = get_prev_insn_idx(st, i, &history);
3291 			if (i >= env->prog->len) {
3292 				/* This can happen if backtracking reached insn 0
3293 				 * and there are still reg_mask or stack_mask
3294 				 * to backtrack.
3295 				 * It means the backtracking missed the spot where
3296 				 * particular register was initialized with a constant.
3297 				 */
3298 				verbose(env, "BUG backtracking idx %d\n", i);
3299 				WARN_ONCE(1, "verifier backtracking bug");
3300 				return -EFAULT;
3301 			}
3302 		}
3303 		st = st->parent;
3304 		if (!st)
3305 			break;
3306 
3307 		new_marks = false;
3308 		func = st->frame[frame];
3309 		bitmap_from_u64(mask, reg_mask);
3310 		for_each_set_bit(i, mask, 32) {
3311 			reg = &func->regs[i];
3312 			if (reg->type != SCALAR_VALUE) {
3313 				reg_mask &= ~(1u << i);
3314 				continue;
3315 			}
3316 			if (!reg->precise)
3317 				new_marks = true;
3318 			reg->precise = true;
3319 		}
3320 
3321 		bitmap_from_u64(mask, stack_mask);
3322 		for_each_set_bit(i, mask, 64) {
3323 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3324 				/* the sequence of instructions:
3325 				 * 2: (bf) r3 = r10
3326 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3327 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3328 				 * doesn't contain jmps. It's backtracked
3329 				 * as a single block.
3330 				 * During backtracking insn 3 is not recognized as
3331 				 * stack access, so at the end of backtracking
3332 				 * stack slot fp-8 is still marked in stack_mask.
3333 				 * However the parent state may not have accessed
3334 				 * fp-8 and it's "unallocated" stack space.
3335 				 * In such case fallback to conservative.
3336 				 */
3337 				mark_all_scalars_precise(env, st);
3338 				return 0;
3339 			}
3340 
3341 			if (!is_spilled_reg(&func->stack[i])) {
3342 				stack_mask &= ~(1ull << i);
3343 				continue;
3344 			}
3345 			reg = &func->stack[i].spilled_ptr;
3346 			if (reg->type != SCALAR_VALUE) {
3347 				stack_mask &= ~(1ull << i);
3348 				continue;
3349 			}
3350 			if (!reg->precise)
3351 				new_marks = true;
3352 			reg->precise = true;
3353 		}
3354 		if (env->log.level & BPF_LOG_LEVEL2) {
3355 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3356 				new_marks ? "didn't have" : "already had",
3357 				reg_mask, stack_mask);
3358 			print_verifier_state(env, func, true);
3359 		}
3360 
3361 		if (!reg_mask && !stack_mask)
3362 			break;
3363 		if (!new_marks)
3364 			break;
3365 
3366 		last_idx = st->last_insn_idx;
3367 		first_idx = st->first_insn_idx;
3368 	}
3369 	return 0;
3370 }
3371 
3372 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3373 {
3374 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3375 }
3376 
3377 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3378 {
3379 	return __mark_chain_precision(env, frame, regno, -1);
3380 }
3381 
3382 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3383 {
3384 	return __mark_chain_precision(env, frame, -1, spi);
3385 }
3386 
3387 static bool is_spillable_regtype(enum bpf_reg_type type)
3388 {
3389 	switch (base_type(type)) {
3390 	case PTR_TO_MAP_VALUE:
3391 	case PTR_TO_STACK:
3392 	case PTR_TO_CTX:
3393 	case PTR_TO_PACKET:
3394 	case PTR_TO_PACKET_META:
3395 	case PTR_TO_PACKET_END:
3396 	case PTR_TO_FLOW_KEYS:
3397 	case CONST_PTR_TO_MAP:
3398 	case PTR_TO_SOCKET:
3399 	case PTR_TO_SOCK_COMMON:
3400 	case PTR_TO_TCP_SOCK:
3401 	case PTR_TO_XDP_SOCK:
3402 	case PTR_TO_BTF_ID:
3403 	case PTR_TO_BUF:
3404 	case PTR_TO_MEM:
3405 	case PTR_TO_FUNC:
3406 	case PTR_TO_MAP_KEY:
3407 		return true;
3408 	default:
3409 		return false;
3410 	}
3411 }
3412 
3413 /* Does this register contain a constant zero? */
3414 static bool register_is_null(struct bpf_reg_state *reg)
3415 {
3416 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3417 }
3418 
3419 static bool register_is_const(struct bpf_reg_state *reg)
3420 {
3421 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3422 }
3423 
3424 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3425 {
3426 	return tnum_is_unknown(reg->var_off) &&
3427 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3428 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3429 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3430 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3431 }
3432 
3433 static bool register_is_bounded(struct bpf_reg_state *reg)
3434 {
3435 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3436 }
3437 
3438 static bool __is_pointer_value(bool allow_ptr_leaks,
3439 			       const struct bpf_reg_state *reg)
3440 {
3441 	if (allow_ptr_leaks)
3442 		return false;
3443 
3444 	return reg->type != SCALAR_VALUE;
3445 }
3446 
3447 /* Copy src state preserving dst->parent and dst->live fields */
3448 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3449 {
3450 	struct bpf_reg_state *parent = dst->parent;
3451 	enum bpf_reg_liveness live = dst->live;
3452 
3453 	*dst = *src;
3454 	dst->parent = parent;
3455 	dst->live = live;
3456 }
3457 
3458 static void save_register_state(struct bpf_func_state *state,
3459 				int spi, struct bpf_reg_state *reg,
3460 				int size)
3461 {
3462 	int i;
3463 
3464 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
3465 	if (size == BPF_REG_SIZE)
3466 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3467 
3468 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3469 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3470 
3471 	/* size < 8 bytes spill */
3472 	for (; i; i--)
3473 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3474 }
3475 
3476 static bool is_bpf_st_mem(struct bpf_insn *insn)
3477 {
3478 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3479 }
3480 
3481 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3482  * stack boundary and alignment are checked in check_mem_access()
3483  */
3484 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3485 				       /* stack frame we're writing to */
3486 				       struct bpf_func_state *state,
3487 				       int off, int size, int value_regno,
3488 				       int insn_idx)
3489 {
3490 	struct bpf_func_state *cur; /* state of the current function */
3491 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3492 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3493 	struct bpf_reg_state *reg = NULL;
3494 	u32 dst_reg = insn->dst_reg;
3495 
3496 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3497 	if (err)
3498 		return err;
3499 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3500 	 * so it's aligned access and [off, off + size) are within stack limits
3501 	 */
3502 	if (!env->allow_ptr_leaks &&
3503 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3504 	    size != BPF_REG_SIZE) {
3505 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3506 		return -EACCES;
3507 	}
3508 
3509 	cur = env->cur_state->frame[env->cur_state->curframe];
3510 	if (value_regno >= 0)
3511 		reg = &cur->regs[value_regno];
3512 	if (!env->bypass_spec_v4) {
3513 		bool sanitize = reg && is_spillable_regtype(reg->type);
3514 
3515 		for (i = 0; i < size; i++) {
3516 			u8 type = state->stack[spi].slot_type[i];
3517 
3518 			if (type != STACK_MISC && type != STACK_ZERO) {
3519 				sanitize = true;
3520 				break;
3521 			}
3522 		}
3523 
3524 		if (sanitize)
3525 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3526 	}
3527 
3528 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3529 	if (err)
3530 		return err;
3531 
3532 	mark_stack_slot_scratched(env, spi);
3533 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3534 	    !register_is_null(reg) && env->bpf_capable) {
3535 		if (dst_reg != BPF_REG_FP) {
3536 			/* The backtracking logic can only recognize explicit
3537 			 * stack slot address like [fp - 8]. Other spill of
3538 			 * scalar via different register has to be conservative.
3539 			 * Backtrack from here and mark all registers as precise
3540 			 * that contributed into 'reg' being a constant.
3541 			 */
3542 			err = mark_chain_precision(env, value_regno);
3543 			if (err)
3544 				return err;
3545 		}
3546 		save_register_state(state, spi, reg, size);
3547 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3548 		   insn->imm != 0 && env->bpf_capable) {
3549 		struct bpf_reg_state fake_reg = {};
3550 
3551 		__mark_reg_known(&fake_reg, (u32)insn->imm);
3552 		fake_reg.type = SCALAR_VALUE;
3553 		save_register_state(state, spi, &fake_reg, size);
3554 	} else if (reg && is_spillable_regtype(reg->type)) {
3555 		/* register containing pointer is being spilled into stack */
3556 		if (size != BPF_REG_SIZE) {
3557 			verbose_linfo(env, insn_idx, "; ");
3558 			verbose(env, "invalid size of register spill\n");
3559 			return -EACCES;
3560 		}
3561 		if (state != cur && reg->type == PTR_TO_STACK) {
3562 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3563 			return -EINVAL;
3564 		}
3565 		save_register_state(state, spi, reg, size);
3566 	} else {
3567 		u8 type = STACK_MISC;
3568 
3569 		/* regular write of data into stack destroys any spilled ptr */
3570 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3571 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3572 		if (is_spilled_reg(&state->stack[spi]))
3573 			for (i = 0; i < BPF_REG_SIZE; i++)
3574 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3575 
3576 		/* only mark the slot as written if all 8 bytes were written
3577 		 * otherwise read propagation may incorrectly stop too soon
3578 		 * when stack slots are partially written.
3579 		 * This heuristic means that read propagation will be
3580 		 * conservative, since it will add reg_live_read marks
3581 		 * to stack slots all the way to first state when programs
3582 		 * writes+reads less than 8 bytes
3583 		 */
3584 		if (size == BPF_REG_SIZE)
3585 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3586 
3587 		/* when we zero initialize stack slots mark them as such */
3588 		if ((reg && register_is_null(reg)) ||
3589 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3590 			/* backtracking doesn't work for STACK_ZERO yet. */
3591 			err = mark_chain_precision(env, value_regno);
3592 			if (err)
3593 				return err;
3594 			type = STACK_ZERO;
3595 		}
3596 
3597 		/* Mark slots affected by this stack write. */
3598 		for (i = 0; i < size; i++)
3599 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3600 				type;
3601 	}
3602 	return 0;
3603 }
3604 
3605 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3606  * known to contain a variable offset.
3607  * This function checks whether the write is permitted and conservatively
3608  * tracks the effects of the write, considering that each stack slot in the
3609  * dynamic range is potentially written to.
3610  *
3611  * 'off' includes 'regno->off'.
3612  * 'value_regno' can be -1, meaning that an unknown value is being written to
3613  * the stack.
3614  *
3615  * Spilled pointers in range are not marked as written because we don't know
3616  * what's going to be actually written. This means that read propagation for
3617  * future reads cannot be terminated by this write.
3618  *
3619  * For privileged programs, uninitialized stack slots are considered
3620  * initialized by this write (even though we don't know exactly what offsets
3621  * are going to be written to). The idea is that we don't want the verifier to
3622  * reject future reads that access slots written to through variable offsets.
3623  */
3624 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3625 				     /* func where register points to */
3626 				     struct bpf_func_state *state,
3627 				     int ptr_regno, int off, int size,
3628 				     int value_regno, int insn_idx)
3629 {
3630 	struct bpf_func_state *cur; /* state of the current function */
3631 	int min_off, max_off;
3632 	int i, err;
3633 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3634 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3635 	bool writing_zero = false;
3636 	/* set if the fact that we're writing a zero is used to let any
3637 	 * stack slots remain STACK_ZERO
3638 	 */
3639 	bool zero_used = false;
3640 
3641 	cur = env->cur_state->frame[env->cur_state->curframe];
3642 	ptr_reg = &cur->regs[ptr_regno];
3643 	min_off = ptr_reg->smin_value + off;
3644 	max_off = ptr_reg->smax_value + off + size;
3645 	if (value_regno >= 0)
3646 		value_reg = &cur->regs[value_regno];
3647 	if ((value_reg && register_is_null(value_reg)) ||
3648 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3649 		writing_zero = true;
3650 
3651 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3652 	if (err)
3653 		return err;
3654 
3655 	for (i = min_off; i < max_off; i++) {
3656 		int spi;
3657 
3658 		spi = __get_spi(i);
3659 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3660 		if (err)
3661 			return err;
3662 	}
3663 
3664 	/* Variable offset writes destroy any spilled pointers in range. */
3665 	for (i = min_off; i < max_off; i++) {
3666 		u8 new_type, *stype;
3667 		int slot, spi;
3668 
3669 		slot = -i - 1;
3670 		spi = slot / BPF_REG_SIZE;
3671 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3672 		mark_stack_slot_scratched(env, spi);
3673 
3674 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3675 			/* Reject the write if range we may write to has not
3676 			 * been initialized beforehand. If we didn't reject
3677 			 * here, the ptr status would be erased below (even
3678 			 * though not all slots are actually overwritten),
3679 			 * possibly opening the door to leaks.
3680 			 *
3681 			 * We do however catch STACK_INVALID case below, and
3682 			 * only allow reading possibly uninitialized memory
3683 			 * later for CAP_PERFMON, as the write may not happen to
3684 			 * that slot.
3685 			 */
3686 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3687 				insn_idx, i);
3688 			return -EINVAL;
3689 		}
3690 
3691 		/* Erase all spilled pointers. */
3692 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3693 
3694 		/* Update the slot type. */
3695 		new_type = STACK_MISC;
3696 		if (writing_zero && *stype == STACK_ZERO) {
3697 			new_type = STACK_ZERO;
3698 			zero_used = true;
3699 		}
3700 		/* If the slot is STACK_INVALID, we check whether it's OK to
3701 		 * pretend that it will be initialized by this write. The slot
3702 		 * might not actually be written to, and so if we mark it as
3703 		 * initialized future reads might leak uninitialized memory.
3704 		 * For privileged programs, we will accept such reads to slots
3705 		 * that may or may not be written because, if we're reject
3706 		 * them, the error would be too confusing.
3707 		 */
3708 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3709 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3710 					insn_idx, i);
3711 			return -EINVAL;
3712 		}
3713 		*stype = new_type;
3714 	}
3715 	if (zero_used) {
3716 		/* backtracking doesn't work for STACK_ZERO yet. */
3717 		err = mark_chain_precision(env, value_regno);
3718 		if (err)
3719 			return err;
3720 	}
3721 	return 0;
3722 }
3723 
3724 /* When register 'dst_regno' is assigned some values from stack[min_off,
3725  * max_off), we set the register's type according to the types of the
3726  * respective stack slots. If all the stack values are known to be zeros, then
3727  * so is the destination reg. Otherwise, the register is considered to be
3728  * SCALAR. This function does not deal with register filling; the caller must
3729  * ensure that all spilled registers in the stack range have been marked as
3730  * read.
3731  */
3732 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3733 				/* func where src register points to */
3734 				struct bpf_func_state *ptr_state,
3735 				int min_off, int max_off, int dst_regno)
3736 {
3737 	struct bpf_verifier_state *vstate = env->cur_state;
3738 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3739 	int i, slot, spi;
3740 	u8 *stype;
3741 	int zeros = 0;
3742 
3743 	for (i = min_off; i < max_off; i++) {
3744 		slot = -i - 1;
3745 		spi = slot / BPF_REG_SIZE;
3746 		stype = ptr_state->stack[spi].slot_type;
3747 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3748 			break;
3749 		zeros++;
3750 	}
3751 	if (zeros == max_off - min_off) {
3752 		/* any access_size read into register is zero extended,
3753 		 * so the whole register == const_zero
3754 		 */
3755 		__mark_reg_const_zero(&state->regs[dst_regno]);
3756 		/* backtracking doesn't support STACK_ZERO yet,
3757 		 * so mark it precise here, so that later
3758 		 * backtracking can stop here.
3759 		 * Backtracking may not need this if this register
3760 		 * doesn't participate in pointer adjustment.
3761 		 * Forward propagation of precise flag is not
3762 		 * necessary either. This mark is only to stop
3763 		 * backtracking. Any register that contributed
3764 		 * to const 0 was marked precise before spill.
3765 		 */
3766 		state->regs[dst_regno].precise = true;
3767 	} else {
3768 		/* have read misc data from the stack */
3769 		mark_reg_unknown(env, state->regs, dst_regno);
3770 	}
3771 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3772 }
3773 
3774 /* Read the stack at 'off' and put the results into the register indicated by
3775  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3776  * spilled reg.
3777  *
3778  * 'dst_regno' can be -1, meaning that the read value is not going to a
3779  * register.
3780  *
3781  * The access is assumed to be within the current stack bounds.
3782  */
3783 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3784 				      /* func where src register points to */
3785 				      struct bpf_func_state *reg_state,
3786 				      int off, int size, int dst_regno)
3787 {
3788 	struct bpf_verifier_state *vstate = env->cur_state;
3789 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3790 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3791 	struct bpf_reg_state *reg;
3792 	u8 *stype, type;
3793 
3794 	stype = reg_state->stack[spi].slot_type;
3795 	reg = &reg_state->stack[spi].spilled_ptr;
3796 
3797 	if (is_spilled_reg(&reg_state->stack[spi])) {
3798 		u8 spill_size = 1;
3799 
3800 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3801 			spill_size++;
3802 
3803 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3804 			if (reg->type != SCALAR_VALUE) {
3805 				verbose_linfo(env, env->insn_idx, "; ");
3806 				verbose(env, "invalid size of register fill\n");
3807 				return -EACCES;
3808 			}
3809 
3810 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3811 			if (dst_regno < 0)
3812 				return 0;
3813 
3814 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3815 				/* The earlier check_reg_arg() has decided the
3816 				 * subreg_def for this insn.  Save it first.
3817 				 */
3818 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3819 
3820 				copy_register_state(&state->regs[dst_regno], reg);
3821 				state->regs[dst_regno].subreg_def = subreg_def;
3822 			} else {
3823 				for (i = 0; i < size; i++) {
3824 					type = stype[(slot - i) % BPF_REG_SIZE];
3825 					if (type == STACK_SPILL)
3826 						continue;
3827 					if (type == STACK_MISC)
3828 						continue;
3829 					if (type == STACK_INVALID && env->allow_uninit_stack)
3830 						continue;
3831 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3832 						off, i, size);
3833 					return -EACCES;
3834 				}
3835 				mark_reg_unknown(env, state->regs, dst_regno);
3836 			}
3837 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3838 			return 0;
3839 		}
3840 
3841 		if (dst_regno >= 0) {
3842 			/* restore register state from stack */
3843 			copy_register_state(&state->regs[dst_regno], reg);
3844 			/* mark reg as written since spilled pointer state likely
3845 			 * has its liveness marks cleared by is_state_visited()
3846 			 * which resets stack/reg liveness for state transitions
3847 			 */
3848 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3849 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3850 			/* If dst_regno==-1, the caller is asking us whether
3851 			 * it is acceptable to use this value as a SCALAR_VALUE
3852 			 * (e.g. for XADD).
3853 			 * We must not allow unprivileged callers to do that
3854 			 * with spilled pointers.
3855 			 */
3856 			verbose(env, "leaking pointer from stack off %d\n",
3857 				off);
3858 			return -EACCES;
3859 		}
3860 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3861 	} else {
3862 		for (i = 0; i < size; i++) {
3863 			type = stype[(slot - i) % BPF_REG_SIZE];
3864 			if (type == STACK_MISC)
3865 				continue;
3866 			if (type == STACK_ZERO)
3867 				continue;
3868 			if (type == STACK_INVALID && env->allow_uninit_stack)
3869 				continue;
3870 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3871 				off, i, size);
3872 			return -EACCES;
3873 		}
3874 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3875 		if (dst_regno >= 0)
3876 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3877 	}
3878 	return 0;
3879 }
3880 
3881 enum bpf_access_src {
3882 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3883 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3884 };
3885 
3886 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3887 					 int regno, int off, int access_size,
3888 					 bool zero_size_allowed,
3889 					 enum bpf_access_src type,
3890 					 struct bpf_call_arg_meta *meta);
3891 
3892 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3893 {
3894 	return cur_regs(env) + regno;
3895 }
3896 
3897 /* Read the stack at 'ptr_regno + off' and put the result into the register
3898  * 'dst_regno'.
3899  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3900  * but not its variable offset.
3901  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3902  *
3903  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3904  * filling registers (i.e. reads of spilled register cannot be detected when
3905  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3906  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3907  * offset; for a fixed offset check_stack_read_fixed_off should be used
3908  * instead.
3909  */
3910 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3911 				    int ptr_regno, int off, int size, int dst_regno)
3912 {
3913 	/* The state of the source register. */
3914 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3915 	struct bpf_func_state *ptr_state = func(env, reg);
3916 	int err;
3917 	int min_off, max_off;
3918 
3919 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3920 	 */
3921 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3922 					    false, ACCESS_DIRECT, NULL);
3923 	if (err)
3924 		return err;
3925 
3926 	min_off = reg->smin_value + off;
3927 	max_off = reg->smax_value + off;
3928 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3929 	return 0;
3930 }
3931 
3932 /* check_stack_read dispatches to check_stack_read_fixed_off or
3933  * check_stack_read_var_off.
3934  *
3935  * The caller must ensure that the offset falls within the allocated stack
3936  * bounds.
3937  *
3938  * 'dst_regno' is a register which will receive the value from the stack. It
3939  * can be -1, meaning that the read value is not going to a register.
3940  */
3941 static int check_stack_read(struct bpf_verifier_env *env,
3942 			    int ptr_regno, int off, int size,
3943 			    int dst_regno)
3944 {
3945 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3946 	struct bpf_func_state *state = func(env, reg);
3947 	int err;
3948 	/* Some accesses are only permitted with a static offset. */
3949 	bool var_off = !tnum_is_const(reg->var_off);
3950 
3951 	/* The offset is required to be static when reads don't go to a
3952 	 * register, in order to not leak pointers (see
3953 	 * check_stack_read_fixed_off).
3954 	 */
3955 	if (dst_regno < 0 && var_off) {
3956 		char tn_buf[48];
3957 
3958 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3959 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3960 			tn_buf, off, size);
3961 		return -EACCES;
3962 	}
3963 	/* Variable offset is prohibited for unprivileged mode for simplicity
3964 	 * since it requires corresponding support in Spectre masking for stack
3965 	 * ALU. See also retrieve_ptr_limit().
3966 	 */
3967 	if (!env->bypass_spec_v1 && var_off) {
3968 		char tn_buf[48];
3969 
3970 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3971 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3972 				ptr_regno, tn_buf);
3973 		return -EACCES;
3974 	}
3975 
3976 	if (!var_off) {
3977 		off += reg->var_off.value;
3978 		err = check_stack_read_fixed_off(env, state, off, size,
3979 						 dst_regno);
3980 	} else {
3981 		/* Variable offset stack reads need more conservative handling
3982 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3983 		 * branch.
3984 		 */
3985 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3986 					       dst_regno);
3987 	}
3988 	return err;
3989 }
3990 
3991 
3992 /* check_stack_write dispatches to check_stack_write_fixed_off or
3993  * check_stack_write_var_off.
3994  *
3995  * 'ptr_regno' is the register used as a pointer into the stack.
3996  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3997  * 'value_regno' is the register whose value we're writing to the stack. It can
3998  * be -1, meaning that we're not writing from a register.
3999  *
4000  * The caller must ensure that the offset falls within the maximum stack size.
4001  */
4002 static int check_stack_write(struct bpf_verifier_env *env,
4003 			     int ptr_regno, int off, int size,
4004 			     int value_regno, int insn_idx)
4005 {
4006 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4007 	struct bpf_func_state *state = func(env, reg);
4008 	int err;
4009 
4010 	if (tnum_is_const(reg->var_off)) {
4011 		off += reg->var_off.value;
4012 		err = check_stack_write_fixed_off(env, state, off, size,
4013 						  value_regno, insn_idx);
4014 	} else {
4015 		/* Variable offset stack reads need more conservative handling
4016 		 * than fixed offset ones.
4017 		 */
4018 		err = check_stack_write_var_off(env, state,
4019 						ptr_regno, off, size,
4020 						value_regno, insn_idx);
4021 	}
4022 	return err;
4023 }
4024 
4025 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4026 				 int off, int size, enum bpf_access_type type)
4027 {
4028 	struct bpf_reg_state *regs = cur_regs(env);
4029 	struct bpf_map *map = regs[regno].map_ptr;
4030 	u32 cap = bpf_map_flags_to_cap(map);
4031 
4032 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4033 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4034 			map->value_size, off, size);
4035 		return -EACCES;
4036 	}
4037 
4038 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4039 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4040 			map->value_size, off, size);
4041 		return -EACCES;
4042 	}
4043 
4044 	return 0;
4045 }
4046 
4047 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4048 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4049 			      int off, int size, u32 mem_size,
4050 			      bool zero_size_allowed)
4051 {
4052 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4053 	struct bpf_reg_state *reg;
4054 
4055 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4056 		return 0;
4057 
4058 	reg = &cur_regs(env)[regno];
4059 	switch (reg->type) {
4060 	case PTR_TO_MAP_KEY:
4061 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4062 			mem_size, off, size);
4063 		break;
4064 	case PTR_TO_MAP_VALUE:
4065 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4066 			mem_size, off, size);
4067 		break;
4068 	case PTR_TO_PACKET:
4069 	case PTR_TO_PACKET_META:
4070 	case PTR_TO_PACKET_END:
4071 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4072 			off, size, regno, reg->id, off, mem_size);
4073 		break;
4074 	case PTR_TO_MEM:
4075 	default:
4076 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4077 			mem_size, off, size);
4078 	}
4079 
4080 	return -EACCES;
4081 }
4082 
4083 /* check read/write into a memory region with possible variable offset */
4084 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4085 				   int off, int size, u32 mem_size,
4086 				   bool zero_size_allowed)
4087 {
4088 	struct bpf_verifier_state *vstate = env->cur_state;
4089 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4090 	struct bpf_reg_state *reg = &state->regs[regno];
4091 	int err;
4092 
4093 	/* We may have adjusted the register pointing to memory region, so we
4094 	 * need to try adding each of min_value and max_value to off
4095 	 * to make sure our theoretical access will be safe.
4096 	 *
4097 	 * The minimum value is only important with signed
4098 	 * comparisons where we can't assume the floor of a
4099 	 * value is 0.  If we are using signed variables for our
4100 	 * index'es we need to make sure that whatever we use
4101 	 * will have a set floor within our range.
4102 	 */
4103 	if (reg->smin_value < 0 &&
4104 	    (reg->smin_value == S64_MIN ||
4105 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4106 	      reg->smin_value + off < 0)) {
4107 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4108 			regno);
4109 		return -EACCES;
4110 	}
4111 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4112 				 mem_size, zero_size_allowed);
4113 	if (err) {
4114 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4115 			regno);
4116 		return err;
4117 	}
4118 
4119 	/* If we haven't set a max value then we need to bail since we can't be
4120 	 * sure we won't do bad things.
4121 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4122 	 */
4123 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4124 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4125 			regno);
4126 		return -EACCES;
4127 	}
4128 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4129 				 mem_size, zero_size_allowed);
4130 	if (err) {
4131 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4132 			regno);
4133 		return err;
4134 	}
4135 
4136 	return 0;
4137 }
4138 
4139 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4140 			       const struct bpf_reg_state *reg, int regno,
4141 			       bool fixed_off_ok)
4142 {
4143 	/* Access to this pointer-typed register or passing it to a helper
4144 	 * is only allowed in its original, unmodified form.
4145 	 */
4146 
4147 	if (reg->off < 0) {
4148 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4149 			reg_type_str(env, reg->type), regno, reg->off);
4150 		return -EACCES;
4151 	}
4152 
4153 	if (!fixed_off_ok && reg->off) {
4154 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4155 			reg_type_str(env, reg->type), regno, reg->off);
4156 		return -EACCES;
4157 	}
4158 
4159 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4160 		char tn_buf[48];
4161 
4162 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4163 		verbose(env, "variable %s access var_off=%s disallowed\n",
4164 			reg_type_str(env, reg->type), tn_buf);
4165 		return -EACCES;
4166 	}
4167 
4168 	return 0;
4169 }
4170 
4171 int check_ptr_off_reg(struct bpf_verifier_env *env,
4172 		      const struct bpf_reg_state *reg, int regno)
4173 {
4174 	return __check_ptr_off_reg(env, reg, regno, false);
4175 }
4176 
4177 static int map_kptr_match_type(struct bpf_verifier_env *env,
4178 			       struct btf_field *kptr_field,
4179 			       struct bpf_reg_state *reg, u32 regno)
4180 {
4181 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4182 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
4183 	const char *reg_name = "";
4184 
4185 	/* Only unreferenced case accepts untrusted pointers */
4186 	if (kptr_field->type == BPF_KPTR_UNREF)
4187 		perm_flags |= PTR_UNTRUSTED;
4188 
4189 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4190 		goto bad_type;
4191 
4192 	if (!btf_is_kernel(reg->btf)) {
4193 		verbose(env, "R%d must point to kernel BTF\n", regno);
4194 		return -EINVAL;
4195 	}
4196 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4197 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
4198 
4199 	/* For ref_ptr case, release function check should ensure we get one
4200 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4201 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4202 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4203 	 * reg->off and reg->ref_obj_id are not needed here.
4204 	 */
4205 	if (__check_ptr_off_reg(env, reg, regno, true))
4206 		return -EACCES;
4207 
4208 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4209 	 * we also need to take into account the reg->off.
4210 	 *
4211 	 * We want to support cases like:
4212 	 *
4213 	 * struct foo {
4214 	 *         struct bar br;
4215 	 *         struct baz bz;
4216 	 * };
4217 	 *
4218 	 * struct foo *v;
4219 	 * v = func();	      // PTR_TO_BTF_ID
4220 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4221 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4222 	 *                    // first member type of struct after comparison fails
4223 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4224 	 *                    // to match type
4225 	 *
4226 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4227 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4228 	 * the struct to match type against first member of struct, i.e. reject
4229 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4230 	 * strict mode to true for type match.
4231 	 */
4232 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4233 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4234 				  kptr_field->type == BPF_KPTR_REF))
4235 		goto bad_type;
4236 	return 0;
4237 bad_type:
4238 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4239 		reg_type_str(env, reg->type), reg_name);
4240 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4241 	if (kptr_field->type == BPF_KPTR_UNREF)
4242 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4243 			targ_name);
4244 	else
4245 		verbose(env, "\n");
4246 	return -EINVAL;
4247 }
4248 
4249 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4250 				 int value_regno, int insn_idx,
4251 				 struct btf_field *kptr_field)
4252 {
4253 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4254 	int class = BPF_CLASS(insn->code);
4255 	struct bpf_reg_state *val_reg;
4256 
4257 	/* Things we already checked for in check_map_access and caller:
4258 	 *  - Reject cases where variable offset may touch kptr
4259 	 *  - size of access (must be BPF_DW)
4260 	 *  - tnum_is_const(reg->var_off)
4261 	 *  - kptr_field->offset == off + reg->var_off.value
4262 	 */
4263 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4264 	if (BPF_MODE(insn->code) != BPF_MEM) {
4265 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4266 		return -EACCES;
4267 	}
4268 
4269 	/* We only allow loading referenced kptr, since it will be marked as
4270 	 * untrusted, similar to unreferenced kptr.
4271 	 */
4272 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4273 		verbose(env, "store to referenced kptr disallowed\n");
4274 		return -EACCES;
4275 	}
4276 
4277 	if (class == BPF_LDX) {
4278 		val_reg = reg_state(env, value_regno);
4279 		/* We can simply mark the value_regno receiving the pointer
4280 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4281 		 */
4282 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4283 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4284 		/* For mark_ptr_or_null_reg */
4285 		val_reg->id = ++env->id_gen;
4286 	} else if (class == BPF_STX) {
4287 		val_reg = reg_state(env, value_regno);
4288 		if (!register_is_null(val_reg) &&
4289 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4290 			return -EACCES;
4291 	} else if (class == BPF_ST) {
4292 		if (insn->imm) {
4293 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4294 				kptr_field->offset);
4295 			return -EACCES;
4296 		}
4297 	} else {
4298 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4299 		return -EACCES;
4300 	}
4301 	return 0;
4302 }
4303 
4304 /* check read/write into a map element with possible variable offset */
4305 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4306 			    int off, int size, bool zero_size_allowed,
4307 			    enum bpf_access_src src)
4308 {
4309 	struct bpf_verifier_state *vstate = env->cur_state;
4310 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4311 	struct bpf_reg_state *reg = &state->regs[regno];
4312 	struct bpf_map *map = reg->map_ptr;
4313 	struct btf_record *rec;
4314 	int err, i;
4315 
4316 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4317 				      zero_size_allowed);
4318 	if (err)
4319 		return err;
4320 
4321 	if (IS_ERR_OR_NULL(map->record))
4322 		return 0;
4323 	rec = map->record;
4324 	for (i = 0; i < rec->cnt; i++) {
4325 		struct btf_field *field = &rec->fields[i];
4326 		u32 p = field->offset;
4327 
4328 		/* If any part of a field  can be touched by load/store, reject
4329 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4330 		 * it is sufficient to check x1 < y2 && y1 < x2.
4331 		 */
4332 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4333 		    p < reg->umax_value + off + size) {
4334 			switch (field->type) {
4335 			case BPF_KPTR_UNREF:
4336 			case BPF_KPTR_REF:
4337 				if (src != ACCESS_DIRECT) {
4338 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4339 					return -EACCES;
4340 				}
4341 				if (!tnum_is_const(reg->var_off)) {
4342 					verbose(env, "kptr access cannot have variable offset\n");
4343 					return -EACCES;
4344 				}
4345 				if (p != off + reg->var_off.value) {
4346 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4347 						p, off + reg->var_off.value);
4348 					return -EACCES;
4349 				}
4350 				if (size != bpf_size_to_bytes(BPF_DW)) {
4351 					verbose(env, "kptr access size must be BPF_DW\n");
4352 					return -EACCES;
4353 				}
4354 				break;
4355 			default:
4356 				verbose(env, "%s cannot be accessed directly by load/store\n",
4357 					btf_field_type_name(field->type));
4358 				return -EACCES;
4359 			}
4360 		}
4361 	}
4362 	return 0;
4363 }
4364 
4365 #define MAX_PACKET_OFF 0xffff
4366 
4367 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4368 				       const struct bpf_call_arg_meta *meta,
4369 				       enum bpf_access_type t)
4370 {
4371 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4372 
4373 	switch (prog_type) {
4374 	/* Program types only with direct read access go here! */
4375 	case BPF_PROG_TYPE_LWT_IN:
4376 	case BPF_PROG_TYPE_LWT_OUT:
4377 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4378 	case BPF_PROG_TYPE_SK_REUSEPORT:
4379 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4380 	case BPF_PROG_TYPE_CGROUP_SKB:
4381 		if (t == BPF_WRITE)
4382 			return false;
4383 		fallthrough;
4384 
4385 	/* Program types with direct read + write access go here! */
4386 	case BPF_PROG_TYPE_SCHED_CLS:
4387 	case BPF_PROG_TYPE_SCHED_ACT:
4388 	case BPF_PROG_TYPE_XDP:
4389 	case BPF_PROG_TYPE_LWT_XMIT:
4390 	case BPF_PROG_TYPE_SK_SKB:
4391 	case BPF_PROG_TYPE_SK_MSG:
4392 		if (meta)
4393 			return meta->pkt_access;
4394 
4395 		env->seen_direct_write = true;
4396 		return true;
4397 
4398 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4399 		if (t == BPF_WRITE)
4400 			env->seen_direct_write = true;
4401 
4402 		return true;
4403 
4404 	default:
4405 		return false;
4406 	}
4407 }
4408 
4409 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4410 			       int size, bool zero_size_allowed)
4411 {
4412 	struct bpf_reg_state *regs = cur_regs(env);
4413 	struct bpf_reg_state *reg = &regs[regno];
4414 	int err;
4415 
4416 	/* We may have added a variable offset to the packet pointer; but any
4417 	 * reg->range we have comes after that.  We are only checking the fixed
4418 	 * offset.
4419 	 */
4420 
4421 	/* We don't allow negative numbers, because we aren't tracking enough
4422 	 * detail to prove they're safe.
4423 	 */
4424 	if (reg->smin_value < 0) {
4425 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4426 			regno);
4427 		return -EACCES;
4428 	}
4429 
4430 	err = reg->range < 0 ? -EINVAL :
4431 	      __check_mem_access(env, regno, off, size, reg->range,
4432 				 zero_size_allowed);
4433 	if (err) {
4434 		verbose(env, "R%d offset is outside of the packet\n", regno);
4435 		return err;
4436 	}
4437 
4438 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4439 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4440 	 * otherwise find_good_pkt_pointers would have refused to set range info
4441 	 * that __check_mem_access would have rejected this pkt access.
4442 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4443 	 */
4444 	env->prog->aux->max_pkt_offset =
4445 		max_t(u32, env->prog->aux->max_pkt_offset,
4446 		      off + reg->umax_value + size - 1);
4447 
4448 	return err;
4449 }
4450 
4451 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4452 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4453 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4454 			    struct btf **btf, u32 *btf_id)
4455 {
4456 	struct bpf_insn_access_aux info = {
4457 		.reg_type = *reg_type,
4458 		.log = &env->log,
4459 	};
4460 
4461 	if (env->ops->is_valid_access &&
4462 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4463 		/* A non zero info.ctx_field_size indicates that this field is a
4464 		 * candidate for later verifier transformation to load the whole
4465 		 * field and then apply a mask when accessed with a narrower
4466 		 * access than actual ctx access size. A zero info.ctx_field_size
4467 		 * will only allow for whole field access and rejects any other
4468 		 * type of narrower access.
4469 		 */
4470 		*reg_type = info.reg_type;
4471 
4472 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4473 			*btf = info.btf;
4474 			*btf_id = info.btf_id;
4475 		} else {
4476 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4477 		}
4478 		/* remember the offset of last byte accessed in ctx */
4479 		if (env->prog->aux->max_ctx_offset < off + size)
4480 			env->prog->aux->max_ctx_offset = off + size;
4481 		return 0;
4482 	}
4483 
4484 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4485 	return -EACCES;
4486 }
4487 
4488 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4489 				  int size)
4490 {
4491 	if (size < 0 || off < 0 ||
4492 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4493 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4494 			off, size);
4495 		return -EACCES;
4496 	}
4497 	return 0;
4498 }
4499 
4500 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4501 			     u32 regno, int off, int size,
4502 			     enum bpf_access_type t)
4503 {
4504 	struct bpf_reg_state *regs = cur_regs(env);
4505 	struct bpf_reg_state *reg = &regs[regno];
4506 	struct bpf_insn_access_aux info = {};
4507 	bool valid;
4508 
4509 	if (reg->smin_value < 0) {
4510 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4511 			regno);
4512 		return -EACCES;
4513 	}
4514 
4515 	switch (reg->type) {
4516 	case PTR_TO_SOCK_COMMON:
4517 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4518 		break;
4519 	case PTR_TO_SOCKET:
4520 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4521 		break;
4522 	case PTR_TO_TCP_SOCK:
4523 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4524 		break;
4525 	case PTR_TO_XDP_SOCK:
4526 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4527 		break;
4528 	default:
4529 		valid = false;
4530 	}
4531 
4532 
4533 	if (valid) {
4534 		env->insn_aux_data[insn_idx].ctx_field_size =
4535 			info.ctx_field_size;
4536 		return 0;
4537 	}
4538 
4539 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4540 		regno, reg_type_str(env, reg->type), off, size);
4541 
4542 	return -EACCES;
4543 }
4544 
4545 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4546 {
4547 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4548 }
4549 
4550 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4551 {
4552 	const struct bpf_reg_state *reg = reg_state(env, regno);
4553 
4554 	return reg->type == PTR_TO_CTX;
4555 }
4556 
4557 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4558 {
4559 	const struct bpf_reg_state *reg = reg_state(env, regno);
4560 
4561 	return type_is_sk_pointer(reg->type);
4562 }
4563 
4564 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4565 {
4566 	const struct bpf_reg_state *reg = reg_state(env, regno);
4567 
4568 	return type_is_pkt_pointer(reg->type);
4569 }
4570 
4571 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4572 {
4573 	const struct bpf_reg_state *reg = reg_state(env, regno);
4574 
4575 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4576 	return reg->type == PTR_TO_FLOW_KEYS;
4577 }
4578 
4579 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4580 {
4581 	/* A referenced register is always trusted. */
4582 	if (reg->ref_obj_id)
4583 		return true;
4584 
4585 	/* If a register is not referenced, it is trusted if it has the
4586 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4587 	 * other type modifiers may be safe, but we elect to take an opt-in
4588 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4589 	 * not.
4590 	 *
4591 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4592 	 * for whether a register is trusted.
4593 	 */
4594 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4595 	       !bpf_type_has_unsafe_modifiers(reg->type);
4596 }
4597 
4598 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4599 {
4600 	return reg->type & MEM_RCU;
4601 }
4602 
4603 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4604 				   const struct bpf_reg_state *reg,
4605 				   int off, int size, bool strict)
4606 {
4607 	struct tnum reg_off;
4608 	int ip_align;
4609 
4610 	/* Byte size accesses are always allowed. */
4611 	if (!strict || size == 1)
4612 		return 0;
4613 
4614 	/* For platforms that do not have a Kconfig enabling
4615 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4616 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4617 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4618 	 * to this code only in strict mode where we want to emulate
4619 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4620 	 * unconditional IP align value of '2'.
4621 	 */
4622 	ip_align = 2;
4623 
4624 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4625 	if (!tnum_is_aligned(reg_off, size)) {
4626 		char tn_buf[48];
4627 
4628 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4629 		verbose(env,
4630 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4631 			ip_align, tn_buf, reg->off, off, size);
4632 		return -EACCES;
4633 	}
4634 
4635 	return 0;
4636 }
4637 
4638 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4639 				       const struct bpf_reg_state *reg,
4640 				       const char *pointer_desc,
4641 				       int off, int size, bool strict)
4642 {
4643 	struct tnum reg_off;
4644 
4645 	/* Byte size accesses are always allowed. */
4646 	if (!strict || size == 1)
4647 		return 0;
4648 
4649 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4650 	if (!tnum_is_aligned(reg_off, size)) {
4651 		char tn_buf[48];
4652 
4653 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4654 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4655 			pointer_desc, tn_buf, reg->off, off, size);
4656 		return -EACCES;
4657 	}
4658 
4659 	return 0;
4660 }
4661 
4662 static int check_ptr_alignment(struct bpf_verifier_env *env,
4663 			       const struct bpf_reg_state *reg, int off,
4664 			       int size, bool strict_alignment_once)
4665 {
4666 	bool strict = env->strict_alignment || strict_alignment_once;
4667 	const char *pointer_desc = "";
4668 
4669 	switch (reg->type) {
4670 	case PTR_TO_PACKET:
4671 	case PTR_TO_PACKET_META:
4672 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4673 		 * right in front, treat it the very same way.
4674 		 */
4675 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4676 	case PTR_TO_FLOW_KEYS:
4677 		pointer_desc = "flow keys ";
4678 		break;
4679 	case PTR_TO_MAP_KEY:
4680 		pointer_desc = "key ";
4681 		break;
4682 	case PTR_TO_MAP_VALUE:
4683 		pointer_desc = "value ";
4684 		break;
4685 	case PTR_TO_CTX:
4686 		pointer_desc = "context ";
4687 		break;
4688 	case PTR_TO_STACK:
4689 		pointer_desc = "stack ";
4690 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4691 		 * and check_stack_read_fixed_off() relies on stack accesses being
4692 		 * aligned.
4693 		 */
4694 		strict = true;
4695 		break;
4696 	case PTR_TO_SOCKET:
4697 		pointer_desc = "sock ";
4698 		break;
4699 	case PTR_TO_SOCK_COMMON:
4700 		pointer_desc = "sock_common ";
4701 		break;
4702 	case PTR_TO_TCP_SOCK:
4703 		pointer_desc = "tcp_sock ";
4704 		break;
4705 	case PTR_TO_XDP_SOCK:
4706 		pointer_desc = "xdp_sock ";
4707 		break;
4708 	default:
4709 		break;
4710 	}
4711 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4712 					   strict);
4713 }
4714 
4715 static int update_stack_depth(struct bpf_verifier_env *env,
4716 			      const struct bpf_func_state *func,
4717 			      int off)
4718 {
4719 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4720 
4721 	if (stack >= -off)
4722 		return 0;
4723 
4724 	/* update known max for given subprogram */
4725 	env->subprog_info[func->subprogno].stack_depth = -off;
4726 	return 0;
4727 }
4728 
4729 /* starting from main bpf function walk all instructions of the function
4730  * and recursively walk all callees that given function can call.
4731  * Ignore jump and exit insns.
4732  * Since recursion is prevented by check_cfg() this algorithm
4733  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4734  */
4735 static int check_max_stack_depth(struct bpf_verifier_env *env)
4736 {
4737 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4738 	struct bpf_subprog_info *subprog = env->subprog_info;
4739 	struct bpf_insn *insn = env->prog->insnsi;
4740 	bool tail_call_reachable = false;
4741 	int ret_insn[MAX_CALL_FRAMES];
4742 	int ret_prog[MAX_CALL_FRAMES];
4743 	int j;
4744 
4745 process_func:
4746 	/* protect against potential stack overflow that might happen when
4747 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4748 	 * depth for such case down to 256 so that the worst case scenario
4749 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4750 	 * 8k).
4751 	 *
4752 	 * To get the idea what might happen, see an example:
4753 	 * func1 -> sub rsp, 128
4754 	 *  subfunc1 -> sub rsp, 256
4755 	 *  tailcall1 -> add rsp, 256
4756 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4757 	 *   subfunc2 -> sub rsp, 64
4758 	 *   subfunc22 -> sub rsp, 128
4759 	 *   tailcall2 -> add rsp, 128
4760 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4761 	 *
4762 	 * tailcall will unwind the current stack frame but it will not get rid
4763 	 * of caller's stack as shown on the example above.
4764 	 */
4765 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4766 		verbose(env,
4767 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4768 			depth);
4769 		return -EACCES;
4770 	}
4771 	/* round up to 32-bytes, since this is granularity
4772 	 * of interpreter stack size
4773 	 */
4774 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4775 	if (depth > MAX_BPF_STACK) {
4776 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4777 			frame + 1, depth);
4778 		return -EACCES;
4779 	}
4780 continue_func:
4781 	subprog_end = subprog[idx + 1].start;
4782 	for (; i < subprog_end; i++) {
4783 		int next_insn;
4784 
4785 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4786 			continue;
4787 		/* remember insn and function to return to */
4788 		ret_insn[frame] = i + 1;
4789 		ret_prog[frame] = idx;
4790 
4791 		/* find the callee */
4792 		next_insn = i + insn[i].imm + 1;
4793 		idx = find_subprog(env, next_insn);
4794 		if (idx < 0) {
4795 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4796 				  next_insn);
4797 			return -EFAULT;
4798 		}
4799 		if (subprog[idx].is_async_cb) {
4800 			if (subprog[idx].has_tail_call) {
4801 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4802 				return -EFAULT;
4803 			}
4804 			 /* async callbacks don't increase bpf prog stack size */
4805 			continue;
4806 		}
4807 		i = next_insn;
4808 
4809 		if (subprog[idx].has_tail_call)
4810 			tail_call_reachable = true;
4811 
4812 		frame++;
4813 		if (frame >= MAX_CALL_FRAMES) {
4814 			verbose(env, "the call stack of %d frames is too deep !\n",
4815 				frame);
4816 			return -E2BIG;
4817 		}
4818 		goto process_func;
4819 	}
4820 	/* if tail call got detected across bpf2bpf calls then mark each of the
4821 	 * currently present subprog frames as tail call reachable subprogs;
4822 	 * this info will be utilized by JIT so that we will be preserving the
4823 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4824 	 */
4825 	if (tail_call_reachable)
4826 		for (j = 0; j < frame; j++)
4827 			subprog[ret_prog[j]].tail_call_reachable = true;
4828 	if (subprog[0].tail_call_reachable)
4829 		env->prog->aux->tail_call_reachable = true;
4830 
4831 	/* end of for() loop means the last insn of the 'subprog'
4832 	 * was reached. Doesn't matter whether it was JA or EXIT
4833 	 */
4834 	if (frame == 0)
4835 		return 0;
4836 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4837 	frame--;
4838 	i = ret_insn[frame];
4839 	idx = ret_prog[frame];
4840 	goto continue_func;
4841 }
4842 
4843 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4844 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4845 				  const struct bpf_insn *insn, int idx)
4846 {
4847 	int start = idx + insn->imm + 1, subprog;
4848 
4849 	subprog = find_subprog(env, start);
4850 	if (subprog < 0) {
4851 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4852 			  start);
4853 		return -EFAULT;
4854 	}
4855 	return env->subprog_info[subprog].stack_depth;
4856 }
4857 #endif
4858 
4859 static int __check_buffer_access(struct bpf_verifier_env *env,
4860 				 const char *buf_info,
4861 				 const struct bpf_reg_state *reg,
4862 				 int regno, int off, int size)
4863 {
4864 	if (off < 0) {
4865 		verbose(env,
4866 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4867 			regno, buf_info, off, size);
4868 		return -EACCES;
4869 	}
4870 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4871 		char tn_buf[48];
4872 
4873 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4874 		verbose(env,
4875 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4876 			regno, off, tn_buf);
4877 		return -EACCES;
4878 	}
4879 
4880 	return 0;
4881 }
4882 
4883 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4884 				  const struct bpf_reg_state *reg,
4885 				  int regno, int off, int size)
4886 {
4887 	int err;
4888 
4889 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4890 	if (err)
4891 		return err;
4892 
4893 	if (off + size > env->prog->aux->max_tp_access)
4894 		env->prog->aux->max_tp_access = off + size;
4895 
4896 	return 0;
4897 }
4898 
4899 static int check_buffer_access(struct bpf_verifier_env *env,
4900 			       const struct bpf_reg_state *reg,
4901 			       int regno, int off, int size,
4902 			       bool zero_size_allowed,
4903 			       u32 *max_access)
4904 {
4905 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4906 	int err;
4907 
4908 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4909 	if (err)
4910 		return err;
4911 
4912 	if (off + size > *max_access)
4913 		*max_access = off + size;
4914 
4915 	return 0;
4916 }
4917 
4918 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4919 static void zext_32_to_64(struct bpf_reg_state *reg)
4920 {
4921 	reg->var_off = tnum_subreg(reg->var_off);
4922 	__reg_assign_32_into_64(reg);
4923 }
4924 
4925 /* truncate register to smaller size (in bytes)
4926  * must be called with size < BPF_REG_SIZE
4927  */
4928 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4929 {
4930 	u64 mask;
4931 
4932 	/* clear high bits in bit representation */
4933 	reg->var_off = tnum_cast(reg->var_off, size);
4934 
4935 	/* fix arithmetic bounds */
4936 	mask = ((u64)1 << (size * 8)) - 1;
4937 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4938 		reg->umin_value &= mask;
4939 		reg->umax_value &= mask;
4940 	} else {
4941 		reg->umin_value = 0;
4942 		reg->umax_value = mask;
4943 	}
4944 	reg->smin_value = reg->umin_value;
4945 	reg->smax_value = reg->umax_value;
4946 
4947 	/* If size is smaller than 32bit register the 32bit register
4948 	 * values are also truncated so we push 64-bit bounds into
4949 	 * 32-bit bounds. Above were truncated < 32-bits already.
4950 	 */
4951 	if (size >= 4)
4952 		return;
4953 	__reg_combine_64_into_32(reg);
4954 }
4955 
4956 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4957 {
4958 	/* A map is considered read-only if the following condition are true:
4959 	 *
4960 	 * 1) BPF program side cannot change any of the map content. The
4961 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4962 	 *    and was set at map creation time.
4963 	 * 2) The map value(s) have been initialized from user space by a
4964 	 *    loader and then "frozen", such that no new map update/delete
4965 	 *    operations from syscall side are possible for the rest of
4966 	 *    the map's lifetime from that point onwards.
4967 	 * 3) Any parallel/pending map update/delete operations from syscall
4968 	 *    side have been completed. Only after that point, it's safe to
4969 	 *    assume that map value(s) are immutable.
4970 	 */
4971 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4972 	       READ_ONCE(map->frozen) &&
4973 	       !bpf_map_write_active(map);
4974 }
4975 
4976 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4977 {
4978 	void *ptr;
4979 	u64 addr;
4980 	int err;
4981 
4982 	err = map->ops->map_direct_value_addr(map, &addr, off);
4983 	if (err)
4984 		return err;
4985 	ptr = (void *)(long)addr + off;
4986 
4987 	switch (size) {
4988 	case sizeof(u8):
4989 		*val = (u64)*(u8 *)ptr;
4990 		break;
4991 	case sizeof(u16):
4992 		*val = (u64)*(u16 *)ptr;
4993 		break;
4994 	case sizeof(u32):
4995 		*val = (u64)*(u32 *)ptr;
4996 		break;
4997 	case sizeof(u64):
4998 		*val = *(u64 *)ptr;
4999 		break;
5000 	default:
5001 		return -EINVAL;
5002 	}
5003 	return 0;
5004 }
5005 
5006 #define BTF_TYPE_SAFE_NESTED(__type)  __PASTE(__type, __safe_fields)
5007 
5008 BTF_TYPE_SAFE_NESTED(struct task_struct) {
5009 	const cpumask_t *cpus_ptr;
5010 };
5011 
5012 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env,
5013 				  struct bpf_reg_state *reg,
5014 				  int off)
5015 {
5016 	/* If its parent is not trusted, it can't regain its trusted status. */
5017 	if (!is_trusted_reg(reg))
5018 		return false;
5019 
5020 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct));
5021 
5022 	return btf_nested_type_is_trusted(&env->log, reg, off);
5023 }
5024 
5025 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5026 				   struct bpf_reg_state *regs,
5027 				   int regno, int off, int size,
5028 				   enum bpf_access_type atype,
5029 				   int value_regno)
5030 {
5031 	struct bpf_reg_state *reg = regs + regno;
5032 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5033 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5034 	enum bpf_type_flag flag = 0;
5035 	u32 btf_id;
5036 	int ret;
5037 
5038 	if (!env->allow_ptr_leaks) {
5039 		verbose(env,
5040 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5041 			tname);
5042 		return -EPERM;
5043 	}
5044 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5045 		verbose(env,
5046 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5047 			tname);
5048 		return -EINVAL;
5049 	}
5050 	if (off < 0) {
5051 		verbose(env,
5052 			"R%d is ptr_%s invalid negative access: off=%d\n",
5053 			regno, tname, off);
5054 		return -EACCES;
5055 	}
5056 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5057 		char tn_buf[48];
5058 
5059 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5060 		verbose(env,
5061 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5062 			regno, tname, off, tn_buf);
5063 		return -EACCES;
5064 	}
5065 
5066 	if (reg->type & MEM_USER) {
5067 		verbose(env,
5068 			"R%d is ptr_%s access user memory: off=%d\n",
5069 			regno, tname, off);
5070 		return -EACCES;
5071 	}
5072 
5073 	if (reg->type & MEM_PERCPU) {
5074 		verbose(env,
5075 			"R%d is ptr_%s access percpu memory: off=%d\n",
5076 			regno, tname, off);
5077 		return -EACCES;
5078 	}
5079 
5080 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5081 		if (!btf_is_kernel(reg->btf)) {
5082 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5083 			return -EFAULT;
5084 		}
5085 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5086 	} else {
5087 		/* Writes are permitted with default btf_struct_access for
5088 		 * program allocated objects (which always have ref_obj_id > 0),
5089 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5090 		 */
5091 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5092 			verbose(env, "only read is supported\n");
5093 			return -EACCES;
5094 		}
5095 
5096 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5097 		    !reg->ref_obj_id) {
5098 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5099 			return -EFAULT;
5100 		}
5101 
5102 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5103 	}
5104 
5105 	if (ret < 0)
5106 		return ret;
5107 
5108 	/* If this is an untrusted pointer, all pointers formed by walking it
5109 	 * also inherit the untrusted flag.
5110 	 */
5111 	if (type_flag(reg->type) & PTR_UNTRUSTED)
5112 		flag |= PTR_UNTRUSTED;
5113 
5114 	/* By default any pointer obtained from walking a trusted pointer is no
5115 	 * longer trusted, unless the field being accessed has explicitly been
5116 	 * marked as inheriting its parent's state of trust.
5117 	 *
5118 	 * An RCU-protected pointer can also be deemed trusted if we are in an
5119 	 * RCU read region. This case is handled below.
5120 	 */
5121 	if (nested_ptr_is_trusted(env, reg, off))
5122 		flag |= PTR_TRUSTED;
5123 	else
5124 		flag &= ~PTR_TRUSTED;
5125 
5126 	if (flag & MEM_RCU) {
5127 		/* Mark value register as MEM_RCU only if it is protected by
5128 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
5129 		 * itself can already indicate trustedness inside the rcu
5130 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
5131 		 * it could be null in some cases.
5132 		 */
5133 		if (!env->cur_state->active_rcu_lock ||
5134 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
5135 			flag &= ~MEM_RCU;
5136 		else
5137 			flag |= PTR_MAYBE_NULL;
5138 	} else if (reg->type & MEM_RCU) {
5139 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
5140 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
5141 		 */
5142 		flag |= PTR_UNTRUSTED;
5143 	}
5144 
5145 	if (atype == BPF_READ && value_regno >= 0)
5146 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5147 
5148 	return 0;
5149 }
5150 
5151 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5152 				   struct bpf_reg_state *regs,
5153 				   int regno, int off, int size,
5154 				   enum bpf_access_type atype,
5155 				   int value_regno)
5156 {
5157 	struct bpf_reg_state *reg = regs + regno;
5158 	struct bpf_map *map = reg->map_ptr;
5159 	struct bpf_reg_state map_reg;
5160 	enum bpf_type_flag flag = 0;
5161 	const struct btf_type *t;
5162 	const char *tname;
5163 	u32 btf_id;
5164 	int ret;
5165 
5166 	if (!btf_vmlinux) {
5167 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5168 		return -ENOTSUPP;
5169 	}
5170 
5171 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5172 		verbose(env, "map_ptr access not supported for map type %d\n",
5173 			map->map_type);
5174 		return -ENOTSUPP;
5175 	}
5176 
5177 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5178 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5179 
5180 	if (!env->allow_ptr_leaks) {
5181 		verbose(env,
5182 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5183 			tname);
5184 		return -EPERM;
5185 	}
5186 
5187 	if (off < 0) {
5188 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5189 			regno, tname, off);
5190 		return -EACCES;
5191 	}
5192 
5193 	if (atype != BPF_READ) {
5194 		verbose(env, "only read from %s is supported\n", tname);
5195 		return -EACCES;
5196 	}
5197 
5198 	/* Simulate access to a PTR_TO_BTF_ID */
5199 	memset(&map_reg, 0, sizeof(map_reg));
5200 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5201 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5202 	if (ret < 0)
5203 		return ret;
5204 
5205 	if (value_regno >= 0)
5206 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5207 
5208 	return 0;
5209 }
5210 
5211 /* Check that the stack access at the given offset is within bounds. The
5212  * maximum valid offset is -1.
5213  *
5214  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5215  * -state->allocated_stack for reads.
5216  */
5217 static int check_stack_slot_within_bounds(int off,
5218 					  struct bpf_func_state *state,
5219 					  enum bpf_access_type t)
5220 {
5221 	int min_valid_off;
5222 
5223 	if (t == BPF_WRITE)
5224 		min_valid_off = -MAX_BPF_STACK;
5225 	else
5226 		min_valid_off = -state->allocated_stack;
5227 
5228 	if (off < min_valid_off || off > -1)
5229 		return -EACCES;
5230 	return 0;
5231 }
5232 
5233 /* Check that the stack access at 'regno + off' falls within the maximum stack
5234  * bounds.
5235  *
5236  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5237  */
5238 static int check_stack_access_within_bounds(
5239 		struct bpf_verifier_env *env,
5240 		int regno, int off, int access_size,
5241 		enum bpf_access_src src, enum bpf_access_type type)
5242 {
5243 	struct bpf_reg_state *regs = cur_regs(env);
5244 	struct bpf_reg_state *reg = regs + regno;
5245 	struct bpf_func_state *state = func(env, reg);
5246 	int min_off, max_off;
5247 	int err;
5248 	char *err_extra;
5249 
5250 	if (src == ACCESS_HELPER)
5251 		/* We don't know if helpers are reading or writing (or both). */
5252 		err_extra = " indirect access to";
5253 	else if (type == BPF_READ)
5254 		err_extra = " read from";
5255 	else
5256 		err_extra = " write to";
5257 
5258 	if (tnum_is_const(reg->var_off)) {
5259 		min_off = reg->var_off.value + off;
5260 		if (access_size > 0)
5261 			max_off = min_off + access_size - 1;
5262 		else
5263 			max_off = min_off;
5264 	} else {
5265 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5266 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5267 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5268 				err_extra, regno);
5269 			return -EACCES;
5270 		}
5271 		min_off = reg->smin_value + off;
5272 		if (access_size > 0)
5273 			max_off = reg->smax_value + off + access_size - 1;
5274 		else
5275 			max_off = min_off;
5276 	}
5277 
5278 	err = check_stack_slot_within_bounds(min_off, state, type);
5279 	if (!err)
5280 		err = check_stack_slot_within_bounds(max_off, state, type);
5281 
5282 	if (err) {
5283 		if (tnum_is_const(reg->var_off)) {
5284 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5285 				err_extra, regno, off, access_size);
5286 		} else {
5287 			char tn_buf[48];
5288 
5289 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5290 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5291 				err_extra, regno, tn_buf, access_size);
5292 		}
5293 	}
5294 	return err;
5295 }
5296 
5297 /* check whether memory at (regno + off) is accessible for t = (read | write)
5298  * if t==write, value_regno is a register which value is stored into memory
5299  * if t==read, value_regno is a register which will receive the value from memory
5300  * if t==write && value_regno==-1, some unknown value is stored into memory
5301  * if t==read && value_regno==-1, don't care what we read from memory
5302  */
5303 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5304 			    int off, int bpf_size, enum bpf_access_type t,
5305 			    int value_regno, bool strict_alignment_once)
5306 {
5307 	struct bpf_reg_state *regs = cur_regs(env);
5308 	struct bpf_reg_state *reg = regs + regno;
5309 	struct bpf_func_state *state;
5310 	int size, err = 0;
5311 
5312 	size = bpf_size_to_bytes(bpf_size);
5313 	if (size < 0)
5314 		return size;
5315 
5316 	/* alignment checks will add in reg->off themselves */
5317 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5318 	if (err)
5319 		return err;
5320 
5321 	/* for access checks, reg->off is just part of off */
5322 	off += reg->off;
5323 
5324 	if (reg->type == PTR_TO_MAP_KEY) {
5325 		if (t == BPF_WRITE) {
5326 			verbose(env, "write to change key R%d not allowed\n", regno);
5327 			return -EACCES;
5328 		}
5329 
5330 		err = check_mem_region_access(env, regno, off, size,
5331 					      reg->map_ptr->key_size, false);
5332 		if (err)
5333 			return err;
5334 		if (value_regno >= 0)
5335 			mark_reg_unknown(env, regs, value_regno);
5336 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5337 		struct btf_field *kptr_field = NULL;
5338 
5339 		if (t == BPF_WRITE && value_regno >= 0 &&
5340 		    is_pointer_value(env, value_regno)) {
5341 			verbose(env, "R%d leaks addr into map\n", value_regno);
5342 			return -EACCES;
5343 		}
5344 		err = check_map_access_type(env, regno, off, size, t);
5345 		if (err)
5346 			return err;
5347 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5348 		if (err)
5349 			return err;
5350 		if (tnum_is_const(reg->var_off))
5351 			kptr_field = btf_record_find(reg->map_ptr->record,
5352 						     off + reg->var_off.value, BPF_KPTR);
5353 		if (kptr_field) {
5354 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5355 		} else if (t == BPF_READ && value_regno >= 0) {
5356 			struct bpf_map *map = reg->map_ptr;
5357 
5358 			/* if map is read-only, track its contents as scalars */
5359 			if (tnum_is_const(reg->var_off) &&
5360 			    bpf_map_is_rdonly(map) &&
5361 			    map->ops->map_direct_value_addr) {
5362 				int map_off = off + reg->var_off.value;
5363 				u64 val = 0;
5364 
5365 				err = bpf_map_direct_read(map, map_off, size,
5366 							  &val);
5367 				if (err)
5368 					return err;
5369 
5370 				regs[value_regno].type = SCALAR_VALUE;
5371 				__mark_reg_known(&regs[value_regno], val);
5372 			} else {
5373 				mark_reg_unknown(env, regs, value_regno);
5374 			}
5375 		}
5376 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5377 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5378 
5379 		if (type_may_be_null(reg->type)) {
5380 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5381 				reg_type_str(env, reg->type));
5382 			return -EACCES;
5383 		}
5384 
5385 		if (t == BPF_WRITE && rdonly_mem) {
5386 			verbose(env, "R%d cannot write into %s\n",
5387 				regno, reg_type_str(env, reg->type));
5388 			return -EACCES;
5389 		}
5390 
5391 		if (t == BPF_WRITE && value_regno >= 0 &&
5392 		    is_pointer_value(env, value_regno)) {
5393 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5394 			return -EACCES;
5395 		}
5396 
5397 		err = check_mem_region_access(env, regno, off, size,
5398 					      reg->mem_size, false);
5399 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5400 			mark_reg_unknown(env, regs, value_regno);
5401 	} else if (reg->type == PTR_TO_CTX) {
5402 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5403 		struct btf *btf = NULL;
5404 		u32 btf_id = 0;
5405 
5406 		if (t == BPF_WRITE && value_regno >= 0 &&
5407 		    is_pointer_value(env, value_regno)) {
5408 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5409 			return -EACCES;
5410 		}
5411 
5412 		err = check_ptr_off_reg(env, reg, regno);
5413 		if (err < 0)
5414 			return err;
5415 
5416 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5417 				       &btf_id);
5418 		if (err)
5419 			verbose_linfo(env, insn_idx, "; ");
5420 		if (!err && t == BPF_READ && value_regno >= 0) {
5421 			/* ctx access returns either a scalar, or a
5422 			 * PTR_TO_PACKET[_META,_END]. In the latter
5423 			 * case, we know the offset is zero.
5424 			 */
5425 			if (reg_type == SCALAR_VALUE) {
5426 				mark_reg_unknown(env, regs, value_regno);
5427 			} else {
5428 				mark_reg_known_zero(env, regs,
5429 						    value_regno);
5430 				if (type_may_be_null(reg_type))
5431 					regs[value_regno].id = ++env->id_gen;
5432 				/* A load of ctx field could have different
5433 				 * actual load size with the one encoded in the
5434 				 * insn. When the dst is PTR, it is for sure not
5435 				 * a sub-register.
5436 				 */
5437 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5438 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5439 					regs[value_regno].btf = btf;
5440 					regs[value_regno].btf_id = btf_id;
5441 				}
5442 			}
5443 			regs[value_regno].type = reg_type;
5444 		}
5445 
5446 	} else if (reg->type == PTR_TO_STACK) {
5447 		/* Basic bounds checks. */
5448 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5449 		if (err)
5450 			return err;
5451 
5452 		state = func(env, reg);
5453 		err = update_stack_depth(env, state, off);
5454 		if (err)
5455 			return err;
5456 
5457 		if (t == BPF_READ)
5458 			err = check_stack_read(env, regno, off, size,
5459 					       value_regno);
5460 		else
5461 			err = check_stack_write(env, regno, off, size,
5462 						value_regno, insn_idx);
5463 	} else if (reg_is_pkt_pointer(reg)) {
5464 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5465 			verbose(env, "cannot write into packet\n");
5466 			return -EACCES;
5467 		}
5468 		if (t == BPF_WRITE && value_regno >= 0 &&
5469 		    is_pointer_value(env, value_regno)) {
5470 			verbose(env, "R%d leaks addr into packet\n",
5471 				value_regno);
5472 			return -EACCES;
5473 		}
5474 		err = check_packet_access(env, regno, off, size, false);
5475 		if (!err && t == BPF_READ && value_regno >= 0)
5476 			mark_reg_unknown(env, regs, value_regno);
5477 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5478 		if (t == BPF_WRITE && value_regno >= 0 &&
5479 		    is_pointer_value(env, value_regno)) {
5480 			verbose(env, "R%d leaks addr into flow keys\n",
5481 				value_regno);
5482 			return -EACCES;
5483 		}
5484 
5485 		err = check_flow_keys_access(env, off, size);
5486 		if (!err && t == BPF_READ && value_regno >= 0)
5487 			mark_reg_unknown(env, regs, value_regno);
5488 	} else if (type_is_sk_pointer(reg->type)) {
5489 		if (t == BPF_WRITE) {
5490 			verbose(env, "R%d cannot write into %s\n",
5491 				regno, reg_type_str(env, reg->type));
5492 			return -EACCES;
5493 		}
5494 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5495 		if (!err && value_regno >= 0)
5496 			mark_reg_unknown(env, regs, value_regno);
5497 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5498 		err = check_tp_buffer_access(env, reg, regno, off, size);
5499 		if (!err && t == BPF_READ && value_regno >= 0)
5500 			mark_reg_unknown(env, regs, value_regno);
5501 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5502 		   !type_may_be_null(reg->type)) {
5503 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5504 					      value_regno);
5505 	} else if (reg->type == CONST_PTR_TO_MAP) {
5506 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5507 					      value_regno);
5508 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5509 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5510 		u32 *max_access;
5511 
5512 		if (rdonly_mem) {
5513 			if (t == BPF_WRITE) {
5514 				verbose(env, "R%d cannot write into %s\n",
5515 					regno, reg_type_str(env, reg->type));
5516 				return -EACCES;
5517 			}
5518 			max_access = &env->prog->aux->max_rdonly_access;
5519 		} else {
5520 			max_access = &env->prog->aux->max_rdwr_access;
5521 		}
5522 
5523 		err = check_buffer_access(env, reg, regno, off, size, false,
5524 					  max_access);
5525 
5526 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5527 			mark_reg_unknown(env, regs, value_regno);
5528 	} else {
5529 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5530 			reg_type_str(env, reg->type));
5531 		return -EACCES;
5532 	}
5533 
5534 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5535 	    regs[value_regno].type == SCALAR_VALUE) {
5536 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5537 		coerce_reg_to_size(&regs[value_regno], size);
5538 	}
5539 	return err;
5540 }
5541 
5542 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5543 {
5544 	int load_reg;
5545 	int err;
5546 
5547 	switch (insn->imm) {
5548 	case BPF_ADD:
5549 	case BPF_ADD | BPF_FETCH:
5550 	case BPF_AND:
5551 	case BPF_AND | BPF_FETCH:
5552 	case BPF_OR:
5553 	case BPF_OR | BPF_FETCH:
5554 	case BPF_XOR:
5555 	case BPF_XOR | BPF_FETCH:
5556 	case BPF_XCHG:
5557 	case BPF_CMPXCHG:
5558 		break;
5559 	default:
5560 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5561 		return -EINVAL;
5562 	}
5563 
5564 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5565 		verbose(env, "invalid atomic operand size\n");
5566 		return -EINVAL;
5567 	}
5568 
5569 	/* check src1 operand */
5570 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5571 	if (err)
5572 		return err;
5573 
5574 	/* check src2 operand */
5575 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5576 	if (err)
5577 		return err;
5578 
5579 	if (insn->imm == BPF_CMPXCHG) {
5580 		/* Check comparison of R0 with memory location */
5581 		const u32 aux_reg = BPF_REG_0;
5582 
5583 		err = check_reg_arg(env, aux_reg, SRC_OP);
5584 		if (err)
5585 			return err;
5586 
5587 		if (is_pointer_value(env, aux_reg)) {
5588 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5589 			return -EACCES;
5590 		}
5591 	}
5592 
5593 	if (is_pointer_value(env, insn->src_reg)) {
5594 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5595 		return -EACCES;
5596 	}
5597 
5598 	if (is_ctx_reg(env, insn->dst_reg) ||
5599 	    is_pkt_reg(env, insn->dst_reg) ||
5600 	    is_flow_key_reg(env, insn->dst_reg) ||
5601 	    is_sk_reg(env, insn->dst_reg)) {
5602 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5603 			insn->dst_reg,
5604 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5605 		return -EACCES;
5606 	}
5607 
5608 	if (insn->imm & BPF_FETCH) {
5609 		if (insn->imm == BPF_CMPXCHG)
5610 			load_reg = BPF_REG_0;
5611 		else
5612 			load_reg = insn->src_reg;
5613 
5614 		/* check and record load of old value */
5615 		err = check_reg_arg(env, load_reg, DST_OP);
5616 		if (err)
5617 			return err;
5618 	} else {
5619 		/* This instruction accesses a memory location but doesn't
5620 		 * actually load it into a register.
5621 		 */
5622 		load_reg = -1;
5623 	}
5624 
5625 	/* Check whether we can read the memory, with second call for fetch
5626 	 * case to simulate the register fill.
5627 	 */
5628 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5629 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5630 	if (!err && load_reg >= 0)
5631 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5632 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5633 				       true);
5634 	if (err)
5635 		return err;
5636 
5637 	/* Check whether we can write into the same memory. */
5638 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5639 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5640 	if (err)
5641 		return err;
5642 
5643 	return 0;
5644 }
5645 
5646 /* When register 'regno' is used to read the stack (either directly or through
5647  * a helper function) make sure that it's within stack boundary and, depending
5648  * on the access type, that all elements of the stack are initialized.
5649  *
5650  * 'off' includes 'regno->off', but not its dynamic part (if any).
5651  *
5652  * All registers that have been spilled on the stack in the slots within the
5653  * read offsets are marked as read.
5654  */
5655 static int check_stack_range_initialized(
5656 		struct bpf_verifier_env *env, int regno, int off,
5657 		int access_size, bool zero_size_allowed,
5658 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5659 {
5660 	struct bpf_reg_state *reg = reg_state(env, regno);
5661 	struct bpf_func_state *state = func(env, reg);
5662 	int err, min_off, max_off, i, j, slot, spi;
5663 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5664 	enum bpf_access_type bounds_check_type;
5665 	/* Some accesses can write anything into the stack, others are
5666 	 * read-only.
5667 	 */
5668 	bool clobber = false;
5669 
5670 	if (access_size == 0 && !zero_size_allowed) {
5671 		verbose(env, "invalid zero-sized read\n");
5672 		return -EACCES;
5673 	}
5674 
5675 	if (type == ACCESS_HELPER) {
5676 		/* The bounds checks for writes are more permissive than for
5677 		 * reads. However, if raw_mode is not set, we'll do extra
5678 		 * checks below.
5679 		 */
5680 		bounds_check_type = BPF_WRITE;
5681 		clobber = true;
5682 	} else {
5683 		bounds_check_type = BPF_READ;
5684 	}
5685 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5686 					       type, bounds_check_type);
5687 	if (err)
5688 		return err;
5689 
5690 
5691 	if (tnum_is_const(reg->var_off)) {
5692 		min_off = max_off = reg->var_off.value + off;
5693 	} else {
5694 		/* Variable offset is prohibited for unprivileged mode for
5695 		 * simplicity since it requires corresponding support in
5696 		 * Spectre masking for stack ALU.
5697 		 * See also retrieve_ptr_limit().
5698 		 */
5699 		if (!env->bypass_spec_v1) {
5700 			char tn_buf[48];
5701 
5702 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5703 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5704 				regno, err_extra, tn_buf);
5705 			return -EACCES;
5706 		}
5707 		/* Only initialized buffer on stack is allowed to be accessed
5708 		 * with variable offset. With uninitialized buffer it's hard to
5709 		 * guarantee that whole memory is marked as initialized on
5710 		 * helper return since specific bounds are unknown what may
5711 		 * cause uninitialized stack leaking.
5712 		 */
5713 		if (meta && meta->raw_mode)
5714 			meta = NULL;
5715 
5716 		min_off = reg->smin_value + off;
5717 		max_off = reg->smax_value + off;
5718 	}
5719 
5720 	if (meta && meta->raw_mode) {
5721 		/* Ensure we won't be overwriting dynptrs when simulating byte
5722 		 * by byte access in check_helper_call using meta.access_size.
5723 		 * This would be a problem if we have a helper in the future
5724 		 * which takes:
5725 		 *
5726 		 *	helper(uninit_mem, len, dynptr)
5727 		 *
5728 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5729 		 * may end up writing to dynptr itself when touching memory from
5730 		 * arg 1. This can be relaxed on a case by case basis for known
5731 		 * safe cases, but reject due to the possibilitiy of aliasing by
5732 		 * default.
5733 		 */
5734 		for (i = min_off; i < max_off + access_size; i++) {
5735 			int stack_off = -i - 1;
5736 
5737 			spi = __get_spi(i);
5738 			/* raw_mode may write past allocated_stack */
5739 			if (state->allocated_stack <= stack_off)
5740 				continue;
5741 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5742 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5743 				return -EACCES;
5744 			}
5745 		}
5746 		meta->access_size = access_size;
5747 		meta->regno = regno;
5748 		return 0;
5749 	}
5750 
5751 	for (i = min_off; i < max_off + access_size; i++) {
5752 		u8 *stype;
5753 
5754 		slot = -i - 1;
5755 		spi = slot / BPF_REG_SIZE;
5756 		if (state->allocated_stack <= slot)
5757 			goto err;
5758 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5759 		if (*stype == STACK_MISC)
5760 			goto mark;
5761 		if ((*stype == STACK_ZERO) ||
5762 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
5763 			if (clobber) {
5764 				/* helper can write anything into the stack */
5765 				*stype = STACK_MISC;
5766 			}
5767 			goto mark;
5768 		}
5769 
5770 		if (is_spilled_reg(&state->stack[spi]) &&
5771 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5772 		     env->allow_ptr_leaks)) {
5773 			if (clobber) {
5774 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5775 				for (j = 0; j < BPF_REG_SIZE; j++)
5776 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5777 			}
5778 			goto mark;
5779 		}
5780 
5781 err:
5782 		if (tnum_is_const(reg->var_off)) {
5783 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5784 				err_extra, regno, min_off, i - min_off, access_size);
5785 		} else {
5786 			char tn_buf[48];
5787 
5788 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5789 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5790 				err_extra, regno, tn_buf, i - min_off, access_size);
5791 		}
5792 		return -EACCES;
5793 mark:
5794 		/* reading any byte out of 8-byte 'spill_slot' will cause
5795 		 * the whole slot to be marked as 'read'
5796 		 */
5797 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5798 			      state->stack[spi].spilled_ptr.parent,
5799 			      REG_LIVE_READ64);
5800 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5801 		 * be sure that whether stack slot is written to or not. Hence,
5802 		 * we must still conservatively propagate reads upwards even if
5803 		 * helper may write to the entire memory range.
5804 		 */
5805 	}
5806 	return update_stack_depth(env, state, min_off);
5807 }
5808 
5809 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5810 				   int access_size, bool zero_size_allowed,
5811 				   struct bpf_call_arg_meta *meta)
5812 {
5813 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5814 	u32 *max_access;
5815 
5816 	switch (base_type(reg->type)) {
5817 	case PTR_TO_PACKET:
5818 	case PTR_TO_PACKET_META:
5819 		return check_packet_access(env, regno, reg->off, access_size,
5820 					   zero_size_allowed);
5821 	case PTR_TO_MAP_KEY:
5822 		if (meta && meta->raw_mode) {
5823 			verbose(env, "R%d cannot write into %s\n", regno,
5824 				reg_type_str(env, reg->type));
5825 			return -EACCES;
5826 		}
5827 		return check_mem_region_access(env, regno, reg->off, access_size,
5828 					       reg->map_ptr->key_size, false);
5829 	case PTR_TO_MAP_VALUE:
5830 		if (check_map_access_type(env, regno, reg->off, access_size,
5831 					  meta && meta->raw_mode ? BPF_WRITE :
5832 					  BPF_READ))
5833 			return -EACCES;
5834 		return check_map_access(env, regno, reg->off, access_size,
5835 					zero_size_allowed, ACCESS_HELPER);
5836 	case PTR_TO_MEM:
5837 		if (type_is_rdonly_mem(reg->type)) {
5838 			if (meta && meta->raw_mode) {
5839 				verbose(env, "R%d cannot write into %s\n", regno,
5840 					reg_type_str(env, reg->type));
5841 				return -EACCES;
5842 			}
5843 		}
5844 		return check_mem_region_access(env, regno, reg->off,
5845 					       access_size, reg->mem_size,
5846 					       zero_size_allowed);
5847 	case PTR_TO_BUF:
5848 		if (type_is_rdonly_mem(reg->type)) {
5849 			if (meta && meta->raw_mode) {
5850 				verbose(env, "R%d cannot write into %s\n", regno,
5851 					reg_type_str(env, reg->type));
5852 				return -EACCES;
5853 			}
5854 
5855 			max_access = &env->prog->aux->max_rdonly_access;
5856 		} else {
5857 			max_access = &env->prog->aux->max_rdwr_access;
5858 		}
5859 		return check_buffer_access(env, reg, regno, reg->off,
5860 					   access_size, zero_size_allowed,
5861 					   max_access);
5862 	case PTR_TO_STACK:
5863 		return check_stack_range_initialized(
5864 				env,
5865 				regno, reg->off, access_size,
5866 				zero_size_allowed, ACCESS_HELPER, meta);
5867 	case PTR_TO_CTX:
5868 		/* in case the function doesn't know how to access the context,
5869 		 * (because we are in a program of type SYSCALL for example), we
5870 		 * can not statically check its size.
5871 		 * Dynamically check it now.
5872 		 */
5873 		if (!env->ops->convert_ctx_access) {
5874 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5875 			int offset = access_size - 1;
5876 
5877 			/* Allow zero-byte read from PTR_TO_CTX */
5878 			if (access_size == 0)
5879 				return zero_size_allowed ? 0 : -EACCES;
5880 
5881 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5882 						atype, -1, false);
5883 		}
5884 
5885 		fallthrough;
5886 	default: /* scalar_value or invalid ptr */
5887 		/* Allow zero-byte read from NULL, regardless of pointer type */
5888 		if (zero_size_allowed && access_size == 0 &&
5889 		    register_is_null(reg))
5890 			return 0;
5891 
5892 		verbose(env, "R%d type=%s ", regno,
5893 			reg_type_str(env, reg->type));
5894 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5895 		return -EACCES;
5896 	}
5897 }
5898 
5899 static int check_mem_size_reg(struct bpf_verifier_env *env,
5900 			      struct bpf_reg_state *reg, u32 regno,
5901 			      bool zero_size_allowed,
5902 			      struct bpf_call_arg_meta *meta)
5903 {
5904 	int err;
5905 
5906 	/* This is used to refine r0 return value bounds for helpers
5907 	 * that enforce this value as an upper bound on return values.
5908 	 * See do_refine_retval_range() for helpers that can refine
5909 	 * the return value. C type of helper is u32 so we pull register
5910 	 * bound from umax_value however, if negative verifier errors
5911 	 * out. Only upper bounds can be learned because retval is an
5912 	 * int type and negative retvals are allowed.
5913 	 */
5914 	meta->msize_max_value = reg->umax_value;
5915 
5916 	/* The register is SCALAR_VALUE; the access check
5917 	 * happens using its boundaries.
5918 	 */
5919 	if (!tnum_is_const(reg->var_off))
5920 		/* For unprivileged variable accesses, disable raw
5921 		 * mode so that the program is required to
5922 		 * initialize all the memory that the helper could
5923 		 * just partially fill up.
5924 		 */
5925 		meta = NULL;
5926 
5927 	if (reg->smin_value < 0) {
5928 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5929 			regno);
5930 		return -EACCES;
5931 	}
5932 
5933 	if (reg->umin_value == 0) {
5934 		err = check_helper_mem_access(env, regno - 1, 0,
5935 					      zero_size_allowed,
5936 					      meta);
5937 		if (err)
5938 			return err;
5939 	}
5940 
5941 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5942 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5943 			regno);
5944 		return -EACCES;
5945 	}
5946 	err = check_helper_mem_access(env, regno - 1,
5947 				      reg->umax_value,
5948 				      zero_size_allowed, meta);
5949 	if (!err)
5950 		err = mark_chain_precision(env, regno);
5951 	return err;
5952 }
5953 
5954 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5955 		   u32 regno, u32 mem_size)
5956 {
5957 	bool may_be_null = type_may_be_null(reg->type);
5958 	struct bpf_reg_state saved_reg;
5959 	struct bpf_call_arg_meta meta;
5960 	int err;
5961 
5962 	if (register_is_null(reg))
5963 		return 0;
5964 
5965 	memset(&meta, 0, sizeof(meta));
5966 	/* Assuming that the register contains a value check if the memory
5967 	 * access is safe. Temporarily save and restore the register's state as
5968 	 * the conversion shouldn't be visible to a caller.
5969 	 */
5970 	if (may_be_null) {
5971 		saved_reg = *reg;
5972 		mark_ptr_not_null_reg(reg);
5973 	}
5974 
5975 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5976 	/* Check access for BPF_WRITE */
5977 	meta.raw_mode = true;
5978 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5979 
5980 	if (may_be_null)
5981 		*reg = saved_reg;
5982 
5983 	return err;
5984 }
5985 
5986 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5987 				    u32 regno)
5988 {
5989 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5990 	bool may_be_null = type_may_be_null(mem_reg->type);
5991 	struct bpf_reg_state saved_reg;
5992 	struct bpf_call_arg_meta meta;
5993 	int err;
5994 
5995 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5996 
5997 	memset(&meta, 0, sizeof(meta));
5998 
5999 	if (may_be_null) {
6000 		saved_reg = *mem_reg;
6001 		mark_ptr_not_null_reg(mem_reg);
6002 	}
6003 
6004 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6005 	/* Check access for BPF_WRITE */
6006 	meta.raw_mode = true;
6007 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6008 
6009 	if (may_be_null)
6010 		*mem_reg = saved_reg;
6011 	return err;
6012 }
6013 
6014 /* Implementation details:
6015  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6016  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6017  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6018  * Two separate bpf_obj_new will also have different reg->id.
6019  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6020  * clears reg->id after value_or_null->value transition, since the verifier only
6021  * cares about the range of access to valid map value pointer and doesn't care
6022  * about actual address of the map element.
6023  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6024  * reg->id > 0 after value_or_null->value transition. By doing so
6025  * two bpf_map_lookups will be considered two different pointers that
6026  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6027  * returned from bpf_obj_new.
6028  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6029  * dead-locks.
6030  * Since only one bpf_spin_lock is allowed the checks are simpler than
6031  * reg_is_refcounted() logic. The verifier needs to remember only
6032  * one spin_lock instead of array of acquired_refs.
6033  * cur_state->active_lock remembers which map value element or allocated
6034  * object got locked and clears it after bpf_spin_unlock.
6035  */
6036 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6037 			     bool is_lock)
6038 {
6039 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6040 	struct bpf_verifier_state *cur = env->cur_state;
6041 	bool is_const = tnum_is_const(reg->var_off);
6042 	u64 val = reg->var_off.value;
6043 	struct bpf_map *map = NULL;
6044 	struct btf *btf = NULL;
6045 	struct btf_record *rec;
6046 
6047 	if (!is_const) {
6048 		verbose(env,
6049 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6050 			regno);
6051 		return -EINVAL;
6052 	}
6053 	if (reg->type == PTR_TO_MAP_VALUE) {
6054 		map = reg->map_ptr;
6055 		if (!map->btf) {
6056 			verbose(env,
6057 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6058 				map->name);
6059 			return -EINVAL;
6060 		}
6061 	} else {
6062 		btf = reg->btf;
6063 	}
6064 
6065 	rec = reg_btf_record(reg);
6066 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6067 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6068 			map ? map->name : "kptr");
6069 		return -EINVAL;
6070 	}
6071 	if (rec->spin_lock_off != val + reg->off) {
6072 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6073 			val + reg->off, rec->spin_lock_off);
6074 		return -EINVAL;
6075 	}
6076 	if (is_lock) {
6077 		if (cur->active_lock.ptr) {
6078 			verbose(env,
6079 				"Locking two bpf_spin_locks are not allowed\n");
6080 			return -EINVAL;
6081 		}
6082 		if (map)
6083 			cur->active_lock.ptr = map;
6084 		else
6085 			cur->active_lock.ptr = btf;
6086 		cur->active_lock.id = reg->id;
6087 	} else {
6088 		void *ptr;
6089 
6090 		if (map)
6091 			ptr = map;
6092 		else
6093 			ptr = btf;
6094 
6095 		if (!cur->active_lock.ptr) {
6096 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6097 			return -EINVAL;
6098 		}
6099 		if (cur->active_lock.ptr != ptr ||
6100 		    cur->active_lock.id != reg->id) {
6101 			verbose(env, "bpf_spin_unlock of different lock\n");
6102 			return -EINVAL;
6103 		}
6104 
6105 		invalidate_non_owning_refs(env);
6106 
6107 		cur->active_lock.ptr = NULL;
6108 		cur->active_lock.id = 0;
6109 	}
6110 	return 0;
6111 }
6112 
6113 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6114 			      struct bpf_call_arg_meta *meta)
6115 {
6116 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6117 	bool is_const = tnum_is_const(reg->var_off);
6118 	struct bpf_map *map = reg->map_ptr;
6119 	u64 val = reg->var_off.value;
6120 
6121 	if (!is_const) {
6122 		verbose(env,
6123 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6124 			regno);
6125 		return -EINVAL;
6126 	}
6127 	if (!map->btf) {
6128 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6129 			map->name);
6130 		return -EINVAL;
6131 	}
6132 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6133 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6134 		return -EINVAL;
6135 	}
6136 	if (map->record->timer_off != val + reg->off) {
6137 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6138 			val + reg->off, map->record->timer_off);
6139 		return -EINVAL;
6140 	}
6141 	if (meta->map_ptr) {
6142 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6143 		return -EFAULT;
6144 	}
6145 	meta->map_uid = reg->map_uid;
6146 	meta->map_ptr = map;
6147 	return 0;
6148 }
6149 
6150 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6151 			     struct bpf_call_arg_meta *meta)
6152 {
6153 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6154 	struct bpf_map *map_ptr = reg->map_ptr;
6155 	struct btf_field *kptr_field;
6156 	u32 kptr_off;
6157 
6158 	if (!tnum_is_const(reg->var_off)) {
6159 		verbose(env,
6160 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6161 			regno);
6162 		return -EINVAL;
6163 	}
6164 	if (!map_ptr->btf) {
6165 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6166 			map_ptr->name);
6167 		return -EINVAL;
6168 	}
6169 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6170 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6171 		return -EINVAL;
6172 	}
6173 
6174 	meta->map_ptr = map_ptr;
6175 	kptr_off = reg->off + reg->var_off.value;
6176 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6177 	if (!kptr_field) {
6178 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6179 		return -EACCES;
6180 	}
6181 	if (kptr_field->type != BPF_KPTR_REF) {
6182 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6183 		return -EACCES;
6184 	}
6185 	meta->kptr_field = kptr_field;
6186 	return 0;
6187 }
6188 
6189 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6190  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6191  *
6192  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6193  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6194  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6195  *
6196  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6197  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6198  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6199  * mutate the view of the dynptr and also possibly destroy it. In the latter
6200  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6201  * memory that dynptr points to.
6202  *
6203  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6204  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6205  * readonly dynptr view yet, hence only the first case is tracked and checked.
6206  *
6207  * This is consistent with how C applies the const modifier to a struct object,
6208  * where the pointer itself inside bpf_dynptr becomes const but not what it
6209  * points to.
6210  *
6211  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6212  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6213  */
6214 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
6215 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
6216 {
6217 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6218 	int spi = 0;
6219 
6220 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6221 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6222 	 */
6223 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6224 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6225 		return -EFAULT;
6226 	}
6227 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
6228 	 * check_func_arg_reg_off's logic. We only need to check offset
6229 	 * and its alignment for PTR_TO_STACK.
6230 	 */
6231 	if (reg->type == PTR_TO_STACK) {
6232 		spi = dynptr_get_spi(env, reg);
6233 		if (spi < 0 && spi != -ERANGE)
6234 			return spi;
6235 	}
6236 
6237 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6238 	 *		 constructing a mutable bpf_dynptr object.
6239 	 *
6240 	 *		 Currently, this is only possible with PTR_TO_STACK
6241 	 *		 pointing to a region of at least 16 bytes which doesn't
6242 	 *		 contain an existing bpf_dynptr.
6243 	 *
6244 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6245 	 *		 mutated or destroyed. However, the memory it points to
6246 	 *		 may be mutated.
6247 	 *
6248 	 *  None       - Points to a initialized dynptr that can be mutated and
6249 	 *		 destroyed, including mutation of the memory it points
6250 	 *		 to.
6251 	 */
6252 	if (arg_type & MEM_UNINIT) {
6253 		if (!is_dynptr_reg_valid_uninit(env, reg, spi)) {
6254 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6255 			return -EINVAL;
6256 		}
6257 
6258 		/* We only support one dynptr being uninitialized at the moment,
6259 		 * which is sufficient for the helper functions we have right now.
6260 		 */
6261 		if (meta->uninit_dynptr_regno) {
6262 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6263 			return -EFAULT;
6264 		}
6265 
6266 		meta->uninit_dynptr_regno = regno;
6267 	} else /* MEM_RDONLY and None case from above */ {
6268 		int err;
6269 
6270 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6271 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6272 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6273 			return -EINVAL;
6274 		}
6275 
6276 		if (!is_dynptr_reg_valid_init(env, reg, spi)) {
6277 			verbose(env,
6278 				"Expected an initialized dynptr as arg #%d\n",
6279 				regno);
6280 			return -EINVAL;
6281 		}
6282 
6283 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6284 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6285 			const char *err_extra = "";
6286 
6287 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6288 			case DYNPTR_TYPE_LOCAL:
6289 				err_extra = "local";
6290 				break;
6291 			case DYNPTR_TYPE_RINGBUF:
6292 				err_extra = "ringbuf";
6293 				break;
6294 			default:
6295 				err_extra = "<unknown>";
6296 				break;
6297 			}
6298 			verbose(env,
6299 				"Expected a dynptr of type %s as arg #%d\n",
6300 				err_extra, regno);
6301 			return -EINVAL;
6302 		}
6303 
6304 		err = mark_dynptr_read(env, reg);
6305 		if (err)
6306 			return err;
6307 	}
6308 	return 0;
6309 }
6310 
6311 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6312 {
6313 	return type == ARG_CONST_SIZE ||
6314 	       type == ARG_CONST_SIZE_OR_ZERO;
6315 }
6316 
6317 static bool arg_type_is_release(enum bpf_arg_type type)
6318 {
6319 	return type & OBJ_RELEASE;
6320 }
6321 
6322 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6323 {
6324 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6325 }
6326 
6327 static int int_ptr_type_to_size(enum bpf_arg_type type)
6328 {
6329 	if (type == ARG_PTR_TO_INT)
6330 		return sizeof(u32);
6331 	else if (type == ARG_PTR_TO_LONG)
6332 		return sizeof(u64);
6333 
6334 	return -EINVAL;
6335 }
6336 
6337 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6338 				 const struct bpf_call_arg_meta *meta,
6339 				 enum bpf_arg_type *arg_type)
6340 {
6341 	if (!meta->map_ptr) {
6342 		/* kernel subsystem misconfigured verifier */
6343 		verbose(env, "invalid map_ptr to access map->type\n");
6344 		return -EACCES;
6345 	}
6346 
6347 	switch (meta->map_ptr->map_type) {
6348 	case BPF_MAP_TYPE_SOCKMAP:
6349 	case BPF_MAP_TYPE_SOCKHASH:
6350 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6351 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6352 		} else {
6353 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6354 			return -EINVAL;
6355 		}
6356 		break;
6357 	case BPF_MAP_TYPE_BLOOM_FILTER:
6358 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6359 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6360 		break;
6361 	default:
6362 		break;
6363 	}
6364 	return 0;
6365 }
6366 
6367 struct bpf_reg_types {
6368 	const enum bpf_reg_type types[10];
6369 	u32 *btf_id;
6370 };
6371 
6372 static const struct bpf_reg_types sock_types = {
6373 	.types = {
6374 		PTR_TO_SOCK_COMMON,
6375 		PTR_TO_SOCKET,
6376 		PTR_TO_TCP_SOCK,
6377 		PTR_TO_XDP_SOCK,
6378 	},
6379 };
6380 
6381 #ifdef CONFIG_NET
6382 static const struct bpf_reg_types btf_id_sock_common_types = {
6383 	.types = {
6384 		PTR_TO_SOCK_COMMON,
6385 		PTR_TO_SOCKET,
6386 		PTR_TO_TCP_SOCK,
6387 		PTR_TO_XDP_SOCK,
6388 		PTR_TO_BTF_ID,
6389 		PTR_TO_BTF_ID | PTR_TRUSTED,
6390 	},
6391 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6392 };
6393 #endif
6394 
6395 static const struct bpf_reg_types mem_types = {
6396 	.types = {
6397 		PTR_TO_STACK,
6398 		PTR_TO_PACKET,
6399 		PTR_TO_PACKET_META,
6400 		PTR_TO_MAP_KEY,
6401 		PTR_TO_MAP_VALUE,
6402 		PTR_TO_MEM,
6403 		PTR_TO_MEM | MEM_RINGBUF,
6404 		PTR_TO_BUF,
6405 	},
6406 };
6407 
6408 static const struct bpf_reg_types int_ptr_types = {
6409 	.types = {
6410 		PTR_TO_STACK,
6411 		PTR_TO_PACKET,
6412 		PTR_TO_PACKET_META,
6413 		PTR_TO_MAP_KEY,
6414 		PTR_TO_MAP_VALUE,
6415 	},
6416 };
6417 
6418 static const struct bpf_reg_types spin_lock_types = {
6419 	.types = {
6420 		PTR_TO_MAP_VALUE,
6421 		PTR_TO_BTF_ID | MEM_ALLOC,
6422 	}
6423 };
6424 
6425 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6426 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6427 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6428 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6429 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6430 static const struct bpf_reg_types btf_ptr_types = {
6431 	.types = {
6432 		PTR_TO_BTF_ID,
6433 		PTR_TO_BTF_ID | PTR_TRUSTED,
6434 		PTR_TO_BTF_ID | MEM_RCU,
6435 	},
6436 };
6437 static const struct bpf_reg_types percpu_btf_ptr_types = {
6438 	.types = {
6439 		PTR_TO_BTF_ID | MEM_PERCPU,
6440 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6441 	}
6442 };
6443 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6444 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6445 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6446 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6447 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6448 static const struct bpf_reg_types dynptr_types = {
6449 	.types = {
6450 		PTR_TO_STACK,
6451 		CONST_PTR_TO_DYNPTR,
6452 	}
6453 };
6454 
6455 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6456 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6457 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6458 	[ARG_CONST_SIZE]		= &scalar_types,
6459 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6460 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6461 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6462 	[ARG_PTR_TO_CTX]		= &context_types,
6463 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6464 #ifdef CONFIG_NET
6465 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6466 #endif
6467 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6468 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6469 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6470 	[ARG_PTR_TO_MEM]		= &mem_types,
6471 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6472 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6473 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6474 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6475 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6476 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6477 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6478 	[ARG_PTR_TO_TIMER]		= &timer_types,
6479 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6480 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6481 };
6482 
6483 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6484 			  enum bpf_arg_type arg_type,
6485 			  const u32 *arg_btf_id,
6486 			  struct bpf_call_arg_meta *meta)
6487 {
6488 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6489 	enum bpf_reg_type expected, type = reg->type;
6490 	const struct bpf_reg_types *compatible;
6491 	int i, j;
6492 
6493 	compatible = compatible_reg_types[base_type(arg_type)];
6494 	if (!compatible) {
6495 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6496 		return -EFAULT;
6497 	}
6498 
6499 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6500 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6501 	 *
6502 	 * Same for MAYBE_NULL:
6503 	 *
6504 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6505 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6506 	 *
6507 	 * Therefore we fold these flags depending on the arg_type before comparison.
6508 	 */
6509 	if (arg_type & MEM_RDONLY)
6510 		type &= ~MEM_RDONLY;
6511 	if (arg_type & PTR_MAYBE_NULL)
6512 		type &= ~PTR_MAYBE_NULL;
6513 
6514 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6515 		expected = compatible->types[i];
6516 		if (expected == NOT_INIT)
6517 			break;
6518 
6519 		if (type == expected)
6520 			goto found;
6521 	}
6522 
6523 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6524 	for (j = 0; j + 1 < i; j++)
6525 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6526 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6527 	return -EACCES;
6528 
6529 found:
6530 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6531 		/* For bpf_sk_release, it needs to match against first member
6532 		 * 'struct sock_common', hence make an exception for it. This
6533 		 * allows bpf_sk_release to work for multiple socket types.
6534 		 */
6535 		bool strict_type_match = arg_type_is_release(arg_type) &&
6536 					 meta->func_id != BPF_FUNC_sk_release;
6537 
6538 		if (!arg_btf_id) {
6539 			if (!compatible->btf_id) {
6540 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6541 				return -EFAULT;
6542 			}
6543 			arg_btf_id = compatible->btf_id;
6544 		}
6545 
6546 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6547 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6548 				return -EACCES;
6549 		} else {
6550 			if (arg_btf_id == BPF_PTR_POISON) {
6551 				verbose(env, "verifier internal error:");
6552 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6553 					regno);
6554 				return -EACCES;
6555 			}
6556 
6557 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6558 						  btf_vmlinux, *arg_btf_id,
6559 						  strict_type_match)) {
6560 				verbose(env, "R%d is of type %s but %s is expected\n",
6561 					regno, kernel_type_name(reg->btf, reg->btf_id),
6562 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6563 				return -EACCES;
6564 			}
6565 		}
6566 	} else if (type_is_alloc(reg->type)) {
6567 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6568 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6569 			return -EFAULT;
6570 		}
6571 	}
6572 
6573 	return 0;
6574 }
6575 
6576 static struct btf_field *
6577 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6578 {
6579 	struct btf_field *field;
6580 	struct btf_record *rec;
6581 
6582 	rec = reg_btf_record(reg);
6583 	if (!rec)
6584 		return NULL;
6585 
6586 	field = btf_record_find(rec, off, fields);
6587 	if (!field)
6588 		return NULL;
6589 
6590 	return field;
6591 }
6592 
6593 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6594 			   const struct bpf_reg_state *reg, int regno,
6595 			   enum bpf_arg_type arg_type)
6596 {
6597 	u32 type = reg->type;
6598 
6599 	/* When referenced register is passed to release function, its fixed
6600 	 * offset must be 0.
6601 	 *
6602 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6603 	 * meta->release_regno.
6604 	 */
6605 	if (arg_type_is_release(arg_type)) {
6606 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6607 		 * may not directly point to the object being released, but to
6608 		 * dynptr pointing to such object, which might be at some offset
6609 		 * on the stack. In that case, we simply to fallback to the
6610 		 * default handling.
6611 		 */
6612 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6613 			return 0;
6614 
6615 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6616 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6617 				return __check_ptr_off_reg(env, reg, regno, true);
6618 
6619 			verbose(env, "R%d must have zero offset when passed to release func\n",
6620 				regno);
6621 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6622 				kernel_type_name(reg->btf, reg->btf_id), reg->off);
6623 			return -EINVAL;
6624 		}
6625 
6626 		/* Doing check_ptr_off_reg check for the offset will catch this
6627 		 * because fixed_off_ok is false, but checking here allows us
6628 		 * to give the user a better error message.
6629 		 */
6630 		if (reg->off) {
6631 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6632 				regno);
6633 			return -EINVAL;
6634 		}
6635 		return __check_ptr_off_reg(env, reg, regno, false);
6636 	}
6637 
6638 	switch (type) {
6639 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6640 	case PTR_TO_STACK:
6641 	case PTR_TO_PACKET:
6642 	case PTR_TO_PACKET_META:
6643 	case PTR_TO_MAP_KEY:
6644 	case PTR_TO_MAP_VALUE:
6645 	case PTR_TO_MEM:
6646 	case PTR_TO_MEM | MEM_RDONLY:
6647 	case PTR_TO_MEM | MEM_RINGBUF:
6648 	case PTR_TO_BUF:
6649 	case PTR_TO_BUF | MEM_RDONLY:
6650 	case SCALAR_VALUE:
6651 		return 0;
6652 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6653 	 * fixed offset.
6654 	 */
6655 	case PTR_TO_BTF_ID:
6656 	case PTR_TO_BTF_ID | MEM_ALLOC:
6657 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6658 	case PTR_TO_BTF_ID | MEM_RCU:
6659 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6660 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6661 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6662 		 * its fixed offset must be 0. In the other cases, fixed offset
6663 		 * can be non-zero. This was already checked above. So pass
6664 		 * fixed_off_ok as true to allow fixed offset for all other
6665 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6666 		 * still need to do checks instead of returning.
6667 		 */
6668 		return __check_ptr_off_reg(env, reg, regno, true);
6669 	default:
6670 		return __check_ptr_off_reg(env, reg, regno, false);
6671 	}
6672 }
6673 
6674 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6675 {
6676 	struct bpf_func_state *state = func(env, reg);
6677 	int spi;
6678 
6679 	if (reg->type == CONST_PTR_TO_DYNPTR)
6680 		return reg->id;
6681 	spi = dynptr_get_spi(env, reg);
6682 	if (spi < 0)
6683 		return spi;
6684 	return state->stack[spi].spilled_ptr.id;
6685 }
6686 
6687 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6688 {
6689 	struct bpf_func_state *state = func(env, reg);
6690 	int spi;
6691 
6692 	if (reg->type == CONST_PTR_TO_DYNPTR)
6693 		return reg->ref_obj_id;
6694 	spi = dynptr_get_spi(env, reg);
6695 	if (spi < 0)
6696 		return spi;
6697 	return state->stack[spi].spilled_ptr.ref_obj_id;
6698 }
6699 
6700 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6701 			  struct bpf_call_arg_meta *meta,
6702 			  const struct bpf_func_proto *fn)
6703 {
6704 	u32 regno = BPF_REG_1 + arg;
6705 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6706 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6707 	enum bpf_reg_type type = reg->type;
6708 	u32 *arg_btf_id = NULL;
6709 	int err = 0;
6710 
6711 	if (arg_type == ARG_DONTCARE)
6712 		return 0;
6713 
6714 	err = check_reg_arg(env, regno, SRC_OP);
6715 	if (err)
6716 		return err;
6717 
6718 	if (arg_type == ARG_ANYTHING) {
6719 		if (is_pointer_value(env, regno)) {
6720 			verbose(env, "R%d leaks addr into helper function\n",
6721 				regno);
6722 			return -EACCES;
6723 		}
6724 		return 0;
6725 	}
6726 
6727 	if (type_is_pkt_pointer(type) &&
6728 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6729 		verbose(env, "helper access to the packet is not allowed\n");
6730 		return -EACCES;
6731 	}
6732 
6733 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6734 		err = resolve_map_arg_type(env, meta, &arg_type);
6735 		if (err)
6736 			return err;
6737 	}
6738 
6739 	if (register_is_null(reg) && type_may_be_null(arg_type))
6740 		/* A NULL register has a SCALAR_VALUE type, so skip
6741 		 * type checking.
6742 		 */
6743 		goto skip_type_check;
6744 
6745 	/* arg_btf_id and arg_size are in a union. */
6746 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6747 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6748 		arg_btf_id = fn->arg_btf_id[arg];
6749 
6750 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6751 	if (err)
6752 		return err;
6753 
6754 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6755 	if (err)
6756 		return err;
6757 
6758 skip_type_check:
6759 	if (arg_type_is_release(arg_type)) {
6760 		if (arg_type_is_dynptr(arg_type)) {
6761 			struct bpf_func_state *state = func(env, reg);
6762 			int spi;
6763 
6764 			/* Only dynptr created on stack can be released, thus
6765 			 * the get_spi and stack state checks for spilled_ptr
6766 			 * should only be done before process_dynptr_func for
6767 			 * PTR_TO_STACK.
6768 			 */
6769 			if (reg->type == PTR_TO_STACK) {
6770 				spi = dynptr_get_spi(env, reg);
6771 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
6772 					verbose(env, "arg %d is an unacquired reference\n", regno);
6773 					return -EINVAL;
6774 				}
6775 			} else {
6776 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6777 				return -EINVAL;
6778 			}
6779 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6780 			verbose(env, "R%d must be referenced when passed to release function\n",
6781 				regno);
6782 			return -EINVAL;
6783 		}
6784 		if (meta->release_regno) {
6785 			verbose(env, "verifier internal error: more than one release argument\n");
6786 			return -EFAULT;
6787 		}
6788 		meta->release_regno = regno;
6789 	}
6790 
6791 	if (reg->ref_obj_id) {
6792 		if (meta->ref_obj_id) {
6793 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6794 				regno, reg->ref_obj_id,
6795 				meta->ref_obj_id);
6796 			return -EFAULT;
6797 		}
6798 		meta->ref_obj_id = reg->ref_obj_id;
6799 	}
6800 
6801 	switch (base_type(arg_type)) {
6802 	case ARG_CONST_MAP_PTR:
6803 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6804 		if (meta->map_ptr) {
6805 			/* Use map_uid (which is unique id of inner map) to reject:
6806 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6807 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6808 			 * if (inner_map1 && inner_map2) {
6809 			 *     timer = bpf_map_lookup_elem(inner_map1);
6810 			 *     if (timer)
6811 			 *         // mismatch would have been allowed
6812 			 *         bpf_timer_init(timer, inner_map2);
6813 			 * }
6814 			 *
6815 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6816 			 */
6817 			if (meta->map_ptr != reg->map_ptr ||
6818 			    meta->map_uid != reg->map_uid) {
6819 				verbose(env,
6820 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6821 					meta->map_uid, reg->map_uid);
6822 				return -EINVAL;
6823 			}
6824 		}
6825 		meta->map_ptr = reg->map_ptr;
6826 		meta->map_uid = reg->map_uid;
6827 		break;
6828 	case ARG_PTR_TO_MAP_KEY:
6829 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6830 		 * check that [key, key + map->key_size) are within
6831 		 * stack limits and initialized
6832 		 */
6833 		if (!meta->map_ptr) {
6834 			/* in function declaration map_ptr must come before
6835 			 * map_key, so that it's verified and known before
6836 			 * we have to check map_key here. Otherwise it means
6837 			 * that kernel subsystem misconfigured verifier
6838 			 */
6839 			verbose(env, "invalid map_ptr to access map->key\n");
6840 			return -EACCES;
6841 		}
6842 		err = check_helper_mem_access(env, regno,
6843 					      meta->map_ptr->key_size, false,
6844 					      NULL);
6845 		break;
6846 	case ARG_PTR_TO_MAP_VALUE:
6847 		if (type_may_be_null(arg_type) && register_is_null(reg))
6848 			return 0;
6849 
6850 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6851 		 * check [value, value + map->value_size) validity
6852 		 */
6853 		if (!meta->map_ptr) {
6854 			/* kernel subsystem misconfigured verifier */
6855 			verbose(env, "invalid map_ptr to access map->value\n");
6856 			return -EACCES;
6857 		}
6858 		meta->raw_mode = arg_type & MEM_UNINIT;
6859 		err = check_helper_mem_access(env, regno,
6860 					      meta->map_ptr->value_size, false,
6861 					      meta);
6862 		break;
6863 	case ARG_PTR_TO_PERCPU_BTF_ID:
6864 		if (!reg->btf_id) {
6865 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6866 			return -EACCES;
6867 		}
6868 		meta->ret_btf = reg->btf;
6869 		meta->ret_btf_id = reg->btf_id;
6870 		break;
6871 	case ARG_PTR_TO_SPIN_LOCK:
6872 		if (in_rbtree_lock_required_cb(env)) {
6873 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
6874 			return -EACCES;
6875 		}
6876 		if (meta->func_id == BPF_FUNC_spin_lock) {
6877 			err = process_spin_lock(env, regno, true);
6878 			if (err)
6879 				return err;
6880 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6881 			err = process_spin_lock(env, regno, false);
6882 			if (err)
6883 				return err;
6884 		} else {
6885 			verbose(env, "verifier internal error\n");
6886 			return -EFAULT;
6887 		}
6888 		break;
6889 	case ARG_PTR_TO_TIMER:
6890 		err = process_timer_func(env, regno, meta);
6891 		if (err)
6892 			return err;
6893 		break;
6894 	case ARG_PTR_TO_FUNC:
6895 		meta->subprogno = reg->subprogno;
6896 		break;
6897 	case ARG_PTR_TO_MEM:
6898 		/* The access to this pointer is only checked when we hit the
6899 		 * next is_mem_size argument below.
6900 		 */
6901 		meta->raw_mode = arg_type & MEM_UNINIT;
6902 		if (arg_type & MEM_FIXED_SIZE) {
6903 			err = check_helper_mem_access(env, regno,
6904 						      fn->arg_size[arg], false,
6905 						      meta);
6906 		}
6907 		break;
6908 	case ARG_CONST_SIZE:
6909 		err = check_mem_size_reg(env, reg, regno, false, meta);
6910 		break;
6911 	case ARG_CONST_SIZE_OR_ZERO:
6912 		err = check_mem_size_reg(env, reg, regno, true, meta);
6913 		break;
6914 	case ARG_PTR_TO_DYNPTR:
6915 		err = process_dynptr_func(env, regno, arg_type, meta);
6916 		if (err)
6917 			return err;
6918 		break;
6919 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6920 		if (!tnum_is_const(reg->var_off)) {
6921 			verbose(env, "R%d is not a known constant'\n",
6922 				regno);
6923 			return -EACCES;
6924 		}
6925 		meta->mem_size = reg->var_off.value;
6926 		err = mark_chain_precision(env, regno);
6927 		if (err)
6928 			return err;
6929 		break;
6930 	case ARG_PTR_TO_INT:
6931 	case ARG_PTR_TO_LONG:
6932 	{
6933 		int size = int_ptr_type_to_size(arg_type);
6934 
6935 		err = check_helper_mem_access(env, regno, size, false, meta);
6936 		if (err)
6937 			return err;
6938 		err = check_ptr_alignment(env, reg, 0, size, true);
6939 		break;
6940 	}
6941 	case ARG_PTR_TO_CONST_STR:
6942 	{
6943 		struct bpf_map *map = reg->map_ptr;
6944 		int map_off;
6945 		u64 map_addr;
6946 		char *str_ptr;
6947 
6948 		if (!bpf_map_is_rdonly(map)) {
6949 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6950 			return -EACCES;
6951 		}
6952 
6953 		if (!tnum_is_const(reg->var_off)) {
6954 			verbose(env, "R%d is not a constant address'\n", regno);
6955 			return -EACCES;
6956 		}
6957 
6958 		if (!map->ops->map_direct_value_addr) {
6959 			verbose(env, "no direct value access support for this map type\n");
6960 			return -EACCES;
6961 		}
6962 
6963 		err = check_map_access(env, regno, reg->off,
6964 				       map->value_size - reg->off, false,
6965 				       ACCESS_HELPER);
6966 		if (err)
6967 			return err;
6968 
6969 		map_off = reg->off + reg->var_off.value;
6970 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6971 		if (err) {
6972 			verbose(env, "direct value access on string failed\n");
6973 			return err;
6974 		}
6975 
6976 		str_ptr = (char *)(long)(map_addr);
6977 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6978 			verbose(env, "string is not zero-terminated\n");
6979 			return -EINVAL;
6980 		}
6981 		break;
6982 	}
6983 	case ARG_PTR_TO_KPTR:
6984 		err = process_kptr_func(env, regno, meta);
6985 		if (err)
6986 			return err;
6987 		break;
6988 	}
6989 
6990 	return err;
6991 }
6992 
6993 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6994 {
6995 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6996 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6997 
6998 	if (func_id != BPF_FUNC_map_update_elem)
6999 		return false;
7000 
7001 	/* It's not possible to get access to a locked struct sock in these
7002 	 * contexts, so updating is safe.
7003 	 */
7004 	switch (type) {
7005 	case BPF_PROG_TYPE_TRACING:
7006 		if (eatype == BPF_TRACE_ITER)
7007 			return true;
7008 		break;
7009 	case BPF_PROG_TYPE_SOCKET_FILTER:
7010 	case BPF_PROG_TYPE_SCHED_CLS:
7011 	case BPF_PROG_TYPE_SCHED_ACT:
7012 	case BPF_PROG_TYPE_XDP:
7013 	case BPF_PROG_TYPE_SK_REUSEPORT:
7014 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
7015 	case BPF_PROG_TYPE_SK_LOOKUP:
7016 		return true;
7017 	default:
7018 		break;
7019 	}
7020 
7021 	verbose(env, "cannot update sockmap in this context\n");
7022 	return false;
7023 }
7024 
7025 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7026 {
7027 	return env->prog->jit_requested &&
7028 	       bpf_jit_supports_subprog_tailcalls();
7029 }
7030 
7031 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7032 					struct bpf_map *map, int func_id)
7033 {
7034 	if (!map)
7035 		return 0;
7036 
7037 	/* We need a two way check, first is from map perspective ... */
7038 	switch (map->map_type) {
7039 	case BPF_MAP_TYPE_PROG_ARRAY:
7040 		if (func_id != BPF_FUNC_tail_call)
7041 			goto error;
7042 		break;
7043 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7044 		if (func_id != BPF_FUNC_perf_event_read &&
7045 		    func_id != BPF_FUNC_perf_event_output &&
7046 		    func_id != BPF_FUNC_skb_output &&
7047 		    func_id != BPF_FUNC_perf_event_read_value &&
7048 		    func_id != BPF_FUNC_xdp_output)
7049 			goto error;
7050 		break;
7051 	case BPF_MAP_TYPE_RINGBUF:
7052 		if (func_id != BPF_FUNC_ringbuf_output &&
7053 		    func_id != BPF_FUNC_ringbuf_reserve &&
7054 		    func_id != BPF_FUNC_ringbuf_query &&
7055 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7056 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7057 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
7058 			goto error;
7059 		break;
7060 	case BPF_MAP_TYPE_USER_RINGBUF:
7061 		if (func_id != BPF_FUNC_user_ringbuf_drain)
7062 			goto error;
7063 		break;
7064 	case BPF_MAP_TYPE_STACK_TRACE:
7065 		if (func_id != BPF_FUNC_get_stackid)
7066 			goto error;
7067 		break;
7068 	case BPF_MAP_TYPE_CGROUP_ARRAY:
7069 		if (func_id != BPF_FUNC_skb_under_cgroup &&
7070 		    func_id != BPF_FUNC_current_task_under_cgroup)
7071 			goto error;
7072 		break;
7073 	case BPF_MAP_TYPE_CGROUP_STORAGE:
7074 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7075 		if (func_id != BPF_FUNC_get_local_storage)
7076 			goto error;
7077 		break;
7078 	case BPF_MAP_TYPE_DEVMAP:
7079 	case BPF_MAP_TYPE_DEVMAP_HASH:
7080 		if (func_id != BPF_FUNC_redirect_map &&
7081 		    func_id != BPF_FUNC_map_lookup_elem)
7082 			goto error;
7083 		break;
7084 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
7085 	 * appear.
7086 	 */
7087 	case BPF_MAP_TYPE_CPUMAP:
7088 		if (func_id != BPF_FUNC_redirect_map)
7089 			goto error;
7090 		break;
7091 	case BPF_MAP_TYPE_XSKMAP:
7092 		if (func_id != BPF_FUNC_redirect_map &&
7093 		    func_id != BPF_FUNC_map_lookup_elem)
7094 			goto error;
7095 		break;
7096 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7097 	case BPF_MAP_TYPE_HASH_OF_MAPS:
7098 		if (func_id != BPF_FUNC_map_lookup_elem)
7099 			goto error;
7100 		break;
7101 	case BPF_MAP_TYPE_SOCKMAP:
7102 		if (func_id != BPF_FUNC_sk_redirect_map &&
7103 		    func_id != BPF_FUNC_sock_map_update &&
7104 		    func_id != BPF_FUNC_map_delete_elem &&
7105 		    func_id != BPF_FUNC_msg_redirect_map &&
7106 		    func_id != BPF_FUNC_sk_select_reuseport &&
7107 		    func_id != BPF_FUNC_map_lookup_elem &&
7108 		    !may_update_sockmap(env, func_id))
7109 			goto error;
7110 		break;
7111 	case BPF_MAP_TYPE_SOCKHASH:
7112 		if (func_id != BPF_FUNC_sk_redirect_hash &&
7113 		    func_id != BPF_FUNC_sock_hash_update &&
7114 		    func_id != BPF_FUNC_map_delete_elem &&
7115 		    func_id != BPF_FUNC_msg_redirect_hash &&
7116 		    func_id != BPF_FUNC_sk_select_reuseport &&
7117 		    func_id != BPF_FUNC_map_lookup_elem &&
7118 		    !may_update_sockmap(env, func_id))
7119 			goto error;
7120 		break;
7121 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7122 		if (func_id != BPF_FUNC_sk_select_reuseport)
7123 			goto error;
7124 		break;
7125 	case BPF_MAP_TYPE_QUEUE:
7126 	case BPF_MAP_TYPE_STACK:
7127 		if (func_id != BPF_FUNC_map_peek_elem &&
7128 		    func_id != BPF_FUNC_map_pop_elem &&
7129 		    func_id != BPF_FUNC_map_push_elem)
7130 			goto error;
7131 		break;
7132 	case BPF_MAP_TYPE_SK_STORAGE:
7133 		if (func_id != BPF_FUNC_sk_storage_get &&
7134 		    func_id != BPF_FUNC_sk_storage_delete)
7135 			goto error;
7136 		break;
7137 	case BPF_MAP_TYPE_INODE_STORAGE:
7138 		if (func_id != BPF_FUNC_inode_storage_get &&
7139 		    func_id != BPF_FUNC_inode_storage_delete)
7140 			goto error;
7141 		break;
7142 	case BPF_MAP_TYPE_TASK_STORAGE:
7143 		if (func_id != BPF_FUNC_task_storage_get &&
7144 		    func_id != BPF_FUNC_task_storage_delete)
7145 			goto error;
7146 		break;
7147 	case BPF_MAP_TYPE_CGRP_STORAGE:
7148 		if (func_id != BPF_FUNC_cgrp_storage_get &&
7149 		    func_id != BPF_FUNC_cgrp_storage_delete)
7150 			goto error;
7151 		break;
7152 	case BPF_MAP_TYPE_BLOOM_FILTER:
7153 		if (func_id != BPF_FUNC_map_peek_elem &&
7154 		    func_id != BPF_FUNC_map_push_elem)
7155 			goto error;
7156 		break;
7157 	default:
7158 		break;
7159 	}
7160 
7161 	/* ... and second from the function itself. */
7162 	switch (func_id) {
7163 	case BPF_FUNC_tail_call:
7164 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7165 			goto error;
7166 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7167 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7168 			return -EINVAL;
7169 		}
7170 		break;
7171 	case BPF_FUNC_perf_event_read:
7172 	case BPF_FUNC_perf_event_output:
7173 	case BPF_FUNC_perf_event_read_value:
7174 	case BPF_FUNC_skb_output:
7175 	case BPF_FUNC_xdp_output:
7176 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7177 			goto error;
7178 		break;
7179 	case BPF_FUNC_ringbuf_output:
7180 	case BPF_FUNC_ringbuf_reserve:
7181 	case BPF_FUNC_ringbuf_query:
7182 	case BPF_FUNC_ringbuf_reserve_dynptr:
7183 	case BPF_FUNC_ringbuf_submit_dynptr:
7184 	case BPF_FUNC_ringbuf_discard_dynptr:
7185 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7186 			goto error;
7187 		break;
7188 	case BPF_FUNC_user_ringbuf_drain:
7189 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7190 			goto error;
7191 		break;
7192 	case BPF_FUNC_get_stackid:
7193 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7194 			goto error;
7195 		break;
7196 	case BPF_FUNC_current_task_under_cgroup:
7197 	case BPF_FUNC_skb_under_cgroup:
7198 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7199 			goto error;
7200 		break;
7201 	case BPF_FUNC_redirect_map:
7202 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7203 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7204 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
7205 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
7206 			goto error;
7207 		break;
7208 	case BPF_FUNC_sk_redirect_map:
7209 	case BPF_FUNC_msg_redirect_map:
7210 	case BPF_FUNC_sock_map_update:
7211 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7212 			goto error;
7213 		break;
7214 	case BPF_FUNC_sk_redirect_hash:
7215 	case BPF_FUNC_msg_redirect_hash:
7216 	case BPF_FUNC_sock_hash_update:
7217 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7218 			goto error;
7219 		break;
7220 	case BPF_FUNC_get_local_storage:
7221 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7222 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7223 			goto error;
7224 		break;
7225 	case BPF_FUNC_sk_select_reuseport:
7226 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7227 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7228 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
7229 			goto error;
7230 		break;
7231 	case BPF_FUNC_map_pop_elem:
7232 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7233 		    map->map_type != BPF_MAP_TYPE_STACK)
7234 			goto error;
7235 		break;
7236 	case BPF_FUNC_map_peek_elem:
7237 	case BPF_FUNC_map_push_elem:
7238 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7239 		    map->map_type != BPF_MAP_TYPE_STACK &&
7240 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7241 			goto error;
7242 		break;
7243 	case BPF_FUNC_map_lookup_percpu_elem:
7244 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7245 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7246 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7247 			goto error;
7248 		break;
7249 	case BPF_FUNC_sk_storage_get:
7250 	case BPF_FUNC_sk_storage_delete:
7251 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7252 			goto error;
7253 		break;
7254 	case BPF_FUNC_inode_storage_get:
7255 	case BPF_FUNC_inode_storage_delete:
7256 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7257 			goto error;
7258 		break;
7259 	case BPF_FUNC_task_storage_get:
7260 	case BPF_FUNC_task_storage_delete:
7261 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7262 			goto error;
7263 		break;
7264 	case BPF_FUNC_cgrp_storage_get:
7265 	case BPF_FUNC_cgrp_storage_delete:
7266 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7267 			goto error;
7268 		break;
7269 	default:
7270 		break;
7271 	}
7272 
7273 	return 0;
7274 error:
7275 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
7276 		map->map_type, func_id_name(func_id), func_id);
7277 	return -EINVAL;
7278 }
7279 
7280 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7281 {
7282 	int count = 0;
7283 
7284 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7285 		count++;
7286 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7287 		count++;
7288 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7289 		count++;
7290 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7291 		count++;
7292 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7293 		count++;
7294 
7295 	/* We only support one arg being in raw mode at the moment,
7296 	 * which is sufficient for the helper functions we have
7297 	 * right now.
7298 	 */
7299 	return count <= 1;
7300 }
7301 
7302 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7303 {
7304 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7305 	bool has_size = fn->arg_size[arg] != 0;
7306 	bool is_next_size = false;
7307 
7308 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7309 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7310 
7311 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7312 		return is_next_size;
7313 
7314 	return has_size == is_next_size || is_next_size == is_fixed;
7315 }
7316 
7317 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7318 {
7319 	/* bpf_xxx(..., buf, len) call will access 'len'
7320 	 * bytes from memory 'buf'. Both arg types need
7321 	 * to be paired, so make sure there's no buggy
7322 	 * helper function specification.
7323 	 */
7324 	if (arg_type_is_mem_size(fn->arg1_type) ||
7325 	    check_args_pair_invalid(fn, 0) ||
7326 	    check_args_pair_invalid(fn, 1) ||
7327 	    check_args_pair_invalid(fn, 2) ||
7328 	    check_args_pair_invalid(fn, 3) ||
7329 	    check_args_pair_invalid(fn, 4))
7330 		return false;
7331 
7332 	return true;
7333 }
7334 
7335 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7336 {
7337 	int i;
7338 
7339 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7340 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7341 			return !!fn->arg_btf_id[i];
7342 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7343 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7344 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7345 		    /* arg_btf_id and arg_size are in a union. */
7346 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7347 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7348 			return false;
7349 	}
7350 
7351 	return true;
7352 }
7353 
7354 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7355 {
7356 	return check_raw_mode_ok(fn) &&
7357 	       check_arg_pair_ok(fn) &&
7358 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7359 }
7360 
7361 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7362  * are now invalid, so turn them into unknown SCALAR_VALUE.
7363  */
7364 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7365 {
7366 	struct bpf_func_state *state;
7367 	struct bpf_reg_state *reg;
7368 
7369 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7370 		if (reg_is_pkt_pointer_any(reg))
7371 			__mark_reg_unknown(env, reg);
7372 	}));
7373 }
7374 
7375 enum {
7376 	AT_PKT_END = -1,
7377 	BEYOND_PKT_END = -2,
7378 };
7379 
7380 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7381 {
7382 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7383 	struct bpf_reg_state *reg = &state->regs[regn];
7384 
7385 	if (reg->type != PTR_TO_PACKET)
7386 		/* PTR_TO_PACKET_META is not supported yet */
7387 		return;
7388 
7389 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7390 	 * How far beyond pkt_end it goes is unknown.
7391 	 * if (!range_open) it's the case of pkt >= pkt_end
7392 	 * if (range_open) it's the case of pkt > pkt_end
7393 	 * hence this pointer is at least 1 byte bigger than pkt_end
7394 	 */
7395 	if (range_open)
7396 		reg->range = BEYOND_PKT_END;
7397 	else
7398 		reg->range = AT_PKT_END;
7399 }
7400 
7401 /* The pointer with the specified id has released its reference to kernel
7402  * resources. Identify all copies of the same pointer and clear the reference.
7403  */
7404 static int release_reference(struct bpf_verifier_env *env,
7405 			     int ref_obj_id)
7406 {
7407 	struct bpf_func_state *state;
7408 	struct bpf_reg_state *reg;
7409 	int err;
7410 
7411 	err = release_reference_state(cur_func(env), ref_obj_id);
7412 	if (err)
7413 		return err;
7414 
7415 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7416 		if (reg->ref_obj_id == ref_obj_id) {
7417 			if (!env->allow_ptr_leaks)
7418 				__mark_reg_not_init(env, reg);
7419 			else
7420 				__mark_reg_unknown(env, reg);
7421 		}
7422 	}));
7423 
7424 	return 0;
7425 }
7426 
7427 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7428 {
7429 	struct bpf_func_state *unused;
7430 	struct bpf_reg_state *reg;
7431 
7432 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7433 		if (type_is_non_owning_ref(reg->type))
7434 			__mark_reg_unknown(env, reg);
7435 	}));
7436 }
7437 
7438 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7439 				    struct bpf_reg_state *regs)
7440 {
7441 	int i;
7442 
7443 	/* after the call registers r0 - r5 were scratched */
7444 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7445 		mark_reg_not_init(env, regs, caller_saved[i]);
7446 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7447 	}
7448 }
7449 
7450 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7451 				   struct bpf_func_state *caller,
7452 				   struct bpf_func_state *callee,
7453 				   int insn_idx);
7454 
7455 static int set_callee_state(struct bpf_verifier_env *env,
7456 			    struct bpf_func_state *caller,
7457 			    struct bpf_func_state *callee, int insn_idx);
7458 
7459 static bool is_callback_calling_kfunc(u32 btf_id);
7460 
7461 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7462 			     int *insn_idx, int subprog,
7463 			     set_callee_state_fn set_callee_state_cb)
7464 {
7465 	struct bpf_verifier_state *state = env->cur_state;
7466 	struct bpf_func_info_aux *func_info_aux;
7467 	struct bpf_func_state *caller, *callee;
7468 	int err;
7469 	bool is_global = false;
7470 
7471 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7472 		verbose(env, "the call stack of %d frames is too deep\n",
7473 			state->curframe + 2);
7474 		return -E2BIG;
7475 	}
7476 
7477 	caller = state->frame[state->curframe];
7478 	if (state->frame[state->curframe + 1]) {
7479 		verbose(env, "verifier bug. Frame %d already allocated\n",
7480 			state->curframe + 1);
7481 		return -EFAULT;
7482 	}
7483 
7484 	func_info_aux = env->prog->aux->func_info_aux;
7485 	if (func_info_aux)
7486 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7487 	err = btf_check_subprog_call(env, subprog, caller->regs);
7488 	if (err == -EFAULT)
7489 		return err;
7490 	if (is_global) {
7491 		if (err) {
7492 			verbose(env, "Caller passes invalid args into func#%d\n",
7493 				subprog);
7494 			return err;
7495 		} else {
7496 			if (env->log.level & BPF_LOG_LEVEL)
7497 				verbose(env,
7498 					"Func#%d is global and valid. Skipping.\n",
7499 					subprog);
7500 			clear_caller_saved_regs(env, caller->regs);
7501 
7502 			/* All global functions return a 64-bit SCALAR_VALUE */
7503 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7504 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7505 
7506 			/* continue with next insn after call */
7507 			return 0;
7508 		}
7509 	}
7510 
7511 	/* set_callee_state is used for direct subprog calls, but we are
7512 	 * interested in validating only BPF helpers that can call subprogs as
7513 	 * callbacks
7514 	 */
7515 	if (set_callee_state_cb != set_callee_state) {
7516 		if (bpf_pseudo_kfunc_call(insn) &&
7517 		    !is_callback_calling_kfunc(insn->imm)) {
7518 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7519 				func_id_name(insn->imm), insn->imm);
7520 			return -EFAULT;
7521 		} else if (!bpf_pseudo_kfunc_call(insn) &&
7522 			   !is_callback_calling_function(insn->imm)) { /* helper */
7523 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7524 				func_id_name(insn->imm), insn->imm);
7525 			return -EFAULT;
7526 		}
7527 	}
7528 
7529 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7530 	    insn->src_reg == 0 &&
7531 	    insn->imm == BPF_FUNC_timer_set_callback) {
7532 		struct bpf_verifier_state *async_cb;
7533 
7534 		/* there is no real recursion here. timer callbacks are async */
7535 		env->subprog_info[subprog].is_async_cb = true;
7536 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7537 					 *insn_idx, subprog);
7538 		if (!async_cb)
7539 			return -EFAULT;
7540 		callee = async_cb->frame[0];
7541 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7542 
7543 		/* Convert bpf_timer_set_callback() args into timer callback args */
7544 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7545 		if (err)
7546 			return err;
7547 
7548 		clear_caller_saved_regs(env, caller->regs);
7549 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7550 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7551 		/* continue with next insn after call */
7552 		return 0;
7553 	}
7554 
7555 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7556 	if (!callee)
7557 		return -ENOMEM;
7558 	state->frame[state->curframe + 1] = callee;
7559 
7560 	/* callee cannot access r0, r6 - r9 for reading and has to write
7561 	 * into its own stack before reading from it.
7562 	 * callee can read/write into caller's stack
7563 	 */
7564 	init_func_state(env, callee,
7565 			/* remember the callsite, it will be used by bpf_exit */
7566 			*insn_idx /* callsite */,
7567 			state->curframe + 1 /* frameno within this callchain */,
7568 			subprog /* subprog number within this prog */);
7569 
7570 	/* Transfer references to the callee */
7571 	err = copy_reference_state(callee, caller);
7572 	if (err)
7573 		goto err_out;
7574 
7575 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7576 	if (err)
7577 		goto err_out;
7578 
7579 	clear_caller_saved_regs(env, caller->regs);
7580 
7581 	/* only increment it after check_reg_arg() finished */
7582 	state->curframe++;
7583 
7584 	/* and go analyze first insn of the callee */
7585 	*insn_idx = env->subprog_info[subprog].start - 1;
7586 
7587 	if (env->log.level & BPF_LOG_LEVEL) {
7588 		verbose(env, "caller:\n");
7589 		print_verifier_state(env, caller, true);
7590 		verbose(env, "callee:\n");
7591 		print_verifier_state(env, callee, true);
7592 	}
7593 	return 0;
7594 
7595 err_out:
7596 	free_func_state(callee);
7597 	state->frame[state->curframe + 1] = NULL;
7598 	return err;
7599 }
7600 
7601 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7602 				   struct bpf_func_state *caller,
7603 				   struct bpf_func_state *callee)
7604 {
7605 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7606 	 *      void *callback_ctx, u64 flags);
7607 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7608 	 *      void *callback_ctx);
7609 	 */
7610 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7611 
7612 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7613 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7614 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7615 
7616 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7617 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7618 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7619 
7620 	/* pointer to stack or null */
7621 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7622 
7623 	/* unused */
7624 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7625 	return 0;
7626 }
7627 
7628 static int set_callee_state(struct bpf_verifier_env *env,
7629 			    struct bpf_func_state *caller,
7630 			    struct bpf_func_state *callee, int insn_idx)
7631 {
7632 	int i;
7633 
7634 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7635 	 * pointers, which connects us up to the liveness chain
7636 	 */
7637 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7638 		callee->regs[i] = caller->regs[i];
7639 	return 0;
7640 }
7641 
7642 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7643 			   int *insn_idx)
7644 {
7645 	int subprog, target_insn;
7646 
7647 	target_insn = *insn_idx + insn->imm + 1;
7648 	subprog = find_subprog(env, target_insn);
7649 	if (subprog < 0) {
7650 		verbose(env, "verifier bug. No program starts at insn %d\n",
7651 			target_insn);
7652 		return -EFAULT;
7653 	}
7654 
7655 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7656 }
7657 
7658 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7659 				       struct bpf_func_state *caller,
7660 				       struct bpf_func_state *callee,
7661 				       int insn_idx)
7662 {
7663 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7664 	struct bpf_map *map;
7665 	int err;
7666 
7667 	if (bpf_map_ptr_poisoned(insn_aux)) {
7668 		verbose(env, "tail_call abusing map_ptr\n");
7669 		return -EINVAL;
7670 	}
7671 
7672 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7673 	if (!map->ops->map_set_for_each_callback_args ||
7674 	    !map->ops->map_for_each_callback) {
7675 		verbose(env, "callback function not allowed for map\n");
7676 		return -ENOTSUPP;
7677 	}
7678 
7679 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7680 	if (err)
7681 		return err;
7682 
7683 	callee->in_callback_fn = true;
7684 	callee->callback_ret_range = tnum_range(0, 1);
7685 	return 0;
7686 }
7687 
7688 static int set_loop_callback_state(struct bpf_verifier_env *env,
7689 				   struct bpf_func_state *caller,
7690 				   struct bpf_func_state *callee,
7691 				   int insn_idx)
7692 {
7693 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7694 	 *	    u64 flags);
7695 	 * callback_fn(u32 index, void *callback_ctx);
7696 	 */
7697 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7698 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7699 
7700 	/* unused */
7701 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7702 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7703 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7704 
7705 	callee->in_callback_fn = true;
7706 	callee->callback_ret_range = tnum_range(0, 1);
7707 	return 0;
7708 }
7709 
7710 static int set_timer_callback_state(struct bpf_verifier_env *env,
7711 				    struct bpf_func_state *caller,
7712 				    struct bpf_func_state *callee,
7713 				    int insn_idx)
7714 {
7715 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7716 
7717 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7718 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7719 	 */
7720 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7721 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7722 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7723 
7724 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7725 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7726 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7727 
7728 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7729 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7730 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7731 
7732 	/* unused */
7733 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7734 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7735 	callee->in_async_callback_fn = true;
7736 	callee->callback_ret_range = tnum_range(0, 1);
7737 	return 0;
7738 }
7739 
7740 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7741 				       struct bpf_func_state *caller,
7742 				       struct bpf_func_state *callee,
7743 				       int insn_idx)
7744 {
7745 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7746 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7747 	 * (callback_fn)(struct task_struct *task,
7748 	 *               struct vm_area_struct *vma, void *callback_ctx);
7749 	 */
7750 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7751 
7752 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7753 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7754 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7755 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7756 
7757 	/* pointer to stack or null */
7758 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7759 
7760 	/* unused */
7761 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7762 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7763 	callee->in_callback_fn = true;
7764 	callee->callback_ret_range = tnum_range(0, 1);
7765 	return 0;
7766 }
7767 
7768 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7769 					   struct bpf_func_state *caller,
7770 					   struct bpf_func_state *callee,
7771 					   int insn_idx)
7772 {
7773 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7774 	 *			  callback_ctx, u64 flags);
7775 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7776 	 */
7777 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7778 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7779 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7780 
7781 	/* unused */
7782 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7783 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7784 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7785 
7786 	callee->in_callback_fn = true;
7787 	callee->callback_ret_range = tnum_range(0, 1);
7788 	return 0;
7789 }
7790 
7791 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
7792 					 struct bpf_func_state *caller,
7793 					 struct bpf_func_state *callee,
7794 					 int insn_idx)
7795 {
7796 	/* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
7797 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
7798 	 *
7799 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
7800 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
7801 	 * by this point, so look at 'root'
7802 	 */
7803 	struct btf_field *field;
7804 
7805 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
7806 				      BPF_RB_ROOT);
7807 	if (!field || !field->graph_root.value_btf_id)
7808 		return -EFAULT;
7809 
7810 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
7811 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
7812 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
7813 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
7814 
7815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7817 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7818 	callee->in_callback_fn = true;
7819 	callee->callback_ret_range = tnum_range(0, 1);
7820 	return 0;
7821 }
7822 
7823 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
7824 
7825 /* Are we currently verifying the callback for a rbtree helper that must
7826  * be called with lock held? If so, no need to complain about unreleased
7827  * lock
7828  */
7829 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
7830 {
7831 	struct bpf_verifier_state *state = env->cur_state;
7832 	struct bpf_insn *insn = env->prog->insnsi;
7833 	struct bpf_func_state *callee;
7834 	int kfunc_btf_id;
7835 
7836 	if (!state->curframe)
7837 		return false;
7838 
7839 	callee = state->frame[state->curframe];
7840 
7841 	if (!callee->in_callback_fn)
7842 		return false;
7843 
7844 	kfunc_btf_id = insn[callee->callsite].imm;
7845 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
7846 }
7847 
7848 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7849 {
7850 	struct bpf_verifier_state *state = env->cur_state;
7851 	struct bpf_func_state *caller, *callee;
7852 	struct bpf_reg_state *r0;
7853 	int err;
7854 
7855 	callee = state->frame[state->curframe];
7856 	r0 = &callee->regs[BPF_REG_0];
7857 	if (r0->type == PTR_TO_STACK) {
7858 		/* technically it's ok to return caller's stack pointer
7859 		 * (or caller's caller's pointer) back to the caller,
7860 		 * since these pointers are valid. Only current stack
7861 		 * pointer will be invalid as soon as function exits,
7862 		 * but let's be conservative
7863 		 */
7864 		verbose(env, "cannot return stack pointer to the caller\n");
7865 		return -EINVAL;
7866 	}
7867 
7868 	caller = state->frame[state->curframe - 1];
7869 	if (callee->in_callback_fn) {
7870 		/* enforce R0 return value range [0, 1]. */
7871 		struct tnum range = callee->callback_ret_range;
7872 
7873 		if (r0->type != SCALAR_VALUE) {
7874 			verbose(env, "R0 not a scalar value\n");
7875 			return -EACCES;
7876 		}
7877 		if (!tnum_in(range, r0->var_off)) {
7878 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7879 			return -EINVAL;
7880 		}
7881 	} else {
7882 		/* return to the caller whatever r0 had in the callee */
7883 		caller->regs[BPF_REG_0] = *r0;
7884 	}
7885 
7886 	/* callback_fn frame should have released its own additions to parent's
7887 	 * reference state at this point, or check_reference_leak would
7888 	 * complain, hence it must be the same as the caller. There is no need
7889 	 * to copy it back.
7890 	 */
7891 	if (!callee->in_callback_fn) {
7892 		/* Transfer references to the caller */
7893 		err = copy_reference_state(caller, callee);
7894 		if (err)
7895 			return err;
7896 	}
7897 
7898 	*insn_idx = callee->callsite + 1;
7899 	if (env->log.level & BPF_LOG_LEVEL) {
7900 		verbose(env, "returning from callee:\n");
7901 		print_verifier_state(env, callee, true);
7902 		verbose(env, "to caller at %d:\n", *insn_idx);
7903 		print_verifier_state(env, caller, true);
7904 	}
7905 	/* clear everything in the callee */
7906 	free_func_state(callee);
7907 	state->frame[state->curframe--] = NULL;
7908 	return 0;
7909 }
7910 
7911 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7912 				   int func_id,
7913 				   struct bpf_call_arg_meta *meta)
7914 {
7915 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7916 
7917 	if (ret_type != RET_INTEGER ||
7918 	    (func_id != BPF_FUNC_get_stack &&
7919 	     func_id != BPF_FUNC_get_task_stack &&
7920 	     func_id != BPF_FUNC_probe_read_str &&
7921 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7922 	     func_id != BPF_FUNC_probe_read_user_str))
7923 		return;
7924 
7925 	ret_reg->smax_value = meta->msize_max_value;
7926 	ret_reg->s32_max_value = meta->msize_max_value;
7927 	ret_reg->smin_value = -MAX_ERRNO;
7928 	ret_reg->s32_min_value = -MAX_ERRNO;
7929 	reg_bounds_sync(ret_reg);
7930 }
7931 
7932 static int
7933 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7934 		int func_id, int insn_idx)
7935 {
7936 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7937 	struct bpf_map *map = meta->map_ptr;
7938 
7939 	if (func_id != BPF_FUNC_tail_call &&
7940 	    func_id != BPF_FUNC_map_lookup_elem &&
7941 	    func_id != BPF_FUNC_map_update_elem &&
7942 	    func_id != BPF_FUNC_map_delete_elem &&
7943 	    func_id != BPF_FUNC_map_push_elem &&
7944 	    func_id != BPF_FUNC_map_pop_elem &&
7945 	    func_id != BPF_FUNC_map_peek_elem &&
7946 	    func_id != BPF_FUNC_for_each_map_elem &&
7947 	    func_id != BPF_FUNC_redirect_map &&
7948 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7949 		return 0;
7950 
7951 	if (map == NULL) {
7952 		verbose(env, "kernel subsystem misconfigured verifier\n");
7953 		return -EINVAL;
7954 	}
7955 
7956 	/* In case of read-only, some additional restrictions
7957 	 * need to be applied in order to prevent altering the
7958 	 * state of the map from program side.
7959 	 */
7960 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7961 	    (func_id == BPF_FUNC_map_delete_elem ||
7962 	     func_id == BPF_FUNC_map_update_elem ||
7963 	     func_id == BPF_FUNC_map_push_elem ||
7964 	     func_id == BPF_FUNC_map_pop_elem)) {
7965 		verbose(env, "write into map forbidden\n");
7966 		return -EACCES;
7967 	}
7968 
7969 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7970 		bpf_map_ptr_store(aux, meta->map_ptr,
7971 				  !meta->map_ptr->bypass_spec_v1);
7972 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7973 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7974 				  !meta->map_ptr->bypass_spec_v1);
7975 	return 0;
7976 }
7977 
7978 static int
7979 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7980 		int func_id, int insn_idx)
7981 {
7982 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7983 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7984 	struct bpf_map *map = meta->map_ptr;
7985 	u64 val, max;
7986 	int err;
7987 
7988 	if (func_id != BPF_FUNC_tail_call)
7989 		return 0;
7990 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7991 		verbose(env, "kernel subsystem misconfigured verifier\n");
7992 		return -EINVAL;
7993 	}
7994 
7995 	reg = &regs[BPF_REG_3];
7996 	val = reg->var_off.value;
7997 	max = map->max_entries;
7998 
7999 	if (!(register_is_const(reg) && val < max)) {
8000 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8001 		return 0;
8002 	}
8003 
8004 	err = mark_chain_precision(env, BPF_REG_3);
8005 	if (err)
8006 		return err;
8007 	if (bpf_map_key_unseen(aux))
8008 		bpf_map_key_store(aux, val);
8009 	else if (!bpf_map_key_poisoned(aux) &&
8010 		  bpf_map_key_immediate(aux) != val)
8011 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8012 	return 0;
8013 }
8014 
8015 static int check_reference_leak(struct bpf_verifier_env *env)
8016 {
8017 	struct bpf_func_state *state = cur_func(env);
8018 	bool refs_lingering = false;
8019 	int i;
8020 
8021 	if (state->frameno && !state->in_callback_fn)
8022 		return 0;
8023 
8024 	for (i = 0; i < state->acquired_refs; i++) {
8025 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8026 			continue;
8027 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8028 			state->refs[i].id, state->refs[i].insn_idx);
8029 		refs_lingering = true;
8030 	}
8031 	return refs_lingering ? -EINVAL : 0;
8032 }
8033 
8034 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8035 				   struct bpf_reg_state *regs)
8036 {
8037 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8038 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8039 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
8040 	struct bpf_bprintf_data data = {};
8041 	int err, fmt_map_off, num_args;
8042 	u64 fmt_addr;
8043 	char *fmt;
8044 
8045 	/* data must be an array of u64 */
8046 	if (data_len_reg->var_off.value % 8)
8047 		return -EINVAL;
8048 	num_args = data_len_reg->var_off.value / 8;
8049 
8050 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8051 	 * and map_direct_value_addr is set.
8052 	 */
8053 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8054 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8055 						  fmt_map_off);
8056 	if (err) {
8057 		verbose(env, "verifier bug\n");
8058 		return -EFAULT;
8059 	}
8060 	fmt = (char *)(long)fmt_addr + fmt_map_off;
8061 
8062 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8063 	 * can focus on validating the format specifiers.
8064 	 */
8065 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8066 	if (err < 0)
8067 		verbose(env, "Invalid format string\n");
8068 
8069 	return err;
8070 }
8071 
8072 static int check_get_func_ip(struct bpf_verifier_env *env)
8073 {
8074 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8075 	int func_id = BPF_FUNC_get_func_ip;
8076 
8077 	if (type == BPF_PROG_TYPE_TRACING) {
8078 		if (!bpf_prog_has_trampoline(env->prog)) {
8079 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8080 				func_id_name(func_id), func_id);
8081 			return -ENOTSUPP;
8082 		}
8083 		return 0;
8084 	} else if (type == BPF_PROG_TYPE_KPROBE) {
8085 		return 0;
8086 	}
8087 
8088 	verbose(env, "func %s#%d not supported for program type %d\n",
8089 		func_id_name(func_id), func_id, type);
8090 	return -ENOTSUPP;
8091 }
8092 
8093 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8094 {
8095 	return &env->insn_aux_data[env->insn_idx];
8096 }
8097 
8098 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8099 {
8100 	struct bpf_reg_state *regs = cur_regs(env);
8101 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
8102 	bool reg_is_null = register_is_null(reg);
8103 
8104 	if (reg_is_null)
8105 		mark_chain_precision(env, BPF_REG_4);
8106 
8107 	return reg_is_null;
8108 }
8109 
8110 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8111 {
8112 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8113 
8114 	if (!state->initialized) {
8115 		state->initialized = 1;
8116 		state->fit_for_inline = loop_flag_is_zero(env);
8117 		state->callback_subprogno = subprogno;
8118 		return;
8119 	}
8120 
8121 	if (!state->fit_for_inline)
8122 		return;
8123 
8124 	state->fit_for_inline = (loop_flag_is_zero(env) &&
8125 				 state->callback_subprogno == subprogno);
8126 }
8127 
8128 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8129 			     int *insn_idx_p)
8130 {
8131 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8132 	const struct bpf_func_proto *fn = NULL;
8133 	enum bpf_return_type ret_type;
8134 	enum bpf_type_flag ret_flag;
8135 	struct bpf_reg_state *regs;
8136 	struct bpf_call_arg_meta meta;
8137 	int insn_idx = *insn_idx_p;
8138 	bool changes_data;
8139 	int i, err, func_id;
8140 
8141 	/* find function prototype */
8142 	func_id = insn->imm;
8143 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8144 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8145 			func_id);
8146 		return -EINVAL;
8147 	}
8148 
8149 	if (env->ops->get_func_proto)
8150 		fn = env->ops->get_func_proto(func_id, env->prog);
8151 	if (!fn) {
8152 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8153 			func_id);
8154 		return -EINVAL;
8155 	}
8156 
8157 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
8158 	if (!env->prog->gpl_compatible && fn->gpl_only) {
8159 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8160 		return -EINVAL;
8161 	}
8162 
8163 	if (fn->allowed && !fn->allowed(env->prog)) {
8164 		verbose(env, "helper call is not allowed in probe\n");
8165 		return -EINVAL;
8166 	}
8167 
8168 	if (!env->prog->aux->sleepable && fn->might_sleep) {
8169 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
8170 		return -EINVAL;
8171 	}
8172 
8173 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
8174 	changes_data = bpf_helper_changes_pkt_data(fn->func);
8175 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8176 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8177 			func_id_name(func_id), func_id);
8178 		return -EINVAL;
8179 	}
8180 
8181 	memset(&meta, 0, sizeof(meta));
8182 	meta.pkt_access = fn->pkt_access;
8183 
8184 	err = check_func_proto(fn, func_id);
8185 	if (err) {
8186 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8187 			func_id_name(func_id), func_id);
8188 		return err;
8189 	}
8190 
8191 	if (env->cur_state->active_rcu_lock) {
8192 		if (fn->might_sleep) {
8193 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8194 				func_id_name(func_id), func_id);
8195 			return -EINVAL;
8196 		}
8197 
8198 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8199 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8200 	}
8201 
8202 	meta.func_id = func_id;
8203 	/* check args */
8204 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8205 		err = check_func_arg(env, i, &meta, fn);
8206 		if (err)
8207 			return err;
8208 	}
8209 
8210 	err = record_func_map(env, &meta, func_id, insn_idx);
8211 	if (err)
8212 		return err;
8213 
8214 	err = record_func_key(env, &meta, func_id, insn_idx);
8215 	if (err)
8216 		return err;
8217 
8218 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
8219 	 * is inferred from register state.
8220 	 */
8221 	for (i = 0; i < meta.access_size; i++) {
8222 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8223 				       BPF_WRITE, -1, false);
8224 		if (err)
8225 			return err;
8226 	}
8227 
8228 	regs = cur_regs(env);
8229 
8230 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8231 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
8232 	 * is safe to do directly.
8233 	 */
8234 	if (meta.uninit_dynptr_regno) {
8235 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
8236 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
8237 			return -EFAULT;
8238 		}
8239 		/* we write BPF_DW bits (8 bytes) at a time */
8240 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8241 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
8242 					       i, BPF_DW, BPF_WRITE, -1, false);
8243 			if (err)
8244 				return err;
8245 		}
8246 
8247 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
8248 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
8249 					      insn_idx);
8250 		if (err)
8251 			return err;
8252 	}
8253 
8254 	if (meta.release_regno) {
8255 		err = -EINVAL;
8256 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8257 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8258 		 * is safe to do directly.
8259 		 */
8260 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8261 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8262 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8263 				return -EFAULT;
8264 			}
8265 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8266 		} else if (meta.ref_obj_id) {
8267 			err = release_reference(env, meta.ref_obj_id);
8268 		} else if (register_is_null(&regs[meta.release_regno])) {
8269 			/* meta.ref_obj_id can only be 0 if register that is meant to be
8270 			 * released is NULL, which must be > R0.
8271 			 */
8272 			err = 0;
8273 		}
8274 		if (err) {
8275 			verbose(env, "func %s#%d reference has not been acquired before\n",
8276 				func_id_name(func_id), func_id);
8277 			return err;
8278 		}
8279 	}
8280 
8281 	switch (func_id) {
8282 	case BPF_FUNC_tail_call:
8283 		err = check_reference_leak(env);
8284 		if (err) {
8285 			verbose(env, "tail_call would lead to reference leak\n");
8286 			return err;
8287 		}
8288 		break;
8289 	case BPF_FUNC_get_local_storage:
8290 		/* check that flags argument in get_local_storage(map, flags) is 0,
8291 		 * this is required because get_local_storage() can't return an error.
8292 		 */
8293 		if (!register_is_null(&regs[BPF_REG_2])) {
8294 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8295 			return -EINVAL;
8296 		}
8297 		break;
8298 	case BPF_FUNC_for_each_map_elem:
8299 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8300 					set_map_elem_callback_state);
8301 		break;
8302 	case BPF_FUNC_timer_set_callback:
8303 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8304 					set_timer_callback_state);
8305 		break;
8306 	case BPF_FUNC_find_vma:
8307 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8308 					set_find_vma_callback_state);
8309 		break;
8310 	case BPF_FUNC_snprintf:
8311 		err = check_bpf_snprintf_call(env, regs);
8312 		break;
8313 	case BPF_FUNC_loop:
8314 		update_loop_inline_state(env, meta.subprogno);
8315 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8316 					set_loop_callback_state);
8317 		break;
8318 	case BPF_FUNC_dynptr_from_mem:
8319 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8320 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8321 				reg_type_str(env, regs[BPF_REG_1].type));
8322 			return -EACCES;
8323 		}
8324 		break;
8325 	case BPF_FUNC_set_retval:
8326 		if (prog_type == BPF_PROG_TYPE_LSM &&
8327 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8328 			if (!env->prog->aux->attach_func_proto->type) {
8329 				/* Make sure programs that attach to void
8330 				 * hooks don't try to modify return value.
8331 				 */
8332 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8333 				return -EINVAL;
8334 			}
8335 		}
8336 		break;
8337 	case BPF_FUNC_dynptr_data:
8338 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8339 			if (arg_type_is_dynptr(fn->arg_type[i])) {
8340 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
8341 				int id, ref_obj_id;
8342 
8343 				if (meta.dynptr_id) {
8344 					verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8345 					return -EFAULT;
8346 				}
8347 
8348 				if (meta.ref_obj_id) {
8349 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8350 					return -EFAULT;
8351 				}
8352 
8353 				id = dynptr_id(env, reg);
8354 				if (id < 0) {
8355 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8356 					return id;
8357 				}
8358 
8359 				ref_obj_id = dynptr_ref_obj_id(env, reg);
8360 				if (ref_obj_id < 0) {
8361 					verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8362 					return ref_obj_id;
8363 				}
8364 
8365 				meta.dynptr_id = id;
8366 				meta.ref_obj_id = ref_obj_id;
8367 				break;
8368 			}
8369 		}
8370 		if (i == MAX_BPF_FUNC_REG_ARGS) {
8371 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
8372 			return -EFAULT;
8373 		}
8374 		break;
8375 	case BPF_FUNC_user_ringbuf_drain:
8376 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8377 					set_user_ringbuf_callback_state);
8378 		break;
8379 	}
8380 
8381 	if (err)
8382 		return err;
8383 
8384 	/* reset caller saved regs */
8385 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8386 		mark_reg_not_init(env, regs, caller_saved[i]);
8387 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8388 	}
8389 
8390 	/* helper call returns 64-bit value. */
8391 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8392 
8393 	/* update return register (already marked as written above) */
8394 	ret_type = fn->ret_type;
8395 	ret_flag = type_flag(ret_type);
8396 
8397 	switch (base_type(ret_type)) {
8398 	case RET_INTEGER:
8399 		/* sets type to SCALAR_VALUE */
8400 		mark_reg_unknown(env, regs, BPF_REG_0);
8401 		break;
8402 	case RET_VOID:
8403 		regs[BPF_REG_0].type = NOT_INIT;
8404 		break;
8405 	case RET_PTR_TO_MAP_VALUE:
8406 		/* There is no offset yet applied, variable or fixed */
8407 		mark_reg_known_zero(env, regs, BPF_REG_0);
8408 		/* remember map_ptr, so that check_map_access()
8409 		 * can check 'value_size' boundary of memory access
8410 		 * to map element returned from bpf_map_lookup_elem()
8411 		 */
8412 		if (meta.map_ptr == NULL) {
8413 			verbose(env,
8414 				"kernel subsystem misconfigured verifier\n");
8415 			return -EINVAL;
8416 		}
8417 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
8418 		regs[BPF_REG_0].map_uid = meta.map_uid;
8419 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8420 		if (!type_may_be_null(ret_type) &&
8421 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8422 			regs[BPF_REG_0].id = ++env->id_gen;
8423 		}
8424 		break;
8425 	case RET_PTR_TO_SOCKET:
8426 		mark_reg_known_zero(env, regs, BPF_REG_0);
8427 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8428 		break;
8429 	case RET_PTR_TO_SOCK_COMMON:
8430 		mark_reg_known_zero(env, regs, BPF_REG_0);
8431 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8432 		break;
8433 	case RET_PTR_TO_TCP_SOCK:
8434 		mark_reg_known_zero(env, regs, BPF_REG_0);
8435 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8436 		break;
8437 	case RET_PTR_TO_MEM:
8438 		mark_reg_known_zero(env, regs, BPF_REG_0);
8439 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8440 		regs[BPF_REG_0].mem_size = meta.mem_size;
8441 		break;
8442 	case RET_PTR_TO_MEM_OR_BTF_ID:
8443 	{
8444 		const struct btf_type *t;
8445 
8446 		mark_reg_known_zero(env, regs, BPF_REG_0);
8447 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8448 		if (!btf_type_is_struct(t)) {
8449 			u32 tsize;
8450 			const struct btf_type *ret;
8451 			const char *tname;
8452 
8453 			/* resolve the type size of ksym. */
8454 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8455 			if (IS_ERR(ret)) {
8456 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8457 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8458 					tname, PTR_ERR(ret));
8459 				return -EINVAL;
8460 			}
8461 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8462 			regs[BPF_REG_0].mem_size = tsize;
8463 		} else {
8464 			/* MEM_RDONLY may be carried from ret_flag, but it
8465 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8466 			 * it will confuse the check of PTR_TO_BTF_ID in
8467 			 * check_mem_access().
8468 			 */
8469 			ret_flag &= ~MEM_RDONLY;
8470 
8471 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8472 			regs[BPF_REG_0].btf = meta.ret_btf;
8473 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8474 		}
8475 		break;
8476 	}
8477 	case RET_PTR_TO_BTF_ID:
8478 	{
8479 		struct btf *ret_btf;
8480 		int ret_btf_id;
8481 
8482 		mark_reg_known_zero(env, regs, BPF_REG_0);
8483 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8484 		if (func_id == BPF_FUNC_kptr_xchg) {
8485 			ret_btf = meta.kptr_field->kptr.btf;
8486 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8487 		} else {
8488 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8489 				verbose(env, "verifier internal error:");
8490 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8491 					func_id_name(func_id));
8492 				return -EINVAL;
8493 			}
8494 			ret_btf = btf_vmlinux;
8495 			ret_btf_id = *fn->ret_btf_id;
8496 		}
8497 		if (ret_btf_id == 0) {
8498 			verbose(env, "invalid return type %u of func %s#%d\n",
8499 				base_type(ret_type), func_id_name(func_id),
8500 				func_id);
8501 			return -EINVAL;
8502 		}
8503 		regs[BPF_REG_0].btf = ret_btf;
8504 		regs[BPF_REG_0].btf_id = ret_btf_id;
8505 		break;
8506 	}
8507 	default:
8508 		verbose(env, "unknown return type %u of func %s#%d\n",
8509 			base_type(ret_type), func_id_name(func_id), func_id);
8510 		return -EINVAL;
8511 	}
8512 
8513 	if (type_may_be_null(regs[BPF_REG_0].type))
8514 		regs[BPF_REG_0].id = ++env->id_gen;
8515 
8516 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8517 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8518 			func_id_name(func_id), func_id);
8519 		return -EFAULT;
8520 	}
8521 
8522 	if (is_dynptr_ref_function(func_id))
8523 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8524 
8525 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8526 		/* For release_reference() */
8527 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8528 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8529 		int id = acquire_reference_state(env, insn_idx);
8530 
8531 		if (id < 0)
8532 			return id;
8533 		/* For mark_ptr_or_null_reg() */
8534 		regs[BPF_REG_0].id = id;
8535 		/* For release_reference() */
8536 		regs[BPF_REG_0].ref_obj_id = id;
8537 	}
8538 
8539 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8540 
8541 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8542 	if (err)
8543 		return err;
8544 
8545 	if ((func_id == BPF_FUNC_get_stack ||
8546 	     func_id == BPF_FUNC_get_task_stack) &&
8547 	    !env->prog->has_callchain_buf) {
8548 		const char *err_str;
8549 
8550 #ifdef CONFIG_PERF_EVENTS
8551 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8552 		err_str = "cannot get callchain buffer for func %s#%d\n";
8553 #else
8554 		err = -ENOTSUPP;
8555 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8556 #endif
8557 		if (err) {
8558 			verbose(env, err_str, func_id_name(func_id), func_id);
8559 			return err;
8560 		}
8561 
8562 		env->prog->has_callchain_buf = true;
8563 	}
8564 
8565 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8566 		env->prog->call_get_stack = true;
8567 
8568 	if (func_id == BPF_FUNC_get_func_ip) {
8569 		if (check_get_func_ip(env))
8570 			return -ENOTSUPP;
8571 		env->prog->call_get_func_ip = true;
8572 	}
8573 
8574 	if (changes_data)
8575 		clear_all_pkt_pointers(env);
8576 	return 0;
8577 }
8578 
8579 /* mark_btf_func_reg_size() is used when the reg size is determined by
8580  * the BTF func_proto's return value size and argument.
8581  */
8582 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8583 				   size_t reg_size)
8584 {
8585 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8586 
8587 	if (regno == BPF_REG_0) {
8588 		/* Function return value */
8589 		reg->live |= REG_LIVE_WRITTEN;
8590 		reg->subreg_def = reg_size == sizeof(u64) ?
8591 			DEF_NOT_SUBREG : env->insn_idx + 1;
8592 	} else {
8593 		/* Function argument */
8594 		if (reg_size == sizeof(u64)) {
8595 			mark_insn_zext(env, reg);
8596 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8597 		} else {
8598 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8599 		}
8600 	}
8601 }
8602 
8603 struct bpf_kfunc_call_arg_meta {
8604 	/* In parameters */
8605 	struct btf *btf;
8606 	u32 func_id;
8607 	u32 kfunc_flags;
8608 	const struct btf_type *func_proto;
8609 	const char *func_name;
8610 	/* Out parameters */
8611 	u32 ref_obj_id;
8612 	u8 release_regno;
8613 	bool r0_rdonly;
8614 	u32 ret_btf_id;
8615 	u64 r0_size;
8616 	u32 subprogno;
8617 	struct {
8618 		u64 value;
8619 		bool found;
8620 	} arg_constant;
8621 	struct {
8622 		struct btf *btf;
8623 		u32 btf_id;
8624 	} arg_obj_drop;
8625 	struct {
8626 		struct btf_field *field;
8627 	} arg_list_head;
8628 	struct {
8629 		struct btf_field *field;
8630 	} arg_rbtree_root;
8631 };
8632 
8633 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8634 {
8635 	return meta->kfunc_flags & KF_ACQUIRE;
8636 }
8637 
8638 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8639 {
8640 	return meta->kfunc_flags & KF_RET_NULL;
8641 }
8642 
8643 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8644 {
8645 	return meta->kfunc_flags & KF_RELEASE;
8646 }
8647 
8648 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8649 {
8650 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8651 }
8652 
8653 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8654 {
8655 	return meta->kfunc_flags & KF_SLEEPABLE;
8656 }
8657 
8658 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8659 {
8660 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8661 }
8662 
8663 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8664 {
8665 	return meta->kfunc_flags & KF_RCU;
8666 }
8667 
8668 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8669 {
8670 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8671 }
8672 
8673 static bool __kfunc_param_match_suffix(const struct btf *btf,
8674 				       const struct btf_param *arg,
8675 				       const char *suffix)
8676 {
8677 	int suffix_len = strlen(suffix), len;
8678 	const char *param_name;
8679 
8680 	/* In the future, this can be ported to use BTF tagging */
8681 	param_name = btf_name_by_offset(btf, arg->name_off);
8682 	if (str_is_empty(param_name))
8683 		return false;
8684 	len = strlen(param_name);
8685 	if (len < suffix_len)
8686 		return false;
8687 	param_name += len - suffix_len;
8688 	return !strncmp(param_name, suffix, suffix_len);
8689 }
8690 
8691 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8692 				  const struct btf_param *arg,
8693 				  const struct bpf_reg_state *reg)
8694 {
8695 	const struct btf_type *t;
8696 
8697 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8698 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8699 		return false;
8700 
8701 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8702 }
8703 
8704 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8705 {
8706 	return __kfunc_param_match_suffix(btf, arg, "__k");
8707 }
8708 
8709 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8710 {
8711 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8712 }
8713 
8714 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8715 {
8716 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8717 }
8718 
8719 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8720 					  const struct btf_param *arg,
8721 					  const char *name)
8722 {
8723 	int len, target_len = strlen(name);
8724 	const char *param_name;
8725 
8726 	param_name = btf_name_by_offset(btf, arg->name_off);
8727 	if (str_is_empty(param_name))
8728 		return false;
8729 	len = strlen(param_name);
8730 	if (len != target_len)
8731 		return false;
8732 	if (strcmp(param_name, name))
8733 		return false;
8734 
8735 	return true;
8736 }
8737 
8738 enum {
8739 	KF_ARG_DYNPTR_ID,
8740 	KF_ARG_LIST_HEAD_ID,
8741 	KF_ARG_LIST_NODE_ID,
8742 	KF_ARG_RB_ROOT_ID,
8743 	KF_ARG_RB_NODE_ID,
8744 };
8745 
8746 BTF_ID_LIST(kf_arg_btf_ids)
8747 BTF_ID(struct, bpf_dynptr_kern)
8748 BTF_ID(struct, bpf_list_head)
8749 BTF_ID(struct, bpf_list_node)
8750 BTF_ID(struct, bpf_rb_root)
8751 BTF_ID(struct, bpf_rb_node)
8752 
8753 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8754 				    const struct btf_param *arg, int type)
8755 {
8756 	const struct btf_type *t;
8757 	u32 res_id;
8758 
8759 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8760 	if (!t)
8761 		return false;
8762 	if (!btf_type_is_ptr(t))
8763 		return false;
8764 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8765 	if (!t)
8766 		return false;
8767 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8768 }
8769 
8770 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8771 {
8772 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8773 }
8774 
8775 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8776 {
8777 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8778 }
8779 
8780 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8781 {
8782 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8783 }
8784 
8785 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
8786 {
8787 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
8788 }
8789 
8790 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
8791 {
8792 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
8793 }
8794 
8795 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
8796 				  const struct btf_param *arg)
8797 {
8798 	const struct btf_type *t;
8799 
8800 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
8801 	if (!t)
8802 		return false;
8803 
8804 	return true;
8805 }
8806 
8807 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8808 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8809 					const struct btf *btf,
8810 					const struct btf_type *t, int rec)
8811 {
8812 	const struct btf_type *member_type;
8813 	const struct btf_member *member;
8814 	u32 i;
8815 
8816 	if (!btf_type_is_struct(t))
8817 		return false;
8818 
8819 	for_each_member(i, t, member) {
8820 		const struct btf_array *array;
8821 
8822 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8823 		if (btf_type_is_struct(member_type)) {
8824 			if (rec >= 3) {
8825 				verbose(env, "max struct nesting depth exceeded\n");
8826 				return false;
8827 			}
8828 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8829 				return false;
8830 			continue;
8831 		}
8832 		if (btf_type_is_array(member_type)) {
8833 			array = btf_array(member_type);
8834 			if (!array->nelems)
8835 				return false;
8836 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8837 			if (!btf_type_is_scalar(member_type))
8838 				return false;
8839 			continue;
8840 		}
8841 		if (!btf_type_is_scalar(member_type))
8842 			return false;
8843 	}
8844 	return true;
8845 }
8846 
8847 
8848 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8849 #ifdef CONFIG_NET
8850 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8851 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8852 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8853 #endif
8854 };
8855 
8856 enum kfunc_ptr_arg_type {
8857 	KF_ARG_PTR_TO_CTX,
8858 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8859 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8860 	KF_ARG_PTR_TO_DYNPTR,
8861 	KF_ARG_PTR_TO_LIST_HEAD,
8862 	KF_ARG_PTR_TO_LIST_NODE,
8863 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8864 	KF_ARG_PTR_TO_MEM,
8865 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8866 	KF_ARG_PTR_TO_CALLBACK,
8867 	KF_ARG_PTR_TO_RB_ROOT,
8868 	KF_ARG_PTR_TO_RB_NODE,
8869 };
8870 
8871 enum special_kfunc_type {
8872 	KF_bpf_obj_new_impl,
8873 	KF_bpf_obj_drop_impl,
8874 	KF_bpf_list_push_front,
8875 	KF_bpf_list_push_back,
8876 	KF_bpf_list_pop_front,
8877 	KF_bpf_list_pop_back,
8878 	KF_bpf_cast_to_kern_ctx,
8879 	KF_bpf_rdonly_cast,
8880 	KF_bpf_rcu_read_lock,
8881 	KF_bpf_rcu_read_unlock,
8882 	KF_bpf_rbtree_remove,
8883 	KF_bpf_rbtree_add,
8884 	KF_bpf_rbtree_first,
8885 };
8886 
8887 BTF_SET_START(special_kfunc_set)
8888 BTF_ID(func, bpf_obj_new_impl)
8889 BTF_ID(func, bpf_obj_drop_impl)
8890 BTF_ID(func, bpf_list_push_front)
8891 BTF_ID(func, bpf_list_push_back)
8892 BTF_ID(func, bpf_list_pop_front)
8893 BTF_ID(func, bpf_list_pop_back)
8894 BTF_ID(func, bpf_cast_to_kern_ctx)
8895 BTF_ID(func, bpf_rdonly_cast)
8896 BTF_ID(func, bpf_rbtree_remove)
8897 BTF_ID(func, bpf_rbtree_add)
8898 BTF_ID(func, bpf_rbtree_first)
8899 BTF_SET_END(special_kfunc_set)
8900 
8901 BTF_ID_LIST(special_kfunc_list)
8902 BTF_ID(func, bpf_obj_new_impl)
8903 BTF_ID(func, bpf_obj_drop_impl)
8904 BTF_ID(func, bpf_list_push_front)
8905 BTF_ID(func, bpf_list_push_back)
8906 BTF_ID(func, bpf_list_pop_front)
8907 BTF_ID(func, bpf_list_pop_back)
8908 BTF_ID(func, bpf_cast_to_kern_ctx)
8909 BTF_ID(func, bpf_rdonly_cast)
8910 BTF_ID(func, bpf_rcu_read_lock)
8911 BTF_ID(func, bpf_rcu_read_unlock)
8912 BTF_ID(func, bpf_rbtree_remove)
8913 BTF_ID(func, bpf_rbtree_add)
8914 BTF_ID(func, bpf_rbtree_first)
8915 
8916 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8917 {
8918 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8919 }
8920 
8921 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8922 {
8923 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8924 }
8925 
8926 static enum kfunc_ptr_arg_type
8927 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8928 		       struct bpf_kfunc_call_arg_meta *meta,
8929 		       const struct btf_type *t, const struct btf_type *ref_t,
8930 		       const char *ref_tname, const struct btf_param *args,
8931 		       int argno, int nargs)
8932 {
8933 	u32 regno = argno + 1;
8934 	struct bpf_reg_state *regs = cur_regs(env);
8935 	struct bpf_reg_state *reg = &regs[regno];
8936 	bool arg_mem_size = false;
8937 
8938 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8939 		return KF_ARG_PTR_TO_CTX;
8940 
8941 	/* In this function, we verify the kfunc's BTF as per the argument type,
8942 	 * leaving the rest of the verification with respect to the register
8943 	 * type to our caller. When a set of conditions hold in the BTF type of
8944 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8945 	 */
8946 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8947 		return KF_ARG_PTR_TO_CTX;
8948 
8949 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8950 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8951 
8952 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8953 		if (!btf_type_is_ptr(ref_t)) {
8954 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8955 			return -EINVAL;
8956 		}
8957 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8958 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8959 		if (!btf_type_is_struct(ref_t)) {
8960 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8961 				meta->func_name, btf_type_str(ref_t), ref_tname);
8962 			return -EINVAL;
8963 		}
8964 		return KF_ARG_PTR_TO_KPTR;
8965 	}
8966 
8967 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8968 		return KF_ARG_PTR_TO_DYNPTR;
8969 
8970 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8971 		return KF_ARG_PTR_TO_LIST_HEAD;
8972 
8973 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8974 		return KF_ARG_PTR_TO_LIST_NODE;
8975 
8976 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
8977 		return KF_ARG_PTR_TO_RB_ROOT;
8978 
8979 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
8980 		return KF_ARG_PTR_TO_RB_NODE;
8981 
8982 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8983 		if (!btf_type_is_struct(ref_t)) {
8984 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8985 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8986 			return -EINVAL;
8987 		}
8988 		return KF_ARG_PTR_TO_BTF_ID;
8989 	}
8990 
8991 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
8992 		return KF_ARG_PTR_TO_CALLBACK;
8993 
8994 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8995 		arg_mem_size = true;
8996 
8997 	/* This is the catch all argument type of register types supported by
8998 	 * check_helper_mem_access. However, we only allow when argument type is
8999 	 * pointer to scalar, or struct composed (recursively) of scalars. When
9000 	 * arg_mem_size is true, the pointer can be void *.
9001 	 */
9002 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9003 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9004 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9005 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9006 		return -EINVAL;
9007 	}
9008 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9009 }
9010 
9011 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9012 					struct bpf_reg_state *reg,
9013 					const struct btf_type *ref_t,
9014 					const char *ref_tname, u32 ref_id,
9015 					struct bpf_kfunc_call_arg_meta *meta,
9016 					int argno)
9017 {
9018 	const struct btf_type *reg_ref_t;
9019 	bool strict_type_match = false;
9020 	const struct btf *reg_btf;
9021 	const char *reg_ref_tname;
9022 	u32 reg_ref_id;
9023 
9024 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
9025 		reg_btf = reg->btf;
9026 		reg_ref_id = reg->btf_id;
9027 	} else {
9028 		reg_btf = btf_vmlinux;
9029 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9030 	}
9031 
9032 	/* Enforce strict type matching for calls to kfuncs that are acquiring
9033 	 * or releasing a reference, or are no-cast aliases. We do _not_
9034 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9035 	 * as we want to enable BPF programs to pass types that are bitwise
9036 	 * equivalent without forcing them to explicitly cast with something
9037 	 * like bpf_cast_to_kern_ctx().
9038 	 *
9039 	 * For example, say we had a type like the following:
9040 	 *
9041 	 * struct bpf_cpumask {
9042 	 *	cpumask_t cpumask;
9043 	 *	refcount_t usage;
9044 	 * };
9045 	 *
9046 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9047 	 * to a struct cpumask, so it would be safe to pass a struct
9048 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9049 	 *
9050 	 * The philosophy here is similar to how we allow scalars of different
9051 	 * types to be passed to kfuncs as long as the size is the same. The
9052 	 * only difference here is that we're simply allowing
9053 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9054 	 * resolve types.
9055 	 */
9056 	if (is_kfunc_acquire(meta) ||
9057 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
9058 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9059 		strict_type_match = true;
9060 
9061 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9062 
9063 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9064 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9065 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9066 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9067 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9068 			btf_type_str(reg_ref_t), reg_ref_tname);
9069 		return -EINVAL;
9070 	}
9071 	return 0;
9072 }
9073 
9074 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9075 				      struct bpf_reg_state *reg,
9076 				      const struct btf_type *ref_t,
9077 				      const char *ref_tname,
9078 				      struct bpf_kfunc_call_arg_meta *meta,
9079 				      int argno)
9080 {
9081 	struct btf_field *kptr_field;
9082 
9083 	/* check_func_arg_reg_off allows var_off for
9084 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9085 	 * off_desc.
9086 	 */
9087 	if (!tnum_is_const(reg->var_off)) {
9088 		verbose(env, "arg#0 must have constant offset\n");
9089 		return -EINVAL;
9090 	}
9091 
9092 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9093 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9094 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9095 			reg->off + reg->var_off.value);
9096 		return -EINVAL;
9097 	}
9098 
9099 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9100 				  kptr_field->kptr.btf_id, true)) {
9101 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9102 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9103 		return -EINVAL;
9104 	}
9105 	return 0;
9106 }
9107 
9108 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9109 {
9110 	struct bpf_verifier_state *state = env->cur_state;
9111 
9112 	if (!state->active_lock.ptr) {
9113 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9114 		return -EFAULT;
9115 	}
9116 
9117 	if (type_flag(reg->type) & NON_OWN_REF) {
9118 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9119 		return -EFAULT;
9120 	}
9121 
9122 	reg->type |= NON_OWN_REF;
9123 	return 0;
9124 }
9125 
9126 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9127 {
9128 	struct bpf_func_state *state, *unused;
9129 	struct bpf_reg_state *reg;
9130 	int i;
9131 
9132 	state = cur_func(env);
9133 
9134 	if (!ref_obj_id) {
9135 		verbose(env, "verifier internal error: ref_obj_id is zero for "
9136 			     "owning -> non-owning conversion\n");
9137 		return -EFAULT;
9138 	}
9139 
9140 	for (i = 0; i < state->acquired_refs; i++) {
9141 		if (state->refs[i].id != ref_obj_id)
9142 			continue;
9143 
9144 		/* Clear ref_obj_id here so release_reference doesn't clobber
9145 		 * the whole reg
9146 		 */
9147 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9148 			if (reg->ref_obj_id == ref_obj_id) {
9149 				reg->ref_obj_id = 0;
9150 				ref_set_non_owning(env, reg);
9151 			}
9152 		}));
9153 		return 0;
9154 	}
9155 
9156 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9157 	return -EFAULT;
9158 }
9159 
9160 /* Implementation details:
9161  *
9162  * Each register points to some region of memory, which we define as an
9163  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9164  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9165  * allocation. The lock and the data it protects are colocated in the same
9166  * memory region.
9167  *
9168  * Hence, everytime a register holds a pointer value pointing to such
9169  * allocation, the verifier preserves a unique reg->id for it.
9170  *
9171  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9172  * bpf_spin_lock is called.
9173  *
9174  * To enable this, lock state in the verifier captures two values:
9175  *	active_lock.ptr = Register's type specific pointer
9176  *	active_lock.id  = A unique ID for each register pointer value
9177  *
9178  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9179  * supported register types.
9180  *
9181  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9182  * allocated objects is the reg->btf pointer.
9183  *
9184  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9185  * can establish the provenance of the map value statically for each distinct
9186  * lookup into such maps. They always contain a single map value hence unique
9187  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9188  *
9189  * So, in case of global variables, they use array maps with max_entries = 1,
9190  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9191  * into the same map value as max_entries is 1, as described above).
9192  *
9193  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9194  * outer map pointer (in verifier context), but each lookup into an inner map
9195  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9196  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9197  * will get different reg->id assigned to each lookup, hence different
9198  * active_lock.id.
9199  *
9200  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9201  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9202  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9203  */
9204 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9205 {
9206 	void *ptr;
9207 	u32 id;
9208 
9209 	switch ((int)reg->type) {
9210 	case PTR_TO_MAP_VALUE:
9211 		ptr = reg->map_ptr;
9212 		break;
9213 	case PTR_TO_BTF_ID | MEM_ALLOC:
9214 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
9215 		ptr = reg->btf;
9216 		break;
9217 	default:
9218 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
9219 		return -EFAULT;
9220 	}
9221 	id = reg->id;
9222 
9223 	if (!env->cur_state->active_lock.ptr)
9224 		return -EINVAL;
9225 	if (env->cur_state->active_lock.ptr != ptr ||
9226 	    env->cur_state->active_lock.id != id) {
9227 		verbose(env, "held lock and object are not in the same allocation\n");
9228 		return -EINVAL;
9229 	}
9230 	return 0;
9231 }
9232 
9233 static bool is_bpf_list_api_kfunc(u32 btf_id)
9234 {
9235 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9236 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9237 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9238 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9239 }
9240 
9241 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9242 {
9243 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9244 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9245 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9246 }
9247 
9248 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9249 {
9250 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9251 }
9252 
9253 static bool is_callback_calling_kfunc(u32 btf_id)
9254 {
9255 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9256 }
9257 
9258 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9259 {
9260 	return is_bpf_rbtree_api_kfunc(btf_id);
9261 }
9262 
9263 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9264 					  enum btf_field_type head_field_type,
9265 					  u32 kfunc_btf_id)
9266 {
9267 	bool ret;
9268 
9269 	switch (head_field_type) {
9270 	case BPF_LIST_HEAD:
9271 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9272 		break;
9273 	case BPF_RB_ROOT:
9274 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9275 		break;
9276 	default:
9277 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9278 			btf_field_type_name(head_field_type));
9279 		return false;
9280 	}
9281 
9282 	if (!ret)
9283 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9284 			btf_field_type_name(head_field_type));
9285 	return ret;
9286 }
9287 
9288 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9289 					  enum btf_field_type node_field_type,
9290 					  u32 kfunc_btf_id)
9291 {
9292 	bool ret;
9293 
9294 	switch (node_field_type) {
9295 	case BPF_LIST_NODE:
9296 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9297 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9298 		break;
9299 	case BPF_RB_NODE:
9300 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9301 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9302 		break;
9303 	default:
9304 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9305 			btf_field_type_name(node_field_type));
9306 		return false;
9307 	}
9308 
9309 	if (!ret)
9310 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9311 			btf_field_type_name(node_field_type));
9312 	return ret;
9313 }
9314 
9315 static int
9316 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9317 				   struct bpf_reg_state *reg, u32 regno,
9318 				   struct bpf_kfunc_call_arg_meta *meta,
9319 				   enum btf_field_type head_field_type,
9320 				   struct btf_field **head_field)
9321 {
9322 	const char *head_type_name;
9323 	struct btf_field *field;
9324 	struct btf_record *rec;
9325 	u32 head_off;
9326 
9327 	if (meta->btf != btf_vmlinux) {
9328 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9329 		return -EFAULT;
9330 	}
9331 
9332 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9333 		return -EFAULT;
9334 
9335 	head_type_name = btf_field_type_name(head_field_type);
9336 	if (!tnum_is_const(reg->var_off)) {
9337 		verbose(env,
9338 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9339 			regno, head_type_name);
9340 		return -EINVAL;
9341 	}
9342 
9343 	rec = reg_btf_record(reg);
9344 	head_off = reg->off + reg->var_off.value;
9345 	field = btf_record_find(rec, head_off, head_field_type);
9346 	if (!field) {
9347 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9348 		return -EINVAL;
9349 	}
9350 
9351 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9352 	if (check_reg_allocation_locked(env, reg)) {
9353 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9354 			rec->spin_lock_off, head_type_name);
9355 		return -EINVAL;
9356 	}
9357 
9358 	if (*head_field) {
9359 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9360 		return -EFAULT;
9361 	}
9362 	*head_field = field;
9363 	return 0;
9364 }
9365 
9366 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9367 					   struct bpf_reg_state *reg, u32 regno,
9368 					   struct bpf_kfunc_call_arg_meta *meta)
9369 {
9370 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9371 							  &meta->arg_list_head.field);
9372 }
9373 
9374 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9375 					     struct bpf_reg_state *reg, u32 regno,
9376 					     struct bpf_kfunc_call_arg_meta *meta)
9377 {
9378 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9379 							  &meta->arg_rbtree_root.field);
9380 }
9381 
9382 static int
9383 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9384 				   struct bpf_reg_state *reg, u32 regno,
9385 				   struct bpf_kfunc_call_arg_meta *meta,
9386 				   enum btf_field_type head_field_type,
9387 				   enum btf_field_type node_field_type,
9388 				   struct btf_field **node_field)
9389 {
9390 	const char *node_type_name;
9391 	const struct btf_type *et, *t;
9392 	struct btf_field *field;
9393 	u32 node_off;
9394 
9395 	if (meta->btf != btf_vmlinux) {
9396 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9397 		return -EFAULT;
9398 	}
9399 
9400 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9401 		return -EFAULT;
9402 
9403 	node_type_name = btf_field_type_name(node_field_type);
9404 	if (!tnum_is_const(reg->var_off)) {
9405 		verbose(env,
9406 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9407 			regno, node_type_name);
9408 		return -EINVAL;
9409 	}
9410 
9411 	node_off = reg->off + reg->var_off.value;
9412 	field = reg_find_field_offset(reg, node_off, node_field_type);
9413 	if (!field || field->offset != node_off) {
9414 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9415 		return -EINVAL;
9416 	}
9417 
9418 	field = *node_field;
9419 
9420 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9421 	t = btf_type_by_id(reg->btf, reg->btf_id);
9422 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9423 				  field->graph_root.value_btf_id, true)) {
9424 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9425 			"in struct %s, but arg is at offset=%d in struct %s\n",
9426 			btf_field_type_name(head_field_type),
9427 			btf_field_type_name(node_field_type),
9428 			field->graph_root.node_offset,
9429 			btf_name_by_offset(field->graph_root.btf, et->name_off),
9430 			node_off, btf_name_by_offset(reg->btf, t->name_off));
9431 		return -EINVAL;
9432 	}
9433 
9434 	if (node_off != field->graph_root.node_offset) {
9435 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9436 			node_off, btf_field_type_name(node_field_type),
9437 			field->graph_root.node_offset,
9438 			btf_name_by_offset(field->graph_root.btf, et->name_off));
9439 		return -EINVAL;
9440 	}
9441 
9442 	return 0;
9443 }
9444 
9445 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9446 					   struct bpf_reg_state *reg, u32 regno,
9447 					   struct bpf_kfunc_call_arg_meta *meta)
9448 {
9449 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9450 						  BPF_LIST_HEAD, BPF_LIST_NODE,
9451 						  &meta->arg_list_head.field);
9452 }
9453 
9454 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9455 					     struct bpf_reg_state *reg, u32 regno,
9456 					     struct bpf_kfunc_call_arg_meta *meta)
9457 {
9458 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9459 						  BPF_RB_ROOT, BPF_RB_NODE,
9460 						  &meta->arg_rbtree_root.field);
9461 }
9462 
9463 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
9464 {
9465 	const char *func_name = meta->func_name, *ref_tname;
9466 	const struct btf *btf = meta->btf;
9467 	const struct btf_param *args;
9468 	u32 i, nargs;
9469 	int ret;
9470 
9471 	args = (const struct btf_param *)(meta->func_proto + 1);
9472 	nargs = btf_type_vlen(meta->func_proto);
9473 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9474 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9475 			MAX_BPF_FUNC_REG_ARGS);
9476 		return -EINVAL;
9477 	}
9478 
9479 	/* Check that BTF function arguments match actual types that the
9480 	 * verifier sees.
9481 	 */
9482 	for (i = 0; i < nargs; i++) {
9483 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9484 		const struct btf_type *t, *ref_t, *resolve_ret;
9485 		enum bpf_arg_type arg_type = ARG_DONTCARE;
9486 		u32 regno = i + 1, ref_id, type_size;
9487 		bool is_ret_buf_sz = false;
9488 		int kf_arg_type;
9489 
9490 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9491 
9492 		if (is_kfunc_arg_ignore(btf, &args[i]))
9493 			continue;
9494 
9495 		if (btf_type_is_scalar(t)) {
9496 			if (reg->type != SCALAR_VALUE) {
9497 				verbose(env, "R%d is not a scalar\n", regno);
9498 				return -EINVAL;
9499 			}
9500 
9501 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9502 				if (meta->arg_constant.found) {
9503 					verbose(env, "verifier internal error: only one constant argument permitted\n");
9504 					return -EFAULT;
9505 				}
9506 				if (!tnum_is_const(reg->var_off)) {
9507 					verbose(env, "R%d must be a known constant\n", regno);
9508 					return -EINVAL;
9509 				}
9510 				ret = mark_chain_precision(env, regno);
9511 				if (ret < 0)
9512 					return ret;
9513 				meta->arg_constant.found = true;
9514 				meta->arg_constant.value = reg->var_off.value;
9515 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9516 				meta->r0_rdonly = true;
9517 				is_ret_buf_sz = true;
9518 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9519 				is_ret_buf_sz = true;
9520 			}
9521 
9522 			if (is_ret_buf_sz) {
9523 				if (meta->r0_size) {
9524 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9525 					return -EINVAL;
9526 				}
9527 
9528 				if (!tnum_is_const(reg->var_off)) {
9529 					verbose(env, "R%d is not a const\n", regno);
9530 					return -EINVAL;
9531 				}
9532 
9533 				meta->r0_size = reg->var_off.value;
9534 				ret = mark_chain_precision(env, regno);
9535 				if (ret)
9536 					return ret;
9537 			}
9538 			continue;
9539 		}
9540 
9541 		if (!btf_type_is_ptr(t)) {
9542 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9543 			return -EINVAL;
9544 		}
9545 
9546 		if (is_kfunc_trusted_args(meta) &&
9547 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
9548 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9549 			return -EACCES;
9550 		}
9551 
9552 		if (reg->ref_obj_id) {
9553 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
9554 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9555 					regno, reg->ref_obj_id,
9556 					meta->ref_obj_id);
9557 				return -EFAULT;
9558 			}
9559 			meta->ref_obj_id = reg->ref_obj_id;
9560 			if (is_kfunc_release(meta))
9561 				meta->release_regno = regno;
9562 		}
9563 
9564 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9565 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9566 
9567 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9568 		if (kf_arg_type < 0)
9569 			return kf_arg_type;
9570 
9571 		switch (kf_arg_type) {
9572 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9573 		case KF_ARG_PTR_TO_BTF_ID:
9574 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9575 				break;
9576 
9577 			if (!is_trusted_reg(reg)) {
9578 				if (!is_kfunc_rcu(meta)) {
9579 					verbose(env, "R%d must be referenced or trusted\n", regno);
9580 					return -EINVAL;
9581 				}
9582 				if (!is_rcu_reg(reg)) {
9583 					verbose(env, "R%d must be a rcu pointer\n", regno);
9584 					return -EINVAL;
9585 				}
9586 			}
9587 
9588 			fallthrough;
9589 		case KF_ARG_PTR_TO_CTX:
9590 			/* Trusted arguments have the same offset checks as release arguments */
9591 			arg_type |= OBJ_RELEASE;
9592 			break;
9593 		case KF_ARG_PTR_TO_KPTR:
9594 		case KF_ARG_PTR_TO_DYNPTR:
9595 		case KF_ARG_PTR_TO_LIST_HEAD:
9596 		case KF_ARG_PTR_TO_LIST_NODE:
9597 		case KF_ARG_PTR_TO_RB_ROOT:
9598 		case KF_ARG_PTR_TO_RB_NODE:
9599 		case KF_ARG_PTR_TO_MEM:
9600 		case KF_ARG_PTR_TO_MEM_SIZE:
9601 		case KF_ARG_PTR_TO_CALLBACK:
9602 			/* Trusted by default */
9603 			break;
9604 		default:
9605 			WARN_ON_ONCE(1);
9606 			return -EFAULT;
9607 		}
9608 
9609 		if (is_kfunc_release(meta) && reg->ref_obj_id)
9610 			arg_type |= OBJ_RELEASE;
9611 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9612 		if (ret < 0)
9613 			return ret;
9614 
9615 		switch (kf_arg_type) {
9616 		case KF_ARG_PTR_TO_CTX:
9617 			if (reg->type != PTR_TO_CTX) {
9618 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9619 				return -EINVAL;
9620 			}
9621 
9622 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9623 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9624 				if (ret < 0)
9625 					return -EINVAL;
9626 				meta->ret_btf_id  = ret;
9627 			}
9628 			break;
9629 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9630 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9631 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9632 				return -EINVAL;
9633 			}
9634 			if (!reg->ref_obj_id) {
9635 				verbose(env, "allocated object must be referenced\n");
9636 				return -EINVAL;
9637 			}
9638 			if (meta->btf == btf_vmlinux &&
9639 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9640 				meta->arg_obj_drop.btf = reg->btf;
9641 				meta->arg_obj_drop.btf_id = reg->btf_id;
9642 			}
9643 			break;
9644 		case KF_ARG_PTR_TO_KPTR:
9645 			if (reg->type != PTR_TO_MAP_VALUE) {
9646 				verbose(env, "arg#0 expected pointer to map value\n");
9647 				return -EINVAL;
9648 			}
9649 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9650 			if (ret < 0)
9651 				return ret;
9652 			break;
9653 		case KF_ARG_PTR_TO_DYNPTR:
9654 			if (reg->type != PTR_TO_STACK &&
9655 			    reg->type != CONST_PTR_TO_DYNPTR) {
9656 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9657 				return -EINVAL;
9658 			}
9659 
9660 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
9661 			if (ret < 0)
9662 				return ret;
9663 			break;
9664 		case KF_ARG_PTR_TO_LIST_HEAD:
9665 			if (reg->type != PTR_TO_MAP_VALUE &&
9666 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9667 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9668 				return -EINVAL;
9669 			}
9670 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9671 				verbose(env, "allocated object must be referenced\n");
9672 				return -EINVAL;
9673 			}
9674 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9675 			if (ret < 0)
9676 				return ret;
9677 			break;
9678 		case KF_ARG_PTR_TO_RB_ROOT:
9679 			if (reg->type != PTR_TO_MAP_VALUE &&
9680 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9681 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9682 				return -EINVAL;
9683 			}
9684 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9685 				verbose(env, "allocated object must be referenced\n");
9686 				return -EINVAL;
9687 			}
9688 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9689 			if (ret < 0)
9690 				return ret;
9691 			break;
9692 		case KF_ARG_PTR_TO_LIST_NODE:
9693 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9694 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9695 				return -EINVAL;
9696 			}
9697 			if (!reg->ref_obj_id) {
9698 				verbose(env, "allocated object must be referenced\n");
9699 				return -EINVAL;
9700 			}
9701 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9702 			if (ret < 0)
9703 				return ret;
9704 			break;
9705 		case KF_ARG_PTR_TO_RB_NODE:
9706 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9707 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9708 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
9709 					return -EINVAL;
9710 				}
9711 				if (in_rbtree_lock_required_cb(env)) {
9712 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9713 					return -EINVAL;
9714 				}
9715 			} else {
9716 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9717 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
9718 					return -EINVAL;
9719 				}
9720 				if (!reg->ref_obj_id) {
9721 					verbose(env, "allocated object must be referenced\n");
9722 					return -EINVAL;
9723 				}
9724 			}
9725 
9726 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
9727 			if (ret < 0)
9728 				return ret;
9729 			break;
9730 		case KF_ARG_PTR_TO_BTF_ID:
9731 			/* Only base_type is checked, further checks are done here */
9732 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9733 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9734 			    !reg2btf_ids[base_type(reg->type)]) {
9735 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9736 				verbose(env, "expected %s or socket\n",
9737 					reg_type_str(env, base_type(reg->type) |
9738 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9739 				return -EINVAL;
9740 			}
9741 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9742 			if (ret < 0)
9743 				return ret;
9744 			break;
9745 		case KF_ARG_PTR_TO_MEM:
9746 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9747 			if (IS_ERR(resolve_ret)) {
9748 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9749 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9750 				return -EINVAL;
9751 			}
9752 			ret = check_mem_reg(env, reg, regno, type_size);
9753 			if (ret < 0)
9754 				return ret;
9755 			break;
9756 		case KF_ARG_PTR_TO_MEM_SIZE:
9757 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9758 			if (ret < 0) {
9759 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9760 				return ret;
9761 			}
9762 			/* Skip next '__sz' argument */
9763 			i++;
9764 			break;
9765 		case KF_ARG_PTR_TO_CALLBACK:
9766 			meta->subprogno = reg->subprogno;
9767 			break;
9768 		}
9769 	}
9770 
9771 	if (is_kfunc_release(meta) && !meta->release_regno) {
9772 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9773 			func_name);
9774 		return -EINVAL;
9775 	}
9776 
9777 	return 0;
9778 }
9779 
9780 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9781 			    int *insn_idx_p)
9782 {
9783 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9784 	u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
9785 	struct bpf_reg_state *regs = cur_regs(env);
9786 	const char *func_name, *ptr_type_name;
9787 	bool sleepable, rcu_lock, rcu_unlock;
9788 	struct bpf_kfunc_call_arg_meta meta;
9789 	int err, insn_idx = *insn_idx_p;
9790 	const struct btf_param *args;
9791 	const struct btf_type *ret_t;
9792 	struct btf *desc_btf;
9793 	u32 *kfunc_flags;
9794 
9795 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9796 	if (!insn->imm)
9797 		return 0;
9798 
9799 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9800 	if (IS_ERR(desc_btf))
9801 		return PTR_ERR(desc_btf);
9802 
9803 	func_id = insn->imm;
9804 	func = btf_type_by_id(desc_btf, func_id);
9805 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9806 	func_proto = btf_type_by_id(desc_btf, func->type);
9807 
9808 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9809 	if (!kfunc_flags) {
9810 		verbose(env, "calling kernel function %s is not allowed\n",
9811 			func_name);
9812 		return -EACCES;
9813 	}
9814 
9815 	/* Prepare kfunc call metadata */
9816 	memset(&meta, 0, sizeof(meta));
9817 	meta.btf = desc_btf;
9818 	meta.func_id = func_id;
9819 	meta.kfunc_flags = *kfunc_flags;
9820 	meta.func_proto = func_proto;
9821 	meta.func_name = func_name;
9822 
9823 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9824 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9825 		return -EACCES;
9826 	}
9827 
9828 	sleepable = is_kfunc_sleepable(&meta);
9829 	if (sleepable && !env->prog->aux->sleepable) {
9830 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9831 		return -EACCES;
9832 	}
9833 
9834 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9835 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9836 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9837 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9838 		return -EACCES;
9839 	}
9840 
9841 	if (env->cur_state->active_rcu_lock) {
9842 		struct bpf_func_state *state;
9843 		struct bpf_reg_state *reg;
9844 
9845 		if (rcu_lock) {
9846 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9847 			return -EINVAL;
9848 		} else if (rcu_unlock) {
9849 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9850 				if (reg->type & MEM_RCU) {
9851 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9852 					reg->type |= PTR_UNTRUSTED;
9853 				}
9854 			}));
9855 			env->cur_state->active_rcu_lock = false;
9856 		} else if (sleepable) {
9857 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9858 			return -EACCES;
9859 		}
9860 	} else if (rcu_lock) {
9861 		env->cur_state->active_rcu_lock = true;
9862 	} else if (rcu_unlock) {
9863 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9864 		return -EINVAL;
9865 	}
9866 
9867 	/* Check the arguments */
9868 	err = check_kfunc_args(env, &meta);
9869 	if (err < 0)
9870 		return err;
9871 	/* In case of release function, we get register number of refcounted
9872 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9873 	 */
9874 	if (meta.release_regno) {
9875 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9876 		if (err) {
9877 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9878 				func_name, func_id);
9879 			return err;
9880 		}
9881 	}
9882 
9883 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
9884 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
9885 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9886 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
9887 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
9888 		if (err) {
9889 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
9890 				func_name, func_id);
9891 			return err;
9892 		}
9893 
9894 		err = release_reference(env, release_ref_obj_id);
9895 		if (err) {
9896 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9897 				func_name, func_id);
9898 			return err;
9899 		}
9900 	}
9901 
9902 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9903 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9904 					set_rbtree_add_callback_state);
9905 		if (err) {
9906 			verbose(env, "kfunc %s#%d failed callback verification\n",
9907 				func_name, func_id);
9908 			return err;
9909 		}
9910 	}
9911 
9912 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9913 		mark_reg_not_init(env, regs, caller_saved[i]);
9914 
9915 	/* Check return type */
9916 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9917 
9918 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9919 		/* Only exception is bpf_obj_new_impl */
9920 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9921 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9922 			return -EINVAL;
9923 		}
9924 	}
9925 
9926 	if (btf_type_is_scalar(t)) {
9927 		mark_reg_unknown(env, regs, BPF_REG_0);
9928 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9929 	} else if (btf_type_is_ptr(t)) {
9930 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9931 
9932 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9933 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9934 				struct btf *ret_btf;
9935 				u32 ret_btf_id;
9936 
9937 				if (unlikely(!bpf_global_ma_set))
9938 					return -ENOMEM;
9939 
9940 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9941 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9942 					return -EINVAL;
9943 				}
9944 
9945 				ret_btf = env->prog->aux->btf;
9946 				ret_btf_id = meta.arg_constant.value;
9947 
9948 				/* This may be NULL due to user not supplying a BTF */
9949 				if (!ret_btf) {
9950 					verbose(env, "bpf_obj_new requires prog BTF\n");
9951 					return -EINVAL;
9952 				}
9953 
9954 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9955 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9956 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9957 					return -EINVAL;
9958 				}
9959 
9960 				mark_reg_known_zero(env, regs, BPF_REG_0);
9961 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9962 				regs[BPF_REG_0].btf = ret_btf;
9963 				regs[BPF_REG_0].btf_id = ret_btf_id;
9964 
9965 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9966 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9967 					btf_find_struct_meta(ret_btf, ret_btf_id);
9968 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9969 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9970 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9971 							     meta.arg_obj_drop.btf_id);
9972 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9973 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9974 				struct btf_field *field = meta.arg_list_head.field;
9975 
9976 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9977 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9978 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
9979 				struct btf_field *field = meta.arg_rbtree_root.field;
9980 
9981 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9982 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9983 				mark_reg_known_zero(env, regs, BPF_REG_0);
9984 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9985 				regs[BPF_REG_0].btf = desc_btf;
9986 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9987 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9988 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9989 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9990 					verbose(env,
9991 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9992 					return -EINVAL;
9993 				}
9994 
9995 				mark_reg_known_zero(env, regs, BPF_REG_0);
9996 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9997 				regs[BPF_REG_0].btf = desc_btf;
9998 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9999 			} else {
10000 				verbose(env, "kernel function %s unhandled dynamic return type\n",
10001 					meta.func_name);
10002 				return -EFAULT;
10003 			}
10004 		} else if (!__btf_type_is_struct(ptr_type)) {
10005 			if (!meta.r0_size) {
10006 				ptr_type_name = btf_name_by_offset(desc_btf,
10007 								   ptr_type->name_off);
10008 				verbose(env,
10009 					"kernel function %s returns pointer type %s %s is not supported\n",
10010 					func_name,
10011 					btf_type_str(ptr_type),
10012 					ptr_type_name);
10013 				return -EINVAL;
10014 			}
10015 
10016 			mark_reg_known_zero(env, regs, BPF_REG_0);
10017 			regs[BPF_REG_0].type = PTR_TO_MEM;
10018 			regs[BPF_REG_0].mem_size = meta.r0_size;
10019 
10020 			if (meta.r0_rdonly)
10021 				regs[BPF_REG_0].type |= MEM_RDONLY;
10022 
10023 			/* Ensures we don't access the memory after a release_reference() */
10024 			if (meta.ref_obj_id)
10025 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10026 		} else {
10027 			mark_reg_known_zero(env, regs, BPF_REG_0);
10028 			regs[BPF_REG_0].btf = desc_btf;
10029 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10030 			regs[BPF_REG_0].btf_id = ptr_type_id;
10031 		}
10032 
10033 		if (is_kfunc_ret_null(&meta)) {
10034 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10035 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10036 			regs[BPF_REG_0].id = ++env->id_gen;
10037 		}
10038 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10039 		if (is_kfunc_acquire(&meta)) {
10040 			int id = acquire_reference_state(env, insn_idx);
10041 
10042 			if (id < 0)
10043 				return id;
10044 			if (is_kfunc_ret_null(&meta))
10045 				regs[BPF_REG_0].id = id;
10046 			regs[BPF_REG_0].ref_obj_id = id;
10047 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10048 			ref_set_non_owning(env, &regs[BPF_REG_0]);
10049 		}
10050 
10051 		if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10052 			invalidate_non_owning_refs(env);
10053 
10054 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10055 			regs[BPF_REG_0].id = ++env->id_gen;
10056 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10057 
10058 	nargs = btf_type_vlen(func_proto);
10059 	args = (const struct btf_param *)(func_proto + 1);
10060 	for (i = 0; i < nargs; i++) {
10061 		u32 regno = i + 1;
10062 
10063 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10064 		if (btf_type_is_ptr(t))
10065 			mark_btf_func_reg_size(env, regno, sizeof(void *));
10066 		else
10067 			/* scalar. ensured by btf_check_kfunc_arg_match() */
10068 			mark_btf_func_reg_size(env, regno, t->size);
10069 	}
10070 
10071 	return 0;
10072 }
10073 
10074 static bool signed_add_overflows(s64 a, s64 b)
10075 {
10076 	/* Do the add in u64, where overflow is well-defined */
10077 	s64 res = (s64)((u64)a + (u64)b);
10078 
10079 	if (b < 0)
10080 		return res > a;
10081 	return res < a;
10082 }
10083 
10084 static bool signed_add32_overflows(s32 a, s32 b)
10085 {
10086 	/* Do the add in u32, where overflow is well-defined */
10087 	s32 res = (s32)((u32)a + (u32)b);
10088 
10089 	if (b < 0)
10090 		return res > a;
10091 	return res < a;
10092 }
10093 
10094 static bool signed_sub_overflows(s64 a, s64 b)
10095 {
10096 	/* Do the sub in u64, where overflow is well-defined */
10097 	s64 res = (s64)((u64)a - (u64)b);
10098 
10099 	if (b < 0)
10100 		return res < a;
10101 	return res > a;
10102 }
10103 
10104 static bool signed_sub32_overflows(s32 a, s32 b)
10105 {
10106 	/* Do the sub in u32, where overflow is well-defined */
10107 	s32 res = (s32)((u32)a - (u32)b);
10108 
10109 	if (b < 0)
10110 		return res < a;
10111 	return res > a;
10112 }
10113 
10114 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10115 				  const struct bpf_reg_state *reg,
10116 				  enum bpf_reg_type type)
10117 {
10118 	bool known = tnum_is_const(reg->var_off);
10119 	s64 val = reg->var_off.value;
10120 	s64 smin = reg->smin_value;
10121 
10122 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10123 		verbose(env, "math between %s pointer and %lld is not allowed\n",
10124 			reg_type_str(env, type), val);
10125 		return false;
10126 	}
10127 
10128 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10129 		verbose(env, "%s pointer offset %d is not allowed\n",
10130 			reg_type_str(env, type), reg->off);
10131 		return false;
10132 	}
10133 
10134 	if (smin == S64_MIN) {
10135 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10136 			reg_type_str(env, type));
10137 		return false;
10138 	}
10139 
10140 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10141 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
10142 			smin, reg_type_str(env, type));
10143 		return false;
10144 	}
10145 
10146 	return true;
10147 }
10148 
10149 enum {
10150 	REASON_BOUNDS	= -1,
10151 	REASON_TYPE	= -2,
10152 	REASON_PATHS	= -3,
10153 	REASON_LIMIT	= -4,
10154 	REASON_STACK	= -5,
10155 };
10156 
10157 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10158 			      u32 *alu_limit, bool mask_to_left)
10159 {
10160 	u32 max = 0, ptr_limit = 0;
10161 
10162 	switch (ptr_reg->type) {
10163 	case PTR_TO_STACK:
10164 		/* Offset 0 is out-of-bounds, but acceptable start for the
10165 		 * left direction, see BPF_REG_FP. Also, unknown scalar
10166 		 * offset where we would need to deal with min/max bounds is
10167 		 * currently prohibited for unprivileged.
10168 		 */
10169 		max = MAX_BPF_STACK + mask_to_left;
10170 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10171 		break;
10172 	case PTR_TO_MAP_VALUE:
10173 		max = ptr_reg->map_ptr->value_size;
10174 		ptr_limit = (mask_to_left ?
10175 			     ptr_reg->smin_value :
10176 			     ptr_reg->umax_value) + ptr_reg->off;
10177 		break;
10178 	default:
10179 		return REASON_TYPE;
10180 	}
10181 
10182 	if (ptr_limit >= max)
10183 		return REASON_LIMIT;
10184 	*alu_limit = ptr_limit;
10185 	return 0;
10186 }
10187 
10188 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10189 				    const struct bpf_insn *insn)
10190 {
10191 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10192 }
10193 
10194 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10195 				       u32 alu_state, u32 alu_limit)
10196 {
10197 	/* If we arrived here from different branches with different
10198 	 * state or limits to sanitize, then this won't work.
10199 	 */
10200 	if (aux->alu_state &&
10201 	    (aux->alu_state != alu_state ||
10202 	     aux->alu_limit != alu_limit))
10203 		return REASON_PATHS;
10204 
10205 	/* Corresponding fixup done in do_misc_fixups(). */
10206 	aux->alu_state = alu_state;
10207 	aux->alu_limit = alu_limit;
10208 	return 0;
10209 }
10210 
10211 static int sanitize_val_alu(struct bpf_verifier_env *env,
10212 			    struct bpf_insn *insn)
10213 {
10214 	struct bpf_insn_aux_data *aux = cur_aux(env);
10215 
10216 	if (can_skip_alu_sanitation(env, insn))
10217 		return 0;
10218 
10219 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10220 }
10221 
10222 static bool sanitize_needed(u8 opcode)
10223 {
10224 	return opcode == BPF_ADD || opcode == BPF_SUB;
10225 }
10226 
10227 struct bpf_sanitize_info {
10228 	struct bpf_insn_aux_data aux;
10229 	bool mask_to_left;
10230 };
10231 
10232 static struct bpf_verifier_state *
10233 sanitize_speculative_path(struct bpf_verifier_env *env,
10234 			  const struct bpf_insn *insn,
10235 			  u32 next_idx, u32 curr_idx)
10236 {
10237 	struct bpf_verifier_state *branch;
10238 	struct bpf_reg_state *regs;
10239 
10240 	branch = push_stack(env, next_idx, curr_idx, true);
10241 	if (branch && insn) {
10242 		regs = branch->frame[branch->curframe]->regs;
10243 		if (BPF_SRC(insn->code) == BPF_K) {
10244 			mark_reg_unknown(env, regs, insn->dst_reg);
10245 		} else if (BPF_SRC(insn->code) == BPF_X) {
10246 			mark_reg_unknown(env, regs, insn->dst_reg);
10247 			mark_reg_unknown(env, regs, insn->src_reg);
10248 		}
10249 	}
10250 	return branch;
10251 }
10252 
10253 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10254 			    struct bpf_insn *insn,
10255 			    const struct bpf_reg_state *ptr_reg,
10256 			    const struct bpf_reg_state *off_reg,
10257 			    struct bpf_reg_state *dst_reg,
10258 			    struct bpf_sanitize_info *info,
10259 			    const bool commit_window)
10260 {
10261 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10262 	struct bpf_verifier_state *vstate = env->cur_state;
10263 	bool off_is_imm = tnum_is_const(off_reg->var_off);
10264 	bool off_is_neg = off_reg->smin_value < 0;
10265 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
10266 	u8 opcode = BPF_OP(insn->code);
10267 	u32 alu_state, alu_limit;
10268 	struct bpf_reg_state tmp;
10269 	bool ret;
10270 	int err;
10271 
10272 	if (can_skip_alu_sanitation(env, insn))
10273 		return 0;
10274 
10275 	/* We already marked aux for masking from non-speculative
10276 	 * paths, thus we got here in the first place. We only care
10277 	 * to explore bad access from here.
10278 	 */
10279 	if (vstate->speculative)
10280 		goto do_sim;
10281 
10282 	if (!commit_window) {
10283 		if (!tnum_is_const(off_reg->var_off) &&
10284 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10285 			return REASON_BOUNDS;
10286 
10287 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
10288 				     (opcode == BPF_SUB && !off_is_neg);
10289 	}
10290 
10291 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10292 	if (err < 0)
10293 		return err;
10294 
10295 	if (commit_window) {
10296 		/* In commit phase we narrow the masking window based on
10297 		 * the observed pointer move after the simulated operation.
10298 		 */
10299 		alu_state = info->aux.alu_state;
10300 		alu_limit = abs(info->aux.alu_limit - alu_limit);
10301 	} else {
10302 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10303 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10304 		alu_state |= ptr_is_dst_reg ?
10305 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10306 
10307 		/* Limit pruning on unknown scalars to enable deep search for
10308 		 * potential masking differences from other program paths.
10309 		 */
10310 		if (!off_is_imm)
10311 			env->explore_alu_limits = true;
10312 	}
10313 
10314 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10315 	if (err < 0)
10316 		return err;
10317 do_sim:
10318 	/* If we're in commit phase, we're done here given we already
10319 	 * pushed the truncated dst_reg into the speculative verification
10320 	 * stack.
10321 	 *
10322 	 * Also, when register is a known constant, we rewrite register-based
10323 	 * operation to immediate-based, and thus do not need masking (and as
10324 	 * a consequence, do not need to simulate the zero-truncation either).
10325 	 */
10326 	if (commit_window || off_is_imm)
10327 		return 0;
10328 
10329 	/* Simulate and find potential out-of-bounds access under
10330 	 * speculative execution from truncation as a result of
10331 	 * masking when off was not within expected range. If off
10332 	 * sits in dst, then we temporarily need to move ptr there
10333 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
10334 	 * for cases where we use K-based arithmetic in one direction
10335 	 * and truncated reg-based in the other in order to explore
10336 	 * bad access.
10337 	 */
10338 	if (!ptr_is_dst_reg) {
10339 		tmp = *dst_reg;
10340 		copy_register_state(dst_reg, ptr_reg);
10341 	}
10342 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10343 					env->insn_idx);
10344 	if (!ptr_is_dst_reg && ret)
10345 		*dst_reg = tmp;
10346 	return !ret ? REASON_STACK : 0;
10347 }
10348 
10349 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10350 {
10351 	struct bpf_verifier_state *vstate = env->cur_state;
10352 
10353 	/* If we simulate paths under speculation, we don't update the
10354 	 * insn as 'seen' such that when we verify unreachable paths in
10355 	 * the non-speculative domain, sanitize_dead_code() can still
10356 	 * rewrite/sanitize them.
10357 	 */
10358 	if (!vstate->speculative)
10359 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10360 }
10361 
10362 static int sanitize_err(struct bpf_verifier_env *env,
10363 			const struct bpf_insn *insn, int reason,
10364 			const struct bpf_reg_state *off_reg,
10365 			const struct bpf_reg_state *dst_reg)
10366 {
10367 	static const char *err = "pointer arithmetic with it prohibited for !root";
10368 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10369 	u32 dst = insn->dst_reg, src = insn->src_reg;
10370 
10371 	switch (reason) {
10372 	case REASON_BOUNDS:
10373 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10374 			off_reg == dst_reg ? dst : src, err);
10375 		break;
10376 	case REASON_TYPE:
10377 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10378 			off_reg == dst_reg ? src : dst, err);
10379 		break;
10380 	case REASON_PATHS:
10381 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10382 			dst, op, err);
10383 		break;
10384 	case REASON_LIMIT:
10385 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10386 			dst, op, err);
10387 		break;
10388 	case REASON_STACK:
10389 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10390 			dst, err);
10391 		break;
10392 	default:
10393 		verbose(env, "verifier internal error: unknown reason (%d)\n",
10394 			reason);
10395 		break;
10396 	}
10397 
10398 	return -EACCES;
10399 }
10400 
10401 /* check that stack access falls within stack limits and that 'reg' doesn't
10402  * have a variable offset.
10403  *
10404  * Variable offset is prohibited for unprivileged mode for simplicity since it
10405  * requires corresponding support in Spectre masking for stack ALU.  See also
10406  * retrieve_ptr_limit().
10407  *
10408  *
10409  * 'off' includes 'reg->off'.
10410  */
10411 static int check_stack_access_for_ptr_arithmetic(
10412 				struct bpf_verifier_env *env,
10413 				int regno,
10414 				const struct bpf_reg_state *reg,
10415 				int off)
10416 {
10417 	if (!tnum_is_const(reg->var_off)) {
10418 		char tn_buf[48];
10419 
10420 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10421 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10422 			regno, tn_buf, off);
10423 		return -EACCES;
10424 	}
10425 
10426 	if (off >= 0 || off < -MAX_BPF_STACK) {
10427 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
10428 			"prohibited for !root; off=%d\n", regno, off);
10429 		return -EACCES;
10430 	}
10431 
10432 	return 0;
10433 }
10434 
10435 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10436 				 const struct bpf_insn *insn,
10437 				 const struct bpf_reg_state *dst_reg)
10438 {
10439 	u32 dst = insn->dst_reg;
10440 
10441 	/* For unprivileged we require that resulting offset must be in bounds
10442 	 * in order to be able to sanitize access later on.
10443 	 */
10444 	if (env->bypass_spec_v1)
10445 		return 0;
10446 
10447 	switch (dst_reg->type) {
10448 	case PTR_TO_STACK:
10449 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10450 					dst_reg->off + dst_reg->var_off.value))
10451 			return -EACCES;
10452 		break;
10453 	case PTR_TO_MAP_VALUE:
10454 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10455 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10456 				"prohibited for !root\n", dst);
10457 			return -EACCES;
10458 		}
10459 		break;
10460 	default:
10461 		break;
10462 	}
10463 
10464 	return 0;
10465 }
10466 
10467 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10468  * Caller should also handle BPF_MOV case separately.
10469  * If we return -EACCES, caller may want to try again treating pointer as a
10470  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10471  */
10472 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10473 				   struct bpf_insn *insn,
10474 				   const struct bpf_reg_state *ptr_reg,
10475 				   const struct bpf_reg_state *off_reg)
10476 {
10477 	struct bpf_verifier_state *vstate = env->cur_state;
10478 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10479 	struct bpf_reg_state *regs = state->regs, *dst_reg;
10480 	bool known = tnum_is_const(off_reg->var_off);
10481 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10482 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10483 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10484 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10485 	struct bpf_sanitize_info info = {};
10486 	u8 opcode = BPF_OP(insn->code);
10487 	u32 dst = insn->dst_reg;
10488 	int ret;
10489 
10490 	dst_reg = &regs[dst];
10491 
10492 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10493 	    smin_val > smax_val || umin_val > umax_val) {
10494 		/* Taint dst register if offset had invalid bounds derived from
10495 		 * e.g. dead branches.
10496 		 */
10497 		__mark_reg_unknown(env, dst_reg);
10498 		return 0;
10499 	}
10500 
10501 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
10502 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
10503 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10504 			__mark_reg_unknown(env, dst_reg);
10505 			return 0;
10506 		}
10507 
10508 		verbose(env,
10509 			"R%d 32-bit pointer arithmetic prohibited\n",
10510 			dst);
10511 		return -EACCES;
10512 	}
10513 
10514 	if (ptr_reg->type & PTR_MAYBE_NULL) {
10515 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10516 			dst, reg_type_str(env, ptr_reg->type));
10517 		return -EACCES;
10518 	}
10519 
10520 	switch (base_type(ptr_reg->type)) {
10521 	case CONST_PTR_TO_MAP:
10522 		/* smin_val represents the known value */
10523 		if (known && smin_val == 0 && opcode == BPF_ADD)
10524 			break;
10525 		fallthrough;
10526 	case PTR_TO_PACKET_END:
10527 	case PTR_TO_SOCKET:
10528 	case PTR_TO_SOCK_COMMON:
10529 	case PTR_TO_TCP_SOCK:
10530 	case PTR_TO_XDP_SOCK:
10531 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10532 			dst, reg_type_str(env, ptr_reg->type));
10533 		return -EACCES;
10534 	default:
10535 		break;
10536 	}
10537 
10538 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10539 	 * The id may be overwritten later if we create a new variable offset.
10540 	 */
10541 	dst_reg->type = ptr_reg->type;
10542 	dst_reg->id = ptr_reg->id;
10543 
10544 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10545 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10546 		return -EINVAL;
10547 
10548 	/* pointer types do not carry 32-bit bounds at the moment. */
10549 	__mark_reg32_unbounded(dst_reg);
10550 
10551 	if (sanitize_needed(opcode)) {
10552 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10553 				       &info, false);
10554 		if (ret < 0)
10555 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10556 	}
10557 
10558 	switch (opcode) {
10559 	case BPF_ADD:
10560 		/* We can take a fixed offset as long as it doesn't overflow
10561 		 * the s32 'off' field
10562 		 */
10563 		if (known && (ptr_reg->off + smin_val ==
10564 			      (s64)(s32)(ptr_reg->off + smin_val))) {
10565 			/* pointer += K.  Accumulate it into fixed offset */
10566 			dst_reg->smin_value = smin_ptr;
10567 			dst_reg->smax_value = smax_ptr;
10568 			dst_reg->umin_value = umin_ptr;
10569 			dst_reg->umax_value = umax_ptr;
10570 			dst_reg->var_off = ptr_reg->var_off;
10571 			dst_reg->off = ptr_reg->off + smin_val;
10572 			dst_reg->raw = ptr_reg->raw;
10573 			break;
10574 		}
10575 		/* A new variable offset is created.  Note that off_reg->off
10576 		 * == 0, since it's a scalar.
10577 		 * dst_reg gets the pointer type and since some positive
10578 		 * integer value was added to the pointer, give it a new 'id'
10579 		 * if it's a PTR_TO_PACKET.
10580 		 * this creates a new 'base' pointer, off_reg (variable) gets
10581 		 * added into the variable offset, and we copy the fixed offset
10582 		 * from ptr_reg.
10583 		 */
10584 		if (signed_add_overflows(smin_ptr, smin_val) ||
10585 		    signed_add_overflows(smax_ptr, smax_val)) {
10586 			dst_reg->smin_value = S64_MIN;
10587 			dst_reg->smax_value = S64_MAX;
10588 		} else {
10589 			dst_reg->smin_value = smin_ptr + smin_val;
10590 			dst_reg->smax_value = smax_ptr + smax_val;
10591 		}
10592 		if (umin_ptr + umin_val < umin_ptr ||
10593 		    umax_ptr + umax_val < umax_ptr) {
10594 			dst_reg->umin_value = 0;
10595 			dst_reg->umax_value = U64_MAX;
10596 		} else {
10597 			dst_reg->umin_value = umin_ptr + umin_val;
10598 			dst_reg->umax_value = umax_ptr + umax_val;
10599 		}
10600 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10601 		dst_reg->off = ptr_reg->off;
10602 		dst_reg->raw = ptr_reg->raw;
10603 		if (reg_is_pkt_pointer(ptr_reg)) {
10604 			dst_reg->id = ++env->id_gen;
10605 			/* something was added to pkt_ptr, set range to zero */
10606 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10607 		}
10608 		break;
10609 	case BPF_SUB:
10610 		if (dst_reg == off_reg) {
10611 			/* scalar -= pointer.  Creates an unknown scalar */
10612 			verbose(env, "R%d tried to subtract pointer from scalar\n",
10613 				dst);
10614 			return -EACCES;
10615 		}
10616 		/* We don't allow subtraction from FP, because (according to
10617 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
10618 		 * be able to deal with it.
10619 		 */
10620 		if (ptr_reg->type == PTR_TO_STACK) {
10621 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
10622 				dst);
10623 			return -EACCES;
10624 		}
10625 		if (known && (ptr_reg->off - smin_val ==
10626 			      (s64)(s32)(ptr_reg->off - smin_val))) {
10627 			/* pointer -= K.  Subtract it from fixed offset */
10628 			dst_reg->smin_value = smin_ptr;
10629 			dst_reg->smax_value = smax_ptr;
10630 			dst_reg->umin_value = umin_ptr;
10631 			dst_reg->umax_value = umax_ptr;
10632 			dst_reg->var_off = ptr_reg->var_off;
10633 			dst_reg->id = ptr_reg->id;
10634 			dst_reg->off = ptr_reg->off - smin_val;
10635 			dst_reg->raw = ptr_reg->raw;
10636 			break;
10637 		}
10638 		/* A new variable offset is created.  If the subtrahend is known
10639 		 * nonnegative, then any reg->range we had before is still good.
10640 		 */
10641 		if (signed_sub_overflows(smin_ptr, smax_val) ||
10642 		    signed_sub_overflows(smax_ptr, smin_val)) {
10643 			/* Overflow possible, we know nothing */
10644 			dst_reg->smin_value = S64_MIN;
10645 			dst_reg->smax_value = S64_MAX;
10646 		} else {
10647 			dst_reg->smin_value = smin_ptr - smax_val;
10648 			dst_reg->smax_value = smax_ptr - smin_val;
10649 		}
10650 		if (umin_ptr < umax_val) {
10651 			/* Overflow possible, we know nothing */
10652 			dst_reg->umin_value = 0;
10653 			dst_reg->umax_value = U64_MAX;
10654 		} else {
10655 			/* Cannot overflow (as long as bounds are consistent) */
10656 			dst_reg->umin_value = umin_ptr - umax_val;
10657 			dst_reg->umax_value = umax_ptr - umin_val;
10658 		}
10659 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10660 		dst_reg->off = ptr_reg->off;
10661 		dst_reg->raw = ptr_reg->raw;
10662 		if (reg_is_pkt_pointer(ptr_reg)) {
10663 			dst_reg->id = ++env->id_gen;
10664 			/* something was added to pkt_ptr, set range to zero */
10665 			if (smin_val < 0)
10666 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10667 		}
10668 		break;
10669 	case BPF_AND:
10670 	case BPF_OR:
10671 	case BPF_XOR:
10672 		/* bitwise ops on pointers are troublesome, prohibit. */
10673 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
10674 			dst, bpf_alu_string[opcode >> 4]);
10675 		return -EACCES;
10676 	default:
10677 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
10678 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
10679 			dst, bpf_alu_string[opcode >> 4]);
10680 		return -EACCES;
10681 	}
10682 
10683 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
10684 		return -EINVAL;
10685 	reg_bounds_sync(dst_reg);
10686 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
10687 		return -EACCES;
10688 	if (sanitize_needed(opcode)) {
10689 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
10690 				       &info, true);
10691 		if (ret < 0)
10692 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10693 	}
10694 
10695 	return 0;
10696 }
10697 
10698 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
10699 				 struct bpf_reg_state *src_reg)
10700 {
10701 	s32 smin_val = src_reg->s32_min_value;
10702 	s32 smax_val = src_reg->s32_max_value;
10703 	u32 umin_val = src_reg->u32_min_value;
10704 	u32 umax_val = src_reg->u32_max_value;
10705 
10706 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
10707 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
10708 		dst_reg->s32_min_value = S32_MIN;
10709 		dst_reg->s32_max_value = S32_MAX;
10710 	} else {
10711 		dst_reg->s32_min_value += smin_val;
10712 		dst_reg->s32_max_value += smax_val;
10713 	}
10714 	if (dst_reg->u32_min_value + umin_val < umin_val ||
10715 	    dst_reg->u32_max_value + umax_val < umax_val) {
10716 		dst_reg->u32_min_value = 0;
10717 		dst_reg->u32_max_value = U32_MAX;
10718 	} else {
10719 		dst_reg->u32_min_value += umin_val;
10720 		dst_reg->u32_max_value += umax_val;
10721 	}
10722 }
10723 
10724 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
10725 			       struct bpf_reg_state *src_reg)
10726 {
10727 	s64 smin_val = src_reg->smin_value;
10728 	s64 smax_val = src_reg->smax_value;
10729 	u64 umin_val = src_reg->umin_value;
10730 	u64 umax_val = src_reg->umax_value;
10731 
10732 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
10733 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
10734 		dst_reg->smin_value = S64_MIN;
10735 		dst_reg->smax_value = S64_MAX;
10736 	} else {
10737 		dst_reg->smin_value += smin_val;
10738 		dst_reg->smax_value += smax_val;
10739 	}
10740 	if (dst_reg->umin_value + umin_val < umin_val ||
10741 	    dst_reg->umax_value + umax_val < umax_val) {
10742 		dst_reg->umin_value = 0;
10743 		dst_reg->umax_value = U64_MAX;
10744 	} else {
10745 		dst_reg->umin_value += umin_val;
10746 		dst_reg->umax_value += umax_val;
10747 	}
10748 }
10749 
10750 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10751 				 struct bpf_reg_state *src_reg)
10752 {
10753 	s32 smin_val = src_reg->s32_min_value;
10754 	s32 smax_val = src_reg->s32_max_value;
10755 	u32 umin_val = src_reg->u32_min_value;
10756 	u32 umax_val = src_reg->u32_max_value;
10757 
10758 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10759 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10760 		/* Overflow possible, we know nothing */
10761 		dst_reg->s32_min_value = S32_MIN;
10762 		dst_reg->s32_max_value = S32_MAX;
10763 	} else {
10764 		dst_reg->s32_min_value -= smax_val;
10765 		dst_reg->s32_max_value -= smin_val;
10766 	}
10767 	if (dst_reg->u32_min_value < umax_val) {
10768 		/* Overflow possible, we know nothing */
10769 		dst_reg->u32_min_value = 0;
10770 		dst_reg->u32_max_value = U32_MAX;
10771 	} else {
10772 		/* Cannot overflow (as long as bounds are consistent) */
10773 		dst_reg->u32_min_value -= umax_val;
10774 		dst_reg->u32_max_value -= umin_val;
10775 	}
10776 }
10777 
10778 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10779 			       struct bpf_reg_state *src_reg)
10780 {
10781 	s64 smin_val = src_reg->smin_value;
10782 	s64 smax_val = src_reg->smax_value;
10783 	u64 umin_val = src_reg->umin_value;
10784 	u64 umax_val = src_reg->umax_value;
10785 
10786 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10787 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10788 		/* Overflow possible, we know nothing */
10789 		dst_reg->smin_value = S64_MIN;
10790 		dst_reg->smax_value = S64_MAX;
10791 	} else {
10792 		dst_reg->smin_value -= smax_val;
10793 		dst_reg->smax_value -= smin_val;
10794 	}
10795 	if (dst_reg->umin_value < umax_val) {
10796 		/* Overflow possible, we know nothing */
10797 		dst_reg->umin_value = 0;
10798 		dst_reg->umax_value = U64_MAX;
10799 	} else {
10800 		/* Cannot overflow (as long as bounds are consistent) */
10801 		dst_reg->umin_value -= umax_val;
10802 		dst_reg->umax_value -= umin_val;
10803 	}
10804 }
10805 
10806 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10807 				 struct bpf_reg_state *src_reg)
10808 {
10809 	s32 smin_val = src_reg->s32_min_value;
10810 	u32 umin_val = src_reg->u32_min_value;
10811 	u32 umax_val = src_reg->u32_max_value;
10812 
10813 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10814 		/* Ain't nobody got time to multiply that sign */
10815 		__mark_reg32_unbounded(dst_reg);
10816 		return;
10817 	}
10818 	/* Both values are positive, so we can work with unsigned and
10819 	 * copy the result to signed (unless it exceeds S32_MAX).
10820 	 */
10821 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10822 		/* Potential overflow, we know nothing */
10823 		__mark_reg32_unbounded(dst_reg);
10824 		return;
10825 	}
10826 	dst_reg->u32_min_value *= umin_val;
10827 	dst_reg->u32_max_value *= umax_val;
10828 	if (dst_reg->u32_max_value > S32_MAX) {
10829 		/* Overflow possible, we know nothing */
10830 		dst_reg->s32_min_value = S32_MIN;
10831 		dst_reg->s32_max_value = S32_MAX;
10832 	} else {
10833 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10834 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10835 	}
10836 }
10837 
10838 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10839 			       struct bpf_reg_state *src_reg)
10840 {
10841 	s64 smin_val = src_reg->smin_value;
10842 	u64 umin_val = src_reg->umin_value;
10843 	u64 umax_val = src_reg->umax_value;
10844 
10845 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10846 		/* Ain't nobody got time to multiply that sign */
10847 		__mark_reg64_unbounded(dst_reg);
10848 		return;
10849 	}
10850 	/* Both values are positive, so we can work with unsigned and
10851 	 * copy the result to signed (unless it exceeds S64_MAX).
10852 	 */
10853 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10854 		/* Potential overflow, we know nothing */
10855 		__mark_reg64_unbounded(dst_reg);
10856 		return;
10857 	}
10858 	dst_reg->umin_value *= umin_val;
10859 	dst_reg->umax_value *= umax_val;
10860 	if (dst_reg->umax_value > S64_MAX) {
10861 		/* Overflow possible, we know nothing */
10862 		dst_reg->smin_value = S64_MIN;
10863 		dst_reg->smax_value = S64_MAX;
10864 	} else {
10865 		dst_reg->smin_value = dst_reg->umin_value;
10866 		dst_reg->smax_value = dst_reg->umax_value;
10867 	}
10868 }
10869 
10870 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10871 				 struct bpf_reg_state *src_reg)
10872 {
10873 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10874 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10875 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10876 	s32 smin_val = src_reg->s32_min_value;
10877 	u32 umax_val = src_reg->u32_max_value;
10878 
10879 	if (src_known && dst_known) {
10880 		__mark_reg32_known(dst_reg, var32_off.value);
10881 		return;
10882 	}
10883 
10884 	/* We get our minimum from the var_off, since that's inherently
10885 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10886 	 */
10887 	dst_reg->u32_min_value = var32_off.value;
10888 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10889 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10890 		/* Lose signed bounds when ANDing negative numbers,
10891 		 * ain't nobody got time for that.
10892 		 */
10893 		dst_reg->s32_min_value = S32_MIN;
10894 		dst_reg->s32_max_value = S32_MAX;
10895 	} else {
10896 		/* ANDing two positives gives a positive, so safe to
10897 		 * cast result into s64.
10898 		 */
10899 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10900 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10901 	}
10902 }
10903 
10904 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10905 			       struct bpf_reg_state *src_reg)
10906 {
10907 	bool src_known = tnum_is_const(src_reg->var_off);
10908 	bool dst_known = tnum_is_const(dst_reg->var_off);
10909 	s64 smin_val = src_reg->smin_value;
10910 	u64 umax_val = src_reg->umax_value;
10911 
10912 	if (src_known && dst_known) {
10913 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10914 		return;
10915 	}
10916 
10917 	/* We get our minimum from the var_off, since that's inherently
10918 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10919 	 */
10920 	dst_reg->umin_value = dst_reg->var_off.value;
10921 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10922 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10923 		/* Lose signed bounds when ANDing negative numbers,
10924 		 * ain't nobody got time for that.
10925 		 */
10926 		dst_reg->smin_value = S64_MIN;
10927 		dst_reg->smax_value = S64_MAX;
10928 	} else {
10929 		/* ANDing two positives gives a positive, so safe to
10930 		 * cast result into s64.
10931 		 */
10932 		dst_reg->smin_value = dst_reg->umin_value;
10933 		dst_reg->smax_value = dst_reg->umax_value;
10934 	}
10935 	/* We may learn something more from the var_off */
10936 	__update_reg_bounds(dst_reg);
10937 }
10938 
10939 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10940 				struct bpf_reg_state *src_reg)
10941 {
10942 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10943 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10944 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10945 	s32 smin_val = src_reg->s32_min_value;
10946 	u32 umin_val = src_reg->u32_min_value;
10947 
10948 	if (src_known && dst_known) {
10949 		__mark_reg32_known(dst_reg, var32_off.value);
10950 		return;
10951 	}
10952 
10953 	/* We get our maximum from the var_off, and our minimum is the
10954 	 * maximum of the operands' minima
10955 	 */
10956 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10957 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10958 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10959 		/* Lose signed bounds when ORing negative numbers,
10960 		 * ain't nobody got time for that.
10961 		 */
10962 		dst_reg->s32_min_value = S32_MIN;
10963 		dst_reg->s32_max_value = S32_MAX;
10964 	} else {
10965 		/* ORing two positives gives a positive, so safe to
10966 		 * cast result into s64.
10967 		 */
10968 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10969 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10970 	}
10971 }
10972 
10973 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10974 			      struct bpf_reg_state *src_reg)
10975 {
10976 	bool src_known = tnum_is_const(src_reg->var_off);
10977 	bool dst_known = tnum_is_const(dst_reg->var_off);
10978 	s64 smin_val = src_reg->smin_value;
10979 	u64 umin_val = src_reg->umin_value;
10980 
10981 	if (src_known && dst_known) {
10982 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10983 		return;
10984 	}
10985 
10986 	/* We get our maximum from the var_off, and our minimum is the
10987 	 * maximum of the operands' minima
10988 	 */
10989 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10990 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10991 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10992 		/* Lose signed bounds when ORing negative numbers,
10993 		 * ain't nobody got time for that.
10994 		 */
10995 		dst_reg->smin_value = S64_MIN;
10996 		dst_reg->smax_value = S64_MAX;
10997 	} else {
10998 		/* ORing two positives gives a positive, so safe to
10999 		 * cast result into s64.
11000 		 */
11001 		dst_reg->smin_value = dst_reg->umin_value;
11002 		dst_reg->smax_value = dst_reg->umax_value;
11003 	}
11004 	/* We may learn something more from the var_off */
11005 	__update_reg_bounds(dst_reg);
11006 }
11007 
11008 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11009 				 struct bpf_reg_state *src_reg)
11010 {
11011 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11012 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11013 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11014 	s32 smin_val = src_reg->s32_min_value;
11015 
11016 	if (src_known && dst_known) {
11017 		__mark_reg32_known(dst_reg, var32_off.value);
11018 		return;
11019 	}
11020 
11021 	/* We get both minimum and maximum from the var32_off. */
11022 	dst_reg->u32_min_value = var32_off.value;
11023 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11024 
11025 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11026 		/* XORing two positive sign numbers gives a positive,
11027 		 * so safe to cast u32 result into s32.
11028 		 */
11029 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11030 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11031 	} else {
11032 		dst_reg->s32_min_value = S32_MIN;
11033 		dst_reg->s32_max_value = S32_MAX;
11034 	}
11035 }
11036 
11037 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11038 			       struct bpf_reg_state *src_reg)
11039 {
11040 	bool src_known = tnum_is_const(src_reg->var_off);
11041 	bool dst_known = tnum_is_const(dst_reg->var_off);
11042 	s64 smin_val = src_reg->smin_value;
11043 
11044 	if (src_known && dst_known) {
11045 		/* dst_reg->var_off.value has been updated earlier */
11046 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11047 		return;
11048 	}
11049 
11050 	/* We get both minimum and maximum from the var_off. */
11051 	dst_reg->umin_value = dst_reg->var_off.value;
11052 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11053 
11054 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11055 		/* XORing two positive sign numbers gives a positive,
11056 		 * so safe to cast u64 result into s64.
11057 		 */
11058 		dst_reg->smin_value = dst_reg->umin_value;
11059 		dst_reg->smax_value = dst_reg->umax_value;
11060 	} else {
11061 		dst_reg->smin_value = S64_MIN;
11062 		dst_reg->smax_value = S64_MAX;
11063 	}
11064 
11065 	__update_reg_bounds(dst_reg);
11066 }
11067 
11068 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11069 				   u64 umin_val, u64 umax_val)
11070 {
11071 	/* We lose all sign bit information (except what we can pick
11072 	 * up from var_off)
11073 	 */
11074 	dst_reg->s32_min_value = S32_MIN;
11075 	dst_reg->s32_max_value = S32_MAX;
11076 	/* If we might shift our top bit out, then we know nothing */
11077 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11078 		dst_reg->u32_min_value = 0;
11079 		dst_reg->u32_max_value = U32_MAX;
11080 	} else {
11081 		dst_reg->u32_min_value <<= umin_val;
11082 		dst_reg->u32_max_value <<= umax_val;
11083 	}
11084 }
11085 
11086 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11087 				 struct bpf_reg_state *src_reg)
11088 {
11089 	u32 umax_val = src_reg->u32_max_value;
11090 	u32 umin_val = src_reg->u32_min_value;
11091 	/* u32 alu operation will zext upper bits */
11092 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11093 
11094 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11095 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11096 	/* Not required but being careful mark reg64 bounds as unknown so
11097 	 * that we are forced to pick them up from tnum and zext later and
11098 	 * if some path skips this step we are still safe.
11099 	 */
11100 	__mark_reg64_unbounded(dst_reg);
11101 	__update_reg32_bounds(dst_reg);
11102 }
11103 
11104 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11105 				   u64 umin_val, u64 umax_val)
11106 {
11107 	/* Special case <<32 because it is a common compiler pattern to sign
11108 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11109 	 * positive we know this shift will also be positive so we can track
11110 	 * bounds correctly. Otherwise we lose all sign bit information except
11111 	 * what we can pick up from var_off. Perhaps we can generalize this
11112 	 * later to shifts of any length.
11113 	 */
11114 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11115 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11116 	else
11117 		dst_reg->smax_value = S64_MAX;
11118 
11119 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11120 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11121 	else
11122 		dst_reg->smin_value = S64_MIN;
11123 
11124 	/* If we might shift our top bit out, then we know nothing */
11125 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11126 		dst_reg->umin_value = 0;
11127 		dst_reg->umax_value = U64_MAX;
11128 	} else {
11129 		dst_reg->umin_value <<= umin_val;
11130 		dst_reg->umax_value <<= umax_val;
11131 	}
11132 }
11133 
11134 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11135 			       struct bpf_reg_state *src_reg)
11136 {
11137 	u64 umax_val = src_reg->umax_value;
11138 	u64 umin_val = src_reg->umin_value;
11139 
11140 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
11141 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11142 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11143 
11144 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11145 	/* We may learn something more from the var_off */
11146 	__update_reg_bounds(dst_reg);
11147 }
11148 
11149 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11150 				 struct bpf_reg_state *src_reg)
11151 {
11152 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11153 	u32 umax_val = src_reg->u32_max_value;
11154 	u32 umin_val = src_reg->u32_min_value;
11155 
11156 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11157 	 * be negative, then either:
11158 	 * 1) src_reg might be zero, so the sign bit of the result is
11159 	 *    unknown, so we lose our signed bounds
11160 	 * 2) it's known negative, thus the unsigned bounds capture the
11161 	 *    signed bounds
11162 	 * 3) the signed bounds cross zero, so they tell us nothing
11163 	 *    about the result
11164 	 * If the value in dst_reg is known nonnegative, then again the
11165 	 * unsigned bounds capture the signed bounds.
11166 	 * Thus, in all cases it suffices to blow away our signed bounds
11167 	 * and rely on inferring new ones from the unsigned bounds and
11168 	 * var_off of the result.
11169 	 */
11170 	dst_reg->s32_min_value = S32_MIN;
11171 	dst_reg->s32_max_value = S32_MAX;
11172 
11173 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
11174 	dst_reg->u32_min_value >>= umax_val;
11175 	dst_reg->u32_max_value >>= umin_val;
11176 
11177 	__mark_reg64_unbounded(dst_reg);
11178 	__update_reg32_bounds(dst_reg);
11179 }
11180 
11181 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11182 			       struct bpf_reg_state *src_reg)
11183 {
11184 	u64 umax_val = src_reg->umax_value;
11185 	u64 umin_val = src_reg->umin_value;
11186 
11187 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11188 	 * be negative, then either:
11189 	 * 1) src_reg might be zero, so the sign bit of the result is
11190 	 *    unknown, so we lose our signed bounds
11191 	 * 2) it's known negative, thus the unsigned bounds capture the
11192 	 *    signed bounds
11193 	 * 3) the signed bounds cross zero, so they tell us nothing
11194 	 *    about the result
11195 	 * If the value in dst_reg is known nonnegative, then again the
11196 	 * unsigned bounds capture the signed bounds.
11197 	 * Thus, in all cases it suffices to blow away our signed bounds
11198 	 * and rely on inferring new ones from the unsigned bounds and
11199 	 * var_off of the result.
11200 	 */
11201 	dst_reg->smin_value = S64_MIN;
11202 	dst_reg->smax_value = S64_MAX;
11203 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11204 	dst_reg->umin_value >>= umax_val;
11205 	dst_reg->umax_value >>= umin_val;
11206 
11207 	/* Its not easy to operate on alu32 bounds here because it depends
11208 	 * on bits being shifted in. Take easy way out and mark unbounded
11209 	 * so we can recalculate later from tnum.
11210 	 */
11211 	__mark_reg32_unbounded(dst_reg);
11212 	__update_reg_bounds(dst_reg);
11213 }
11214 
11215 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11216 				  struct bpf_reg_state *src_reg)
11217 {
11218 	u64 umin_val = src_reg->u32_min_value;
11219 
11220 	/* Upon reaching here, src_known is true and
11221 	 * umax_val is equal to umin_val.
11222 	 */
11223 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11224 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11225 
11226 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11227 
11228 	/* blow away the dst_reg umin_value/umax_value and rely on
11229 	 * dst_reg var_off to refine the result.
11230 	 */
11231 	dst_reg->u32_min_value = 0;
11232 	dst_reg->u32_max_value = U32_MAX;
11233 
11234 	__mark_reg64_unbounded(dst_reg);
11235 	__update_reg32_bounds(dst_reg);
11236 }
11237 
11238 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11239 				struct bpf_reg_state *src_reg)
11240 {
11241 	u64 umin_val = src_reg->umin_value;
11242 
11243 	/* Upon reaching here, src_known is true and umax_val is equal
11244 	 * to umin_val.
11245 	 */
11246 	dst_reg->smin_value >>= umin_val;
11247 	dst_reg->smax_value >>= umin_val;
11248 
11249 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11250 
11251 	/* blow away the dst_reg umin_value/umax_value and rely on
11252 	 * dst_reg var_off to refine the result.
11253 	 */
11254 	dst_reg->umin_value = 0;
11255 	dst_reg->umax_value = U64_MAX;
11256 
11257 	/* Its not easy to operate on alu32 bounds here because it depends
11258 	 * on bits being shifted in from upper 32-bits. Take easy way out
11259 	 * and mark unbounded so we can recalculate later from tnum.
11260 	 */
11261 	__mark_reg32_unbounded(dst_reg);
11262 	__update_reg_bounds(dst_reg);
11263 }
11264 
11265 /* WARNING: This function does calculations on 64-bit values, but the actual
11266  * execution may occur on 32-bit values. Therefore, things like bitshifts
11267  * need extra checks in the 32-bit case.
11268  */
11269 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11270 				      struct bpf_insn *insn,
11271 				      struct bpf_reg_state *dst_reg,
11272 				      struct bpf_reg_state src_reg)
11273 {
11274 	struct bpf_reg_state *regs = cur_regs(env);
11275 	u8 opcode = BPF_OP(insn->code);
11276 	bool src_known;
11277 	s64 smin_val, smax_val;
11278 	u64 umin_val, umax_val;
11279 	s32 s32_min_val, s32_max_val;
11280 	u32 u32_min_val, u32_max_val;
11281 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11282 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11283 	int ret;
11284 
11285 	smin_val = src_reg.smin_value;
11286 	smax_val = src_reg.smax_value;
11287 	umin_val = src_reg.umin_value;
11288 	umax_val = src_reg.umax_value;
11289 
11290 	s32_min_val = src_reg.s32_min_value;
11291 	s32_max_val = src_reg.s32_max_value;
11292 	u32_min_val = src_reg.u32_min_value;
11293 	u32_max_val = src_reg.u32_max_value;
11294 
11295 	if (alu32) {
11296 		src_known = tnum_subreg_is_const(src_reg.var_off);
11297 		if ((src_known &&
11298 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11299 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11300 			/* Taint dst register if offset had invalid bounds
11301 			 * derived from e.g. dead branches.
11302 			 */
11303 			__mark_reg_unknown(env, dst_reg);
11304 			return 0;
11305 		}
11306 	} else {
11307 		src_known = tnum_is_const(src_reg.var_off);
11308 		if ((src_known &&
11309 		     (smin_val != smax_val || umin_val != umax_val)) ||
11310 		    smin_val > smax_val || umin_val > umax_val) {
11311 			/* Taint dst register if offset had invalid bounds
11312 			 * derived from e.g. dead branches.
11313 			 */
11314 			__mark_reg_unknown(env, dst_reg);
11315 			return 0;
11316 		}
11317 	}
11318 
11319 	if (!src_known &&
11320 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11321 		__mark_reg_unknown(env, dst_reg);
11322 		return 0;
11323 	}
11324 
11325 	if (sanitize_needed(opcode)) {
11326 		ret = sanitize_val_alu(env, insn);
11327 		if (ret < 0)
11328 			return sanitize_err(env, insn, ret, NULL, NULL);
11329 	}
11330 
11331 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11332 	 * There are two classes of instructions: The first class we track both
11333 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
11334 	 * greatest amount of precision when alu operations are mixed with jmp32
11335 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11336 	 * and BPF_OR. This is possible because these ops have fairly easy to
11337 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11338 	 * See alu32 verifier tests for examples. The second class of
11339 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11340 	 * with regards to tracking sign/unsigned bounds because the bits may
11341 	 * cross subreg boundaries in the alu64 case. When this happens we mark
11342 	 * the reg unbounded in the subreg bound space and use the resulting
11343 	 * tnum to calculate an approximation of the sign/unsigned bounds.
11344 	 */
11345 	switch (opcode) {
11346 	case BPF_ADD:
11347 		scalar32_min_max_add(dst_reg, &src_reg);
11348 		scalar_min_max_add(dst_reg, &src_reg);
11349 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11350 		break;
11351 	case BPF_SUB:
11352 		scalar32_min_max_sub(dst_reg, &src_reg);
11353 		scalar_min_max_sub(dst_reg, &src_reg);
11354 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11355 		break;
11356 	case BPF_MUL:
11357 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11358 		scalar32_min_max_mul(dst_reg, &src_reg);
11359 		scalar_min_max_mul(dst_reg, &src_reg);
11360 		break;
11361 	case BPF_AND:
11362 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11363 		scalar32_min_max_and(dst_reg, &src_reg);
11364 		scalar_min_max_and(dst_reg, &src_reg);
11365 		break;
11366 	case BPF_OR:
11367 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11368 		scalar32_min_max_or(dst_reg, &src_reg);
11369 		scalar_min_max_or(dst_reg, &src_reg);
11370 		break;
11371 	case BPF_XOR:
11372 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11373 		scalar32_min_max_xor(dst_reg, &src_reg);
11374 		scalar_min_max_xor(dst_reg, &src_reg);
11375 		break;
11376 	case BPF_LSH:
11377 		if (umax_val >= insn_bitness) {
11378 			/* Shifts greater than 31 or 63 are undefined.
11379 			 * This includes shifts by a negative number.
11380 			 */
11381 			mark_reg_unknown(env, regs, insn->dst_reg);
11382 			break;
11383 		}
11384 		if (alu32)
11385 			scalar32_min_max_lsh(dst_reg, &src_reg);
11386 		else
11387 			scalar_min_max_lsh(dst_reg, &src_reg);
11388 		break;
11389 	case BPF_RSH:
11390 		if (umax_val >= insn_bitness) {
11391 			/* Shifts greater than 31 or 63 are undefined.
11392 			 * This includes shifts by a negative number.
11393 			 */
11394 			mark_reg_unknown(env, regs, insn->dst_reg);
11395 			break;
11396 		}
11397 		if (alu32)
11398 			scalar32_min_max_rsh(dst_reg, &src_reg);
11399 		else
11400 			scalar_min_max_rsh(dst_reg, &src_reg);
11401 		break;
11402 	case BPF_ARSH:
11403 		if (umax_val >= insn_bitness) {
11404 			/* Shifts greater than 31 or 63 are undefined.
11405 			 * This includes shifts by a negative number.
11406 			 */
11407 			mark_reg_unknown(env, regs, insn->dst_reg);
11408 			break;
11409 		}
11410 		if (alu32)
11411 			scalar32_min_max_arsh(dst_reg, &src_reg);
11412 		else
11413 			scalar_min_max_arsh(dst_reg, &src_reg);
11414 		break;
11415 	default:
11416 		mark_reg_unknown(env, regs, insn->dst_reg);
11417 		break;
11418 	}
11419 
11420 	/* ALU32 ops are zero extended into 64bit register */
11421 	if (alu32)
11422 		zext_32_to_64(dst_reg);
11423 	reg_bounds_sync(dst_reg);
11424 	return 0;
11425 }
11426 
11427 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11428  * and var_off.
11429  */
11430 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11431 				   struct bpf_insn *insn)
11432 {
11433 	struct bpf_verifier_state *vstate = env->cur_state;
11434 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11435 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11436 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11437 	u8 opcode = BPF_OP(insn->code);
11438 	int err;
11439 
11440 	dst_reg = &regs[insn->dst_reg];
11441 	src_reg = NULL;
11442 	if (dst_reg->type != SCALAR_VALUE)
11443 		ptr_reg = dst_reg;
11444 	else
11445 		/* Make sure ID is cleared otherwise dst_reg min/max could be
11446 		 * incorrectly propagated into other registers by find_equal_scalars()
11447 		 */
11448 		dst_reg->id = 0;
11449 	if (BPF_SRC(insn->code) == BPF_X) {
11450 		src_reg = &regs[insn->src_reg];
11451 		if (src_reg->type != SCALAR_VALUE) {
11452 			if (dst_reg->type != SCALAR_VALUE) {
11453 				/* Combining two pointers by any ALU op yields
11454 				 * an arbitrary scalar. Disallow all math except
11455 				 * pointer subtraction
11456 				 */
11457 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11458 					mark_reg_unknown(env, regs, insn->dst_reg);
11459 					return 0;
11460 				}
11461 				verbose(env, "R%d pointer %s pointer prohibited\n",
11462 					insn->dst_reg,
11463 					bpf_alu_string[opcode >> 4]);
11464 				return -EACCES;
11465 			} else {
11466 				/* scalar += pointer
11467 				 * This is legal, but we have to reverse our
11468 				 * src/dest handling in computing the range
11469 				 */
11470 				err = mark_chain_precision(env, insn->dst_reg);
11471 				if (err)
11472 					return err;
11473 				return adjust_ptr_min_max_vals(env, insn,
11474 							       src_reg, dst_reg);
11475 			}
11476 		} else if (ptr_reg) {
11477 			/* pointer += scalar */
11478 			err = mark_chain_precision(env, insn->src_reg);
11479 			if (err)
11480 				return err;
11481 			return adjust_ptr_min_max_vals(env, insn,
11482 						       dst_reg, src_reg);
11483 		} else if (dst_reg->precise) {
11484 			/* if dst_reg is precise, src_reg should be precise as well */
11485 			err = mark_chain_precision(env, insn->src_reg);
11486 			if (err)
11487 				return err;
11488 		}
11489 	} else {
11490 		/* Pretend the src is a reg with a known value, since we only
11491 		 * need to be able to read from this state.
11492 		 */
11493 		off_reg.type = SCALAR_VALUE;
11494 		__mark_reg_known(&off_reg, insn->imm);
11495 		src_reg = &off_reg;
11496 		if (ptr_reg) /* pointer += K */
11497 			return adjust_ptr_min_max_vals(env, insn,
11498 						       ptr_reg, src_reg);
11499 	}
11500 
11501 	/* Got here implies adding two SCALAR_VALUEs */
11502 	if (WARN_ON_ONCE(ptr_reg)) {
11503 		print_verifier_state(env, state, true);
11504 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
11505 		return -EINVAL;
11506 	}
11507 	if (WARN_ON(!src_reg)) {
11508 		print_verifier_state(env, state, true);
11509 		verbose(env, "verifier internal error: no src_reg\n");
11510 		return -EINVAL;
11511 	}
11512 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11513 }
11514 
11515 /* check validity of 32-bit and 64-bit arithmetic operations */
11516 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11517 {
11518 	struct bpf_reg_state *regs = cur_regs(env);
11519 	u8 opcode = BPF_OP(insn->code);
11520 	int err;
11521 
11522 	if (opcode == BPF_END || opcode == BPF_NEG) {
11523 		if (opcode == BPF_NEG) {
11524 			if (BPF_SRC(insn->code) != BPF_K ||
11525 			    insn->src_reg != BPF_REG_0 ||
11526 			    insn->off != 0 || insn->imm != 0) {
11527 				verbose(env, "BPF_NEG uses reserved fields\n");
11528 				return -EINVAL;
11529 			}
11530 		} else {
11531 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11532 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11533 			    BPF_CLASS(insn->code) == BPF_ALU64) {
11534 				verbose(env, "BPF_END uses reserved fields\n");
11535 				return -EINVAL;
11536 			}
11537 		}
11538 
11539 		/* check src operand */
11540 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11541 		if (err)
11542 			return err;
11543 
11544 		if (is_pointer_value(env, insn->dst_reg)) {
11545 			verbose(env, "R%d pointer arithmetic prohibited\n",
11546 				insn->dst_reg);
11547 			return -EACCES;
11548 		}
11549 
11550 		/* check dest operand */
11551 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
11552 		if (err)
11553 			return err;
11554 
11555 	} else if (opcode == BPF_MOV) {
11556 
11557 		if (BPF_SRC(insn->code) == BPF_X) {
11558 			if (insn->imm != 0 || insn->off != 0) {
11559 				verbose(env, "BPF_MOV uses reserved fields\n");
11560 				return -EINVAL;
11561 			}
11562 
11563 			/* check src operand */
11564 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11565 			if (err)
11566 				return err;
11567 		} else {
11568 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11569 				verbose(env, "BPF_MOV uses reserved fields\n");
11570 				return -EINVAL;
11571 			}
11572 		}
11573 
11574 		/* check dest operand, mark as required later */
11575 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11576 		if (err)
11577 			return err;
11578 
11579 		if (BPF_SRC(insn->code) == BPF_X) {
11580 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
11581 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11582 
11583 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11584 				/* case: R1 = R2
11585 				 * copy register state to dest reg
11586 				 */
11587 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11588 					/* Assign src and dst registers the same ID
11589 					 * that will be used by find_equal_scalars()
11590 					 * to propagate min/max range.
11591 					 */
11592 					src_reg->id = ++env->id_gen;
11593 				copy_register_state(dst_reg, src_reg);
11594 				dst_reg->live |= REG_LIVE_WRITTEN;
11595 				dst_reg->subreg_def = DEF_NOT_SUBREG;
11596 			} else {
11597 				/* R1 = (u32) R2 */
11598 				if (is_pointer_value(env, insn->src_reg)) {
11599 					verbose(env,
11600 						"R%d partial copy of pointer\n",
11601 						insn->src_reg);
11602 					return -EACCES;
11603 				} else if (src_reg->type == SCALAR_VALUE) {
11604 					copy_register_state(dst_reg, src_reg);
11605 					/* Make sure ID is cleared otherwise
11606 					 * dst_reg min/max could be incorrectly
11607 					 * propagated into src_reg by find_equal_scalars()
11608 					 */
11609 					dst_reg->id = 0;
11610 					dst_reg->live |= REG_LIVE_WRITTEN;
11611 					dst_reg->subreg_def = env->insn_idx + 1;
11612 				} else {
11613 					mark_reg_unknown(env, regs,
11614 							 insn->dst_reg);
11615 				}
11616 				zext_32_to_64(dst_reg);
11617 				reg_bounds_sync(dst_reg);
11618 			}
11619 		} else {
11620 			/* case: R = imm
11621 			 * remember the value we stored into this reg
11622 			 */
11623 			/* clear any state __mark_reg_known doesn't set */
11624 			mark_reg_unknown(env, regs, insn->dst_reg);
11625 			regs[insn->dst_reg].type = SCALAR_VALUE;
11626 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11627 				__mark_reg_known(regs + insn->dst_reg,
11628 						 insn->imm);
11629 			} else {
11630 				__mark_reg_known(regs + insn->dst_reg,
11631 						 (u32)insn->imm);
11632 			}
11633 		}
11634 
11635 	} else if (opcode > BPF_END) {
11636 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11637 		return -EINVAL;
11638 
11639 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
11640 
11641 		if (BPF_SRC(insn->code) == BPF_X) {
11642 			if (insn->imm != 0 || insn->off != 0) {
11643 				verbose(env, "BPF_ALU uses reserved fields\n");
11644 				return -EINVAL;
11645 			}
11646 			/* check src1 operand */
11647 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11648 			if (err)
11649 				return err;
11650 		} else {
11651 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11652 				verbose(env, "BPF_ALU uses reserved fields\n");
11653 				return -EINVAL;
11654 			}
11655 		}
11656 
11657 		/* check src2 operand */
11658 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11659 		if (err)
11660 			return err;
11661 
11662 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11663 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11664 			verbose(env, "div by zero\n");
11665 			return -EINVAL;
11666 		}
11667 
11668 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11669 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11670 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11671 
11672 			if (insn->imm < 0 || insn->imm >= size) {
11673 				verbose(env, "invalid shift %d\n", insn->imm);
11674 				return -EINVAL;
11675 			}
11676 		}
11677 
11678 		/* check dest operand */
11679 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11680 		if (err)
11681 			return err;
11682 
11683 		return adjust_reg_min_max_vals(env, insn);
11684 	}
11685 
11686 	return 0;
11687 }
11688 
11689 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
11690 				   struct bpf_reg_state *dst_reg,
11691 				   enum bpf_reg_type type,
11692 				   bool range_right_open)
11693 {
11694 	struct bpf_func_state *state;
11695 	struct bpf_reg_state *reg;
11696 	int new_range;
11697 
11698 	if (dst_reg->off < 0 ||
11699 	    (dst_reg->off == 0 && range_right_open))
11700 		/* This doesn't give us any range */
11701 		return;
11702 
11703 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
11704 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
11705 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
11706 		 * than pkt_end, but that's because it's also less than pkt.
11707 		 */
11708 		return;
11709 
11710 	new_range = dst_reg->off;
11711 	if (range_right_open)
11712 		new_range++;
11713 
11714 	/* Examples for register markings:
11715 	 *
11716 	 * pkt_data in dst register:
11717 	 *
11718 	 *   r2 = r3;
11719 	 *   r2 += 8;
11720 	 *   if (r2 > pkt_end) goto <handle exception>
11721 	 *   <access okay>
11722 	 *
11723 	 *   r2 = r3;
11724 	 *   r2 += 8;
11725 	 *   if (r2 < pkt_end) goto <access okay>
11726 	 *   <handle exception>
11727 	 *
11728 	 *   Where:
11729 	 *     r2 == dst_reg, pkt_end == src_reg
11730 	 *     r2=pkt(id=n,off=8,r=0)
11731 	 *     r3=pkt(id=n,off=0,r=0)
11732 	 *
11733 	 * pkt_data in src register:
11734 	 *
11735 	 *   r2 = r3;
11736 	 *   r2 += 8;
11737 	 *   if (pkt_end >= r2) goto <access okay>
11738 	 *   <handle exception>
11739 	 *
11740 	 *   r2 = r3;
11741 	 *   r2 += 8;
11742 	 *   if (pkt_end <= r2) goto <handle exception>
11743 	 *   <access okay>
11744 	 *
11745 	 *   Where:
11746 	 *     pkt_end == dst_reg, r2 == src_reg
11747 	 *     r2=pkt(id=n,off=8,r=0)
11748 	 *     r3=pkt(id=n,off=0,r=0)
11749 	 *
11750 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11751 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11752 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11753 	 * the check.
11754 	 */
11755 
11756 	/* If our ids match, then we must have the same max_value.  And we
11757 	 * don't care about the other reg's fixed offset, since if it's too big
11758 	 * the range won't allow anything.
11759 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11760 	 */
11761 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11762 		if (reg->type == type && reg->id == dst_reg->id)
11763 			/* keep the maximum range already checked */
11764 			reg->range = max(reg->range, new_range);
11765 	}));
11766 }
11767 
11768 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11769 {
11770 	struct tnum subreg = tnum_subreg(reg->var_off);
11771 	s32 sval = (s32)val;
11772 
11773 	switch (opcode) {
11774 	case BPF_JEQ:
11775 		if (tnum_is_const(subreg))
11776 			return !!tnum_equals_const(subreg, val);
11777 		break;
11778 	case BPF_JNE:
11779 		if (tnum_is_const(subreg))
11780 			return !tnum_equals_const(subreg, val);
11781 		break;
11782 	case BPF_JSET:
11783 		if ((~subreg.mask & subreg.value) & val)
11784 			return 1;
11785 		if (!((subreg.mask | subreg.value) & val))
11786 			return 0;
11787 		break;
11788 	case BPF_JGT:
11789 		if (reg->u32_min_value > val)
11790 			return 1;
11791 		else if (reg->u32_max_value <= val)
11792 			return 0;
11793 		break;
11794 	case BPF_JSGT:
11795 		if (reg->s32_min_value > sval)
11796 			return 1;
11797 		else if (reg->s32_max_value <= sval)
11798 			return 0;
11799 		break;
11800 	case BPF_JLT:
11801 		if (reg->u32_max_value < val)
11802 			return 1;
11803 		else if (reg->u32_min_value >= val)
11804 			return 0;
11805 		break;
11806 	case BPF_JSLT:
11807 		if (reg->s32_max_value < sval)
11808 			return 1;
11809 		else if (reg->s32_min_value >= sval)
11810 			return 0;
11811 		break;
11812 	case BPF_JGE:
11813 		if (reg->u32_min_value >= val)
11814 			return 1;
11815 		else if (reg->u32_max_value < val)
11816 			return 0;
11817 		break;
11818 	case BPF_JSGE:
11819 		if (reg->s32_min_value >= sval)
11820 			return 1;
11821 		else if (reg->s32_max_value < sval)
11822 			return 0;
11823 		break;
11824 	case BPF_JLE:
11825 		if (reg->u32_max_value <= val)
11826 			return 1;
11827 		else if (reg->u32_min_value > val)
11828 			return 0;
11829 		break;
11830 	case BPF_JSLE:
11831 		if (reg->s32_max_value <= sval)
11832 			return 1;
11833 		else if (reg->s32_min_value > sval)
11834 			return 0;
11835 		break;
11836 	}
11837 
11838 	return -1;
11839 }
11840 
11841 
11842 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11843 {
11844 	s64 sval = (s64)val;
11845 
11846 	switch (opcode) {
11847 	case BPF_JEQ:
11848 		if (tnum_is_const(reg->var_off))
11849 			return !!tnum_equals_const(reg->var_off, val);
11850 		break;
11851 	case BPF_JNE:
11852 		if (tnum_is_const(reg->var_off))
11853 			return !tnum_equals_const(reg->var_off, val);
11854 		break;
11855 	case BPF_JSET:
11856 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11857 			return 1;
11858 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11859 			return 0;
11860 		break;
11861 	case BPF_JGT:
11862 		if (reg->umin_value > val)
11863 			return 1;
11864 		else if (reg->umax_value <= val)
11865 			return 0;
11866 		break;
11867 	case BPF_JSGT:
11868 		if (reg->smin_value > sval)
11869 			return 1;
11870 		else if (reg->smax_value <= sval)
11871 			return 0;
11872 		break;
11873 	case BPF_JLT:
11874 		if (reg->umax_value < val)
11875 			return 1;
11876 		else if (reg->umin_value >= val)
11877 			return 0;
11878 		break;
11879 	case BPF_JSLT:
11880 		if (reg->smax_value < sval)
11881 			return 1;
11882 		else if (reg->smin_value >= sval)
11883 			return 0;
11884 		break;
11885 	case BPF_JGE:
11886 		if (reg->umin_value >= val)
11887 			return 1;
11888 		else if (reg->umax_value < val)
11889 			return 0;
11890 		break;
11891 	case BPF_JSGE:
11892 		if (reg->smin_value >= sval)
11893 			return 1;
11894 		else if (reg->smax_value < sval)
11895 			return 0;
11896 		break;
11897 	case BPF_JLE:
11898 		if (reg->umax_value <= val)
11899 			return 1;
11900 		else if (reg->umin_value > val)
11901 			return 0;
11902 		break;
11903 	case BPF_JSLE:
11904 		if (reg->smax_value <= sval)
11905 			return 1;
11906 		else if (reg->smin_value > sval)
11907 			return 0;
11908 		break;
11909 	}
11910 
11911 	return -1;
11912 }
11913 
11914 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11915  * and return:
11916  *  1 - branch will be taken and "goto target" will be executed
11917  *  0 - branch will not be taken and fall-through to next insn
11918  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11919  *      range [0,10]
11920  */
11921 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11922 			   bool is_jmp32)
11923 {
11924 	if (__is_pointer_value(false, reg)) {
11925 		if (!reg_type_not_null(reg->type))
11926 			return -1;
11927 
11928 		/* If pointer is valid tests against zero will fail so we can
11929 		 * use this to direct branch taken.
11930 		 */
11931 		if (val != 0)
11932 			return -1;
11933 
11934 		switch (opcode) {
11935 		case BPF_JEQ:
11936 			return 0;
11937 		case BPF_JNE:
11938 			return 1;
11939 		default:
11940 			return -1;
11941 		}
11942 	}
11943 
11944 	if (is_jmp32)
11945 		return is_branch32_taken(reg, val, opcode);
11946 	return is_branch64_taken(reg, val, opcode);
11947 }
11948 
11949 static int flip_opcode(u32 opcode)
11950 {
11951 	/* How can we transform "a <op> b" into "b <op> a"? */
11952 	static const u8 opcode_flip[16] = {
11953 		/* these stay the same */
11954 		[BPF_JEQ  >> 4] = BPF_JEQ,
11955 		[BPF_JNE  >> 4] = BPF_JNE,
11956 		[BPF_JSET >> 4] = BPF_JSET,
11957 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11958 		[BPF_JGE  >> 4] = BPF_JLE,
11959 		[BPF_JGT  >> 4] = BPF_JLT,
11960 		[BPF_JLE  >> 4] = BPF_JGE,
11961 		[BPF_JLT  >> 4] = BPF_JGT,
11962 		[BPF_JSGE >> 4] = BPF_JSLE,
11963 		[BPF_JSGT >> 4] = BPF_JSLT,
11964 		[BPF_JSLE >> 4] = BPF_JSGE,
11965 		[BPF_JSLT >> 4] = BPF_JSGT
11966 	};
11967 	return opcode_flip[opcode >> 4];
11968 }
11969 
11970 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11971 				   struct bpf_reg_state *src_reg,
11972 				   u8 opcode)
11973 {
11974 	struct bpf_reg_state *pkt;
11975 
11976 	if (src_reg->type == PTR_TO_PACKET_END) {
11977 		pkt = dst_reg;
11978 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11979 		pkt = src_reg;
11980 		opcode = flip_opcode(opcode);
11981 	} else {
11982 		return -1;
11983 	}
11984 
11985 	if (pkt->range >= 0)
11986 		return -1;
11987 
11988 	switch (opcode) {
11989 	case BPF_JLE:
11990 		/* pkt <= pkt_end */
11991 		fallthrough;
11992 	case BPF_JGT:
11993 		/* pkt > pkt_end */
11994 		if (pkt->range == BEYOND_PKT_END)
11995 			/* pkt has at last one extra byte beyond pkt_end */
11996 			return opcode == BPF_JGT;
11997 		break;
11998 	case BPF_JLT:
11999 		/* pkt < pkt_end */
12000 		fallthrough;
12001 	case BPF_JGE:
12002 		/* pkt >= pkt_end */
12003 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12004 			return opcode == BPF_JGE;
12005 		break;
12006 	}
12007 	return -1;
12008 }
12009 
12010 /* Adjusts the register min/max values in the case that the dst_reg is the
12011  * variable register that we are working on, and src_reg is a constant or we're
12012  * simply doing a BPF_K check.
12013  * In JEQ/JNE cases we also adjust the var_off values.
12014  */
12015 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12016 			    struct bpf_reg_state *false_reg,
12017 			    u64 val, u32 val32,
12018 			    u8 opcode, bool is_jmp32)
12019 {
12020 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
12021 	struct tnum false_64off = false_reg->var_off;
12022 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
12023 	struct tnum true_64off = true_reg->var_off;
12024 	s64 sval = (s64)val;
12025 	s32 sval32 = (s32)val32;
12026 
12027 	/* If the dst_reg is a pointer, we can't learn anything about its
12028 	 * variable offset from the compare (unless src_reg were a pointer into
12029 	 * the same object, but we don't bother with that.
12030 	 * Since false_reg and true_reg have the same type by construction, we
12031 	 * only need to check one of them for pointerness.
12032 	 */
12033 	if (__is_pointer_value(false, false_reg))
12034 		return;
12035 
12036 	switch (opcode) {
12037 	/* JEQ/JNE comparison doesn't change the register equivalence.
12038 	 *
12039 	 * r1 = r2;
12040 	 * if (r1 == 42) goto label;
12041 	 * ...
12042 	 * label: // here both r1 and r2 are known to be 42.
12043 	 *
12044 	 * Hence when marking register as known preserve it's ID.
12045 	 */
12046 	case BPF_JEQ:
12047 		if (is_jmp32) {
12048 			__mark_reg32_known(true_reg, val32);
12049 			true_32off = tnum_subreg(true_reg->var_off);
12050 		} else {
12051 			___mark_reg_known(true_reg, val);
12052 			true_64off = true_reg->var_off;
12053 		}
12054 		break;
12055 	case BPF_JNE:
12056 		if (is_jmp32) {
12057 			__mark_reg32_known(false_reg, val32);
12058 			false_32off = tnum_subreg(false_reg->var_off);
12059 		} else {
12060 			___mark_reg_known(false_reg, val);
12061 			false_64off = false_reg->var_off;
12062 		}
12063 		break;
12064 	case BPF_JSET:
12065 		if (is_jmp32) {
12066 			false_32off = tnum_and(false_32off, tnum_const(~val32));
12067 			if (is_power_of_2(val32))
12068 				true_32off = tnum_or(true_32off,
12069 						     tnum_const(val32));
12070 		} else {
12071 			false_64off = tnum_and(false_64off, tnum_const(~val));
12072 			if (is_power_of_2(val))
12073 				true_64off = tnum_or(true_64off,
12074 						     tnum_const(val));
12075 		}
12076 		break;
12077 	case BPF_JGE:
12078 	case BPF_JGT:
12079 	{
12080 		if (is_jmp32) {
12081 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12082 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12083 
12084 			false_reg->u32_max_value = min(false_reg->u32_max_value,
12085 						       false_umax);
12086 			true_reg->u32_min_value = max(true_reg->u32_min_value,
12087 						      true_umin);
12088 		} else {
12089 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12090 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12091 
12092 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
12093 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
12094 		}
12095 		break;
12096 	}
12097 	case BPF_JSGE:
12098 	case BPF_JSGT:
12099 	{
12100 		if (is_jmp32) {
12101 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12102 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12103 
12104 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12105 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12106 		} else {
12107 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12108 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12109 
12110 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
12111 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
12112 		}
12113 		break;
12114 	}
12115 	case BPF_JLE:
12116 	case BPF_JLT:
12117 	{
12118 		if (is_jmp32) {
12119 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12120 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12121 
12122 			false_reg->u32_min_value = max(false_reg->u32_min_value,
12123 						       false_umin);
12124 			true_reg->u32_max_value = min(true_reg->u32_max_value,
12125 						      true_umax);
12126 		} else {
12127 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12128 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12129 
12130 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
12131 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
12132 		}
12133 		break;
12134 	}
12135 	case BPF_JSLE:
12136 	case BPF_JSLT:
12137 	{
12138 		if (is_jmp32) {
12139 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12140 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12141 
12142 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12143 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12144 		} else {
12145 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12146 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12147 
12148 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
12149 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
12150 		}
12151 		break;
12152 	}
12153 	default:
12154 		return;
12155 	}
12156 
12157 	if (is_jmp32) {
12158 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12159 					     tnum_subreg(false_32off));
12160 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12161 					    tnum_subreg(true_32off));
12162 		__reg_combine_32_into_64(false_reg);
12163 		__reg_combine_32_into_64(true_reg);
12164 	} else {
12165 		false_reg->var_off = false_64off;
12166 		true_reg->var_off = true_64off;
12167 		__reg_combine_64_into_32(false_reg);
12168 		__reg_combine_64_into_32(true_reg);
12169 	}
12170 }
12171 
12172 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12173  * the variable reg.
12174  */
12175 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12176 				struct bpf_reg_state *false_reg,
12177 				u64 val, u32 val32,
12178 				u8 opcode, bool is_jmp32)
12179 {
12180 	opcode = flip_opcode(opcode);
12181 	/* This uses zero as "not present in table"; luckily the zero opcode,
12182 	 * BPF_JA, can't get here.
12183 	 */
12184 	if (opcode)
12185 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12186 }
12187 
12188 /* Regs are known to be equal, so intersect their min/max/var_off */
12189 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12190 				  struct bpf_reg_state *dst_reg)
12191 {
12192 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12193 							dst_reg->umin_value);
12194 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12195 							dst_reg->umax_value);
12196 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12197 							dst_reg->smin_value);
12198 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12199 							dst_reg->smax_value);
12200 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12201 							     dst_reg->var_off);
12202 	reg_bounds_sync(src_reg);
12203 	reg_bounds_sync(dst_reg);
12204 }
12205 
12206 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12207 				struct bpf_reg_state *true_dst,
12208 				struct bpf_reg_state *false_src,
12209 				struct bpf_reg_state *false_dst,
12210 				u8 opcode)
12211 {
12212 	switch (opcode) {
12213 	case BPF_JEQ:
12214 		__reg_combine_min_max(true_src, true_dst);
12215 		break;
12216 	case BPF_JNE:
12217 		__reg_combine_min_max(false_src, false_dst);
12218 		break;
12219 	}
12220 }
12221 
12222 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12223 				 struct bpf_reg_state *reg, u32 id,
12224 				 bool is_null)
12225 {
12226 	if (type_may_be_null(reg->type) && reg->id == id &&
12227 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12228 		/* Old offset (both fixed and variable parts) should have been
12229 		 * known-zero, because we don't allow pointer arithmetic on
12230 		 * pointers that might be NULL. If we see this happening, don't
12231 		 * convert the register.
12232 		 *
12233 		 * But in some cases, some helpers that return local kptrs
12234 		 * advance offset for the returned pointer. In those cases, it
12235 		 * is fine to expect to see reg->off.
12236 		 */
12237 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12238 			return;
12239 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12240 		    WARN_ON_ONCE(reg->off))
12241 			return;
12242 
12243 		if (is_null) {
12244 			reg->type = SCALAR_VALUE;
12245 			/* We don't need id and ref_obj_id from this point
12246 			 * onwards anymore, thus we should better reset it,
12247 			 * so that state pruning has chances to take effect.
12248 			 */
12249 			reg->id = 0;
12250 			reg->ref_obj_id = 0;
12251 
12252 			return;
12253 		}
12254 
12255 		mark_ptr_not_null_reg(reg);
12256 
12257 		if (!reg_may_point_to_spin_lock(reg)) {
12258 			/* For not-NULL ptr, reg->ref_obj_id will be reset
12259 			 * in release_reference().
12260 			 *
12261 			 * reg->id is still used by spin_lock ptr. Other
12262 			 * than spin_lock ptr type, reg->id can be reset.
12263 			 */
12264 			reg->id = 0;
12265 		}
12266 	}
12267 }
12268 
12269 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12270  * be folded together at some point.
12271  */
12272 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12273 				  bool is_null)
12274 {
12275 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12276 	struct bpf_reg_state *regs = state->regs, *reg;
12277 	u32 ref_obj_id = regs[regno].ref_obj_id;
12278 	u32 id = regs[regno].id;
12279 
12280 	if (ref_obj_id && ref_obj_id == id && is_null)
12281 		/* regs[regno] is in the " == NULL" branch.
12282 		 * No one could have freed the reference state before
12283 		 * doing the NULL check.
12284 		 */
12285 		WARN_ON_ONCE(release_reference_state(state, id));
12286 
12287 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12288 		mark_ptr_or_null_reg(state, reg, id, is_null);
12289 	}));
12290 }
12291 
12292 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12293 				   struct bpf_reg_state *dst_reg,
12294 				   struct bpf_reg_state *src_reg,
12295 				   struct bpf_verifier_state *this_branch,
12296 				   struct bpf_verifier_state *other_branch)
12297 {
12298 	if (BPF_SRC(insn->code) != BPF_X)
12299 		return false;
12300 
12301 	/* Pointers are always 64-bit. */
12302 	if (BPF_CLASS(insn->code) == BPF_JMP32)
12303 		return false;
12304 
12305 	switch (BPF_OP(insn->code)) {
12306 	case BPF_JGT:
12307 		if ((dst_reg->type == PTR_TO_PACKET &&
12308 		     src_reg->type == PTR_TO_PACKET_END) ||
12309 		    (dst_reg->type == PTR_TO_PACKET_META &&
12310 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12311 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12312 			find_good_pkt_pointers(this_branch, dst_reg,
12313 					       dst_reg->type, false);
12314 			mark_pkt_end(other_branch, insn->dst_reg, true);
12315 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12316 			    src_reg->type == PTR_TO_PACKET) ||
12317 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12318 			    src_reg->type == PTR_TO_PACKET_META)) {
12319 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
12320 			find_good_pkt_pointers(other_branch, src_reg,
12321 					       src_reg->type, true);
12322 			mark_pkt_end(this_branch, insn->src_reg, false);
12323 		} else {
12324 			return false;
12325 		}
12326 		break;
12327 	case BPF_JLT:
12328 		if ((dst_reg->type == PTR_TO_PACKET &&
12329 		     src_reg->type == PTR_TO_PACKET_END) ||
12330 		    (dst_reg->type == PTR_TO_PACKET_META &&
12331 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12332 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
12333 			find_good_pkt_pointers(other_branch, dst_reg,
12334 					       dst_reg->type, true);
12335 			mark_pkt_end(this_branch, insn->dst_reg, false);
12336 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12337 			    src_reg->type == PTR_TO_PACKET) ||
12338 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12339 			    src_reg->type == PTR_TO_PACKET_META)) {
12340 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
12341 			find_good_pkt_pointers(this_branch, src_reg,
12342 					       src_reg->type, false);
12343 			mark_pkt_end(other_branch, insn->src_reg, true);
12344 		} else {
12345 			return false;
12346 		}
12347 		break;
12348 	case BPF_JGE:
12349 		if ((dst_reg->type == PTR_TO_PACKET &&
12350 		     src_reg->type == PTR_TO_PACKET_END) ||
12351 		    (dst_reg->type == PTR_TO_PACKET_META &&
12352 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12353 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
12354 			find_good_pkt_pointers(this_branch, dst_reg,
12355 					       dst_reg->type, true);
12356 			mark_pkt_end(other_branch, insn->dst_reg, false);
12357 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12358 			    src_reg->type == PTR_TO_PACKET) ||
12359 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12360 			    src_reg->type == PTR_TO_PACKET_META)) {
12361 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
12362 			find_good_pkt_pointers(other_branch, src_reg,
12363 					       src_reg->type, false);
12364 			mark_pkt_end(this_branch, insn->src_reg, true);
12365 		} else {
12366 			return false;
12367 		}
12368 		break;
12369 	case BPF_JLE:
12370 		if ((dst_reg->type == PTR_TO_PACKET &&
12371 		     src_reg->type == PTR_TO_PACKET_END) ||
12372 		    (dst_reg->type == PTR_TO_PACKET_META &&
12373 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12374 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
12375 			find_good_pkt_pointers(other_branch, dst_reg,
12376 					       dst_reg->type, false);
12377 			mark_pkt_end(this_branch, insn->dst_reg, true);
12378 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12379 			    src_reg->type == PTR_TO_PACKET) ||
12380 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12381 			    src_reg->type == PTR_TO_PACKET_META)) {
12382 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
12383 			find_good_pkt_pointers(this_branch, src_reg,
12384 					       src_reg->type, true);
12385 			mark_pkt_end(other_branch, insn->src_reg, false);
12386 		} else {
12387 			return false;
12388 		}
12389 		break;
12390 	default:
12391 		return false;
12392 	}
12393 
12394 	return true;
12395 }
12396 
12397 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12398 			       struct bpf_reg_state *known_reg)
12399 {
12400 	struct bpf_func_state *state;
12401 	struct bpf_reg_state *reg;
12402 
12403 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12404 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12405 			copy_register_state(reg, known_reg);
12406 	}));
12407 }
12408 
12409 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12410 			     struct bpf_insn *insn, int *insn_idx)
12411 {
12412 	struct bpf_verifier_state *this_branch = env->cur_state;
12413 	struct bpf_verifier_state *other_branch;
12414 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12415 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12416 	struct bpf_reg_state *eq_branch_regs;
12417 	u8 opcode = BPF_OP(insn->code);
12418 	bool is_jmp32;
12419 	int pred = -1;
12420 	int err;
12421 
12422 	/* Only conditional jumps are expected to reach here. */
12423 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
12424 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12425 		return -EINVAL;
12426 	}
12427 
12428 	if (BPF_SRC(insn->code) == BPF_X) {
12429 		if (insn->imm != 0) {
12430 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12431 			return -EINVAL;
12432 		}
12433 
12434 		/* check src1 operand */
12435 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12436 		if (err)
12437 			return err;
12438 
12439 		if (is_pointer_value(env, insn->src_reg)) {
12440 			verbose(env, "R%d pointer comparison prohibited\n",
12441 				insn->src_reg);
12442 			return -EACCES;
12443 		}
12444 		src_reg = &regs[insn->src_reg];
12445 	} else {
12446 		if (insn->src_reg != BPF_REG_0) {
12447 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12448 			return -EINVAL;
12449 		}
12450 	}
12451 
12452 	/* check src2 operand */
12453 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12454 	if (err)
12455 		return err;
12456 
12457 	dst_reg = &regs[insn->dst_reg];
12458 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12459 
12460 	if (BPF_SRC(insn->code) == BPF_K) {
12461 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12462 	} else if (src_reg->type == SCALAR_VALUE &&
12463 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12464 		pred = is_branch_taken(dst_reg,
12465 				       tnum_subreg(src_reg->var_off).value,
12466 				       opcode,
12467 				       is_jmp32);
12468 	} else if (src_reg->type == SCALAR_VALUE &&
12469 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12470 		pred = is_branch_taken(dst_reg,
12471 				       src_reg->var_off.value,
12472 				       opcode,
12473 				       is_jmp32);
12474 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
12475 		   reg_is_pkt_pointer_any(src_reg) &&
12476 		   !is_jmp32) {
12477 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12478 	}
12479 
12480 	if (pred >= 0) {
12481 		/* If we get here with a dst_reg pointer type it is because
12482 		 * above is_branch_taken() special cased the 0 comparison.
12483 		 */
12484 		if (!__is_pointer_value(false, dst_reg))
12485 			err = mark_chain_precision(env, insn->dst_reg);
12486 		if (BPF_SRC(insn->code) == BPF_X && !err &&
12487 		    !__is_pointer_value(false, src_reg))
12488 			err = mark_chain_precision(env, insn->src_reg);
12489 		if (err)
12490 			return err;
12491 	}
12492 
12493 	if (pred == 1) {
12494 		/* Only follow the goto, ignore fall-through. If needed, push
12495 		 * the fall-through branch for simulation under speculative
12496 		 * execution.
12497 		 */
12498 		if (!env->bypass_spec_v1 &&
12499 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
12500 					       *insn_idx))
12501 			return -EFAULT;
12502 		*insn_idx += insn->off;
12503 		return 0;
12504 	} else if (pred == 0) {
12505 		/* Only follow the fall-through branch, since that's where the
12506 		 * program will go. If needed, push the goto branch for
12507 		 * simulation under speculative execution.
12508 		 */
12509 		if (!env->bypass_spec_v1 &&
12510 		    !sanitize_speculative_path(env, insn,
12511 					       *insn_idx + insn->off + 1,
12512 					       *insn_idx))
12513 			return -EFAULT;
12514 		return 0;
12515 	}
12516 
12517 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12518 				  false);
12519 	if (!other_branch)
12520 		return -EFAULT;
12521 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12522 
12523 	/* detect if we are comparing against a constant value so we can adjust
12524 	 * our min/max values for our dst register.
12525 	 * this is only legit if both are scalars (or pointers to the same
12526 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12527 	 * because otherwise the different base pointers mean the offsets aren't
12528 	 * comparable.
12529 	 */
12530 	if (BPF_SRC(insn->code) == BPF_X) {
12531 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12532 
12533 		if (dst_reg->type == SCALAR_VALUE &&
12534 		    src_reg->type == SCALAR_VALUE) {
12535 			if (tnum_is_const(src_reg->var_off) ||
12536 			    (is_jmp32 &&
12537 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
12538 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
12539 						dst_reg,
12540 						src_reg->var_off.value,
12541 						tnum_subreg(src_reg->var_off).value,
12542 						opcode, is_jmp32);
12543 			else if (tnum_is_const(dst_reg->var_off) ||
12544 				 (is_jmp32 &&
12545 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
12546 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12547 						    src_reg,
12548 						    dst_reg->var_off.value,
12549 						    tnum_subreg(dst_reg->var_off).value,
12550 						    opcode, is_jmp32);
12551 			else if (!is_jmp32 &&
12552 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
12553 				/* Comparing for equality, we can combine knowledge */
12554 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
12555 						    &other_branch_regs[insn->dst_reg],
12556 						    src_reg, dst_reg, opcode);
12557 			if (src_reg->id &&
12558 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12559 				find_equal_scalars(this_branch, src_reg);
12560 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12561 			}
12562 
12563 		}
12564 	} else if (dst_reg->type == SCALAR_VALUE) {
12565 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
12566 					dst_reg, insn->imm, (u32)insn->imm,
12567 					opcode, is_jmp32);
12568 	}
12569 
12570 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12571 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12572 		find_equal_scalars(this_branch, dst_reg);
12573 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12574 	}
12575 
12576 	/* if one pointer register is compared to another pointer
12577 	 * register check if PTR_MAYBE_NULL could be lifted.
12578 	 * E.g. register A - maybe null
12579 	 *      register B - not null
12580 	 * for JNE A, B, ... - A is not null in the false branch;
12581 	 * for JEQ A, B, ... - A is not null in the true branch.
12582 	 *
12583 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
12584 	 * not need to be null checked by the BPF program, i.e.,
12585 	 * could be null even without PTR_MAYBE_NULL marking, so
12586 	 * only propagate nullness when neither reg is that type.
12587 	 */
12588 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12589 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12590 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12591 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
12592 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12593 		eq_branch_regs = NULL;
12594 		switch (opcode) {
12595 		case BPF_JEQ:
12596 			eq_branch_regs = other_branch_regs;
12597 			break;
12598 		case BPF_JNE:
12599 			eq_branch_regs = regs;
12600 			break;
12601 		default:
12602 			/* do nothing */
12603 			break;
12604 		}
12605 		if (eq_branch_regs) {
12606 			if (type_may_be_null(src_reg->type))
12607 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12608 			else
12609 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12610 		}
12611 	}
12612 
12613 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12614 	 * NOTE: these optimizations below are related with pointer comparison
12615 	 *       which will never be JMP32.
12616 	 */
12617 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12618 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12619 	    type_may_be_null(dst_reg->type)) {
12620 		/* Mark all identical registers in each branch as either
12621 		 * safe or unknown depending R == 0 or R != 0 conditional.
12622 		 */
12623 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12624 				      opcode == BPF_JNE);
12625 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12626 				      opcode == BPF_JEQ);
12627 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12628 					   this_branch, other_branch) &&
12629 		   is_pointer_value(env, insn->dst_reg)) {
12630 		verbose(env, "R%d pointer comparison prohibited\n",
12631 			insn->dst_reg);
12632 		return -EACCES;
12633 	}
12634 	if (env->log.level & BPF_LOG_LEVEL)
12635 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
12636 	return 0;
12637 }
12638 
12639 /* verify BPF_LD_IMM64 instruction */
12640 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12641 {
12642 	struct bpf_insn_aux_data *aux = cur_aux(env);
12643 	struct bpf_reg_state *regs = cur_regs(env);
12644 	struct bpf_reg_state *dst_reg;
12645 	struct bpf_map *map;
12646 	int err;
12647 
12648 	if (BPF_SIZE(insn->code) != BPF_DW) {
12649 		verbose(env, "invalid BPF_LD_IMM insn\n");
12650 		return -EINVAL;
12651 	}
12652 	if (insn->off != 0) {
12653 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12654 		return -EINVAL;
12655 	}
12656 
12657 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
12658 	if (err)
12659 		return err;
12660 
12661 	dst_reg = &regs[insn->dst_reg];
12662 	if (insn->src_reg == 0) {
12663 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12664 
12665 		dst_reg->type = SCALAR_VALUE;
12666 		__mark_reg_known(&regs[insn->dst_reg], imm);
12667 		return 0;
12668 	}
12669 
12670 	/* All special src_reg cases are listed below. From this point onwards
12671 	 * we either succeed and assign a corresponding dst_reg->type after
12672 	 * zeroing the offset, or fail and reject the program.
12673 	 */
12674 	mark_reg_known_zero(env, regs, insn->dst_reg);
12675 
12676 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
12677 		dst_reg->type = aux->btf_var.reg_type;
12678 		switch (base_type(dst_reg->type)) {
12679 		case PTR_TO_MEM:
12680 			dst_reg->mem_size = aux->btf_var.mem_size;
12681 			break;
12682 		case PTR_TO_BTF_ID:
12683 			dst_reg->btf = aux->btf_var.btf;
12684 			dst_reg->btf_id = aux->btf_var.btf_id;
12685 			break;
12686 		default:
12687 			verbose(env, "bpf verifier is misconfigured\n");
12688 			return -EFAULT;
12689 		}
12690 		return 0;
12691 	}
12692 
12693 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
12694 		struct bpf_prog_aux *aux = env->prog->aux;
12695 		u32 subprogno = find_subprog(env,
12696 					     env->insn_idx + insn->imm + 1);
12697 
12698 		if (!aux->func_info) {
12699 			verbose(env, "missing btf func_info\n");
12700 			return -EINVAL;
12701 		}
12702 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
12703 			verbose(env, "callback function not static\n");
12704 			return -EINVAL;
12705 		}
12706 
12707 		dst_reg->type = PTR_TO_FUNC;
12708 		dst_reg->subprogno = subprogno;
12709 		return 0;
12710 	}
12711 
12712 	map = env->used_maps[aux->map_index];
12713 	dst_reg->map_ptr = map;
12714 
12715 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
12716 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
12717 		dst_reg->type = PTR_TO_MAP_VALUE;
12718 		dst_reg->off = aux->map_off;
12719 		WARN_ON_ONCE(map->max_entries != 1);
12720 		/* We want reg->id to be same (0) as map_value is not distinct */
12721 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
12722 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
12723 		dst_reg->type = CONST_PTR_TO_MAP;
12724 	} else {
12725 		verbose(env, "bpf verifier is misconfigured\n");
12726 		return -EINVAL;
12727 	}
12728 
12729 	return 0;
12730 }
12731 
12732 static bool may_access_skb(enum bpf_prog_type type)
12733 {
12734 	switch (type) {
12735 	case BPF_PROG_TYPE_SOCKET_FILTER:
12736 	case BPF_PROG_TYPE_SCHED_CLS:
12737 	case BPF_PROG_TYPE_SCHED_ACT:
12738 		return true;
12739 	default:
12740 		return false;
12741 	}
12742 }
12743 
12744 /* verify safety of LD_ABS|LD_IND instructions:
12745  * - they can only appear in the programs where ctx == skb
12746  * - since they are wrappers of function calls, they scratch R1-R5 registers,
12747  *   preserve R6-R9, and store return value into R0
12748  *
12749  * Implicit input:
12750  *   ctx == skb == R6 == CTX
12751  *
12752  * Explicit input:
12753  *   SRC == any register
12754  *   IMM == 32-bit immediate
12755  *
12756  * Output:
12757  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12758  */
12759 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12760 {
12761 	struct bpf_reg_state *regs = cur_regs(env);
12762 	static const int ctx_reg = BPF_REG_6;
12763 	u8 mode = BPF_MODE(insn->code);
12764 	int i, err;
12765 
12766 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12767 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12768 		return -EINVAL;
12769 	}
12770 
12771 	if (!env->ops->gen_ld_abs) {
12772 		verbose(env, "bpf verifier is misconfigured\n");
12773 		return -EINVAL;
12774 	}
12775 
12776 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12777 	    BPF_SIZE(insn->code) == BPF_DW ||
12778 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12779 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12780 		return -EINVAL;
12781 	}
12782 
12783 	/* check whether implicit source operand (register R6) is readable */
12784 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12785 	if (err)
12786 		return err;
12787 
12788 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12789 	 * gen_ld_abs() may terminate the program at runtime, leading to
12790 	 * reference leak.
12791 	 */
12792 	err = check_reference_leak(env);
12793 	if (err) {
12794 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12795 		return err;
12796 	}
12797 
12798 	if (env->cur_state->active_lock.ptr) {
12799 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12800 		return -EINVAL;
12801 	}
12802 
12803 	if (env->cur_state->active_rcu_lock) {
12804 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12805 		return -EINVAL;
12806 	}
12807 
12808 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12809 		verbose(env,
12810 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12811 		return -EINVAL;
12812 	}
12813 
12814 	if (mode == BPF_IND) {
12815 		/* check explicit source operand */
12816 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12817 		if (err)
12818 			return err;
12819 	}
12820 
12821 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12822 	if (err < 0)
12823 		return err;
12824 
12825 	/* reset caller saved regs to unreadable */
12826 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12827 		mark_reg_not_init(env, regs, caller_saved[i]);
12828 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12829 	}
12830 
12831 	/* mark destination R0 register as readable, since it contains
12832 	 * the value fetched from the packet.
12833 	 * Already marked as written above.
12834 	 */
12835 	mark_reg_unknown(env, regs, BPF_REG_0);
12836 	/* ld_abs load up to 32-bit skb data. */
12837 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12838 	return 0;
12839 }
12840 
12841 static int check_return_code(struct bpf_verifier_env *env)
12842 {
12843 	struct tnum enforce_attach_type_range = tnum_unknown;
12844 	const struct bpf_prog *prog = env->prog;
12845 	struct bpf_reg_state *reg;
12846 	struct tnum range = tnum_range(0, 1);
12847 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12848 	int err;
12849 	struct bpf_func_state *frame = env->cur_state->frame[0];
12850 	const bool is_subprog = frame->subprogno;
12851 
12852 	/* LSM and struct_ops func-ptr's return type could be "void" */
12853 	if (!is_subprog) {
12854 		switch (prog_type) {
12855 		case BPF_PROG_TYPE_LSM:
12856 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12857 				/* See below, can be 0 or 0-1 depending on hook. */
12858 				break;
12859 			fallthrough;
12860 		case BPF_PROG_TYPE_STRUCT_OPS:
12861 			if (!prog->aux->attach_func_proto->type)
12862 				return 0;
12863 			break;
12864 		default:
12865 			break;
12866 		}
12867 	}
12868 
12869 	/* eBPF calling convention is such that R0 is used
12870 	 * to return the value from eBPF program.
12871 	 * Make sure that it's readable at this time
12872 	 * of bpf_exit, which means that program wrote
12873 	 * something into it earlier
12874 	 */
12875 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12876 	if (err)
12877 		return err;
12878 
12879 	if (is_pointer_value(env, BPF_REG_0)) {
12880 		verbose(env, "R0 leaks addr as return value\n");
12881 		return -EACCES;
12882 	}
12883 
12884 	reg = cur_regs(env) + BPF_REG_0;
12885 
12886 	if (frame->in_async_callback_fn) {
12887 		/* enforce return zero from async callbacks like timer */
12888 		if (reg->type != SCALAR_VALUE) {
12889 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12890 				reg_type_str(env, reg->type));
12891 			return -EINVAL;
12892 		}
12893 
12894 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12895 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12896 			return -EINVAL;
12897 		}
12898 		return 0;
12899 	}
12900 
12901 	if (is_subprog) {
12902 		if (reg->type != SCALAR_VALUE) {
12903 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12904 				reg_type_str(env, reg->type));
12905 			return -EINVAL;
12906 		}
12907 		return 0;
12908 	}
12909 
12910 	switch (prog_type) {
12911 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12912 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12913 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12914 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12915 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12916 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12917 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12918 			range = tnum_range(1, 1);
12919 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12920 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12921 			range = tnum_range(0, 3);
12922 		break;
12923 	case BPF_PROG_TYPE_CGROUP_SKB:
12924 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12925 			range = tnum_range(0, 3);
12926 			enforce_attach_type_range = tnum_range(2, 3);
12927 		}
12928 		break;
12929 	case BPF_PROG_TYPE_CGROUP_SOCK:
12930 	case BPF_PROG_TYPE_SOCK_OPS:
12931 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12932 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12933 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12934 		break;
12935 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12936 		if (!env->prog->aux->attach_btf_id)
12937 			return 0;
12938 		range = tnum_const(0);
12939 		break;
12940 	case BPF_PROG_TYPE_TRACING:
12941 		switch (env->prog->expected_attach_type) {
12942 		case BPF_TRACE_FENTRY:
12943 		case BPF_TRACE_FEXIT:
12944 			range = tnum_const(0);
12945 			break;
12946 		case BPF_TRACE_RAW_TP:
12947 		case BPF_MODIFY_RETURN:
12948 			return 0;
12949 		case BPF_TRACE_ITER:
12950 			break;
12951 		default:
12952 			return -ENOTSUPP;
12953 		}
12954 		break;
12955 	case BPF_PROG_TYPE_SK_LOOKUP:
12956 		range = tnum_range(SK_DROP, SK_PASS);
12957 		break;
12958 
12959 	case BPF_PROG_TYPE_LSM:
12960 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12961 			/* Regular BPF_PROG_TYPE_LSM programs can return
12962 			 * any value.
12963 			 */
12964 			return 0;
12965 		}
12966 		if (!env->prog->aux->attach_func_proto->type) {
12967 			/* Make sure programs that attach to void
12968 			 * hooks don't try to modify return value.
12969 			 */
12970 			range = tnum_range(1, 1);
12971 		}
12972 		break;
12973 
12974 	case BPF_PROG_TYPE_EXT:
12975 		/* freplace program can return anything as its return value
12976 		 * depends on the to-be-replaced kernel func or bpf program.
12977 		 */
12978 	default:
12979 		return 0;
12980 	}
12981 
12982 	if (reg->type != SCALAR_VALUE) {
12983 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12984 			reg_type_str(env, reg->type));
12985 		return -EINVAL;
12986 	}
12987 
12988 	if (!tnum_in(range, reg->var_off)) {
12989 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12990 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12991 		    prog_type == BPF_PROG_TYPE_LSM &&
12992 		    !prog->aux->attach_func_proto->type)
12993 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12994 		return -EINVAL;
12995 	}
12996 
12997 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12998 	    tnum_in(enforce_attach_type_range, reg->var_off))
12999 		env->prog->enforce_expected_attach_type = 1;
13000 	return 0;
13001 }
13002 
13003 /* non-recursive DFS pseudo code
13004  * 1  procedure DFS-iterative(G,v):
13005  * 2      label v as discovered
13006  * 3      let S be a stack
13007  * 4      S.push(v)
13008  * 5      while S is not empty
13009  * 6            t <- S.peek()
13010  * 7            if t is what we're looking for:
13011  * 8                return t
13012  * 9            for all edges e in G.adjacentEdges(t) do
13013  * 10               if edge e is already labelled
13014  * 11                   continue with the next edge
13015  * 12               w <- G.adjacentVertex(t,e)
13016  * 13               if vertex w is not discovered and not explored
13017  * 14                   label e as tree-edge
13018  * 15                   label w as discovered
13019  * 16                   S.push(w)
13020  * 17                   continue at 5
13021  * 18               else if vertex w is discovered
13022  * 19                   label e as back-edge
13023  * 20               else
13024  * 21                   // vertex w is explored
13025  * 22                   label e as forward- or cross-edge
13026  * 23           label t as explored
13027  * 24           S.pop()
13028  *
13029  * convention:
13030  * 0x10 - discovered
13031  * 0x11 - discovered and fall-through edge labelled
13032  * 0x12 - discovered and fall-through and branch edges labelled
13033  * 0x20 - explored
13034  */
13035 
13036 enum {
13037 	DISCOVERED = 0x10,
13038 	EXPLORED = 0x20,
13039 	FALLTHROUGH = 1,
13040 	BRANCH = 2,
13041 };
13042 
13043 static u32 state_htab_size(struct bpf_verifier_env *env)
13044 {
13045 	return env->prog->len;
13046 }
13047 
13048 static struct bpf_verifier_state_list **explored_state(
13049 					struct bpf_verifier_env *env,
13050 					int idx)
13051 {
13052 	struct bpf_verifier_state *cur = env->cur_state;
13053 	struct bpf_func_state *state = cur->frame[cur->curframe];
13054 
13055 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13056 }
13057 
13058 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13059 {
13060 	env->insn_aux_data[idx].prune_point = true;
13061 }
13062 
13063 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13064 {
13065 	return env->insn_aux_data[insn_idx].prune_point;
13066 }
13067 
13068 enum {
13069 	DONE_EXPLORING = 0,
13070 	KEEP_EXPLORING = 1,
13071 };
13072 
13073 /* t, w, e - match pseudo-code above:
13074  * t - index of current instruction
13075  * w - next instruction
13076  * e - edge
13077  */
13078 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13079 		     bool loop_ok)
13080 {
13081 	int *insn_stack = env->cfg.insn_stack;
13082 	int *insn_state = env->cfg.insn_state;
13083 
13084 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13085 		return DONE_EXPLORING;
13086 
13087 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13088 		return DONE_EXPLORING;
13089 
13090 	if (w < 0 || w >= env->prog->len) {
13091 		verbose_linfo(env, t, "%d: ", t);
13092 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
13093 		return -EINVAL;
13094 	}
13095 
13096 	if (e == BRANCH) {
13097 		/* mark branch target for state pruning */
13098 		mark_prune_point(env, w);
13099 		mark_jmp_point(env, w);
13100 	}
13101 
13102 	if (insn_state[w] == 0) {
13103 		/* tree-edge */
13104 		insn_state[t] = DISCOVERED | e;
13105 		insn_state[w] = DISCOVERED;
13106 		if (env->cfg.cur_stack >= env->prog->len)
13107 			return -E2BIG;
13108 		insn_stack[env->cfg.cur_stack++] = w;
13109 		return KEEP_EXPLORING;
13110 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13111 		if (loop_ok && env->bpf_capable)
13112 			return DONE_EXPLORING;
13113 		verbose_linfo(env, t, "%d: ", t);
13114 		verbose_linfo(env, w, "%d: ", w);
13115 		verbose(env, "back-edge from insn %d to %d\n", t, w);
13116 		return -EINVAL;
13117 	} else if (insn_state[w] == EXPLORED) {
13118 		/* forward- or cross-edge */
13119 		insn_state[t] = DISCOVERED | e;
13120 	} else {
13121 		verbose(env, "insn state internal bug\n");
13122 		return -EFAULT;
13123 	}
13124 	return DONE_EXPLORING;
13125 }
13126 
13127 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13128 				struct bpf_verifier_env *env,
13129 				bool visit_callee)
13130 {
13131 	int ret;
13132 
13133 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13134 	if (ret)
13135 		return ret;
13136 
13137 	mark_prune_point(env, t + 1);
13138 	/* when we exit from subprog, we need to record non-linear history */
13139 	mark_jmp_point(env, t + 1);
13140 
13141 	if (visit_callee) {
13142 		mark_prune_point(env, t);
13143 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13144 				/* It's ok to allow recursion from CFG point of
13145 				 * view. __check_func_call() will do the actual
13146 				 * check.
13147 				 */
13148 				bpf_pseudo_func(insns + t));
13149 	}
13150 	return ret;
13151 }
13152 
13153 /* Visits the instruction at index t and returns one of the following:
13154  *  < 0 - an error occurred
13155  *  DONE_EXPLORING - the instruction was fully explored
13156  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
13157  */
13158 static int visit_insn(int t, struct bpf_verifier_env *env)
13159 {
13160 	struct bpf_insn *insns = env->prog->insnsi;
13161 	int ret;
13162 
13163 	if (bpf_pseudo_func(insns + t))
13164 		return visit_func_call_insn(t, insns, env, true);
13165 
13166 	/* All non-branch instructions have a single fall-through edge. */
13167 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
13168 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
13169 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
13170 
13171 	switch (BPF_OP(insns[t].code)) {
13172 	case BPF_EXIT:
13173 		return DONE_EXPLORING;
13174 
13175 	case BPF_CALL:
13176 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
13177 			/* Mark this call insn as a prune point to trigger
13178 			 * is_state_visited() check before call itself is
13179 			 * processed by __check_func_call(). Otherwise new
13180 			 * async state will be pushed for further exploration.
13181 			 */
13182 			mark_prune_point(env, t);
13183 		return visit_func_call_insn(t, insns, env,
13184 					    insns[t].src_reg == BPF_PSEUDO_CALL);
13185 
13186 	case BPF_JA:
13187 		if (BPF_SRC(insns[t].code) != BPF_K)
13188 			return -EINVAL;
13189 
13190 		/* unconditional jump with single edge */
13191 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
13192 				true);
13193 		if (ret)
13194 			return ret;
13195 
13196 		mark_prune_point(env, t + insns[t].off + 1);
13197 		mark_jmp_point(env, t + insns[t].off + 1);
13198 
13199 		return ret;
13200 
13201 	default:
13202 		/* conditional jump with two edges */
13203 		mark_prune_point(env, t);
13204 
13205 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13206 		if (ret)
13207 			return ret;
13208 
13209 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
13210 	}
13211 }
13212 
13213 /* non-recursive depth-first-search to detect loops in BPF program
13214  * loop == back-edge in directed graph
13215  */
13216 static int check_cfg(struct bpf_verifier_env *env)
13217 {
13218 	int insn_cnt = env->prog->len;
13219 	int *insn_stack, *insn_state;
13220 	int ret = 0;
13221 	int i;
13222 
13223 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13224 	if (!insn_state)
13225 		return -ENOMEM;
13226 
13227 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13228 	if (!insn_stack) {
13229 		kvfree(insn_state);
13230 		return -ENOMEM;
13231 	}
13232 
13233 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13234 	insn_stack[0] = 0; /* 0 is the first instruction */
13235 	env->cfg.cur_stack = 1;
13236 
13237 	while (env->cfg.cur_stack > 0) {
13238 		int t = insn_stack[env->cfg.cur_stack - 1];
13239 
13240 		ret = visit_insn(t, env);
13241 		switch (ret) {
13242 		case DONE_EXPLORING:
13243 			insn_state[t] = EXPLORED;
13244 			env->cfg.cur_stack--;
13245 			break;
13246 		case KEEP_EXPLORING:
13247 			break;
13248 		default:
13249 			if (ret > 0) {
13250 				verbose(env, "visit_insn internal bug\n");
13251 				ret = -EFAULT;
13252 			}
13253 			goto err_free;
13254 		}
13255 	}
13256 
13257 	if (env->cfg.cur_stack < 0) {
13258 		verbose(env, "pop stack internal bug\n");
13259 		ret = -EFAULT;
13260 		goto err_free;
13261 	}
13262 
13263 	for (i = 0; i < insn_cnt; i++) {
13264 		if (insn_state[i] != EXPLORED) {
13265 			verbose(env, "unreachable insn %d\n", i);
13266 			ret = -EINVAL;
13267 			goto err_free;
13268 		}
13269 	}
13270 	ret = 0; /* cfg looks good */
13271 
13272 err_free:
13273 	kvfree(insn_state);
13274 	kvfree(insn_stack);
13275 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
13276 	return ret;
13277 }
13278 
13279 static int check_abnormal_return(struct bpf_verifier_env *env)
13280 {
13281 	int i;
13282 
13283 	for (i = 1; i < env->subprog_cnt; i++) {
13284 		if (env->subprog_info[i].has_ld_abs) {
13285 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13286 			return -EINVAL;
13287 		}
13288 		if (env->subprog_info[i].has_tail_call) {
13289 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13290 			return -EINVAL;
13291 		}
13292 	}
13293 	return 0;
13294 }
13295 
13296 /* The minimum supported BTF func info size */
13297 #define MIN_BPF_FUNCINFO_SIZE	8
13298 #define MAX_FUNCINFO_REC_SIZE	252
13299 
13300 static int check_btf_func(struct bpf_verifier_env *env,
13301 			  const union bpf_attr *attr,
13302 			  bpfptr_t uattr)
13303 {
13304 	const struct btf_type *type, *func_proto, *ret_type;
13305 	u32 i, nfuncs, urec_size, min_size;
13306 	u32 krec_size = sizeof(struct bpf_func_info);
13307 	struct bpf_func_info *krecord;
13308 	struct bpf_func_info_aux *info_aux = NULL;
13309 	struct bpf_prog *prog;
13310 	const struct btf *btf;
13311 	bpfptr_t urecord;
13312 	u32 prev_offset = 0;
13313 	bool scalar_return;
13314 	int ret = -ENOMEM;
13315 
13316 	nfuncs = attr->func_info_cnt;
13317 	if (!nfuncs) {
13318 		if (check_abnormal_return(env))
13319 			return -EINVAL;
13320 		return 0;
13321 	}
13322 
13323 	if (nfuncs != env->subprog_cnt) {
13324 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13325 		return -EINVAL;
13326 	}
13327 
13328 	urec_size = attr->func_info_rec_size;
13329 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13330 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
13331 	    urec_size % sizeof(u32)) {
13332 		verbose(env, "invalid func info rec size %u\n", urec_size);
13333 		return -EINVAL;
13334 	}
13335 
13336 	prog = env->prog;
13337 	btf = prog->aux->btf;
13338 
13339 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13340 	min_size = min_t(u32, krec_size, urec_size);
13341 
13342 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13343 	if (!krecord)
13344 		return -ENOMEM;
13345 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13346 	if (!info_aux)
13347 		goto err_free;
13348 
13349 	for (i = 0; i < nfuncs; i++) {
13350 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13351 		if (ret) {
13352 			if (ret == -E2BIG) {
13353 				verbose(env, "nonzero tailing record in func info");
13354 				/* set the size kernel expects so loader can zero
13355 				 * out the rest of the record.
13356 				 */
13357 				if (copy_to_bpfptr_offset(uattr,
13358 							  offsetof(union bpf_attr, func_info_rec_size),
13359 							  &min_size, sizeof(min_size)))
13360 					ret = -EFAULT;
13361 			}
13362 			goto err_free;
13363 		}
13364 
13365 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13366 			ret = -EFAULT;
13367 			goto err_free;
13368 		}
13369 
13370 		/* check insn_off */
13371 		ret = -EINVAL;
13372 		if (i == 0) {
13373 			if (krecord[i].insn_off) {
13374 				verbose(env,
13375 					"nonzero insn_off %u for the first func info record",
13376 					krecord[i].insn_off);
13377 				goto err_free;
13378 			}
13379 		} else if (krecord[i].insn_off <= prev_offset) {
13380 			verbose(env,
13381 				"same or smaller insn offset (%u) than previous func info record (%u)",
13382 				krecord[i].insn_off, prev_offset);
13383 			goto err_free;
13384 		}
13385 
13386 		if (env->subprog_info[i].start != krecord[i].insn_off) {
13387 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13388 			goto err_free;
13389 		}
13390 
13391 		/* check type_id */
13392 		type = btf_type_by_id(btf, krecord[i].type_id);
13393 		if (!type || !btf_type_is_func(type)) {
13394 			verbose(env, "invalid type id %d in func info",
13395 				krecord[i].type_id);
13396 			goto err_free;
13397 		}
13398 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13399 
13400 		func_proto = btf_type_by_id(btf, type->type);
13401 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13402 			/* btf_func_check() already verified it during BTF load */
13403 			goto err_free;
13404 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13405 		scalar_return =
13406 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13407 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13408 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13409 			goto err_free;
13410 		}
13411 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13412 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13413 			goto err_free;
13414 		}
13415 
13416 		prev_offset = krecord[i].insn_off;
13417 		bpfptr_add(&urecord, urec_size);
13418 	}
13419 
13420 	prog->aux->func_info = krecord;
13421 	prog->aux->func_info_cnt = nfuncs;
13422 	prog->aux->func_info_aux = info_aux;
13423 	return 0;
13424 
13425 err_free:
13426 	kvfree(krecord);
13427 	kfree(info_aux);
13428 	return ret;
13429 }
13430 
13431 static void adjust_btf_func(struct bpf_verifier_env *env)
13432 {
13433 	struct bpf_prog_aux *aux = env->prog->aux;
13434 	int i;
13435 
13436 	if (!aux->func_info)
13437 		return;
13438 
13439 	for (i = 0; i < env->subprog_cnt; i++)
13440 		aux->func_info[i].insn_off = env->subprog_info[i].start;
13441 }
13442 
13443 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
13444 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
13445 
13446 static int check_btf_line(struct bpf_verifier_env *env,
13447 			  const union bpf_attr *attr,
13448 			  bpfptr_t uattr)
13449 {
13450 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13451 	struct bpf_subprog_info *sub;
13452 	struct bpf_line_info *linfo;
13453 	struct bpf_prog *prog;
13454 	const struct btf *btf;
13455 	bpfptr_t ulinfo;
13456 	int err;
13457 
13458 	nr_linfo = attr->line_info_cnt;
13459 	if (!nr_linfo)
13460 		return 0;
13461 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13462 		return -EINVAL;
13463 
13464 	rec_size = attr->line_info_rec_size;
13465 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13466 	    rec_size > MAX_LINEINFO_REC_SIZE ||
13467 	    rec_size & (sizeof(u32) - 1))
13468 		return -EINVAL;
13469 
13470 	/* Need to zero it in case the userspace may
13471 	 * pass in a smaller bpf_line_info object.
13472 	 */
13473 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13474 			 GFP_KERNEL | __GFP_NOWARN);
13475 	if (!linfo)
13476 		return -ENOMEM;
13477 
13478 	prog = env->prog;
13479 	btf = prog->aux->btf;
13480 
13481 	s = 0;
13482 	sub = env->subprog_info;
13483 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13484 	expected_size = sizeof(struct bpf_line_info);
13485 	ncopy = min_t(u32, expected_size, rec_size);
13486 	for (i = 0; i < nr_linfo; i++) {
13487 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13488 		if (err) {
13489 			if (err == -E2BIG) {
13490 				verbose(env, "nonzero tailing record in line_info");
13491 				if (copy_to_bpfptr_offset(uattr,
13492 							  offsetof(union bpf_attr, line_info_rec_size),
13493 							  &expected_size, sizeof(expected_size)))
13494 					err = -EFAULT;
13495 			}
13496 			goto err_free;
13497 		}
13498 
13499 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13500 			err = -EFAULT;
13501 			goto err_free;
13502 		}
13503 
13504 		/*
13505 		 * Check insn_off to ensure
13506 		 * 1) strictly increasing AND
13507 		 * 2) bounded by prog->len
13508 		 *
13509 		 * The linfo[0].insn_off == 0 check logically falls into
13510 		 * the later "missing bpf_line_info for func..." case
13511 		 * because the first linfo[0].insn_off must be the
13512 		 * first sub also and the first sub must have
13513 		 * subprog_info[0].start == 0.
13514 		 */
13515 		if ((i && linfo[i].insn_off <= prev_offset) ||
13516 		    linfo[i].insn_off >= prog->len) {
13517 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13518 				i, linfo[i].insn_off, prev_offset,
13519 				prog->len);
13520 			err = -EINVAL;
13521 			goto err_free;
13522 		}
13523 
13524 		if (!prog->insnsi[linfo[i].insn_off].code) {
13525 			verbose(env,
13526 				"Invalid insn code at line_info[%u].insn_off\n",
13527 				i);
13528 			err = -EINVAL;
13529 			goto err_free;
13530 		}
13531 
13532 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13533 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13534 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13535 			err = -EINVAL;
13536 			goto err_free;
13537 		}
13538 
13539 		if (s != env->subprog_cnt) {
13540 			if (linfo[i].insn_off == sub[s].start) {
13541 				sub[s].linfo_idx = i;
13542 				s++;
13543 			} else if (sub[s].start < linfo[i].insn_off) {
13544 				verbose(env, "missing bpf_line_info for func#%u\n", s);
13545 				err = -EINVAL;
13546 				goto err_free;
13547 			}
13548 		}
13549 
13550 		prev_offset = linfo[i].insn_off;
13551 		bpfptr_add(&ulinfo, rec_size);
13552 	}
13553 
13554 	if (s != env->subprog_cnt) {
13555 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13556 			env->subprog_cnt - s, s);
13557 		err = -EINVAL;
13558 		goto err_free;
13559 	}
13560 
13561 	prog->aux->linfo = linfo;
13562 	prog->aux->nr_linfo = nr_linfo;
13563 
13564 	return 0;
13565 
13566 err_free:
13567 	kvfree(linfo);
13568 	return err;
13569 }
13570 
13571 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
13572 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
13573 
13574 static int check_core_relo(struct bpf_verifier_env *env,
13575 			   const union bpf_attr *attr,
13576 			   bpfptr_t uattr)
13577 {
13578 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13579 	struct bpf_core_relo core_relo = {};
13580 	struct bpf_prog *prog = env->prog;
13581 	const struct btf *btf = prog->aux->btf;
13582 	struct bpf_core_ctx ctx = {
13583 		.log = &env->log,
13584 		.btf = btf,
13585 	};
13586 	bpfptr_t u_core_relo;
13587 	int err;
13588 
13589 	nr_core_relo = attr->core_relo_cnt;
13590 	if (!nr_core_relo)
13591 		return 0;
13592 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13593 		return -EINVAL;
13594 
13595 	rec_size = attr->core_relo_rec_size;
13596 	if (rec_size < MIN_CORE_RELO_SIZE ||
13597 	    rec_size > MAX_CORE_RELO_SIZE ||
13598 	    rec_size % sizeof(u32))
13599 		return -EINVAL;
13600 
13601 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13602 	expected_size = sizeof(struct bpf_core_relo);
13603 	ncopy = min_t(u32, expected_size, rec_size);
13604 
13605 	/* Unlike func_info and line_info, copy and apply each CO-RE
13606 	 * relocation record one at a time.
13607 	 */
13608 	for (i = 0; i < nr_core_relo; i++) {
13609 		/* future proofing when sizeof(bpf_core_relo) changes */
13610 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13611 		if (err) {
13612 			if (err == -E2BIG) {
13613 				verbose(env, "nonzero tailing record in core_relo");
13614 				if (copy_to_bpfptr_offset(uattr,
13615 							  offsetof(union bpf_attr, core_relo_rec_size),
13616 							  &expected_size, sizeof(expected_size)))
13617 					err = -EFAULT;
13618 			}
13619 			break;
13620 		}
13621 
13622 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13623 			err = -EFAULT;
13624 			break;
13625 		}
13626 
13627 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13628 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13629 				i, core_relo.insn_off, prog->len);
13630 			err = -EINVAL;
13631 			break;
13632 		}
13633 
13634 		err = bpf_core_apply(&ctx, &core_relo, i,
13635 				     &prog->insnsi[core_relo.insn_off / 8]);
13636 		if (err)
13637 			break;
13638 		bpfptr_add(&u_core_relo, rec_size);
13639 	}
13640 	return err;
13641 }
13642 
13643 static int check_btf_info(struct bpf_verifier_env *env,
13644 			  const union bpf_attr *attr,
13645 			  bpfptr_t uattr)
13646 {
13647 	struct btf *btf;
13648 	int err;
13649 
13650 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
13651 		if (check_abnormal_return(env))
13652 			return -EINVAL;
13653 		return 0;
13654 	}
13655 
13656 	btf = btf_get_by_fd(attr->prog_btf_fd);
13657 	if (IS_ERR(btf))
13658 		return PTR_ERR(btf);
13659 	if (btf_is_kernel(btf)) {
13660 		btf_put(btf);
13661 		return -EACCES;
13662 	}
13663 	env->prog->aux->btf = btf;
13664 
13665 	err = check_btf_func(env, attr, uattr);
13666 	if (err)
13667 		return err;
13668 
13669 	err = check_btf_line(env, attr, uattr);
13670 	if (err)
13671 		return err;
13672 
13673 	err = check_core_relo(env, attr, uattr);
13674 	if (err)
13675 		return err;
13676 
13677 	return 0;
13678 }
13679 
13680 /* check %cur's range satisfies %old's */
13681 static bool range_within(struct bpf_reg_state *old,
13682 			 struct bpf_reg_state *cur)
13683 {
13684 	return old->umin_value <= cur->umin_value &&
13685 	       old->umax_value >= cur->umax_value &&
13686 	       old->smin_value <= cur->smin_value &&
13687 	       old->smax_value >= cur->smax_value &&
13688 	       old->u32_min_value <= cur->u32_min_value &&
13689 	       old->u32_max_value >= cur->u32_max_value &&
13690 	       old->s32_min_value <= cur->s32_min_value &&
13691 	       old->s32_max_value >= cur->s32_max_value;
13692 }
13693 
13694 /* If in the old state two registers had the same id, then they need to have
13695  * the same id in the new state as well.  But that id could be different from
13696  * the old state, so we need to track the mapping from old to new ids.
13697  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
13698  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
13699  * regs with a different old id could still have new id 9, we don't care about
13700  * that.
13701  * So we look through our idmap to see if this old id has been seen before.  If
13702  * so, we require the new id to match; otherwise, we add the id pair to the map.
13703  */
13704 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
13705 {
13706 	unsigned int i;
13707 
13708 	/* either both IDs should be set or both should be zero */
13709 	if (!!old_id != !!cur_id)
13710 		return false;
13711 
13712 	if (old_id == 0) /* cur_id == 0 as well */
13713 		return true;
13714 
13715 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
13716 		if (!idmap[i].old) {
13717 			/* Reached an empty slot; haven't seen this id before */
13718 			idmap[i].old = old_id;
13719 			idmap[i].cur = cur_id;
13720 			return true;
13721 		}
13722 		if (idmap[i].old == old_id)
13723 			return idmap[i].cur == cur_id;
13724 	}
13725 	/* We ran out of idmap slots, which should be impossible */
13726 	WARN_ON_ONCE(1);
13727 	return false;
13728 }
13729 
13730 static void clean_func_state(struct bpf_verifier_env *env,
13731 			     struct bpf_func_state *st)
13732 {
13733 	enum bpf_reg_liveness live;
13734 	int i, j;
13735 
13736 	for (i = 0; i < BPF_REG_FP; i++) {
13737 		live = st->regs[i].live;
13738 		/* liveness must not touch this register anymore */
13739 		st->regs[i].live |= REG_LIVE_DONE;
13740 		if (!(live & REG_LIVE_READ))
13741 			/* since the register is unused, clear its state
13742 			 * to make further comparison simpler
13743 			 */
13744 			__mark_reg_not_init(env, &st->regs[i]);
13745 	}
13746 
13747 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
13748 		live = st->stack[i].spilled_ptr.live;
13749 		/* liveness must not touch this stack slot anymore */
13750 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13751 		if (!(live & REG_LIVE_READ)) {
13752 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13753 			for (j = 0; j < BPF_REG_SIZE; j++)
13754 				st->stack[i].slot_type[j] = STACK_INVALID;
13755 		}
13756 	}
13757 }
13758 
13759 static void clean_verifier_state(struct bpf_verifier_env *env,
13760 				 struct bpf_verifier_state *st)
13761 {
13762 	int i;
13763 
13764 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13765 		/* all regs in this state in all frames were already marked */
13766 		return;
13767 
13768 	for (i = 0; i <= st->curframe; i++)
13769 		clean_func_state(env, st->frame[i]);
13770 }
13771 
13772 /* the parentage chains form a tree.
13773  * the verifier states are added to state lists at given insn and
13774  * pushed into state stack for future exploration.
13775  * when the verifier reaches bpf_exit insn some of the verifer states
13776  * stored in the state lists have their final liveness state already,
13777  * but a lot of states will get revised from liveness point of view when
13778  * the verifier explores other branches.
13779  * Example:
13780  * 1: r0 = 1
13781  * 2: if r1 == 100 goto pc+1
13782  * 3: r0 = 2
13783  * 4: exit
13784  * when the verifier reaches exit insn the register r0 in the state list of
13785  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13786  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13787  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13788  *
13789  * Since the verifier pushes the branch states as it sees them while exploring
13790  * the program the condition of walking the branch instruction for the second
13791  * time means that all states below this branch were already explored and
13792  * their final liveness marks are already propagated.
13793  * Hence when the verifier completes the search of state list in is_state_visited()
13794  * we can call this clean_live_states() function to mark all liveness states
13795  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13796  * will not be used.
13797  * This function also clears the registers and stack for states that !READ
13798  * to simplify state merging.
13799  *
13800  * Important note here that walking the same branch instruction in the callee
13801  * doesn't meant that the states are DONE. The verifier has to compare
13802  * the callsites
13803  */
13804 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13805 			      struct bpf_verifier_state *cur)
13806 {
13807 	struct bpf_verifier_state_list *sl;
13808 	int i;
13809 
13810 	sl = *explored_state(env, insn);
13811 	while (sl) {
13812 		if (sl->state.branches)
13813 			goto next;
13814 		if (sl->state.insn_idx != insn ||
13815 		    sl->state.curframe != cur->curframe)
13816 			goto next;
13817 		for (i = 0; i <= cur->curframe; i++)
13818 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13819 				goto next;
13820 		clean_verifier_state(env, &sl->state);
13821 next:
13822 		sl = sl->next;
13823 	}
13824 }
13825 
13826 static bool regs_exact(const struct bpf_reg_state *rold,
13827 		       const struct bpf_reg_state *rcur,
13828 		       struct bpf_id_pair *idmap)
13829 {
13830 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13831 	       check_ids(rold->id, rcur->id, idmap) &&
13832 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13833 }
13834 
13835 /* Returns true if (rold safe implies rcur safe) */
13836 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13837 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13838 {
13839 	if (!(rold->live & REG_LIVE_READ))
13840 		/* explored state didn't use this */
13841 		return true;
13842 	if (rold->type == NOT_INIT)
13843 		/* explored state can't have used this */
13844 		return true;
13845 	if (rcur->type == NOT_INIT)
13846 		return false;
13847 
13848 	/* Enforce that register types have to match exactly, including their
13849 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13850 	 * rule.
13851 	 *
13852 	 * One can make a point that using a pointer register as unbounded
13853 	 * SCALAR would be technically acceptable, but this could lead to
13854 	 * pointer leaks because scalars are allowed to leak while pointers
13855 	 * are not. We could make this safe in special cases if root is
13856 	 * calling us, but it's probably not worth the hassle.
13857 	 *
13858 	 * Also, register types that are *not* MAYBE_NULL could technically be
13859 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13860 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13861 	 * to the same map).
13862 	 * However, if the old MAYBE_NULL register then got NULL checked,
13863 	 * doing so could have affected others with the same id, and we can't
13864 	 * check for that because we lost the id when we converted to
13865 	 * a non-MAYBE_NULL variant.
13866 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13867 	 * non-MAYBE_NULL registers as well.
13868 	 */
13869 	if (rold->type != rcur->type)
13870 		return false;
13871 
13872 	switch (base_type(rold->type)) {
13873 	case SCALAR_VALUE:
13874 		if (regs_exact(rold, rcur, idmap))
13875 			return true;
13876 		if (env->explore_alu_limits)
13877 			return false;
13878 		if (!rold->precise)
13879 			return true;
13880 		/* new val must satisfy old val knowledge */
13881 		return range_within(rold, rcur) &&
13882 		       tnum_in(rold->var_off, rcur->var_off);
13883 	case PTR_TO_MAP_KEY:
13884 	case PTR_TO_MAP_VALUE:
13885 		/* If the new min/max/var_off satisfy the old ones and
13886 		 * everything else matches, we are OK.
13887 		 */
13888 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13889 		       range_within(rold, rcur) &&
13890 		       tnum_in(rold->var_off, rcur->var_off) &&
13891 		       check_ids(rold->id, rcur->id, idmap);
13892 	case PTR_TO_PACKET_META:
13893 	case PTR_TO_PACKET:
13894 		/* We must have at least as much range as the old ptr
13895 		 * did, so that any accesses which were safe before are
13896 		 * still safe.  This is true even if old range < old off,
13897 		 * since someone could have accessed through (ptr - k), or
13898 		 * even done ptr -= k in a register, to get a safe access.
13899 		 */
13900 		if (rold->range > rcur->range)
13901 			return false;
13902 		/* If the offsets don't match, we can't trust our alignment;
13903 		 * nor can we be sure that we won't fall out of range.
13904 		 */
13905 		if (rold->off != rcur->off)
13906 			return false;
13907 		/* id relations must be preserved */
13908 		if (!check_ids(rold->id, rcur->id, idmap))
13909 			return false;
13910 		/* new val must satisfy old val knowledge */
13911 		return range_within(rold, rcur) &&
13912 		       tnum_in(rold->var_off, rcur->var_off);
13913 	case PTR_TO_STACK:
13914 		/* two stack pointers are equal only if they're pointing to
13915 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13916 		 */
13917 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13918 	default:
13919 		return regs_exact(rold, rcur, idmap);
13920 	}
13921 }
13922 
13923 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13924 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13925 {
13926 	int i, spi;
13927 
13928 	/* walk slots of the explored stack and ignore any additional
13929 	 * slots in the current stack, since explored(safe) state
13930 	 * didn't use them
13931 	 */
13932 	for (i = 0; i < old->allocated_stack; i++) {
13933 		spi = i / BPF_REG_SIZE;
13934 
13935 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13936 			i += BPF_REG_SIZE - 1;
13937 			/* explored state didn't use this */
13938 			continue;
13939 		}
13940 
13941 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13942 			continue;
13943 
13944 		if (env->allow_uninit_stack &&
13945 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
13946 			continue;
13947 
13948 		/* explored stack has more populated slots than current stack
13949 		 * and these slots were used
13950 		 */
13951 		if (i >= cur->allocated_stack)
13952 			return false;
13953 
13954 		/* if old state was safe with misc data in the stack
13955 		 * it will be safe with zero-initialized stack.
13956 		 * The opposite is not true
13957 		 */
13958 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13959 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13960 			continue;
13961 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13962 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13963 			/* Ex: old explored (safe) state has STACK_SPILL in
13964 			 * this stack slot, but current has STACK_MISC ->
13965 			 * this verifier states are not equivalent,
13966 			 * return false to continue verification of this path
13967 			 */
13968 			return false;
13969 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13970 			continue;
13971 		/* Both old and cur are having same slot_type */
13972 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
13973 		case STACK_SPILL:
13974 			/* when explored and current stack slot are both storing
13975 			 * spilled registers, check that stored pointers types
13976 			 * are the same as well.
13977 			 * Ex: explored safe path could have stored
13978 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13979 			 * but current path has stored:
13980 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13981 			 * such verifier states are not equivalent.
13982 			 * return false to continue verification of this path
13983 			 */
13984 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
13985 				     &cur->stack[spi].spilled_ptr, idmap))
13986 				return false;
13987 			break;
13988 		case STACK_DYNPTR:
13989 		{
13990 			const struct bpf_reg_state *old_reg, *cur_reg;
13991 
13992 			old_reg = &old->stack[spi].spilled_ptr;
13993 			cur_reg = &cur->stack[spi].spilled_ptr;
13994 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
13995 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
13996 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
13997 				return false;
13998 			break;
13999 		}
14000 		case STACK_MISC:
14001 		case STACK_ZERO:
14002 		case STACK_INVALID:
14003 			continue;
14004 		/* Ensure that new unhandled slot types return false by default */
14005 		default:
14006 			return false;
14007 		}
14008 	}
14009 	return true;
14010 }
14011 
14012 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14013 		    struct bpf_id_pair *idmap)
14014 {
14015 	int i;
14016 
14017 	if (old->acquired_refs != cur->acquired_refs)
14018 		return false;
14019 
14020 	for (i = 0; i < old->acquired_refs; i++) {
14021 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14022 			return false;
14023 	}
14024 
14025 	return true;
14026 }
14027 
14028 /* compare two verifier states
14029  *
14030  * all states stored in state_list are known to be valid, since
14031  * verifier reached 'bpf_exit' instruction through them
14032  *
14033  * this function is called when verifier exploring different branches of
14034  * execution popped from the state stack. If it sees an old state that has
14035  * more strict register state and more strict stack state then this execution
14036  * branch doesn't need to be explored further, since verifier already
14037  * concluded that more strict state leads to valid finish.
14038  *
14039  * Therefore two states are equivalent if register state is more conservative
14040  * and explored stack state is more conservative than the current one.
14041  * Example:
14042  *       explored                   current
14043  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14044  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14045  *
14046  * In other words if current stack state (one being explored) has more
14047  * valid slots than old one that already passed validation, it means
14048  * the verifier can stop exploring and conclude that current state is valid too
14049  *
14050  * Similarly with registers. If explored state has register type as invalid
14051  * whereas register type in current state is meaningful, it means that
14052  * the current state will reach 'bpf_exit' instruction safely
14053  */
14054 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14055 			      struct bpf_func_state *cur)
14056 {
14057 	int i;
14058 
14059 	for (i = 0; i < MAX_BPF_REG; i++)
14060 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
14061 			     env->idmap_scratch))
14062 			return false;
14063 
14064 	if (!stacksafe(env, old, cur, env->idmap_scratch))
14065 		return false;
14066 
14067 	if (!refsafe(old, cur, env->idmap_scratch))
14068 		return false;
14069 
14070 	return true;
14071 }
14072 
14073 static bool states_equal(struct bpf_verifier_env *env,
14074 			 struct bpf_verifier_state *old,
14075 			 struct bpf_verifier_state *cur)
14076 {
14077 	int i;
14078 
14079 	if (old->curframe != cur->curframe)
14080 		return false;
14081 
14082 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14083 
14084 	/* Verification state from speculative execution simulation
14085 	 * must never prune a non-speculative execution one.
14086 	 */
14087 	if (old->speculative && !cur->speculative)
14088 		return false;
14089 
14090 	if (old->active_lock.ptr != cur->active_lock.ptr)
14091 		return false;
14092 
14093 	/* Old and cur active_lock's have to be either both present
14094 	 * or both absent.
14095 	 */
14096 	if (!!old->active_lock.id != !!cur->active_lock.id)
14097 		return false;
14098 
14099 	if (old->active_lock.id &&
14100 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14101 		return false;
14102 
14103 	if (old->active_rcu_lock != cur->active_rcu_lock)
14104 		return false;
14105 
14106 	/* for states to be equal callsites have to be the same
14107 	 * and all frame states need to be equivalent
14108 	 */
14109 	for (i = 0; i <= old->curframe; i++) {
14110 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
14111 			return false;
14112 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14113 			return false;
14114 	}
14115 	return true;
14116 }
14117 
14118 /* Return 0 if no propagation happened. Return negative error code if error
14119  * happened. Otherwise, return the propagated bit.
14120  */
14121 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14122 				  struct bpf_reg_state *reg,
14123 				  struct bpf_reg_state *parent_reg)
14124 {
14125 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14126 	u8 flag = reg->live & REG_LIVE_READ;
14127 	int err;
14128 
14129 	/* When comes here, read flags of PARENT_REG or REG could be any of
14130 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14131 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14132 	 */
14133 	if (parent_flag == REG_LIVE_READ64 ||
14134 	    /* Or if there is no read flag from REG. */
14135 	    !flag ||
14136 	    /* Or if the read flag from REG is the same as PARENT_REG. */
14137 	    parent_flag == flag)
14138 		return 0;
14139 
14140 	err = mark_reg_read(env, reg, parent_reg, flag);
14141 	if (err)
14142 		return err;
14143 
14144 	return flag;
14145 }
14146 
14147 /* A write screens off any subsequent reads; but write marks come from the
14148  * straight-line code between a state and its parent.  When we arrive at an
14149  * equivalent state (jump target or such) we didn't arrive by the straight-line
14150  * code, so read marks in the state must propagate to the parent regardless
14151  * of the state's write marks. That's what 'parent == state->parent' comparison
14152  * in mark_reg_read() is for.
14153  */
14154 static int propagate_liveness(struct bpf_verifier_env *env,
14155 			      const struct bpf_verifier_state *vstate,
14156 			      struct bpf_verifier_state *vparent)
14157 {
14158 	struct bpf_reg_state *state_reg, *parent_reg;
14159 	struct bpf_func_state *state, *parent;
14160 	int i, frame, err = 0;
14161 
14162 	if (vparent->curframe != vstate->curframe) {
14163 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
14164 		     vparent->curframe, vstate->curframe);
14165 		return -EFAULT;
14166 	}
14167 	/* Propagate read liveness of registers... */
14168 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14169 	for (frame = 0; frame <= vstate->curframe; frame++) {
14170 		parent = vparent->frame[frame];
14171 		state = vstate->frame[frame];
14172 		parent_reg = parent->regs;
14173 		state_reg = state->regs;
14174 		/* We don't need to worry about FP liveness, it's read-only */
14175 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14176 			err = propagate_liveness_reg(env, &state_reg[i],
14177 						     &parent_reg[i]);
14178 			if (err < 0)
14179 				return err;
14180 			if (err == REG_LIVE_READ64)
14181 				mark_insn_zext(env, &parent_reg[i]);
14182 		}
14183 
14184 		/* Propagate stack slots. */
14185 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14186 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14187 			parent_reg = &parent->stack[i].spilled_ptr;
14188 			state_reg = &state->stack[i].spilled_ptr;
14189 			err = propagate_liveness_reg(env, state_reg,
14190 						     parent_reg);
14191 			if (err < 0)
14192 				return err;
14193 		}
14194 	}
14195 	return 0;
14196 }
14197 
14198 /* find precise scalars in the previous equivalent state and
14199  * propagate them into the current state
14200  */
14201 static int propagate_precision(struct bpf_verifier_env *env,
14202 			       const struct bpf_verifier_state *old)
14203 {
14204 	struct bpf_reg_state *state_reg;
14205 	struct bpf_func_state *state;
14206 	int i, err = 0, fr;
14207 
14208 	for (fr = old->curframe; fr >= 0; fr--) {
14209 		state = old->frame[fr];
14210 		state_reg = state->regs;
14211 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14212 			if (state_reg->type != SCALAR_VALUE ||
14213 			    !state_reg->precise)
14214 				continue;
14215 			if (env->log.level & BPF_LOG_LEVEL2)
14216 				verbose(env, "frame %d: propagating r%d\n", i, fr);
14217 			err = mark_chain_precision_frame(env, fr, i);
14218 			if (err < 0)
14219 				return err;
14220 		}
14221 
14222 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14223 			if (!is_spilled_reg(&state->stack[i]))
14224 				continue;
14225 			state_reg = &state->stack[i].spilled_ptr;
14226 			if (state_reg->type != SCALAR_VALUE ||
14227 			    !state_reg->precise)
14228 				continue;
14229 			if (env->log.level & BPF_LOG_LEVEL2)
14230 				verbose(env, "frame %d: propagating fp%d\n",
14231 					(-i - 1) * BPF_REG_SIZE, fr);
14232 			err = mark_chain_precision_stack_frame(env, fr, i);
14233 			if (err < 0)
14234 				return err;
14235 		}
14236 	}
14237 	return 0;
14238 }
14239 
14240 static bool states_maybe_looping(struct bpf_verifier_state *old,
14241 				 struct bpf_verifier_state *cur)
14242 {
14243 	struct bpf_func_state *fold, *fcur;
14244 	int i, fr = cur->curframe;
14245 
14246 	if (old->curframe != fr)
14247 		return false;
14248 
14249 	fold = old->frame[fr];
14250 	fcur = cur->frame[fr];
14251 	for (i = 0; i < MAX_BPF_REG; i++)
14252 		if (memcmp(&fold->regs[i], &fcur->regs[i],
14253 			   offsetof(struct bpf_reg_state, parent)))
14254 			return false;
14255 	return true;
14256 }
14257 
14258 
14259 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14260 {
14261 	struct bpf_verifier_state_list *new_sl;
14262 	struct bpf_verifier_state_list *sl, **pprev;
14263 	struct bpf_verifier_state *cur = env->cur_state, *new;
14264 	int i, j, err, states_cnt = 0;
14265 	bool add_new_state = env->test_state_freq ? true : false;
14266 
14267 	/* bpf progs typically have pruning point every 4 instructions
14268 	 * http://vger.kernel.org/bpfconf2019.html#session-1
14269 	 * Do not add new state for future pruning if the verifier hasn't seen
14270 	 * at least 2 jumps and at least 8 instructions.
14271 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14272 	 * In tests that amounts to up to 50% reduction into total verifier
14273 	 * memory consumption and 20% verifier time speedup.
14274 	 */
14275 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14276 	    env->insn_processed - env->prev_insn_processed >= 8)
14277 		add_new_state = true;
14278 
14279 	pprev = explored_state(env, insn_idx);
14280 	sl = *pprev;
14281 
14282 	clean_live_states(env, insn_idx, cur);
14283 
14284 	while (sl) {
14285 		states_cnt++;
14286 		if (sl->state.insn_idx != insn_idx)
14287 			goto next;
14288 
14289 		if (sl->state.branches) {
14290 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14291 
14292 			if (frame->in_async_callback_fn &&
14293 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14294 				/* Different async_entry_cnt means that the verifier is
14295 				 * processing another entry into async callback.
14296 				 * Seeing the same state is not an indication of infinite
14297 				 * loop or infinite recursion.
14298 				 * But finding the same state doesn't mean that it's safe
14299 				 * to stop processing the current state. The previous state
14300 				 * hasn't yet reached bpf_exit, since state.branches > 0.
14301 				 * Checking in_async_callback_fn alone is not enough either.
14302 				 * Since the verifier still needs to catch infinite loops
14303 				 * inside async callbacks.
14304 				 */
14305 			} else if (states_maybe_looping(&sl->state, cur) &&
14306 				   states_equal(env, &sl->state, cur)) {
14307 				verbose_linfo(env, insn_idx, "; ");
14308 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14309 				return -EINVAL;
14310 			}
14311 			/* if the verifier is processing a loop, avoid adding new state
14312 			 * too often, since different loop iterations have distinct
14313 			 * states and may not help future pruning.
14314 			 * This threshold shouldn't be too low to make sure that
14315 			 * a loop with large bound will be rejected quickly.
14316 			 * The most abusive loop will be:
14317 			 * r1 += 1
14318 			 * if r1 < 1000000 goto pc-2
14319 			 * 1M insn_procssed limit / 100 == 10k peak states.
14320 			 * This threshold shouldn't be too high either, since states
14321 			 * at the end of the loop are likely to be useful in pruning.
14322 			 */
14323 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
14324 			    env->insn_processed - env->prev_insn_processed < 100)
14325 				add_new_state = false;
14326 			goto miss;
14327 		}
14328 		if (states_equal(env, &sl->state, cur)) {
14329 			sl->hit_cnt++;
14330 			/* reached equivalent register/stack state,
14331 			 * prune the search.
14332 			 * Registers read by the continuation are read by us.
14333 			 * If we have any write marks in env->cur_state, they
14334 			 * will prevent corresponding reads in the continuation
14335 			 * from reaching our parent (an explored_state).  Our
14336 			 * own state will get the read marks recorded, but
14337 			 * they'll be immediately forgotten as we're pruning
14338 			 * this state and will pop a new one.
14339 			 */
14340 			err = propagate_liveness(env, &sl->state, cur);
14341 
14342 			/* if previous state reached the exit with precision and
14343 			 * current state is equivalent to it (except precsion marks)
14344 			 * the precision needs to be propagated back in
14345 			 * the current state.
14346 			 */
14347 			err = err ? : push_jmp_history(env, cur);
14348 			err = err ? : propagate_precision(env, &sl->state);
14349 			if (err)
14350 				return err;
14351 			return 1;
14352 		}
14353 miss:
14354 		/* when new state is not going to be added do not increase miss count.
14355 		 * Otherwise several loop iterations will remove the state
14356 		 * recorded earlier. The goal of these heuristics is to have
14357 		 * states from some iterations of the loop (some in the beginning
14358 		 * and some at the end) to help pruning.
14359 		 */
14360 		if (add_new_state)
14361 			sl->miss_cnt++;
14362 		/* heuristic to determine whether this state is beneficial
14363 		 * to keep checking from state equivalence point of view.
14364 		 * Higher numbers increase max_states_per_insn and verification time,
14365 		 * but do not meaningfully decrease insn_processed.
14366 		 */
14367 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14368 			/* the state is unlikely to be useful. Remove it to
14369 			 * speed up verification
14370 			 */
14371 			*pprev = sl->next;
14372 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14373 				u32 br = sl->state.branches;
14374 
14375 				WARN_ONCE(br,
14376 					  "BUG live_done but branches_to_explore %d\n",
14377 					  br);
14378 				free_verifier_state(&sl->state, false);
14379 				kfree(sl);
14380 				env->peak_states--;
14381 			} else {
14382 				/* cannot free this state, since parentage chain may
14383 				 * walk it later. Add it for free_list instead to
14384 				 * be freed at the end of verification
14385 				 */
14386 				sl->next = env->free_list;
14387 				env->free_list = sl;
14388 			}
14389 			sl = *pprev;
14390 			continue;
14391 		}
14392 next:
14393 		pprev = &sl->next;
14394 		sl = *pprev;
14395 	}
14396 
14397 	if (env->max_states_per_insn < states_cnt)
14398 		env->max_states_per_insn = states_cnt;
14399 
14400 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14401 		return 0;
14402 
14403 	if (!add_new_state)
14404 		return 0;
14405 
14406 	/* There were no equivalent states, remember the current one.
14407 	 * Technically the current state is not proven to be safe yet,
14408 	 * but it will either reach outer most bpf_exit (which means it's safe)
14409 	 * or it will be rejected. When there are no loops the verifier won't be
14410 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14411 	 * again on the way to bpf_exit.
14412 	 * When looping the sl->state.branches will be > 0 and this state
14413 	 * will not be considered for equivalence until branches == 0.
14414 	 */
14415 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14416 	if (!new_sl)
14417 		return -ENOMEM;
14418 	env->total_states++;
14419 	env->peak_states++;
14420 	env->prev_jmps_processed = env->jmps_processed;
14421 	env->prev_insn_processed = env->insn_processed;
14422 
14423 	/* forget precise markings we inherited, see __mark_chain_precision */
14424 	if (env->bpf_capable)
14425 		mark_all_scalars_imprecise(env, cur);
14426 
14427 	/* add new state to the head of linked list */
14428 	new = &new_sl->state;
14429 	err = copy_verifier_state(new, cur);
14430 	if (err) {
14431 		free_verifier_state(new, false);
14432 		kfree(new_sl);
14433 		return err;
14434 	}
14435 	new->insn_idx = insn_idx;
14436 	WARN_ONCE(new->branches != 1,
14437 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14438 
14439 	cur->parent = new;
14440 	cur->first_insn_idx = insn_idx;
14441 	clear_jmp_history(cur);
14442 	new_sl->next = *explored_state(env, insn_idx);
14443 	*explored_state(env, insn_idx) = new_sl;
14444 	/* connect new state to parentage chain. Current frame needs all
14445 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
14446 	 * to the stack implicitly by JITs) so in callers' frames connect just
14447 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14448 	 * the state of the call instruction (with WRITTEN set), and r0 comes
14449 	 * from callee with its full parentage chain, anyway.
14450 	 */
14451 	/* clear write marks in current state: the writes we did are not writes
14452 	 * our child did, so they don't screen off its reads from us.
14453 	 * (There are no read marks in current state, because reads always mark
14454 	 * their parent and current state never has children yet.  Only
14455 	 * explored_states can get read marks.)
14456 	 */
14457 	for (j = 0; j <= cur->curframe; j++) {
14458 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14459 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14460 		for (i = 0; i < BPF_REG_FP; i++)
14461 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14462 	}
14463 
14464 	/* all stack frames are accessible from callee, clear them all */
14465 	for (j = 0; j <= cur->curframe; j++) {
14466 		struct bpf_func_state *frame = cur->frame[j];
14467 		struct bpf_func_state *newframe = new->frame[j];
14468 
14469 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14470 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14471 			frame->stack[i].spilled_ptr.parent =
14472 						&newframe->stack[i].spilled_ptr;
14473 		}
14474 	}
14475 	return 0;
14476 }
14477 
14478 /* Return true if it's OK to have the same insn return a different type. */
14479 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14480 {
14481 	switch (base_type(type)) {
14482 	case PTR_TO_CTX:
14483 	case PTR_TO_SOCKET:
14484 	case PTR_TO_SOCK_COMMON:
14485 	case PTR_TO_TCP_SOCK:
14486 	case PTR_TO_XDP_SOCK:
14487 	case PTR_TO_BTF_ID:
14488 		return false;
14489 	default:
14490 		return true;
14491 	}
14492 }
14493 
14494 /* If an instruction was previously used with particular pointer types, then we
14495  * need to be careful to avoid cases such as the below, where it may be ok
14496  * for one branch accessing the pointer, but not ok for the other branch:
14497  *
14498  * R1 = sock_ptr
14499  * goto X;
14500  * ...
14501  * R1 = some_other_valid_ptr;
14502  * goto X;
14503  * ...
14504  * R2 = *(u32 *)(R1 + 0);
14505  */
14506 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14507 {
14508 	return src != prev && (!reg_type_mismatch_ok(src) ||
14509 			       !reg_type_mismatch_ok(prev));
14510 }
14511 
14512 static int do_check(struct bpf_verifier_env *env)
14513 {
14514 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14515 	struct bpf_verifier_state *state = env->cur_state;
14516 	struct bpf_insn *insns = env->prog->insnsi;
14517 	struct bpf_reg_state *regs;
14518 	int insn_cnt = env->prog->len;
14519 	bool do_print_state = false;
14520 	int prev_insn_idx = -1;
14521 
14522 	for (;;) {
14523 		struct bpf_insn *insn;
14524 		u8 class;
14525 		int err;
14526 
14527 		env->prev_insn_idx = prev_insn_idx;
14528 		if (env->insn_idx >= insn_cnt) {
14529 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
14530 				env->insn_idx, insn_cnt);
14531 			return -EFAULT;
14532 		}
14533 
14534 		insn = &insns[env->insn_idx];
14535 		class = BPF_CLASS(insn->code);
14536 
14537 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14538 			verbose(env,
14539 				"BPF program is too large. Processed %d insn\n",
14540 				env->insn_processed);
14541 			return -E2BIG;
14542 		}
14543 
14544 		state->last_insn_idx = env->prev_insn_idx;
14545 
14546 		if (is_prune_point(env, env->insn_idx)) {
14547 			err = is_state_visited(env, env->insn_idx);
14548 			if (err < 0)
14549 				return err;
14550 			if (err == 1) {
14551 				/* found equivalent state, can prune the search */
14552 				if (env->log.level & BPF_LOG_LEVEL) {
14553 					if (do_print_state)
14554 						verbose(env, "\nfrom %d to %d%s: safe\n",
14555 							env->prev_insn_idx, env->insn_idx,
14556 							env->cur_state->speculative ?
14557 							" (speculative execution)" : "");
14558 					else
14559 						verbose(env, "%d: safe\n", env->insn_idx);
14560 				}
14561 				goto process_bpf_exit;
14562 			}
14563 		}
14564 
14565 		if (is_jmp_point(env, env->insn_idx)) {
14566 			err = push_jmp_history(env, state);
14567 			if (err)
14568 				return err;
14569 		}
14570 
14571 		if (signal_pending(current))
14572 			return -EAGAIN;
14573 
14574 		if (need_resched())
14575 			cond_resched();
14576 
14577 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14578 			verbose(env, "\nfrom %d to %d%s:",
14579 				env->prev_insn_idx, env->insn_idx,
14580 				env->cur_state->speculative ?
14581 				" (speculative execution)" : "");
14582 			print_verifier_state(env, state->frame[state->curframe], true);
14583 			do_print_state = false;
14584 		}
14585 
14586 		if (env->log.level & BPF_LOG_LEVEL) {
14587 			const struct bpf_insn_cbs cbs = {
14588 				.cb_call	= disasm_kfunc_name,
14589 				.cb_print	= verbose,
14590 				.private_data	= env,
14591 			};
14592 
14593 			if (verifier_state_scratched(env))
14594 				print_insn_state(env, state->frame[state->curframe]);
14595 
14596 			verbose_linfo(env, env->insn_idx, "; ");
14597 			env->prev_log_len = env->log.len_used;
14598 			verbose(env, "%d: ", env->insn_idx);
14599 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14600 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14601 			env->prev_log_len = env->log.len_used;
14602 		}
14603 
14604 		if (bpf_prog_is_offloaded(env->prog->aux)) {
14605 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14606 							   env->prev_insn_idx);
14607 			if (err)
14608 				return err;
14609 		}
14610 
14611 		regs = cur_regs(env);
14612 		sanitize_mark_insn_seen(env);
14613 		prev_insn_idx = env->insn_idx;
14614 
14615 		if (class == BPF_ALU || class == BPF_ALU64) {
14616 			err = check_alu_op(env, insn);
14617 			if (err)
14618 				return err;
14619 
14620 		} else if (class == BPF_LDX) {
14621 			enum bpf_reg_type *prev_src_type, src_reg_type;
14622 
14623 			/* check for reserved fields is already done */
14624 
14625 			/* check src operand */
14626 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14627 			if (err)
14628 				return err;
14629 
14630 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14631 			if (err)
14632 				return err;
14633 
14634 			src_reg_type = regs[insn->src_reg].type;
14635 
14636 			/* check that memory (src_reg + off) is readable,
14637 			 * the state of dst_reg will be updated by this func
14638 			 */
14639 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
14640 					       insn->off, BPF_SIZE(insn->code),
14641 					       BPF_READ, insn->dst_reg, false);
14642 			if (err)
14643 				return err;
14644 
14645 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14646 
14647 			if (*prev_src_type == NOT_INIT) {
14648 				/* saw a valid insn
14649 				 * dst_reg = *(u32 *)(src_reg + off)
14650 				 * save type to validate intersecting paths
14651 				 */
14652 				*prev_src_type = src_reg_type;
14653 
14654 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
14655 				/* ABuser program is trying to use the same insn
14656 				 * dst_reg = *(u32*) (src_reg + off)
14657 				 * with different pointer types:
14658 				 * src_reg == ctx in one branch and
14659 				 * src_reg == stack|map in some other branch.
14660 				 * Reject it.
14661 				 */
14662 				verbose(env, "same insn cannot be used with different pointers\n");
14663 				return -EINVAL;
14664 			}
14665 
14666 		} else if (class == BPF_STX) {
14667 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
14668 
14669 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
14670 				err = check_atomic(env, env->insn_idx, insn);
14671 				if (err)
14672 					return err;
14673 				env->insn_idx++;
14674 				continue;
14675 			}
14676 
14677 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
14678 				verbose(env, "BPF_STX uses reserved fields\n");
14679 				return -EINVAL;
14680 			}
14681 
14682 			/* check src1 operand */
14683 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14684 			if (err)
14685 				return err;
14686 			/* check src2 operand */
14687 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14688 			if (err)
14689 				return err;
14690 
14691 			dst_reg_type = regs[insn->dst_reg].type;
14692 
14693 			/* check that memory (dst_reg + off) is writeable */
14694 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14695 					       insn->off, BPF_SIZE(insn->code),
14696 					       BPF_WRITE, insn->src_reg, false);
14697 			if (err)
14698 				return err;
14699 
14700 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14701 
14702 			if (*prev_dst_type == NOT_INIT) {
14703 				*prev_dst_type = dst_reg_type;
14704 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
14705 				verbose(env, "same insn cannot be used with different pointers\n");
14706 				return -EINVAL;
14707 			}
14708 
14709 		} else if (class == BPF_ST) {
14710 			if (BPF_MODE(insn->code) != BPF_MEM ||
14711 			    insn->src_reg != BPF_REG_0) {
14712 				verbose(env, "BPF_ST uses reserved fields\n");
14713 				return -EINVAL;
14714 			}
14715 			/* check src operand */
14716 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14717 			if (err)
14718 				return err;
14719 
14720 			if (is_ctx_reg(env, insn->dst_reg)) {
14721 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
14722 					insn->dst_reg,
14723 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
14724 				return -EACCES;
14725 			}
14726 
14727 			/* check that memory (dst_reg + off) is writeable */
14728 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14729 					       insn->off, BPF_SIZE(insn->code),
14730 					       BPF_WRITE, -1, false);
14731 			if (err)
14732 				return err;
14733 
14734 		} else if (class == BPF_JMP || class == BPF_JMP32) {
14735 			u8 opcode = BPF_OP(insn->code);
14736 
14737 			env->jmps_processed++;
14738 			if (opcode == BPF_CALL) {
14739 				if (BPF_SRC(insn->code) != BPF_K ||
14740 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
14741 				     && insn->off != 0) ||
14742 				    (insn->src_reg != BPF_REG_0 &&
14743 				     insn->src_reg != BPF_PSEUDO_CALL &&
14744 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
14745 				    insn->dst_reg != BPF_REG_0 ||
14746 				    class == BPF_JMP32) {
14747 					verbose(env, "BPF_CALL uses reserved fields\n");
14748 					return -EINVAL;
14749 				}
14750 
14751 				if (env->cur_state->active_lock.ptr) {
14752 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
14753 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
14754 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
14755 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
14756 						verbose(env, "function calls are not allowed while holding a lock\n");
14757 						return -EINVAL;
14758 					}
14759 				}
14760 				if (insn->src_reg == BPF_PSEUDO_CALL)
14761 					err = check_func_call(env, insn, &env->insn_idx);
14762 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
14763 					err = check_kfunc_call(env, insn, &env->insn_idx);
14764 				else
14765 					err = check_helper_call(env, insn, &env->insn_idx);
14766 				if (err)
14767 					return err;
14768 			} else if (opcode == BPF_JA) {
14769 				if (BPF_SRC(insn->code) != BPF_K ||
14770 				    insn->imm != 0 ||
14771 				    insn->src_reg != BPF_REG_0 ||
14772 				    insn->dst_reg != BPF_REG_0 ||
14773 				    class == BPF_JMP32) {
14774 					verbose(env, "BPF_JA uses reserved fields\n");
14775 					return -EINVAL;
14776 				}
14777 
14778 				env->insn_idx += insn->off + 1;
14779 				continue;
14780 
14781 			} else if (opcode == BPF_EXIT) {
14782 				if (BPF_SRC(insn->code) != BPF_K ||
14783 				    insn->imm != 0 ||
14784 				    insn->src_reg != BPF_REG_0 ||
14785 				    insn->dst_reg != BPF_REG_0 ||
14786 				    class == BPF_JMP32) {
14787 					verbose(env, "BPF_EXIT uses reserved fields\n");
14788 					return -EINVAL;
14789 				}
14790 
14791 				if (env->cur_state->active_lock.ptr &&
14792 				    !in_rbtree_lock_required_cb(env)) {
14793 					verbose(env, "bpf_spin_unlock is missing\n");
14794 					return -EINVAL;
14795 				}
14796 
14797 				if (env->cur_state->active_rcu_lock) {
14798 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14799 					return -EINVAL;
14800 				}
14801 
14802 				/* We must do check_reference_leak here before
14803 				 * prepare_func_exit to handle the case when
14804 				 * state->curframe > 0, it may be a callback
14805 				 * function, for which reference_state must
14806 				 * match caller reference state when it exits.
14807 				 */
14808 				err = check_reference_leak(env);
14809 				if (err)
14810 					return err;
14811 
14812 				if (state->curframe) {
14813 					/* exit from nested function */
14814 					err = prepare_func_exit(env, &env->insn_idx);
14815 					if (err)
14816 						return err;
14817 					do_print_state = true;
14818 					continue;
14819 				}
14820 
14821 				err = check_return_code(env);
14822 				if (err)
14823 					return err;
14824 process_bpf_exit:
14825 				mark_verifier_state_scratched(env);
14826 				update_branch_counts(env, env->cur_state);
14827 				err = pop_stack(env, &prev_insn_idx,
14828 						&env->insn_idx, pop_log);
14829 				if (err < 0) {
14830 					if (err != -ENOENT)
14831 						return err;
14832 					break;
14833 				} else {
14834 					do_print_state = true;
14835 					continue;
14836 				}
14837 			} else {
14838 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14839 				if (err)
14840 					return err;
14841 			}
14842 		} else if (class == BPF_LD) {
14843 			u8 mode = BPF_MODE(insn->code);
14844 
14845 			if (mode == BPF_ABS || mode == BPF_IND) {
14846 				err = check_ld_abs(env, insn);
14847 				if (err)
14848 					return err;
14849 
14850 			} else if (mode == BPF_IMM) {
14851 				err = check_ld_imm(env, insn);
14852 				if (err)
14853 					return err;
14854 
14855 				env->insn_idx++;
14856 				sanitize_mark_insn_seen(env);
14857 			} else {
14858 				verbose(env, "invalid BPF_LD mode\n");
14859 				return -EINVAL;
14860 			}
14861 		} else {
14862 			verbose(env, "unknown insn class %d\n", class);
14863 			return -EINVAL;
14864 		}
14865 
14866 		env->insn_idx++;
14867 	}
14868 
14869 	return 0;
14870 }
14871 
14872 static int find_btf_percpu_datasec(struct btf *btf)
14873 {
14874 	const struct btf_type *t;
14875 	const char *tname;
14876 	int i, n;
14877 
14878 	/*
14879 	 * Both vmlinux and module each have their own ".data..percpu"
14880 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14881 	 * types to look at only module's own BTF types.
14882 	 */
14883 	n = btf_nr_types(btf);
14884 	if (btf_is_module(btf))
14885 		i = btf_nr_types(btf_vmlinux);
14886 	else
14887 		i = 1;
14888 
14889 	for(; i < n; i++) {
14890 		t = btf_type_by_id(btf, i);
14891 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14892 			continue;
14893 
14894 		tname = btf_name_by_offset(btf, t->name_off);
14895 		if (!strcmp(tname, ".data..percpu"))
14896 			return i;
14897 	}
14898 
14899 	return -ENOENT;
14900 }
14901 
14902 /* replace pseudo btf_id with kernel symbol address */
14903 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14904 			       struct bpf_insn *insn,
14905 			       struct bpf_insn_aux_data *aux)
14906 {
14907 	const struct btf_var_secinfo *vsi;
14908 	const struct btf_type *datasec;
14909 	struct btf_mod_pair *btf_mod;
14910 	const struct btf_type *t;
14911 	const char *sym_name;
14912 	bool percpu = false;
14913 	u32 type, id = insn->imm;
14914 	struct btf *btf;
14915 	s32 datasec_id;
14916 	u64 addr;
14917 	int i, btf_fd, err;
14918 
14919 	btf_fd = insn[1].imm;
14920 	if (btf_fd) {
14921 		btf = btf_get_by_fd(btf_fd);
14922 		if (IS_ERR(btf)) {
14923 			verbose(env, "invalid module BTF object FD specified.\n");
14924 			return -EINVAL;
14925 		}
14926 	} else {
14927 		if (!btf_vmlinux) {
14928 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14929 			return -EINVAL;
14930 		}
14931 		btf = btf_vmlinux;
14932 		btf_get(btf);
14933 	}
14934 
14935 	t = btf_type_by_id(btf, id);
14936 	if (!t) {
14937 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14938 		err = -ENOENT;
14939 		goto err_put;
14940 	}
14941 
14942 	if (!btf_type_is_var(t)) {
14943 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14944 		err = -EINVAL;
14945 		goto err_put;
14946 	}
14947 
14948 	sym_name = btf_name_by_offset(btf, t->name_off);
14949 	addr = kallsyms_lookup_name(sym_name);
14950 	if (!addr) {
14951 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14952 			sym_name);
14953 		err = -ENOENT;
14954 		goto err_put;
14955 	}
14956 
14957 	datasec_id = find_btf_percpu_datasec(btf);
14958 	if (datasec_id > 0) {
14959 		datasec = btf_type_by_id(btf, datasec_id);
14960 		for_each_vsi(i, datasec, vsi) {
14961 			if (vsi->type == id) {
14962 				percpu = true;
14963 				break;
14964 			}
14965 		}
14966 	}
14967 
14968 	insn[0].imm = (u32)addr;
14969 	insn[1].imm = addr >> 32;
14970 
14971 	type = t->type;
14972 	t = btf_type_skip_modifiers(btf, type, NULL);
14973 	if (percpu) {
14974 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14975 		aux->btf_var.btf = btf;
14976 		aux->btf_var.btf_id = type;
14977 	} else if (!btf_type_is_struct(t)) {
14978 		const struct btf_type *ret;
14979 		const char *tname;
14980 		u32 tsize;
14981 
14982 		/* resolve the type size of ksym. */
14983 		ret = btf_resolve_size(btf, t, &tsize);
14984 		if (IS_ERR(ret)) {
14985 			tname = btf_name_by_offset(btf, t->name_off);
14986 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14987 				tname, PTR_ERR(ret));
14988 			err = -EINVAL;
14989 			goto err_put;
14990 		}
14991 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14992 		aux->btf_var.mem_size = tsize;
14993 	} else {
14994 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14995 		aux->btf_var.btf = btf;
14996 		aux->btf_var.btf_id = type;
14997 	}
14998 
14999 	/* check whether we recorded this BTF (and maybe module) already */
15000 	for (i = 0; i < env->used_btf_cnt; i++) {
15001 		if (env->used_btfs[i].btf == btf) {
15002 			btf_put(btf);
15003 			return 0;
15004 		}
15005 	}
15006 
15007 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
15008 		err = -E2BIG;
15009 		goto err_put;
15010 	}
15011 
15012 	btf_mod = &env->used_btfs[env->used_btf_cnt];
15013 	btf_mod->btf = btf;
15014 	btf_mod->module = NULL;
15015 
15016 	/* if we reference variables from kernel module, bump its refcount */
15017 	if (btf_is_module(btf)) {
15018 		btf_mod->module = btf_try_get_module(btf);
15019 		if (!btf_mod->module) {
15020 			err = -ENXIO;
15021 			goto err_put;
15022 		}
15023 	}
15024 
15025 	env->used_btf_cnt++;
15026 
15027 	return 0;
15028 err_put:
15029 	btf_put(btf);
15030 	return err;
15031 }
15032 
15033 static bool is_tracing_prog_type(enum bpf_prog_type type)
15034 {
15035 	switch (type) {
15036 	case BPF_PROG_TYPE_KPROBE:
15037 	case BPF_PROG_TYPE_TRACEPOINT:
15038 	case BPF_PROG_TYPE_PERF_EVENT:
15039 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15040 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15041 		return true;
15042 	default:
15043 		return false;
15044 	}
15045 }
15046 
15047 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15048 					struct bpf_map *map,
15049 					struct bpf_prog *prog)
15050 
15051 {
15052 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15053 
15054 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15055 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
15056 		if (is_tracing_prog_type(prog_type)) {
15057 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15058 			return -EINVAL;
15059 		}
15060 	}
15061 
15062 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15063 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15064 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15065 			return -EINVAL;
15066 		}
15067 
15068 		if (is_tracing_prog_type(prog_type)) {
15069 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15070 			return -EINVAL;
15071 		}
15072 
15073 		if (prog->aux->sleepable) {
15074 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15075 			return -EINVAL;
15076 		}
15077 	}
15078 
15079 	if (btf_record_has_field(map->record, BPF_TIMER)) {
15080 		if (is_tracing_prog_type(prog_type)) {
15081 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
15082 			return -EINVAL;
15083 		}
15084 	}
15085 
15086 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15087 	    !bpf_offload_prog_map_match(prog, map)) {
15088 		verbose(env, "offload device mismatch between prog and map\n");
15089 		return -EINVAL;
15090 	}
15091 
15092 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15093 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15094 		return -EINVAL;
15095 	}
15096 
15097 	if (prog->aux->sleepable)
15098 		switch (map->map_type) {
15099 		case BPF_MAP_TYPE_HASH:
15100 		case BPF_MAP_TYPE_LRU_HASH:
15101 		case BPF_MAP_TYPE_ARRAY:
15102 		case BPF_MAP_TYPE_PERCPU_HASH:
15103 		case BPF_MAP_TYPE_PERCPU_ARRAY:
15104 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15105 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15106 		case BPF_MAP_TYPE_HASH_OF_MAPS:
15107 		case BPF_MAP_TYPE_RINGBUF:
15108 		case BPF_MAP_TYPE_USER_RINGBUF:
15109 		case BPF_MAP_TYPE_INODE_STORAGE:
15110 		case BPF_MAP_TYPE_SK_STORAGE:
15111 		case BPF_MAP_TYPE_TASK_STORAGE:
15112 		case BPF_MAP_TYPE_CGRP_STORAGE:
15113 			break;
15114 		default:
15115 			verbose(env,
15116 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15117 			return -EINVAL;
15118 		}
15119 
15120 	return 0;
15121 }
15122 
15123 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15124 {
15125 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15126 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15127 }
15128 
15129 /* find and rewrite pseudo imm in ld_imm64 instructions:
15130  *
15131  * 1. if it accesses map FD, replace it with actual map pointer.
15132  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15133  *
15134  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15135  */
15136 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15137 {
15138 	struct bpf_insn *insn = env->prog->insnsi;
15139 	int insn_cnt = env->prog->len;
15140 	int i, j, err;
15141 
15142 	err = bpf_prog_calc_tag(env->prog);
15143 	if (err)
15144 		return err;
15145 
15146 	for (i = 0; i < insn_cnt; i++, insn++) {
15147 		if (BPF_CLASS(insn->code) == BPF_LDX &&
15148 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15149 			verbose(env, "BPF_LDX uses reserved fields\n");
15150 			return -EINVAL;
15151 		}
15152 
15153 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15154 			struct bpf_insn_aux_data *aux;
15155 			struct bpf_map *map;
15156 			struct fd f;
15157 			u64 addr;
15158 			u32 fd;
15159 
15160 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
15161 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15162 			    insn[1].off != 0) {
15163 				verbose(env, "invalid bpf_ld_imm64 insn\n");
15164 				return -EINVAL;
15165 			}
15166 
15167 			if (insn[0].src_reg == 0)
15168 				/* valid generic load 64-bit imm */
15169 				goto next_insn;
15170 
15171 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15172 				aux = &env->insn_aux_data[i];
15173 				err = check_pseudo_btf_id(env, insn, aux);
15174 				if (err)
15175 					return err;
15176 				goto next_insn;
15177 			}
15178 
15179 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15180 				aux = &env->insn_aux_data[i];
15181 				aux->ptr_type = PTR_TO_FUNC;
15182 				goto next_insn;
15183 			}
15184 
15185 			/* In final convert_pseudo_ld_imm64() step, this is
15186 			 * converted into regular 64-bit imm load insn.
15187 			 */
15188 			switch (insn[0].src_reg) {
15189 			case BPF_PSEUDO_MAP_VALUE:
15190 			case BPF_PSEUDO_MAP_IDX_VALUE:
15191 				break;
15192 			case BPF_PSEUDO_MAP_FD:
15193 			case BPF_PSEUDO_MAP_IDX:
15194 				if (insn[1].imm == 0)
15195 					break;
15196 				fallthrough;
15197 			default:
15198 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15199 				return -EINVAL;
15200 			}
15201 
15202 			switch (insn[0].src_reg) {
15203 			case BPF_PSEUDO_MAP_IDX_VALUE:
15204 			case BPF_PSEUDO_MAP_IDX:
15205 				if (bpfptr_is_null(env->fd_array)) {
15206 					verbose(env, "fd_idx without fd_array is invalid\n");
15207 					return -EPROTO;
15208 				}
15209 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
15210 							    insn[0].imm * sizeof(fd),
15211 							    sizeof(fd)))
15212 					return -EFAULT;
15213 				break;
15214 			default:
15215 				fd = insn[0].imm;
15216 				break;
15217 			}
15218 
15219 			f = fdget(fd);
15220 			map = __bpf_map_get(f);
15221 			if (IS_ERR(map)) {
15222 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
15223 					insn[0].imm);
15224 				return PTR_ERR(map);
15225 			}
15226 
15227 			err = check_map_prog_compatibility(env, map, env->prog);
15228 			if (err) {
15229 				fdput(f);
15230 				return err;
15231 			}
15232 
15233 			aux = &env->insn_aux_data[i];
15234 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15235 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15236 				addr = (unsigned long)map;
15237 			} else {
15238 				u32 off = insn[1].imm;
15239 
15240 				if (off >= BPF_MAX_VAR_OFF) {
15241 					verbose(env, "direct value offset of %u is not allowed\n", off);
15242 					fdput(f);
15243 					return -EINVAL;
15244 				}
15245 
15246 				if (!map->ops->map_direct_value_addr) {
15247 					verbose(env, "no direct value access support for this map type\n");
15248 					fdput(f);
15249 					return -EINVAL;
15250 				}
15251 
15252 				err = map->ops->map_direct_value_addr(map, &addr, off);
15253 				if (err) {
15254 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15255 						map->value_size, off);
15256 					fdput(f);
15257 					return err;
15258 				}
15259 
15260 				aux->map_off = off;
15261 				addr += off;
15262 			}
15263 
15264 			insn[0].imm = (u32)addr;
15265 			insn[1].imm = addr >> 32;
15266 
15267 			/* check whether we recorded this map already */
15268 			for (j = 0; j < env->used_map_cnt; j++) {
15269 				if (env->used_maps[j] == map) {
15270 					aux->map_index = j;
15271 					fdput(f);
15272 					goto next_insn;
15273 				}
15274 			}
15275 
15276 			if (env->used_map_cnt >= MAX_USED_MAPS) {
15277 				fdput(f);
15278 				return -E2BIG;
15279 			}
15280 
15281 			/* hold the map. If the program is rejected by verifier,
15282 			 * the map will be released by release_maps() or it
15283 			 * will be used by the valid program until it's unloaded
15284 			 * and all maps are released in free_used_maps()
15285 			 */
15286 			bpf_map_inc(map);
15287 
15288 			aux->map_index = env->used_map_cnt;
15289 			env->used_maps[env->used_map_cnt++] = map;
15290 
15291 			if (bpf_map_is_cgroup_storage(map) &&
15292 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
15293 				verbose(env, "only one cgroup storage of each type is allowed\n");
15294 				fdput(f);
15295 				return -EBUSY;
15296 			}
15297 
15298 			fdput(f);
15299 next_insn:
15300 			insn++;
15301 			i++;
15302 			continue;
15303 		}
15304 
15305 		/* Basic sanity check before we invest more work here. */
15306 		if (!bpf_opcode_in_insntable(insn->code)) {
15307 			verbose(env, "unknown opcode %02x\n", insn->code);
15308 			return -EINVAL;
15309 		}
15310 	}
15311 
15312 	/* now all pseudo BPF_LD_IMM64 instructions load valid
15313 	 * 'struct bpf_map *' into a register instead of user map_fd.
15314 	 * These pointers will be used later by verifier to validate map access.
15315 	 */
15316 	return 0;
15317 }
15318 
15319 /* drop refcnt of maps used by the rejected program */
15320 static void release_maps(struct bpf_verifier_env *env)
15321 {
15322 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
15323 			     env->used_map_cnt);
15324 }
15325 
15326 /* drop refcnt of maps used by the rejected program */
15327 static void release_btfs(struct bpf_verifier_env *env)
15328 {
15329 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15330 			     env->used_btf_cnt);
15331 }
15332 
15333 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15334 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15335 {
15336 	struct bpf_insn *insn = env->prog->insnsi;
15337 	int insn_cnt = env->prog->len;
15338 	int i;
15339 
15340 	for (i = 0; i < insn_cnt; i++, insn++) {
15341 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15342 			continue;
15343 		if (insn->src_reg == BPF_PSEUDO_FUNC)
15344 			continue;
15345 		insn->src_reg = 0;
15346 	}
15347 }
15348 
15349 /* single env->prog->insni[off] instruction was replaced with the range
15350  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
15351  * [0, off) and [off, end) to new locations, so the patched range stays zero
15352  */
15353 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15354 				 struct bpf_insn_aux_data *new_data,
15355 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
15356 {
15357 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15358 	struct bpf_insn *insn = new_prog->insnsi;
15359 	u32 old_seen = old_data[off].seen;
15360 	u32 prog_len;
15361 	int i;
15362 
15363 	/* aux info at OFF always needs adjustment, no matter fast path
15364 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15365 	 * original insn at old prog.
15366 	 */
15367 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15368 
15369 	if (cnt == 1)
15370 		return;
15371 	prog_len = new_prog->len;
15372 
15373 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15374 	memcpy(new_data + off + cnt - 1, old_data + off,
15375 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15376 	for (i = off; i < off + cnt - 1; i++) {
15377 		/* Expand insni[off]'s seen count to the patched range. */
15378 		new_data[i].seen = old_seen;
15379 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
15380 	}
15381 	env->insn_aux_data = new_data;
15382 	vfree(old_data);
15383 }
15384 
15385 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15386 {
15387 	int i;
15388 
15389 	if (len == 1)
15390 		return;
15391 	/* NOTE: fake 'exit' subprog should be updated as well. */
15392 	for (i = 0; i <= env->subprog_cnt; i++) {
15393 		if (env->subprog_info[i].start <= off)
15394 			continue;
15395 		env->subprog_info[i].start += len - 1;
15396 	}
15397 }
15398 
15399 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15400 {
15401 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15402 	int i, sz = prog->aux->size_poke_tab;
15403 	struct bpf_jit_poke_descriptor *desc;
15404 
15405 	for (i = 0; i < sz; i++) {
15406 		desc = &tab[i];
15407 		if (desc->insn_idx <= off)
15408 			continue;
15409 		desc->insn_idx += len - 1;
15410 	}
15411 }
15412 
15413 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15414 					    const struct bpf_insn *patch, u32 len)
15415 {
15416 	struct bpf_prog *new_prog;
15417 	struct bpf_insn_aux_data *new_data = NULL;
15418 
15419 	if (len > 1) {
15420 		new_data = vzalloc(array_size(env->prog->len + len - 1,
15421 					      sizeof(struct bpf_insn_aux_data)));
15422 		if (!new_data)
15423 			return NULL;
15424 	}
15425 
15426 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15427 	if (IS_ERR(new_prog)) {
15428 		if (PTR_ERR(new_prog) == -ERANGE)
15429 			verbose(env,
15430 				"insn %d cannot be patched due to 16-bit range\n",
15431 				env->insn_aux_data[off].orig_idx);
15432 		vfree(new_data);
15433 		return NULL;
15434 	}
15435 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
15436 	adjust_subprog_starts(env, off, len);
15437 	adjust_poke_descs(new_prog, off, len);
15438 	return new_prog;
15439 }
15440 
15441 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15442 					      u32 off, u32 cnt)
15443 {
15444 	int i, j;
15445 
15446 	/* find first prog starting at or after off (first to remove) */
15447 	for (i = 0; i < env->subprog_cnt; i++)
15448 		if (env->subprog_info[i].start >= off)
15449 			break;
15450 	/* find first prog starting at or after off + cnt (first to stay) */
15451 	for (j = i; j < env->subprog_cnt; j++)
15452 		if (env->subprog_info[j].start >= off + cnt)
15453 			break;
15454 	/* if j doesn't start exactly at off + cnt, we are just removing
15455 	 * the front of previous prog
15456 	 */
15457 	if (env->subprog_info[j].start != off + cnt)
15458 		j--;
15459 
15460 	if (j > i) {
15461 		struct bpf_prog_aux *aux = env->prog->aux;
15462 		int move;
15463 
15464 		/* move fake 'exit' subprog as well */
15465 		move = env->subprog_cnt + 1 - j;
15466 
15467 		memmove(env->subprog_info + i,
15468 			env->subprog_info + j,
15469 			sizeof(*env->subprog_info) * move);
15470 		env->subprog_cnt -= j - i;
15471 
15472 		/* remove func_info */
15473 		if (aux->func_info) {
15474 			move = aux->func_info_cnt - j;
15475 
15476 			memmove(aux->func_info + i,
15477 				aux->func_info + j,
15478 				sizeof(*aux->func_info) * move);
15479 			aux->func_info_cnt -= j - i;
15480 			/* func_info->insn_off is set after all code rewrites,
15481 			 * in adjust_btf_func() - no need to adjust
15482 			 */
15483 		}
15484 	} else {
15485 		/* convert i from "first prog to remove" to "first to adjust" */
15486 		if (env->subprog_info[i].start == off)
15487 			i++;
15488 	}
15489 
15490 	/* update fake 'exit' subprog as well */
15491 	for (; i <= env->subprog_cnt; i++)
15492 		env->subprog_info[i].start -= cnt;
15493 
15494 	return 0;
15495 }
15496 
15497 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15498 				      u32 cnt)
15499 {
15500 	struct bpf_prog *prog = env->prog;
15501 	u32 i, l_off, l_cnt, nr_linfo;
15502 	struct bpf_line_info *linfo;
15503 
15504 	nr_linfo = prog->aux->nr_linfo;
15505 	if (!nr_linfo)
15506 		return 0;
15507 
15508 	linfo = prog->aux->linfo;
15509 
15510 	/* find first line info to remove, count lines to be removed */
15511 	for (i = 0; i < nr_linfo; i++)
15512 		if (linfo[i].insn_off >= off)
15513 			break;
15514 
15515 	l_off = i;
15516 	l_cnt = 0;
15517 	for (; i < nr_linfo; i++)
15518 		if (linfo[i].insn_off < off + cnt)
15519 			l_cnt++;
15520 		else
15521 			break;
15522 
15523 	/* First live insn doesn't match first live linfo, it needs to "inherit"
15524 	 * last removed linfo.  prog is already modified, so prog->len == off
15525 	 * means no live instructions after (tail of the program was removed).
15526 	 */
15527 	if (prog->len != off && l_cnt &&
15528 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15529 		l_cnt--;
15530 		linfo[--i].insn_off = off + cnt;
15531 	}
15532 
15533 	/* remove the line info which refer to the removed instructions */
15534 	if (l_cnt) {
15535 		memmove(linfo + l_off, linfo + i,
15536 			sizeof(*linfo) * (nr_linfo - i));
15537 
15538 		prog->aux->nr_linfo -= l_cnt;
15539 		nr_linfo = prog->aux->nr_linfo;
15540 	}
15541 
15542 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
15543 	for (i = l_off; i < nr_linfo; i++)
15544 		linfo[i].insn_off -= cnt;
15545 
15546 	/* fix up all subprogs (incl. 'exit') which start >= off */
15547 	for (i = 0; i <= env->subprog_cnt; i++)
15548 		if (env->subprog_info[i].linfo_idx > l_off) {
15549 			/* program may have started in the removed region but
15550 			 * may not be fully removed
15551 			 */
15552 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15553 				env->subprog_info[i].linfo_idx -= l_cnt;
15554 			else
15555 				env->subprog_info[i].linfo_idx = l_off;
15556 		}
15557 
15558 	return 0;
15559 }
15560 
15561 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15562 {
15563 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15564 	unsigned int orig_prog_len = env->prog->len;
15565 	int err;
15566 
15567 	if (bpf_prog_is_offloaded(env->prog->aux))
15568 		bpf_prog_offload_remove_insns(env, off, cnt);
15569 
15570 	err = bpf_remove_insns(env->prog, off, cnt);
15571 	if (err)
15572 		return err;
15573 
15574 	err = adjust_subprog_starts_after_remove(env, off, cnt);
15575 	if (err)
15576 		return err;
15577 
15578 	err = bpf_adj_linfo_after_remove(env, off, cnt);
15579 	if (err)
15580 		return err;
15581 
15582 	memmove(aux_data + off,	aux_data + off + cnt,
15583 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
15584 
15585 	return 0;
15586 }
15587 
15588 /* The verifier does more data flow analysis than llvm and will not
15589  * explore branches that are dead at run time. Malicious programs can
15590  * have dead code too. Therefore replace all dead at-run-time code
15591  * with 'ja -1'.
15592  *
15593  * Just nops are not optimal, e.g. if they would sit at the end of the
15594  * program and through another bug we would manage to jump there, then
15595  * we'd execute beyond program memory otherwise. Returning exception
15596  * code also wouldn't work since we can have subprogs where the dead
15597  * code could be located.
15598  */
15599 static void sanitize_dead_code(struct bpf_verifier_env *env)
15600 {
15601 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15602 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15603 	struct bpf_insn *insn = env->prog->insnsi;
15604 	const int insn_cnt = env->prog->len;
15605 	int i;
15606 
15607 	for (i = 0; i < insn_cnt; i++) {
15608 		if (aux_data[i].seen)
15609 			continue;
15610 		memcpy(insn + i, &trap, sizeof(trap));
15611 		aux_data[i].zext_dst = false;
15612 	}
15613 }
15614 
15615 static bool insn_is_cond_jump(u8 code)
15616 {
15617 	u8 op;
15618 
15619 	if (BPF_CLASS(code) == BPF_JMP32)
15620 		return true;
15621 
15622 	if (BPF_CLASS(code) != BPF_JMP)
15623 		return false;
15624 
15625 	op = BPF_OP(code);
15626 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15627 }
15628 
15629 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15630 {
15631 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15632 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15633 	struct bpf_insn *insn = env->prog->insnsi;
15634 	const int insn_cnt = env->prog->len;
15635 	int i;
15636 
15637 	for (i = 0; i < insn_cnt; i++, insn++) {
15638 		if (!insn_is_cond_jump(insn->code))
15639 			continue;
15640 
15641 		if (!aux_data[i + 1].seen)
15642 			ja.off = insn->off;
15643 		else if (!aux_data[i + 1 + insn->off].seen)
15644 			ja.off = 0;
15645 		else
15646 			continue;
15647 
15648 		if (bpf_prog_is_offloaded(env->prog->aux))
15649 			bpf_prog_offload_replace_insn(env, i, &ja);
15650 
15651 		memcpy(insn, &ja, sizeof(ja));
15652 	}
15653 }
15654 
15655 static int opt_remove_dead_code(struct bpf_verifier_env *env)
15656 {
15657 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15658 	int insn_cnt = env->prog->len;
15659 	int i, err;
15660 
15661 	for (i = 0; i < insn_cnt; i++) {
15662 		int j;
15663 
15664 		j = 0;
15665 		while (i + j < insn_cnt && !aux_data[i + j].seen)
15666 			j++;
15667 		if (!j)
15668 			continue;
15669 
15670 		err = verifier_remove_insns(env, i, j);
15671 		if (err)
15672 			return err;
15673 		insn_cnt = env->prog->len;
15674 	}
15675 
15676 	return 0;
15677 }
15678 
15679 static int opt_remove_nops(struct bpf_verifier_env *env)
15680 {
15681 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15682 	struct bpf_insn *insn = env->prog->insnsi;
15683 	int insn_cnt = env->prog->len;
15684 	int i, err;
15685 
15686 	for (i = 0; i < insn_cnt; i++) {
15687 		if (memcmp(&insn[i], &ja, sizeof(ja)))
15688 			continue;
15689 
15690 		err = verifier_remove_insns(env, i, 1);
15691 		if (err)
15692 			return err;
15693 		insn_cnt--;
15694 		i--;
15695 	}
15696 
15697 	return 0;
15698 }
15699 
15700 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
15701 					 const union bpf_attr *attr)
15702 {
15703 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
15704 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15705 	int i, patch_len, delta = 0, len = env->prog->len;
15706 	struct bpf_insn *insns = env->prog->insnsi;
15707 	struct bpf_prog *new_prog;
15708 	bool rnd_hi32;
15709 
15710 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
15711 	zext_patch[1] = BPF_ZEXT_REG(0);
15712 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
15713 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
15714 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
15715 	for (i = 0; i < len; i++) {
15716 		int adj_idx = i + delta;
15717 		struct bpf_insn insn;
15718 		int load_reg;
15719 
15720 		insn = insns[adj_idx];
15721 		load_reg = insn_def_regno(&insn);
15722 		if (!aux[adj_idx].zext_dst) {
15723 			u8 code, class;
15724 			u32 imm_rnd;
15725 
15726 			if (!rnd_hi32)
15727 				continue;
15728 
15729 			code = insn.code;
15730 			class = BPF_CLASS(code);
15731 			if (load_reg == -1)
15732 				continue;
15733 
15734 			/* NOTE: arg "reg" (the fourth one) is only used for
15735 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
15736 			 *       here.
15737 			 */
15738 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
15739 				if (class == BPF_LD &&
15740 				    BPF_MODE(code) == BPF_IMM)
15741 					i++;
15742 				continue;
15743 			}
15744 
15745 			/* ctx load could be transformed into wider load. */
15746 			if (class == BPF_LDX &&
15747 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
15748 				continue;
15749 
15750 			imm_rnd = get_random_u32();
15751 			rnd_hi32_patch[0] = insn;
15752 			rnd_hi32_patch[1].imm = imm_rnd;
15753 			rnd_hi32_patch[3].dst_reg = load_reg;
15754 			patch = rnd_hi32_patch;
15755 			patch_len = 4;
15756 			goto apply_patch_buffer;
15757 		}
15758 
15759 		/* Add in an zero-extend instruction if a) the JIT has requested
15760 		 * it or b) it's a CMPXCHG.
15761 		 *
15762 		 * The latter is because: BPF_CMPXCHG always loads a value into
15763 		 * R0, therefore always zero-extends. However some archs'
15764 		 * equivalent instruction only does this load when the
15765 		 * comparison is successful. This detail of CMPXCHG is
15766 		 * orthogonal to the general zero-extension behaviour of the
15767 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
15768 		 */
15769 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
15770 			continue;
15771 
15772 		/* Zero-extension is done by the caller. */
15773 		if (bpf_pseudo_kfunc_call(&insn))
15774 			continue;
15775 
15776 		if (WARN_ON(load_reg == -1)) {
15777 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15778 			return -EFAULT;
15779 		}
15780 
15781 		zext_patch[0] = insn;
15782 		zext_patch[1].dst_reg = load_reg;
15783 		zext_patch[1].src_reg = load_reg;
15784 		patch = zext_patch;
15785 		patch_len = 2;
15786 apply_patch_buffer:
15787 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15788 		if (!new_prog)
15789 			return -ENOMEM;
15790 		env->prog = new_prog;
15791 		insns = new_prog->insnsi;
15792 		aux = env->insn_aux_data;
15793 		delta += patch_len - 1;
15794 	}
15795 
15796 	return 0;
15797 }
15798 
15799 /* convert load instructions that access fields of a context type into a
15800  * sequence of instructions that access fields of the underlying structure:
15801  *     struct __sk_buff    -> struct sk_buff
15802  *     struct bpf_sock_ops -> struct sock
15803  */
15804 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15805 {
15806 	const struct bpf_verifier_ops *ops = env->ops;
15807 	int i, cnt, size, ctx_field_size, delta = 0;
15808 	const int insn_cnt = env->prog->len;
15809 	struct bpf_insn insn_buf[16], *insn;
15810 	u32 target_size, size_default, off;
15811 	struct bpf_prog *new_prog;
15812 	enum bpf_access_type type;
15813 	bool is_narrower_load;
15814 
15815 	if (ops->gen_prologue || env->seen_direct_write) {
15816 		if (!ops->gen_prologue) {
15817 			verbose(env, "bpf verifier is misconfigured\n");
15818 			return -EINVAL;
15819 		}
15820 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15821 					env->prog);
15822 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15823 			verbose(env, "bpf verifier is misconfigured\n");
15824 			return -EINVAL;
15825 		} else if (cnt) {
15826 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15827 			if (!new_prog)
15828 				return -ENOMEM;
15829 
15830 			env->prog = new_prog;
15831 			delta += cnt - 1;
15832 		}
15833 	}
15834 
15835 	if (bpf_prog_is_offloaded(env->prog->aux))
15836 		return 0;
15837 
15838 	insn = env->prog->insnsi + delta;
15839 
15840 	for (i = 0; i < insn_cnt; i++, insn++) {
15841 		bpf_convert_ctx_access_t convert_ctx_access;
15842 		bool ctx_access;
15843 
15844 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15845 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15846 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15847 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15848 			type = BPF_READ;
15849 			ctx_access = true;
15850 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15851 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15852 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15853 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15854 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15855 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15856 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15857 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15858 			type = BPF_WRITE;
15859 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15860 		} else {
15861 			continue;
15862 		}
15863 
15864 		if (type == BPF_WRITE &&
15865 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15866 			struct bpf_insn patch[] = {
15867 				*insn,
15868 				BPF_ST_NOSPEC(),
15869 			};
15870 
15871 			cnt = ARRAY_SIZE(patch);
15872 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15873 			if (!new_prog)
15874 				return -ENOMEM;
15875 
15876 			delta    += cnt - 1;
15877 			env->prog = new_prog;
15878 			insn      = new_prog->insnsi + i + delta;
15879 			continue;
15880 		}
15881 
15882 		if (!ctx_access)
15883 			continue;
15884 
15885 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15886 		case PTR_TO_CTX:
15887 			if (!ops->convert_ctx_access)
15888 				continue;
15889 			convert_ctx_access = ops->convert_ctx_access;
15890 			break;
15891 		case PTR_TO_SOCKET:
15892 		case PTR_TO_SOCK_COMMON:
15893 			convert_ctx_access = bpf_sock_convert_ctx_access;
15894 			break;
15895 		case PTR_TO_TCP_SOCK:
15896 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15897 			break;
15898 		case PTR_TO_XDP_SOCK:
15899 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15900 			break;
15901 		case PTR_TO_BTF_ID:
15902 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15903 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15904 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15905 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15906 		 * any faults for loads into such types. BPF_WRITE is disallowed
15907 		 * for this case.
15908 		 */
15909 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15910 			if (type == BPF_READ) {
15911 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15912 					BPF_SIZE((insn)->code);
15913 				env->prog->aux->num_exentries++;
15914 			}
15915 			continue;
15916 		default:
15917 			continue;
15918 		}
15919 
15920 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15921 		size = BPF_LDST_BYTES(insn);
15922 
15923 		/* If the read access is a narrower load of the field,
15924 		 * convert to a 4/8-byte load, to minimum program type specific
15925 		 * convert_ctx_access changes. If conversion is successful,
15926 		 * we will apply proper mask to the result.
15927 		 */
15928 		is_narrower_load = size < ctx_field_size;
15929 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15930 		off = insn->off;
15931 		if (is_narrower_load) {
15932 			u8 size_code;
15933 
15934 			if (type == BPF_WRITE) {
15935 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15936 				return -EINVAL;
15937 			}
15938 
15939 			size_code = BPF_H;
15940 			if (ctx_field_size == 4)
15941 				size_code = BPF_W;
15942 			else if (ctx_field_size == 8)
15943 				size_code = BPF_DW;
15944 
15945 			insn->off = off & ~(size_default - 1);
15946 			insn->code = BPF_LDX | BPF_MEM | size_code;
15947 		}
15948 
15949 		target_size = 0;
15950 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15951 					 &target_size);
15952 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15953 		    (ctx_field_size && !target_size)) {
15954 			verbose(env, "bpf verifier is misconfigured\n");
15955 			return -EINVAL;
15956 		}
15957 
15958 		if (is_narrower_load && size < target_size) {
15959 			u8 shift = bpf_ctx_narrow_access_offset(
15960 				off, size, size_default) * 8;
15961 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15962 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15963 				return -EINVAL;
15964 			}
15965 			if (ctx_field_size <= 4) {
15966 				if (shift)
15967 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15968 									insn->dst_reg,
15969 									shift);
15970 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15971 								(1 << size * 8) - 1);
15972 			} else {
15973 				if (shift)
15974 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15975 									insn->dst_reg,
15976 									shift);
15977 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15978 								(1ULL << size * 8) - 1);
15979 			}
15980 		}
15981 
15982 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15983 		if (!new_prog)
15984 			return -ENOMEM;
15985 
15986 		delta += cnt - 1;
15987 
15988 		/* keep walking new program and skip insns we just inserted */
15989 		env->prog = new_prog;
15990 		insn      = new_prog->insnsi + i + delta;
15991 	}
15992 
15993 	return 0;
15994 }
15995 
15996 static int jit_subprogs(struct bpf_verifier_env *env)
15997 {
15998 	struct bpf_prog *prog = env->prog, **func, *tmp;
15999 	int i, j, subprog_start, subprog_end = 0, len, subprog;
16000 	struct bpf_map *map_ptr;
16001 	struct bpf_insn *insn;
16002 	void *old_bpf_func;
16003 	int err, num_exentries;
16004 
16005 	if (env->subprog_cnt <= 1)
16006 		return 0;
16007 
16008 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16009 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
16010 			continue;
16011 
16012 		/* Upon error here we cannot fall back to interpreter but
16013 		 * need a hard reject of the program. Thus -EFAULT is
16014 		 * propagated in any case.
16015 		 */
16016 		subprog = find_subprog(env, i + insn->imm + 1);
16017 		if (subprog < 0) {
16018 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
16019 				  i + insn->imm + 1);
16020 			return -EFAULT;
16021 		}
16022 		/* temporarily remember subprog id inside insn instead of
16023 		 * aux_data, since next loop will split up all insns into funcs
16024 		 */
16025 		insn->off = subprog;
16026 		/* remember original imm in case JIT fails and fallback
16027 		 * to interpreter will be needed
16028 		 */
16029 		env->insn_aux_data[i].call_imm = insn->imm;
16030 		/* point imm to __bpf_call_base+1 from JITs point of view */
16031 		insn->imm = 1;
16032 		if (bpf_pseudo_func(insn))
16033 			/* jit (e.g. x86_64) may emit fewer instructions
16034 			 * if it learns a u32 imm is the same as a u64 imm.
16035 			 * Force a non zero here.
16036 			 */
16037 			insn[1].imm = 1;
16038 	}
16039 
16040 	err = bpf_prog_alloc_jited_linfo(prog);
16041 	if (err)
16042 		goto out_undo_insn;
16043 
16044 	err = -ENOMEM;
16045 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16046 	if (!func)
16047 		goto out_undo_insn;
16048 
16049 	for (i = 0; i < env->subprog_cnt; i++) {
16050 		subprog_start = subprog_end;
16051 		subprog_end = env->subprog_info[i + 1].start;
16052 
16053 		len = subprog_end - subprog_start;
16054 		/* bpf_prog_run() doesn't call subprogs directly,
16055 		 * hence main prog stats include the runtime of subprogs.
16056 		 * subprogs don't have IDs and not reachable via prog_get_next_id
16057 		 * func[i]->stats will never be accessed and stays NULL
16058 		 */
16059 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16060 		if (!func[i])
16061 			goto out_free;
16062 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16063 		       len * sizeof(struct bpf_insn));
16064 		func[i]->type = prog->type;
16065 		func[i]->len = len;
16066 		if (bpf_prog_calc_tag(func[i]))
16067 			goto out_free;
16068 		func[i]->is_func = 1;
16069 		func[i]->aux->func_idx = i;
16070 		/* Below members will be freed only at prog->aux */
16071 		func[i]->aux->btf = prog->aux->btf;
16072 		func[i]->aux->func_info = prog->aux->func_info;
16073 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16074 		func[i]->aux->poke_tab = prog->aux->poke_tab;
16075 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16076 
16077 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
16078 			struct bpf_jit_poke_descriptor *poke;
16079 
16080 			poke = &prog->aux->poke_tab[j];
16081 			if (poke->insn_idx < subprog_end &&
16082 			    poke->insn_idx >= subprog_start)
16083 				poke->aux = func[i]->aux;
16084 		}
16085 
16086 		func[i]->aux->name[0] = 'F';
16087 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16088 		func[i]->jit_requested = 1;
16089 		func[i]->blinding_requested = prog->blinding_requested;
16090 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16091 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16092 		func[i]->aux->linfo = prog->aux->linfo;
16093 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16094 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16095 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16096 		num_exentries = 0;
16097 		insn = func[i]->insnsi;
16098 		for (j = 0; j < func[i]->len; j++, insn++) {
16099 			if (BPF_CLASS(insn->code) == BPF_LDX &&
16100 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
16101 				num_exentries++;
16102 		}
16103 		func[i]->aux->num_exentries = num_exentries;
16104 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16105 		func[i] = bpf_int_jit_compile(func[i]);
16106 		if (!func[i]->jited) {
16107 			err = -ENOTSUPP;
16108 			goto out_free;
16109 		}
16110 		cond_resched();
16111 	}
16112 
16113 	/* at this point all bpf functions were successfully JITed
16114 	 * now populate all bpf_calls with correct addresses and
16115 	 * run last pass of JIT
16116 	 */
16117 	for (i = 0; i < env->subprog_cnt; i++) {
16118 		insn = func[i]->insnsi;
16119 		for (j = 0; j < func[i]->len; j++, insn++) {
16120 			if (bpf_pseudo_func(insn)) {
16121 				subprog = insn->off;
16122 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16123 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16124 				continue;
16125 			}
16126 			if (!bpf_pseudo_call(insn))
16127 				continue;
16128 			subprog = insn->off;
16129 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16130 		}
16131 
16132 		/* we use the aux data to keep a list of the start addresses
16133 		 * of the JITed images for each function in the program
16134 		 *
16135 		 * for some architectures, such as powerpc64, the imm field
16136 		 * might not be large enough to hold the offset of the start
16137 		 * address of the callee's JITed image from __bpf_call_base
16138 		 *
16139 		 * in such cases, we can lookup the start address of a callee
16140 		 * by using its subprog id, available from the off field of
16141 		 * the call instruction, as an index for this list
16142 		 */
16143 		func[i]->aux->func = func;
16144 		func[i]->aux->func_cnt = env->subprog_cnt;
16145 	}
16146 	for (i = 0; i < env->subprog_cnt; i++) {
16147 		old_bpf_func = func[i]->bpf_func;
16148 		tmp = bpf_int_jit_compile(func[i]);
16149 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16150 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16151 			err = -ENOTSUPP;
16152 			goto out_free;
16153 		}
16154 		cond_resched();
16155 	}
16156 
16157 	/* finally lock prog and jit images for all functions and
16158 	 * populate kallsysm
16159 	 */
16160 	for (i = 0; i < env->subprog_cnt; i++) {
16161 		bpf_prog_lock_ro(func[i]);
16162 		bpf_prog_kallsyms_add(func[i]);
16163 	}
16164 
16165 	/* Last step: make now unused interpreter insns from main
16166 	 * prog consistent for later dump requests, so they can
16167 	 * later look the same as if they were interpreted only.
16168 	 */
16169 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16170 		if (bpf_pseudo_func(insn)) {
16171 			insn[0].imm = env->insn_aux_data[i].call_imm;
16172 			insn[1].imm = insn->off;
16173 			insn->off = 0;
16174 			continue;
16175 		}
16176 		if (!bpf_pseudo_call(insn))
16177 			continue;
16178 		insn->off = env->insn_aux_data[i].call_imm;
16179 		subprog = find_subprog(env, i + insn->off + 1);
16180 		insn->imm = subprog;
16181 	}
16182 
16183 	prog->jited = 1;
16184 	prog->bpf_func = func[0]->bpf_func;
16185 	prog->jited_len = func[0]->jited_len;
16186 	prog->aux->func = func;
16187 	prog->aux->func_cnt = env->subprog_cnt;
16188 	bpf_prog_jit_attempt_done(prog);
16189 	return 0;
16190 out_free:
16191 	/* We failed JIT'ing, so at this point we need to unregister poke
16192 	 * descriptors from subprogs, so that kernel is not attempting to
16193 	 * patch it anymore as we're freeing the subprog JIT memory.
16194 	 */
16195 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16196 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16197 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16198 	}
16199 	/* At this point we're guaranteed that poke descriptors are not
16200 	 * live anymore. We can just unlink its descriptor table as it's
16201 	 * released with the main prog.
16202 	 */
16203 	for (i = 0; i < env->subprog_cnt; i++) {
16204 		if (!func[i])
16205 			continue;
16206 		func[i]->aux->poke_tab = NULL;
16207 		bpf_jit_free(func[i]);
16208 	}
16209 	kfree(func);
16210 out_undo_insn:
16211 	/* cleanup main prog to be interpreted */
16212 	prog->jit_requested = 0;
16213 	prog->blinding_requested = 0;
16214 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16215 		if (!bpf_pseudo_call(insn))
16216 			continue;
16217 		insn->off = 0;
16218 		insn->imm = env->insn_aux_data[i].call_imm;
16219 	}
16220 	bpf_prog_jit_attempt_done(prog);
16221 	return err;
16222 }
16223 
16224 static int fixup_call_args(struct bpf_verifier_env *env)
16225 {
16226 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16227 	struct bpf_prog *prog = env->prog;
16228 	struct bpf_insn *insn = prog->insnsi;
16229 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16230 	int i, depth;
16231 #endif
16232 	int err = 0;
16233 
16234 	if (env->prog->jit_requested &&
16235 	    !bpf_prog_is_offloaded(env->prog->aux)) {
16236 		err = jit_subprogs(env);
16237 		if (err == 0)
16238 			return 0;
16239 		if (err == -EFAULT)
16240 			return err;
16241 	}
16242 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16243 	if (has_kfunc_call) {
16244 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16245 		return -EINVAL;
16246 	}
16247 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16248 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
16249 		 * have to be rejected, since interpreter doesn't support them yet.
16250 		 */
16251 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16252 		return -EINVAL;
16253 	}
16254 	for (i = 0; i < prog->len; i++, insn++) {
16255 		if (bpf_pseudo_func(insn)) {
16256 			/* When JIT fails the progs with callback calls
16257 			 * have to be rejected, since interpreter doesn't support them yet.
16258 			 */
16259 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
16260 			return -EINVAL;
16261 		}
16262 
16263 		if (!bpf_pseudo_call(insn))
16264 			continue;
16265 		depth = get_callee_stack_depth(env, insn, i);
16266 		if (depth < 0)
16267 			return depth;
16268 		bpf_patch_call_args(insn, depth);
16269 	}
16270 	err = 0;
16271 #endif
16272 	return err;
16273 }
16274 
16275 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16276 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16277 {
16278 	const struct bpf_kfunc_desc *desc;
16279 	void *xdp_kfunc;
16280 
16281 	if (!insn->imm) {
16282 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16283 		return -EINVAL;
16284 	}
16285 
16286 	*cnt = 0;
16287 
16288 	if (bpf_dev_bound_kfunc_id(insn->imm)) {
16289 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16290 		if (xdp_kfunc) {
16291 			insn->imm = BPF_CALL_IMM(xdp_kfunc);
16292 			return 0;
16293 		}
16294 
16295 		/* fallback to default kfunc when not supported by netdev */
16296 	}
16297 
16298 	/* insn->imm has the btf func_id. Replace it with
16299 	 * an address (relative to __bpf_call_base).
16300 	 */
16301 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16302 	if (!desc) {
16303 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16304 			insn->imm);
16305 		return -EFAULT;
16306 	}
16307 
16308 	insn->imm = desc->imm;
16309 	if (insn->off)
16310 		return 0;
16311 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16312 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16313 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16314 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16315 
16316 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16317 		insn_buf[1] = addr[0];
16318 		insn_buf[2] = addr[1];
16319 		insn_buf[3] = *insn;
16320 		*cnt = 4;
16321 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16322 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16323 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16324 
16325 		insn_buf[0] = addr[0];
16326 		insn_buf[1] = addr[1];
16327 		insn_buf[2] = *insn;
16328 		*cnt = 3;
16329 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16330 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16331 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16332 		*cnt = 1;
16333 	}
16334 	return 0;
16335 }
16336 
16337 /* Do various post-verification rewrites in a single program pass.
16338  * These rewrites simplify JIT and interpreter implementations.
16339  */
16340 static int do_misc_fixups(struct bpf_verifier_env *env)
16341 {
16342 	struct bpf_prog *prog = env->prog;
16343 	enum bpf_attach_type eatype = prog->expected_attach_type;
16344 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16345 	struct bpf_insn *insn = prog->insnsi;
16346 	const struct bpf_func_proto *fn;
16347 	const int insn_cnt = prog->len;
16348 	const struct bpf_map_ops *ops;
16349 	struct bpf_insn_aux_data *aux;
16350 	struct bpf_insn insn_buf[16];
16351 	struct bpf_prog *new_prog;
16352 	struct bpf_map *map_ptr;
16353 	int i, ret, cnt, delta = 0;
16354 
16355 	for (i = 0; i < insn_cnt; i++, insn++) {
16356 		/* Make divide-by-zero exceptions impossible. */
16357 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16358 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16359 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16360 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16361 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16362 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16363 			struct bpf_insn *patchlet;
16364 			struct bpf_insn chk_and_div[] = {
16365 				/* [R,W]x div 0 -> 0 */
16366 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16367 					     BPF_JNE | BPF_K, insn->src_reg,
16368 					     0, 2, 0),
16369 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16370 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16371 				*insn,
16372 			};
16373 			struct bpf_insn chk_and_mod[] = {
16374 				/* [R,W]x mod 0 -> [R,W]x */
16375 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16376 					     BPF_JEQ | BPF_K, insn->src_reg,
16377 					     0, 1 + (is64 ? 0 : 1), 0),
16378 				*insn,
16379 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16380 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16381 			};
16382 
16383 			patchlet = isdiv ? chk_and_div : chk_and_mod;
16384 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16385 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16386 
16387 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16388 			if (!new_prog)
16389 				return -ENOMEM;
16390 
16391 			delta    += cnt - 1;
16392 			env->prog = prog = new_prog;
16393 			insn      = new_prog->insnsi + i + delta;
16394 			continue;
16395 		}
16396 
16397 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16398 		if (BPF_CLASS(insn->code) == BPF_LD &&
16399 		    (BPF_MODE(insn->code) == BPF_ABS ||
16400 		     BPF_MODE(insn->code) == BPF_IND)) {
16401 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
16402 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16403 				verbose(env, "bpf verifier is misconfigured\n");
16404 				return -EINVAL;
16405 			}
16406 
16407 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16408 			if (!new_prog)
16409 				return -ENOMEM;
16410 
16411 			delta    += cnt - 1;
16412 			env->prog = prog = new_prog;
16413 			insn      = new_prog->insnsi + i + delta;
16414 			continue;
16415 		}
16416 
16417 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
16418 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16419 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16420 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16421 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16422 			struct bpf_insn *patch = &insn_buf[0];
16423 			bool issrc, isneg, isimm;
16424 			u32 off_reg;
16425 
16426 			aux = &env->insn_aux_data[i + delta];
16427 			if (!aux->alu_state ||
16428 			    aux->alu_state == BPF_ALU_NON_POINTER)
16429 				continue;
16430 
16431 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16432 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16433 				BPF_ALU_SANITIZE_SRC;
16434 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16435 
16436 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
16437 			if (isimm) {
16438 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16439 			} else {
16440 				if (isneg)
16441 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16442 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16443 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16444 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16445 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16446 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16447 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16448 			}
16449 			if (!issrc)
16450 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16451 			insn->src_reg = BPF_REG_AX;
16452 			if (isneg)
16453 				insn->code = insn->code == code_add ?
16454 					     code_sub : code_add;
16455 			*patch++ = *insn;
16456 			if (issrc && isneg && !isimm)
16457 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16458 			cnt = patch - insn_buf;
16459 
16460 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16461 			if (!new_prog)
16462 				return -ENOMEM;
16463 
16464 			delta    += cnt - 1;
16465 			env->prog = prog = new_prog;
16466 			insn      = new_prog->insnsi + i + delta;
16467 			continue;
16468 		}
16469 
16470 		if (insn->code != (BPF_JMP | BPF_CALL))
16471 			continue;
16472 		if (insn->src_reg == BPF_PSEUDO_CALL)
16473 			continue;
16474 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16475 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16476 			if (ret)
16477 				return ret;
16478 			if (cnt == 0)
16479 				continue;
16480 
16481 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16482 			if (!new_prog)
16483 				return -ENOMEM;
16484 
16485 			delta	 += cnt - 1;
16486 			env->prog = prog = new_prog;
16487 			insn	  = new_prog->insnsi + i + delta;
16488 			continue;
16489 		}
16490 
16491 		if (insn->imm == BPF_FUNC_get_route_realm)
16492 			prog->dst_needed = 1;
16493 		if (insn->imm == BPF_FUNC_get_prandom_u32)
16494 			bpf_user_rnd_init_once();
16495 		if (insn->imm == BPF_FUNC_override_return)
16496 			prog->kprobe_override = 1;
16497 		if (insn->imm == BPF_FUNC_tail_call) {
16498 			/* If we tail call into other programs, we
16499 			 * cannot make any assumptions since they can
16500 			 * be replaced dynamically during runtime in
16501 			 * the program array.
16502 			 */
16503 			prog->cb_access = 1;
16504 			if (!allow_tail_call_in_subprogs(env))
16505 				prog->aux->stack_depth = MAX_BPF_STACK;
16506 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16507 
16508 			/* mark bpf_tail_call as different opcode to avoid
16509 			 * conditional branch in the interpreter for every normal
16510 			 * call and to prevent accidental JITing by JIT compiler
16511 			 * that doesn't support bpf_tail_call yet
16512 			 */
16513 			insn->imm = 0;
16514 			insn->code = BPF_JMP | BPF_TAIL_CALL;
16515 
16516 			aux = &env->insn_aux_data[i + delta];
16517 			if (env->bpf_capable && !prog->blinding_requested &&
16518 			    prog->jit_requested &&
16519 			    !bpf_map_key_poisoned(aux) &&
16520 			    !bpf_map_ptr_poisoned(aux) &&
16521 			    !bpf_map_ptr_unpriv(aux)) {
16522 				struct bpf_jit_poke_descriptor desc = {
16523 					.reason = BPF_POKE_REASON_TAIL_CALL,
16524 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16525 					.tail_call.key = bpf_map_key_immediate(aux),
16526 					.insn_idx = i + delta,
16527 				};
16528 
16529 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
16530 				if (ret < 0) {
16531 					verbose(env, "adding tail call poke descriptor failed\n");
16532 					return ret;
16533 				}
16534 
16535 				insn->imm = ret + 1;
16536 				continue;
16537 			}
16538 
16539 			if (!bpf_map_ptr_unpriv(aux))
16540 				continue;
16541 
16542 			/* instead of changing every JIT dealing with tail_call
16543 			 * emit two extra insns:
16544 			 * if (index >= max_entries) goto out;
16545 			 * index &= array->index_mask;
16546 			 * to avoid out-of-bounds cpu speculation
16547 			 */
16548 			if (bpf_map_ptr_poisoned(aux)) {
16549 				verbose(env, "tail_call abusing map_ptr\n");
16550 				return -EINVAL;
16551 			}
16552 
16553 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16554 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16555 						  map_ptr->max_entries, 2);
16556 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16557 						    container_of(map_ptr,
16558 								 struct bpf_array,
16559 								 map)->index_mask);
16560 			insn_buf[2] = *insn;
16561 			cnt = 3;
16562 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16563 			if (!new_prog)
16564 				return -ENOMEM;
16565 
16566 			delta    += cnt - 1;
16567 			env->prog = prog = new_prog;
16568 			insn      = new_prog->insnsi + i + delta;
16569 			continue;
16570 		}
16571 
16572 		if (insn->imm == BPF_FUNC_timer_set_callback) {
16573 			/* The verifier will process callback_fn as many times as necessary
16574 			 * with different maps and the register states prepared by
16575 			 * set_timer_callback_state will be accurate.
16576 			 *
16577 			 * The following use case is valid:
16578 			 *   map1 is shared by prog1, prog2, prog3.
16579 			 *   prog1 calls bpf_timer_init for some map1 elements
16580 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
16581 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
16582 			 *   prog3 calls bpf_timer_start for some map1 elements.
16583 			 *     Those that were not both bpf_timer_init-ed and
16584 			 *     bpf_timer_set_callback-ed will return -EINVAL.
16585 			 */
16586 			struct bpf_insn ld_addrs[2] = {
16587 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16588 			};
16589 
16590 			insn_buf[0] = ld_addrs[0];
16591 			insn_buf[1] = ld_addrs[1];
16592 			insn_buf[2] = *insn;
16593 			cnt = 3;
16594 
16595 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16596 			if (!new_prog)
16597 				return -ENOMEM;
16598 
16599 			delta    += cnt - 1;
16600 			env->prog = prog = new_prog;
16601 			insn      = new_prog->insnsi + i + delta;
16602 			goto patch_call_imm;
16603 		}
16604 
16605 		if (is_storage_get_function(insn->imm)) {
16606 			if (!env->prog->aux->sleepable ||
16607 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
16608 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16609 			else
16610 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16611 			insn_buf[1] = *insn;
16612 			cnt = 2;
16613 
16614 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16615 			if (!new_prog)
16616 				return -ENOMEM;
16617 
16618 			delta += cnt - 1;
16619 			env->prog = prog = new_prog;
16620 			insn = new_prog->insnsi + i + delta;
16621 			goto patch_call_imm;
16622 		}
16623 
16624 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16625 		 * and other inlining handlers are currently limited to 64 bit
16626 		 * only.
16627 		 */
16628 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16629 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
16630 		     insn->imm == BPF_FUNC_map_update_elem ||
16631 		     insn->imm == BPF_FUNC_map_delete_elem ||
16632 		     insn->imm == BPF_FUNC_map_push_elem   ||
16633 		     insn->imm == BPF_FUNC_map_pop_elem    ||
16634 		     insn->imm == BPF_FUNC_map_peek_elem   ||
16635 		     insn->imm == BPF_FUNC_redirect_map    ||
16636 		     insn->imm == BPF_FUNC_for_each_map_elem ||
16637 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16638 			aux = &env->insn_aux_data[i + delta];
16639 			if (bpf_map_ptr_poisoned(aux))
16640 				goto patch_call_imm;
16641 
16642 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16643 			ops = map_ptr->ops;
16644 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
16645 			    ops->map_gen_lookup) {
16646 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16647 				if (cnt == -EOPNOTSUPP)
16648 					goto patch_map_ops_generic;
16649 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16650 					verbose(env, "bpf verifier is misconfigured\n");
16651 					return -EINVAL;
16652 				}
16653 
16654 				new_prog = bpf_patch_insn_data(env, i + delta,
16655 							       insn_buf, cnt);
16656 				if (!new_prog)
16657 					return -ENOMEM;
16658 
16659 				delta    += cnt - 1;
16660 				env->prog = prog = new_prog;
16661 				insn      = new_prog->insnsi + i + delta;
16662 				continue;
16663 			}
16664 
16665 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
16666 				     (void *(*)(struct bpf_map *map, void *key))NULL));
16667 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
16668 				     (int (*)(struct bpf_map *map, void *key))NULL));
16669 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
16670 				     (int (*)(struct bpf_map *map, void *key, void *value,
16671 					      u64 flags))NULL));
16672 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
16673 				     (int (*)(struct bpf_map *map, void *value,
16674 					      u64 flags))NULL));
16675 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
16676 				     (int (*)(struct bpf_map *map, void *value))NULL));
16677 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
16678 				     (int (*)(struct bpf_map *map, void *value))NULL));
16679 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
16680 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
16681 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
16682 				     (int (*)(struct bpf_map *map,
16683 					      bpf_callback_t callback_fn,
16684 					      void *callback_ctx,
16685 					      u64 flags))NULL));
16686 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
16687 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
16688 
16689 patch_map_ops_generic:
16690 			switch (insn->imm) {
16691 			case BPF_FUNC_map_lookup_elem:
16692 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
16693 				continue;
16694 			case BPF_FUNC_map_update_elem:
16695 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
16696 				continue;
16697 			case BPF_FUNC_map_delete_elem:
16698 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
16699 				continue;
16700 			case BPF_FUNC_map_push_elem:
16701 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
16702 				continue;
16703 			case BPF_FUNC_map_pop_elem:
16704 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
16705 				continue;
16706 			case BPF_FUNC_map_peek_elem:
16707 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
16708 				continue;
16709 			case BPF_FUNC_redirect_map:
16710 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
16711 				continue;
16712 			case BPF_FUNC_for_each_map_elem:
16713 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
16714 				continue;
16715 			case BPF_FUNC_map_lookup_percpu_elem:
16716 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
16717 				continue;
16718 			}
16719 
16720 			goto patch_call_imm;
16721 		}
16722 
16723 		/* Implement bpf_jiffies64 inline. */
16724 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16725 		    insn->imm == BPF_FUNC_jiffies64) {
16726 			struct bpf_insn ld_jiffies_addr[2] = {
16727 				BPF_LD_IMM64(BPF_REG_0,
16728 					     (unsigned long)&jiffies),
16729 			};
16730 
16731 			insn_buf[0] = ld_jiffies_addr[0];
16732 			insn_buf[1] = ld_jiffies_addr[1];
16733 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
16734 						  BPF_REG_0, 0);
16735 			cnt = 3;
16736 
16737 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
16738 						       cnt);
16739 			if (!new_prog)
16740 				return -ENOMEM;
16741 
16742 			delta    += cnt - 1;
16743 			env->prog = prog = new_prog;
16744 			insn      = new_prog->insnsi + i + delta;
16745 			continue;
16746 		}
16747 
16748 		/* Implement bpf_get_func_arg inline. */
16749 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16750 		    insn->imm == BPF_FUNC_get_func_arg) {
16751 			/* Load nr_args from ctx - 8 */
16752 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16753 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
16754 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
16755 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
16756 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
16757 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16758 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
16759 			insn_buf[7] = BPF_JMP_A(1);
16760 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
16761 			cnt = 9;
16762 
16763 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16764 			if (!new_prog)
16765 				return -ENOMEM;
16766 
16767 			delta    += cnt - 1;
16768 			env->prog = prog = new_prog;
16769 			insn      = new_prog->insnsi + i + delta;
16770 			continue;
16771 		}
16772 
16773 		/* Implement bpf_get_func_ret inline. */
16774 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16775 		    insn->imm == BPF_FUNC_get_func_ret) {
16776 			if (eatype == BPF_TRACE_FEXIT ||
16777 			    eatype == BPF_MODIFY_RETURN) {
16778 				/* Load nr_args from ctx - 8 */
16779 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16780 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
16781 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
16782 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16783 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
16784 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
16785 				cnt = 6;
16786 			} else {
16787 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
16788 				cnt = 1;
16789 			}
16790 
16791 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16792 			if (!new_prog)
16793 				return -ENOMEM;
16794 
16795 			delta    += cnt - 1;
16796 			env->prog = prog = new_prog;
16797 			insn      = new_prog->insnsi + i + delta;
16798 			continue;
16799 		}
16800 
16801 		/* Implement get_func_arg_cnt inline. */
16802 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16803 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16804 			/* Load nr_args from ctx - 8 */
16805 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16806 
16807 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16808 			if (!new_prog)
16809 				return -ENOMEM;
16810 
16811 			env->prog = prog = new_prog;
16812 			insn      = new_prog->insnsi + i + delta;
16813 			continue;
16814 		}
16815 
16816 		/* Implement bpf_get_func_ip inline. */
16817 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16818 		    insn->imm == BPF_FUNC_get_func_ip) {
16819 			/* Load IP address from ctx - 16 */
16820 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16821 
16822 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16823 			if (!new_prog)
16824 				return -ENOMEM;
16825 
16826 			env->prog = prog = new_prog;
16827 			insn      = new_prog->insnsi + i + delta;
16828 			continue;
16829 		}
16830 
16831 patch_call_imm:
16832 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16833 		/* all functions that have prototype and verifier allowed
16834 		 * programs to call them, must be real in-kernel functions
16835 		 */
16836 		if (!fn->func) {
16837 			verbose(env,
16838 				"kernel subsystem misconfigured func %s#%d\n",
16839 				func_id_name(insn->imm), insn->imm);
16840 			return -EFAULT;
16841 		}
16842 		insn->imm = fn->func - __bpf_call_base;
16843 	}
16844 
16845 	/* Since poke tab is now finalized, publish aux to tracker. */
16846 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16847 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16848 		if (!map_ptr->ops->map_poke_track ||
16849 		    !map_ptr->ops->map_poke_untrack ||
16850 		    !map_ptr->ops->map_poke_run) {
16851 			verbose(env, "bpf verifier is misconfigured\n");
16852 			return -EINVAL;
16853 		}
16854 
16855 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16856 		if (ret < 0) {
16857 			verbose(env, "tracking tail call prog failed\n");
16858 			return ret;
16859 		}
16860 	}
16861 
16862 	sort_kfunc_descs_by_imm(env->prog);
16863 
16864 	return 0;
16865 }
16866 
16867 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16868 					int position,
16869 					s32 stack_base,
16870 					u32 callback_subprogno,
16871 					u32 *cnt)
16872 {
16873 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16874 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16875 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16876 	int reg_loop_max = BPF_REG_6;
16877 	int reg_loop_cnt = BPF_REG_7;
16878 	int reg_loop_ctx = BPF_REG_8;
16879 
16880 	struct bpf_prog *new_prog;
16881 	u32 callback_start;
16882 	u32 call_insn_offset;
16883 	s32 callback_offset;
16884 
16885 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16886 	 * be careful to modify this code in sync.
16887 	 */
16888 	struct bpf_insn insn_buf[] = {
16889 		/* Return error and jump to the end of the patch if
16890 		 * expected number of iterations is too big.
16891 		 */
16892 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16893 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16894 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16895 		/* spill R6, R7, R8 to use these as loop vars */
16896 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16897 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16898 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16899 		/* initialize loop vars */
16900 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16901 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16902 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16903 		/* loop header,
16904 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16905 		 */
16906 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16907 		/* callback call,
16908 		 * correct callback offset would be set after patching
16909 		 */
16910 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16911 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16912 		BPF_CALL_REL(0),
16913 		/* increment loop counter */
16914 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16915 		/* jump to loop header if callback returned 0 */
16916 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16917 		/* return value of bpf_loop,
16918 		 * set R0 to the number of iterations
16919 		 */
16920 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16921 		/* restore original values of R6, R7, R8 */
16922 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16923 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16924 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16925 	};
16926 
16927 	*cnt = ARRAY_SIZE(insn_buf);
16928 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16929 	if (!new_prog)
16930 		return new_prog;
16931 
16932 	/* callback start is known only after patching */
16933 	callback_start = env->subprog_info[callback_subprogno].start;
16934 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16935 	call_insn_offset = position + 12;
16936 	callback_offset = callback_start - call_insn_offset - 1;
16937 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16938 
16939 	return new_prog;
16940 }
16941 
16942 static bool is_bpf_loop_call(struct bpf_insn *insn)
16943 {
16944 	return insn->code == (BPF_JMP | BPF_CALL) &&
16945 		insn->src_reg == 0 &&
16946 		insn->imm == BPF_FUNC_loop;
16947 }
16948 
16949 /* For all sub-programs in the program (including main) check
16950  * insn_aux_data to see if there are bpf_loop calls that require
16951  * inlining. If such calls are found the calls are replaced with a
16952  * sequence of instructions produced by `inline_bpf_loop` function and
16953  * subprog stack_depth is increased by the size of 3 registers.
16954  * This stack space is used to spill values of the R6, R7, R8.  These
16955  * registers are used to store the loop bound, counter and context
16956  * variables.
16957  */
16958 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16959 {
16960 	struct bpf_subprog_info *subprogs = env->subprog_info;
16961 	int i, cur_subprog = 0, cnt, delta = 0;
16962 	struct bpf_insn *insn = env->prog->insnsi;
16963 	int insn_cnt = env->prog->len;
16964 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16965 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16966 	u16 stack_depth_extra = 0;
16967 
16968 	for (i = 0; i < insn_cnt; i++, insn++) {
16969 		struct bpf_loop_inline_state *inline_state =
16970 			&env->insn_aux_data[i + delta].loop_inline_state;
16971 
16972 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16973 			struct bpf_prog *new_prog;
16974 
16975 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16976 			new_prog = inline_bpf_loop(env,
16977 						   i + delta,
16978 						   -(stack_depth + stack_depth_extra),
16979 						   inline_state->callback_subprogno,
16980 						   &cnt);
16981 			if (!new_prog)
16982 				return -ENOMEM;
16983 
16984 			delta     += cnt - 1;
16985 			env->prog  = new_prog;
16986 			insn       = new_prog->insnsi + i + delta;
16987 		}
16988 
16989 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16990 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16991 			cur_subprog++;
16992 			stack_depth = subprogs[cur_subprog].stack_depth;
16993 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16994 			stack_depth_extra = 0;
16995 		}
16996 	}
16997 
16998 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16999 
17000 	return 0;
17001 }
17002 
17003 static void free_states(struct bpf_verifier_env *env)
17004 {
17005 	struct bpf_verifier_state_list *sl, *sln;
17006 	int i;
17007 
17008 	sl = env->free_list;
17009 	while (sl) {
17010 		sln = sl->next;
17011 		free_verifier_state(&sl->state, false);
17012 		kfree(sl);
17013 		sl = sln;
17014 	}
17015 	env->free_list = NULL;
17016 
17017 	if (!env->explored_states)
17018 		return;
17019 
17020 	for (i = 0; i < state_htab_size(env); i++) {
17021 		sl = env->explored_states[i];
17022 
17023 		while (sl) {
17024 			sln = sl->next;
17025 			free_verifier_state(&sl->state, false);
17026 			kfree(sl);
17027 			sl = sln;
17028 		}
17029 		env->explored_states[i] = NULL;
17030 	}
17031 }
17032 
17033 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17034 {
17035 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17036 	struct bpf_verifier_state *state;
17037 	struct bpf_reg_state *regs;
17038 	int ret, i;
17039 
17040 	env->prev_linfo = NULL;
17041 	env->pass_cnt++;
17042 
17043 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17044 	if (!state)
17045 		return -ENOMEM;
17046 	state->curframe = 0;
17047 	state->speculative = false;
17048 	state->branches = 1;
17049 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17050 	if (!state->frame[0]) {
17051 		kfree(state);
17052 		return -ENOMEM;
17053 	}
17054 	env->cur_state = state;
17055 	init_func_state(env, state->frame[0],
17056 			BPF_MAIN_FUNC /* callsite */,
17057 			0 /* frameno */,
17058 			subprog);
17059 	state->first_insn_idx = env->subprog_info[subprog].start;
17060 	state->last_insn_idx = -1;
17061 
17062 	regs = state->frame[state->curframe]->regs;
17063 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17064 		ret = btf_prepare_func_args(env, subprog, regs);
17065 		if (ret)
17066 			goto out;
17067 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17068 			if (regs[i].type == PTR_TO_CTX)
17069 				mark_reg_known_zero(env, regs, i);
17070 			else if (regs[i].type == SCALAR_VALUE)
17071 				mark_reg_unknown(env, regs, i);
17072 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
17073 				const u32 mem_size = regs[i].mem_size;
17074 
17075 				mark_reg_known_zero(env, regs, i);
17076 				regs[i].mem_size = mem_size;
17077 				regs[i].id = ++env->id_gen;
17078 			}
17079 		}
17080 	} else {
17081 		/* 1st arg to a function */
17082 		regs[BPF_REG_1].type = PTR_TO_CTX;
17083 		mark_reg_known_zero(env, regs, BPF_REG_1);
17084 		ret = btf_check_subprog_arg_match(env, subprog, regs);
17085 		if (ret == -EFAULT)
17086 			/* unlikely verifier bug. abort.
17087 			 * ret == 0 and ret < 0 are sadly acceptable for
17088 			 * main() function due to backward compatibility.
17089 			 * Like socket filter program may be written as:
17090 			 * int bpf_prog(struct pt_regs *ctx)
17091 			 * and never dereference that ctx in the program.
17092 			 * 'struct pt_regs' is a type mismatch for socket
17093 			 * filter that should be using 'struct __sk_buff'.
17094 			 */
17095 			goto out;
17096 	}
17097 
17098 	ret = do_check(env);
17099 out:
17100 	/* check for NULL is necessary, since cur_state can be freed inside
17101 	 * do_check() under memory pressure.
17102 	 */
17103 	if (env->cur_state) {
17104 		free_verifier_state(env->cur_state, true);
17105 		env->cur_state = NULL;
17106 	}
17107 	while (!pop_stack(env, NULL, NULL, false));
17108 	if (!ret && pop_log)
17109 		bpf_vlog_reset(&env->log, 0);
17110 	free_states(env);
17111 	return ret;
17112 }
17113 
17114 /* Verify all global functions in a BPF program one by one based on their BTF.
17115  * All global functions must pass verification. Otherwise the whole program is rejected.
17116  * Consider:
17117  * int bar(int);
17118  * int foo(int f)
17119  * {
17120  *    return bar(f);
17121  * }
17122  * int bar(int b)
17123  * {
17124  *    ...
17125  * }
17126  * foo() will be verified first for R1=any_scalar_value. During verification it
17127  * will be assumed that bar() already verified successfully and call to bar()
17128  * from foo() will be checked for type match only. Later bar() will be verified
17129  * independently to check that it's safe for R1=any_scalar_value.
17130  */
17131 static int do_check_subprogs(struct bpf_verifier_env *env)
17132 {
17133 	struct bpf_prog_aux *aux = env->prog->aux;
17134 	int i, ret;
17135 
17136 	if (!aux->func_info)
17137 		return 0;
17138 
17139 	for (i = 1; i < env->subprog_cnt; i++) {
17140 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17141 			continue;
17142 		env->insn_idx = env->subprog_info[i].start;
17143 		WARN_ON_ONCE(env->insn_idx == 0);
17144 		ret = do_check_common(env, i);
17145 		if (ret) {
17146 			return ret;
17147 		} else if (env->log.level & BPF_LOG_LEVEL) {
17148 			verbose(env,
17149 				"Func#%d is safe for any args that match its prototype\n",
17150 				i);
17151 		}
17152 	}
17153 	return 0;
17154 }
17155 
17156 static int do_check_main(struct bpf_verifier_env *env)
17157 {
17158 	int ret;
17159 
17160 	env->insn_idx = 0;
17161 	ret = do_check_common(env, 0);
17162 	if (!ret)
17163 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17164 	return ret;
17165 }
17166 
17167 
17168 static void print_verification_stats(struct bpf_verifier_env *env)
17169 {
17170 	int i;
17171 
17172 	if (env->log.level & BPF_LOG_STATS) {
17173 		verbose(env, "verification time %lld usec\n",
17174 			div_u64(env->verification_time, 1000));
17175 		verbose(env, "stack depth ");
17176 		for (i = 0; i < env->subprog_cnt; i++) {
17177 			u32 depth = env->subprog_info[i].stack_depth;
17178 
17179 			verbose(env, "%d", depth);
17180 			if (i + 1 < env->subprog_cnt)
17181 				verbose(env, "+");
17182 		}
17183 		verbose(env, "\n");
17184 	}
17185 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17186 		"total_states %d peak_states %d mark_read %d\n",
17187 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17188 		env->max_states_per_insn, env->total_states,
17189 		env->peak_states, env->longest_mark_read_walk);
17190 }
17191 
17192 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17193 {
17194 	const struct btf_type *t, *func_proto;
17195 	const struct bpf_struct_ops *st_ops;
17196 	const struct btf_member *member;
17197 	struct bpf_prog *prog = env->prog;
17198 	u32 btf_id, member_idx;
17199 	const char *mname;
17200 
17201 	if (!prog->gpl_compatible) {
17202 		verbose(env, "struct ops programs must have a GPL compatible license\n");
17203 		return -EINVAL;
17204 	}
17205 
17206 	btf_id = prog->aux->attach_btf_id;
17207 	st_ops = bpf_struct_ops_find(btf_id);
17208 	if (!st_ops) {
17209 		verbose(env, "attach_btf_id %u is not a supported struct\n",
17210 			btf_id);
17211 		return -ENOTSUPP;
17212 	}
17213 
17214 	t = st_ops->type;
17215 	member_idx = prog->expected_attach_type;
17216 	if (member_idx >= btf_type_vlen(t)) {
17217 		verbose(env, "attach to invalid member idx %u of struct %s\n",
17218 			member_idx, st_ops->name);
17219 		return -EINVAL;
17220 	}
17221 
17222 	member = &btf_type_member(t)[member_idx];
17223 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17224 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17225 					       NULL);
17226 	if (!func_proto) {
17227 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17228 			mname, member_idx, st_ops->name);
17229 		return -EINVAL;
17230 	}
17231 
17232 	if (st_ops->check_member) {
17233 		int err = st_ops->check_member(t, member, prog);
17234 
17235 		if (err) {
17236 			verbose(env, "attach to unsupported member %s of struct %s\n",
17237 				mname, st_ops->name);
17238 			return err;
17239 		}
17240 	}
17241 
17242 	prog->aux->attach_func_proto = func_proto;
17243 	prog->aux->attach_func_name = mname;
17244 	env->ops = st_ops->verifier_ops;
17245 
17246 	return 0;
17247 }
17248 #define SECURITY_PREFIX "security_"
17249 
17250 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17251 {
17252 	if (within_error_injection_list(addr) ||
17253 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17254 		return 0;
17255 
17256 	return -EINVAL;
17257 }
17258 
17259 /* list of non-sleepable functions that are otherwise on
17260  * ALLOW_ERROR_INJECTION list
17261  */
17262 BTF_SET_START(btf_non_sleepable_error_inject)
17263 /* Three functions below can be called from sleepable and non-sleepable context.
17264  * Assume non-sleepable from bpf safety point of view.
17265  */
17266 BTF_ID(func, __filemap_add_folio)
17267 BTF_ID(func, should_fail_alloc_page)
17268 BTF_ID(func, should_failslab)
17269 BTF_SET_END(btf_non_sleepable_error_inject)
17270 
17271 static int check_non_sleepable_error_inject(u32 btf_id)
17272 {
17273 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17274 }
17275 
17276 int bpf_check_attach_target(struct bpf_verifier_log *log,
17277 			    const struct bpf_prog *prog,
17278 			    const struct bpf_prog *tgt_prog,
17279 			    u32 btf_id,
17280 			    struct bpf_attach_target_info *tgt_info)
17281 {
17282 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17283 	const char prefix[] = "btf_trace_";
17284 	int ret = 0, subprog = -1, i;
17285 	const struct btf_type *t;
17286 	bool conservative = true;
17287 	const char *tname;
17288 	struct btf *btf;
17289 	long addr = 0;
17290 
17291 	if (!btf_id) {
17292 		bpf_log(log, "Tracing programs must provide btf_id\n");
17293 		return -EINVAL;
17294 	}
17295 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17296 	if (!btf) {
17297 		bpf_log(log,
17298 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17299 		return -EINVAL;
17300 	}
17301 	t = btf_type_by_id(btf, btf_id);
17302 	if (!t) {
17303 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17304 		return -EINVAL;
17305 	}
17306 	tname = btf_name_by_offset(btf, t->name_off);
17307 	if (!tname) {
17308 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17309 		return -EINVAL;
17310 	}
17311 	if (tgt_prog) {
17312 		struct bpf_prog_aux *aux = tgt_prog->aux;
17313 
17314 		if (bpf_prog_is_dev_bound(prog->aux) &&
17315 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17316 			bpf_log(log, "Target program bound device mismatch");
17317 			return -EINVAL;
17318 		}
17319 
17320 		for (i = 0; i < aux->func_info_cnt; i++)
17321 			if (aux->func_info[i].type_id == btf_id) {
17322 				subprog = i;
17323 				break;
17324 			}
17325 		if (subprog == -1) {
17326 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
17327 			return -EINVAL;
17328 		}
17329 		conservative = aux->func_info_aux[subprog].unreliable;
17330 		if (prog_extension) {
17331 			if (conservative) {
17332 				bpf_log(log,
17333 					"Cannot replace static functions\n");
17334 				return -EINVAL;
17335 			}
17336 			if (!prog->jit_requested) {
17337 				bpf_log(log,
17338 					"Extension programs should be JITed\n");
17339 				return -EINVAL;
17340 			}
17341 		}
17342 		if (!tgt_prog->jited) {
17343 			bpf_log(log, "Can attach to only JITed progs\n");
17344 			return -EINVAL;
17345 		}
17346 		if (tgt_prog->type == prog->type) {
17347 			/* Cannot fentry/fexit another fentry/fexit program.
17348 			 * Cannot attach program extension to another extension.
17349 			 * It's ok to attach fentry/fexit to extension program.
17350 			 */
17351 			bpf_log(log, "Cannot recursively attach\n");
17352 			return -EINVAL;
17353 		}
17354 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17355 		    prog_extension &&
17356 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17357 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17358 			/* Program extensions can extend all program types
17359 			 * except fentry/fexit. The reason is the following.
17360 			 * The fentry/fexit programs are used for performance
17361 			 * analysis, stats and can be attached to any program
17362 			 * type except themselves. When extension program is
17363 			 * replacing XDP function it is necessary to allow
17364 			 * performance analysis of all functions. Both original
17365 			 * XDP program and its program extension. Hence
17366 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17367 			 * allowed. If extending of fentry/fexit was allowed it
17368 			 * would be possible to create long call chain
17369 			 * fentry->extension->fentry->extension beyond
17370 			 * reasonable stack size. Hence extending fentry is not
17371 			 * allowed.
17372 			 */
17373 			bpf_log(log, "Cannot extend fentry/fexit\n");
17374 			return -EINVAL;
17375 		}
17376 	} else {
17377 		if (prog_extension) {
17378 			bpf_log(log, "Cannot replace kernel functions\n");
17379 			return -EINVAL;
17380 		}
17381 	}
17382 
17383 	switch (prog->expected_attach_type) {
17384 	case BPF_TRACE_RAW_TP:
17385 		if (tgt_prog) {
17386 			bpf_log(log,
17387 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17388 			return -EINVAL;
17389 		}
17390 		if (!btf_type_is_typedef(t)) {
17391 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
17392 				btf_id);
17393 			return -EINVAL;
17394 		}
17395 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17396 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17397 				btf_id, tname);
17398 			return -EINVAL;
17399 		}
17400 		tname += sizeof(prefix) - 1;
17401 		t = btf_type_by_id(btf, t->type);
17402 		if (!btf_type_is_ptr(t))
17403 			/* should never happen in valid vmlinux build */
17404 			return -EINVAL;
17405 		t = btf_type_by_id(btf, t->type);
17406 		if (!btf_type_is_func_proto(t))
17407 			/* should never happen in valid vmlinux build */
17408 			return -EINVAL;
17409 
17410 		break;
17411 	case BPF_TRACE_ITER:
17412 		if (!btf_type_is_func(t)) {
17413 			bpf_log(log, "attach_btf_id %u is not a function\n",
17414 				btf_id);
17415 			return -EINVAL;
17416 		}
17417 		t = btf_type_by_id(btf, t->type);
17418 		if (!btf_type_is_func_proto(t))
17419 			return -EINVAL;
17420 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17421 		if (ret)
17422 			return ret;
17423 		break;
17424 	default:
17425 		if (!prog_extension)
17426 			return -EINVAL;
17427 		fallthrough;
17428 	case BPF_MODIFY_RETURN:
17429 	case BPF_LSM_MAC:
17430 	case BPF_LSM_CGROUP:
17431 	case BPF_TRACE_FENTRY:
17432 	case BPF_TRACE_FEXIT:
17433 		if (!btf_type_is_func(t)) {
17434 			bpf_log(log, "attach_btf_id %u is not a function\n",
17435 				btf_id);
17436 			return -EINVAL;
17437 		}
17438 		if (prog_extension &&
17439 		    btf_check_type_match(log, prog, btf, t))
17440 			return -EINVAL;
17441 		t = btf_type_by_id(btf, t->type);
17442 		if (!btf_type_is_func_proto(t))
17443 			return -EINVAL;
17444 
17445 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17446 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17447 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17448 			return -EINVAL;
17449 
17450 		if (tgt_prog && conservative)
17451 			t = NULL;
17452 
17453 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17454 		if (ret < 0)
17455 			return ret;
17456 
17457 		if (tgt_prog) {
17458 			if (subprog == 0)
17459 				addr = (long) tgt_prog->bpf_func;
17460 			else
17461 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17462 		} else {
17463 			addr = kallsyms_lookup_name(tname);
17464 			if (!addr) {
17465 				bpf_log(log,
17466 					"The address of function %s cannot be found\n",
17467 					tname);
17468 				return -ENOENT;
17469 			}
17470 		}
17471 
17472 		if (prog->aux->sleepable) {
17473 			ret = -EINVAL;
17474 			switch (prog->type) {
17475 			case BPF_PROG_TYPE_TRACING:
17476 
17477 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
17478 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17479 				 */
17480 				if (!check_non_sleepable_error_inject(btf_id) &&
17481 				    within_error_injection_list(addr))
17482 					ret = 0;
17483 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
17484 				 * in the fmodret id set with the KF_SLEEPABLE flag.
17485 				 */
17486 				else {
17487 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17488 
17489 					if (flags && (*flags & KF_SLEEPABLE))
17490 						ret = 0;
17491 				}
17492 				break;
17493 			case BPF_PROG_TYPE_LSM:
17494 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
17495 				 * Only some of them are sleepable.
17496 				 */
17497 				if (bpf_lsm_is_sleepable_hook(btf_id))
17498 					ret = 0;
17499 				break;
17500 			default:
17501 				break;
17502 			}
17503 			if (ret) {
17504 				bpf_log(log, "%s is not sleepable\n", tname);
17505 				return ret;
17506 			}
17507 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17508 			if (tgt_prog) {
17509 				bpf_log(log, "can't modify return codes of BPF programs\n");
17510 				return -EINVAL;
17511 			}
17512 			ret = -EINVAL;
17513 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
17514 			    !check_attach_modify_return(addr, tname))
17515 				ret = 0;
17516 			if (ret) {
17517 				bpf_log(log, "%s() is not modifiable\n", tname);
17518 				return ret;
17519 			}
17520 		}
17521 
17522 		break;
17523 	}
17524 	tgt_info->tgt_addr = addr;
17525 	tgt_info->tgt_name = tname;
17526 	tgt_info->tgt_type = t;
17527 	return 0;
17528 }
17529 
17530 BTF_SET_START(btf_id_deny)
17531 BTF_ID_UNUSED
17532 #ifdef CONFIG_SMP
17533 BTF_ID(func, migrate_disable)
17534 BTF_ID(func, migrate_enable)
17535 #endif
17536 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17537 BTF_ID(func, rcu_read_unlock_strict)
17538 #endif
17539 BTF_SET_END(btf_id_deny)
17540 
17541 static bool can_be_sleepable(struct bpf_prog *prog)
17542 {
17543 	if (prog->type == BPF_PROG_TYPE_TRACING) {
17544 		switch (prog->expected_attach_type) {
17545 		case BPF_TRACE_FENTRY:
17546 		case BPF_TRACE_FEXIT:
17547 		case BPF_MODIFY_RETURN:
17548 		case BPF_TRACE_ITER:
17549 			return true;
17550 		default:
17551 			return false;
17552 		}
17553 	}
17554 	return prog->type == BPF_PROG_TYPE_LSM ||
17555 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17556 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17557 }
17558 
17559 static int check_attach_btf_id(struct bpf_verifier_env *env)
17560 {
17561 	struct bpf_prog *prog = env->prog;
17562 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17563 	struct bpf_attach_target_info tgt_info = {};
17564 	u32 btf_id = prog->aux->attach_btf_id;
17565 	struct bpf_trampoline *tr;
17566 	int ret;
17567 	u64 key;
17568 
17569 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17570 		if (prog->aux->sleepable)
17571 			/* attach_btf_id checked to be zero already */
17572 			return 0;
17573 		verbose(env, "Syscall programs can only be sleepable\n");
17574 		return -EINVAL;
17575 	}
17576 
17577 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17578 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17579 		return -EINVAL;
17580 	}
17581 
17582 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17583 		return check_struct_ops_btf_id(env);
17584 
17585 	if (prog->type != BPF_PROG_TYPE_TRACING &&
17586 	    prog->type != BPF_PROG_TYPE_LSM &&
17587 	    prog->type != BPF_PROG_TYPE_EXT)
17588 		return 0;
17589 
17590 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17591 	if (ret)
17592 		return ret;
17593 
17594 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17595 		/* to make freplace equivalent to their targets, they need to
17596 		 * inherit env->ops and expected_attach_type for the rest of the
17597 		 * verification
17598 		 */
17599 		env->ops = bpf_verifier_ops[tgt_prog->type];
17600 		prog->expected_attach_type = tgt_prog->expected_attach_type;
17601 	}
17602 
17603 	/* store info about the attachment target that will be used later */
17604 	prog->aux->attach_func_proto = tgt_info.tgt_type;
17605 	prog->aux->attach_func_name = tgt_info.tgt_name;
17606 
17607 	if (tgt_prog) {
17608 		prog->aux->saved_dst_prog_type = tgt_prog->type;
17609 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17610 	}
17611 
17612 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17613 		prog->aux->attach_btf_trace = true;
17614 		return 0;
17615 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17616 		if (!bpf_iter_prog_supported(prog))
17617 			return -EINVAL;
17618 		return 0;
17619 	}
17620 
17621 	if (prog->type == BPF_PROG_TYPE_LSM) {
17622 		ret = bpf_lsm_verify_prog(&env->log, prog);
17623 		if (ret < 0)
17624 			return ret;
17625 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
17626 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
17627 		return -EINVAL;
17628 	}
17629 
17630 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17631 	tr = bpf_trampoline_get(key, &tgt_info);
17632 	if (!tr)
17633 		return -ENOMEM;
17634 
17635 	prog->aux->dst_trampoline = tr;
17636 	return 0;
17637 }
17638 
17639 struct btf *bpf_get_btf_vmlinux(void)
17640 {
17641 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17642 		mutex_lock(&bpf_verifier_lock);
17643 		if (!btf_vmlinux)
17644 			btf_vmlinux = btf_parse_vmlinux();
17645 		mutex_unlock(&bpf_verifier_lock);
17646 	}
17647 	return btf_vmlinux;
17648 }
17649 
17650 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
17651 {
17652 	u64 start_time = ktime_get_ns();
17653 	struct bpf_verifier_env *env;
17654 	struct bpf_verifier_log *log;
17655 	int i, len, ret = -EINVAL;
17656 	bool is_priv;
17657 
17658 	/* no program is valid */
17659 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
17660 		return -EINVAL;
17661 
17662 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
17663 	 * allocate/free it every time bpf_check() is called
17664 	 */
17665 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
17666 	if (!env)
17667 		return -ENOMEM;
17668 	log = &env->log;
17669 
17670 	len = (*prog)->len;
17671 	env->insn_aux_data =
17672 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
17673 	ret = -ENOMEM;
17674 	if (!env->insn_aux_data)
17675 		goto err_free_env;
17676 	for (i = 0; i < len; i++)
17677 		env->insn_aux_data[i].orig_idx = i;
17678 	env->prog = *prog;
17679 	env->ops = bpf_verifier_ops[env->prog->type];
17680 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
17681 	is_priv = bpf_capable();
17682 
17683 	bpf_get_btf_vmlinux();
17684 
17685 	/* grab the mutex to protect few globals used by verifier */
17686 	if (!is_priv)
17687 		mutex_lock(&bpf_verifier_lock);
17688 
17689 	if (attr->log_level || attr->log_buf || attr->log_size) {
17690 		/* user requested verbose verifier output
17691 		 * and supplied buffer to store the verification trace
17692 		 */
17693 		log->level = attr->log_level;
17694 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
17695 		log->len_total = attr->log_size;
17696 
17697 		/* log attributes have to be sane */
17698 		if (!bpf_verifier_log_attr_valid(log)) {
17699 			ret = -EINVAL;
17700 			goto err_unlock;
17701 		}
17702 	}
17703 
17704 	mark_verifier_state_clean(env);
17705 
17706 	if (IS_ERR(btf_vmlinux)) {
17707 		/* Either gcc or pahole or kernel are broken. */
17708 		verbose(env, "in-kernel BTF is malformed\n");
17709 		ret = PTR_ERR(btf_vmlinux);
17710 		goto skip_full_check;
17711 	}
17712 
17713 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
17714 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
17715 		env->strict_alignment = true;
17716 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
17717 		env->strict_alignment = false;
17718 
17719 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
17720 	env->allow_uninit_stack = bpf_allow_uninit_stack();
17721 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
17722 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
17723 	env->bpf_capable = bpf_capable();
17724 	env->rcu_tag_supported = btf_vmlinux &&
17725 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
17726 
17727 	if (is_priv)
17728 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
17729 
17730 	env->explored_states = kvcalloc(state_htab_size(env),
17731 				       sizeof(struct bpf_verifier_state_list *),
17732 				       GFP_USER);
17733 	ret = -ENOMEM;
17734 	if (!env->explored_states)
17735 		goto skip_full_check;
17736 
17737 	ret = add_subprog_and_kfunc(env);
17738 	if (ret < 0)
17739 		goto skip_full_check;
17740 
17741 	ret = check_subprogs(env);
17742 	if (ret < 0)
17743 		goto skip_full_check;
17744 
17745 	ret = check_btf_info(env, attr, uattr);
17746 	if (ret < 0)
17747 		goto skip_full_check;
17748 
17749 	ret = check_attach_btf_id(env);
17750 	if (ret)
17751 		goto skip_full_check;
17752 
17753 	ret = resolve_pseudo_ldimm64(env);
17754 	if (ret < 0)
17755 		goto skip_full_check;
17756 
17757 	if (bpf_prog_is_offloaded(env->prog->aux)) {
17758 		ret = bpf_prog_offload_verifier_prep(env->prog);
17759 		if (ret)
17760 			goto skip_full_check;
17761 	}
17762 
17763 	ret = check_cfg(env);
17764 	if (ret < 0)
17765 		goto skip_full_check;
17766 
17767 	ret = do_check_subprogs(env);
17768 	ret = ret ?: do_check_main(env);
17769 
17770 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
17771 		ret = bpf_prog_offload_finalize(env);
17772 
17773 skip_full_check:
17774 	kvfree(env->explored_states);
17775 
17776 	if (ret == 0)
17777 		ret = check_max_stack_depth(env);
17778 
17779 	/* instruction rewrites happen after this point */
17780 	if (ret == 0)
17781 		ret = optimize_bpf_loop(env);
17782 
17783 	if (is_priv) {
17784 		if (ret == 0)
17785 			opt_hard_wire_dead_code_branches(env);
17786 		if (ret == 0)
17787 			ret = opt_remove_dead_code(env);
17788 		if (ret == 0)
17789 			ret = opt_remove_nops(env);
17790 	} else {
17791 		if (ret == 0)
17792 			sanitize_dead_code(env);
17793 	}
17794 
17795 	if (ret == 0)
17796 		/* program is valid, convert *(u32*)(ctx + off) accesses */
17797 		ret = convert_ctx_accesses(env);
17798 
17799 	if (ret == 0)
17800 		ret = do_misc_fixups(env);
17801 
17802 	/* do 32-bit optimization after insn patching has done so those patched
17803 	 * insns could be handled correctly.
17804 	 */
17805 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
17806 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
17807 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
17808 								     : false;
17809 	}
17810 
17811 	if (ret == 0)
17812 		ret = fixup_call_args(env);
17813 
17814 	env->verification_time = ktime_get_ns() - start_time;
17815 	print_verification_stats(env);
17816 	env->prog->aux->verified_insns = env->insn_processed;
17817 
17818 	if (log->level && bpf_verifier_log_full(log))
17819 		ret = -ENOSPC;
17820 	if (log->level && !log->ubuf) {
17821 		ret = -EFAULT;
17822 		goto err_release_maps;
17823 	}
17824 
17825 	if (ret)
17826 		goto err_release_maps;
17827 
17828 	if (env->used_map_cnt) {
17829 		/* if program passed verifier, update used_maps in bpf_prog_info */
17830 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17831 							  sizeof(env->used_maps[0]),
17832 							  GFP_KERNEL);
17833 
17834 		if (!env->prog->aux->used_maps) {
17835 			ret = -ENOMEM;
17836 			goto err_release_maps;
17837 		}
17838 
17839 		memcpy(env->prog->aux->used_maps, env->used_maps,
17840 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17841 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17842 	}
17843 	if (env->used_btf_cnt) {
17844 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17845 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17846 							  sizeof(env->used_btfs[0]),
17847 							  GFP_KERNEL);
17848 		if (!env->prog->aux->used_btfs) {
17849 			ret = -ENOMEM;
17850 			goto err_release_maps;
17851 		}
17852 
17853 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17854 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17855 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17856 	}
17857 	if (env->used_map_cnt || env->used_btf_cnt) {
17858 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17859 		 * bpf_ld_imm64 instructions
17860 		 */
17861 		convert_pseudo_ld_imm64(env);
17862 	}
17863 
17864 	adjust_btf_func(env);
17865 
17866 err_release_maps:
17867 	if (!env->prog->aux->used_maps)
17868 		/* if we didn't copy map pointers into bpf_prog_info, release
17869 		 * them now. Otherwise free_used_maps() will release them.
17870 		 */
17871 		release_maps(env);
17872 	if (!env->prog->aux->used_btfs)
17873 		release_btfs(env);
17874 
17875 	/* extension progs temporarily inherit the attach_type of their targets
17876 	   for verification purposes, so set it back to zero before returning
17877 	 */
17878 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17879 		env->prog->expected_attach_type = 0;
17880 
17881 	*prog = env->prog;
17882 err_unlock:
17883 	if (!is_priv)
17884 		mutex_unlock(&bpf_verifier_lock);
17885 	vfree(env->insn_aux_data);
17886 err_free_env:
17887 	kfree(env);
17888 	return ret;
17889 }
17890