xref: /linux/kernel/bpf/verifier.c (revision 524581d1216411a807d34181cb880d991fcb4b96)
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 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3477  * stack boundary and alignment are checked in check_mem_access()
3478  */
3479 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3480 				       /* stack frame we're writing to */
3481 				       struct bpf_func_state *state,
3482 				       int off, int size, int value_regno,
3483 				       int insn_idx)
3484 {
3485 	struct bpf_func_state *cur; /* state of the current function */
3486 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3487 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3488 	struct bpf_reg_state *reg = NULL;
3489 
3490 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3491 	if (err)
3492 		return err;
3493 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3494 	 * so it's aligned access and [off, off + size) are within stack limits
3495 	 */
3496 	if (!env->allow_ptr_leaks &&
3497 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3498 	    size != BPF_REG_SIZE) {
3499 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3500 		return -EACCES;
3501 	}
3502 
3503 	cur = env->cur_state->frame[env->cur_state->curframe];
3504 	if (value_regno >= 0)
3505 		reg = &cur->regs[value_regno];
3506 	if (!env->bypass_spec_v4) {
3507 		bool sanitize = reg && is_spillable_regtype(reg->type);
3508 
3509 		for (i = 0; i < size; i++) {
3510 			u8 type = state->stack[spi].slot_type[i];
3511 
3512 			if (type != STACK_MISC && type != STACK_ZERO) {
3513 				sanitize = true;
3514 				break;
3515 			}
3516 		}
3517 
3518 		if (sanitize)
3519 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3520 	}
3521 
3522 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3523 	if (err)
3524 		return err;
3525 
3526 	mark_stack_slot_scratched(env, spi);
3527 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3528 	    !register_is_null(reg) && env->bpf_capable) {
3529 		if (dst_reg != BPF_REG_FP) {
3530 			/* The backtracking logic can only recognize explicit
3531 			 * stack slot address like [fp - 8]. Other spill of
3532 			 * scalar via different register has to be conservative.
3533 			 * Backtrack from here and mark all registers as precise
3534 			 * that contributed into 'reg' being a constant.
3535 			 */
3536 			err = mark_chain_precision(env, value_regno);
3537 			if (err)
3538 				return err;
3539 		}
3540 		save_register_state(state, spi, reg, size);
3541 	} else if (reg && is_spillable_regtype(reg->type)) {
3542 		/* register containing pointer is being spilled into stack */
3543 		if (size != BPF_REG_SIZE) {
3544 			verbose_linfo(env, insn_idx, "; ");
3545 			verbose(env, "invalid size of register spill\n");
3546 			return -EACCES;
3547 		}
3548 		if (state != cur && reg->type == PTR_TO_STACK) {
3549 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3550 			return -EINVAL;
3551 		}
3552 		save_register_state(state, spi, reg, size);
3553 	} else {
3554 		u8 type = STACK_MISC;
3555 
3556 		/* regular write of data into stack destroys any spilled ptr */
3557 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3558 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3559 		if (is_spilled_reg(&state->stack[spi]))
3560 			for (i = 0; i < BPF_REG_SIZE; i++)
3561 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3562 
3563 		/* only mark the slot as written if all 8 bytes were written
3564 		 * otherwise read propagation may incorrectly stop too soon
3565 		 * when stack slots are partially written.
3566 		 * This heuristic means that read propagation will be
3567 		 * conservative, since it will add reg_live_read marks
3568 		 * to stack slots all the way to first state when programs
3569 		 * writes+reads less than 8 bytes
3570 		 */
3571 		if (size == BPF_REG_SIZE)
3572 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3573 
3574 		/* when we zero initialize stack slots mark them as such */
3575 		if (reg && register_is_null(reg)) {
3576 			/* backtracking doesn't work for STACK_ZERO yet. */
3577 			err = mark_chain_precision(env, value_regno);
3578 			if (err)
3579 				return err;
3580 			type = STACK_ZERO;
3581 		}
3582 
3583 		/* Mark slots affected by this stack write. */
3584 		for (i = 0; i < size; i++)
3585 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3586 				type;
3587 	}
3588 	return 0;
3589 }
3590 
3591 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3592  * known to contain a variable offset.
3593  * This function checks whether the write is permitted and conservatively
3594  * tracks the effects of the write, considering that each stack slot in the
3595  * dynamic range is potentially written to.
3596  *
3597  * 'off' includes 'regno->off'.
3598  * 'value_regno' can be -1, meaning that an unknown value is being written to
3599  * the stack.
3600  *
3601  * Spilled pointers in range are not marked as written because we don't know
3602  * what's going to be actually written. This means that read propagation for
3603  * future reads cannot be terminated by this write.
3604  *
3605  * For privileged programs, uninitialized stack slots are considered
3606  * initialized by this write (even though we don't know exactly what offsets
3607  * are going to be written to). The idea is that we don't want the verifier to
3608  * reject future reads that access slots written to through variable offsets.
3609  */
3610 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3611 				     /* func where register points to */
3612 				     struct bpf_func_state *state,
3613 				     int ptr_regno, int off, int size,
3614 				     int value_regno, int insn_idx)
3615 {
3616 	struct bpf_func_state *cur; /* state of the current function */
3617 	int min_off, max_off;
3618 	int i, err;
3619 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3620 	bool writing_zero = false;
3621 	/* set if the fact that we're writing a zero is used to let any
3622 	 * stack slots remain STACK_ZERO
3623 	 */
3624 	bool zero_used = false;
3625 
3626 	cur = env->cur_state->frame[env->cur_state->curframe];
3627 	ptr_reg = &cur->regs[ptr_regno];
3628 	min_off = ptr_reg->smin_value + off;
3629 	max_off = ptr_reg->smax_value + off + size;
3630 	if (value_regno >= 0)
3631 		value_reg = &cur->regs[value_regno];
3632 	if (value_reg && register_is_null(value_reg))
3633 		writing_zero = true;
3634 
3635 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3636 	if (err)
3637 		return err;
3638 
3639 	for (i = min_off; i < max_off; i++) {
3640 		int spi;
3641 
3642 		spi = __get_spi(i);
3643 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3644 		if (err)
3645 			return err;
3646 	}
3647 
3648 	/* Variable offset writes destroy any spilled pointers in range. */
3649 	for (i = min_off; i < max_off; i++) {
3650 		u8 new_type, *stype;
3651 		int slot, spi;
3652 
3653 		slot = -i - 1;
3654 		spi = slot / BPF_REG_SIZE;
3655 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3656 		mark_stack_slot_scratched(env, spi);
3657 
3658 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3659 			/* Reject the write if range we may write to has not
3660 			 * been initialized beforehand. If we didn't reject
3661 			 * here, the ptr status would be erased below (even
3662 			 * though not all slots are actually overwritten),
3663 			 * possibly opening the door to leaks.
3664 			 *
3665 			 * We do however catch STACK_INVALID case below, and
3666 			 * only allow reading possibly uninitialized memory
3667 			 * later for CAP_PERFMON, as the write may not happen to
3668 			 * that slot.
3669 			 */
3670 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3671 				insn_idx, i);
3672 			return -EINVAL;
3673 		}
3674 
3675 		/* Erase all spilled pointers. */
3676 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3677 
3678 		/* Update the slot type. */
3679 		new_type = STACK_MISC;
3680 		if (writing_zero && *stype == STACK_ZERO) {
3681 			new_type = STACK_ZERO;
3682 			zero_used = true;
3683 		}
3684 		/* If the slot is STACK_INVALID, we check whether it's OK to
3685 		 * pretend that it will be initialized by this write. The slot
3686 		 * might not actually be written to, and so if we mark it as
3687 		 * initialized future reads might leak uninitialized memory.
3688 		 * For privileged programs, we will accept such reads to slots
3689 		 * that may or may not be written because, if we're reject
3690 		 * them, the error would be too confusing.
3691 		 */
3692 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3693 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3694 					insn_idx, i);
3695 			return -EINVAL;
3696 		}
3697 		*stype = new_type;
3698 	}
3699 	if (zero_used) {
3700 		/* backtracking doesn't work for STACK_ZERO yet. */
3701 		err = mark_chain_precision(env, value_regno);
3702 		if (err)
3703 			return err;
3704 	}
3705 	return 0;
3706 }
3707 
3708 /* When register 'dst_regno' is assigned some values from stack[min_off,
3709  * max_off), we set the register's type according to the types of the
3710  * respective stack slots. If all the stack values are known to be zeros, then
3711  * so is the destination reg. Otherwise, the register is considered to be
3712  * SCALAR. This function does not deal with register filling; the caller must
3713  * ensure that all spilled registers in the stack range have been marked as
3714  * read.
3715  */
3716 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3717 				/* func where src register points to */
3718 				struct bpf_func_state *ptr_state,
3719 				int min_off, int max_off, int dst_regno)
3720 {
3721 	struct bpf_verifier_state *vstate = env->cur_state;
3722 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3723 	int i, slot, spi;
3724 	u8 *stype;
3725 	int zeros = 0;
3726 
3727 	for (i = min_off; i < max_off; i++) {
3728 		slot = -i - 1;
3729 		spi = slot / BPF_REG_SIZE;
3730 		stype = ptr_state->stack[spi].slot_type;
3731 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3732 			break;
3733 		zeros++;
3734 	}
3735 	if (zeros == max_off - min_off) {
3736 		/* any access_size read into register is zero extended,
3737 		 * so the whole register == const_zero
3738 		 */
3739 		__mark_reg_const_zero(&state->regs[dst_regno]);
3740 		/* backtracking doesn't support STACK_ZERO yet,
3741 		 * so mark it precise here, so that later
3742 		 * backtracking can stop here.
3743 		 * Backtracking may not need this if this register
3744 		 * doesn't participate in pointer adjustment.
3745 		 * Forward propagation of precise flag is not
3746 		 * necessary either. This mark is only to stop
3747 		 * backtracking. Any register that contributed
3748 		 * to const 0 was marked precise before spill.
3749 		 */
3750 		state->regs[dst_regno].precise = true;
3751 	} else {
3752 		/* have read misc data from the stack */
3753 		mark_reg_unknown(env, state->regs, dst_regno);
3754 	}
3755 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3756 }
3757 
3758 /* Read the stack at 'off' and put the results into the register indicated by
3759  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3760  * spilled reg.
3761  *
3762  * 'dst_regno' can be -1, meaning that the read value is not going to a
3763  * register.
3764  *
3765  * The access is assumed to be within the current stack bounds.
3766  */
3767 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3768 				      /* func where src register points to */
3769 				      struct bpf_func_state *reg_state,
3770 				      int off, int size, int dst_regno)
3771 {
3772 	struct bpf_verifier_state *vstate = env->cur_state;
3773 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3774 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3775 	struct bpf_reg_state *reg;
3776 	u8 *stype, type;
3777 
3778 	stype = reg_state->stack[spi].slot_type;
3779 	reg = &reg_state->stack[spi].spilled_ptr;
3780 
3781 	if (is_spilled_reg(&reg_state->stack[spi])) {
3782 		u8 spill_size = 1;
3783 
3784 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3785 			spill_size++;
3786 
3787 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3788 			if (reg->type != SCALAR_VALUE) {
3789 				verbose_linfo(env, env->insn_idx, "; ");
3790 				verbose(env, "invalid size of register fill\n");
3791 				return -EACCES;
3792 			}
3793 
3794 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3795 			if (dst_regno < 0)
3796 				return 0;
3797 
3798 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3799 				/* The earlier check_reg_arg() has decided the
3800 				 * subreg_def for this insn.  Save it first.
3801 				 */
3802 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3803 
3804 				copy_register_state(&state->regs[dst_regno], reg);
3805 				state->regs[dst_regno].subreg_def = subreg_def;
3806 			} else {
3807 				for (i = 0; i < size; i++) {
3808 					type = stype[(slot - i) % BPF_REG_SIZE];
3809 					if (type == STACK_SPILL)
3810 						continue;
3811 					if (type == STACK_MISC)
3812 						continue;
3813 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3814 						off, i, size);
3815 					return -EACCES;
3816 				}
3817 				mark_reg_unknown(env, state->regs, dst_regno);
3818 			}
3819 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3820 			return 0;
3821 		}
3822 
3823 		if (dst_regno >= 0) {
3824 			/* restore register state from stack */
3825 			copy_register_state(&state->regs[dst_regno], reg);
3826 			/* mark reg as written since spilled pointer state likely
3827 			 * has its liveness marks cleared by is_state_visited()
3828 			 * which resets stack/reg liveness for state transitions
3829 			 */
3830 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3831 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3832 			/* If dst_regno==-1, the caller is asking us whether
3833 			 * it is acceptable to use this value as a SCALAR_VALUE
3834 			 * (e.g. for XADD).
3835 			 * We must not allow unprivileged callers to do that
3836 			 * with spilled pointers.
3837 			 */
3838 			verbose(env, "leaking pointer from stack off %d\n",
3839 				off);
3840 			return -EACCES;
3841 		}
3842 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3843 	} else {
3844 		for (i = 0; i < size; i++) {
3845 			type = stype[(slot - i) % BPF_REG_SIZE];
3846 			if (type == STACK_MISC)
3847 				continue;
3848 			if (type == STACK_ZERO)
3849 				continue;
3850 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3851 				off, i, size);
3852 			return -EACCES;
3853 		}
3854 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3855 		if (dst_regno >= 0)
3856 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3857 	}
3858 	return 0;
3859 }
3860 
3861 enum bpf_access_src {
3862 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3863 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3864 };
3865 
3866 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3867 					 int regno, int off, int access_size,
3868 					 bool zero_size_allowed,
3869 					 enum bpf_access_src type,
3870 					 struct bpf_call_arg_meta *meta);
3871 
3872 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3873 {
3874 	return cur_regs(env) + regno;
3875 }
3876 
3877 /* Read the stack at 'ptr_regno + off' and put the result into the register
3878  * 'dst_regno'.
3879  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3880  * but not its variable offset.
3881  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3882  *
3883  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3884  * filling registers (i.e. reads of spilled register cannot be detected when
3885  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3886  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3887  * offset; for a fixed offset check_stack_read_fixed_off should be used
3888  * instead.
3889  */
3890 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3891 				    int ptr_regno, int off, int size, int dst_regno)
3892 {
3893 	/* The state of the source register. */
3894 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3895 	struct bpf_func_state *ptr_state = func(env, reg);
3896 	int err;
3897 	int min_off, max_off;
3898 
3899 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3900 	 */
3901 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3902 					    false, ACCESS_DIRECT, NULL);
3903 	if (err)
3904 		return err;
3905 
3906 	min_off = reg->smin_value + off;
3907 	max_off = reg->smax_value + off;
3908 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3909 	return 0;
3910 }
3911 
3912 /* check_stack_read dispatches to check_stack_read_fixed_off or
3913  * check_stack_read_var_off.
3914  *
3915  * The caller must ensure that the offset falls within the allocated stack
3916  * bounds.
3917  *
3918  * 'dst_regno' is a register which will receive the value from the stack. It
3919  * can be -1, meaning that the read value is not going to a register.
3920  */
3921 static int check_stack_read(struct bpf_verifier_env *env,
3922 			    int ptr_regno, int off, int size,
3923 			    int dst_regno)
3924 {
3925 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3926 	struct bpf_func_state *state = func(env, reg);
3927 	int err;
3928 	/* Some accesses are only permitted with a static offset. */
3929 	bool var_off = !tnum_is_const(reg->var_off);
3930 
3931 	/* The offset is required to be static when reads don't go to a
3932 	 * register, in order to not leak pointers (see
3933 	 * check_stack_read_fixed_off).
3934 	 */
3935 	if (dst_regno < 0 && var_off) {
3936 		char tn_buf[48];
3937 
3938 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3939 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3940 			tn_buf, off, size);
3941 		return -EACCES;
3942 	}
3943 	/* Variable offset is prohibited for unprivileged mode for simplicity
3944 	 * since it requires corresponding support in Spectre masking for stack
3945 	 * ALU. See also retrieve_ptr_limit().
3946 	 */
3947 	if (!env->bypass_spec_v1 && var_off) {
3948 		char tn_buf[48];
3949 
3950 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3951 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3952 				ptr_regno, tn_buf);
3953 		return -EACCES;
3954 	}
3955 
3956 	if (!var_off) {
3957 		off += reg->var_off.value;
3958 		err = check_stack_read_fixed_off(env, state, off, size,
3959 						 dst_regno);
3960 	} else {
3961 		/* Variable offset stack reads need more conservative handling
3962 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3963 		 * branch.
3964 		 */
3965 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3966 					       dst_regno);
3967 	}
3968 	return err;
3969 }
3970 
3971 
3972 /* check_stack_write dispatches to check_stack_write_fixed_off or
3973  * check_stack_write_var_off.
3974  *
3975  * 'ptr_regno' is the register used as a pointer into the stack.
3976  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3977  * 'value_regno' is the register whose value we're writing to the stack. It can
3978  * be -1, meaning that we're not writing from a register.
3979  *
3980  * The caller must ensure that the offset falls within the maximum stack size.
3981  */
3982 static int check_stack_write(struct bpf_verifier_env *env,
3983 			     int ptr_regno, int off, int size,
3984 			     int value_regno, int insn_idx)
3985 {
3986 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3987 	struct bpf_func_state *state = func(env, reg);
3988 	int err;
3989 
3990 	if (tnum_is_const(reg->var_off)) {
3991 		off += reg->var_off.value;
3992 		err = check_stack_write_fixed_off(env, state, off, size,
3993 						  value_regno, insn_idx);
3994 	} else {
3995 		/* Variable offset stack reads need more conservative handling
3996 		 * than fixed offset ones.
3997 		 */
3998 		err = check_stack_write_var_off(env, state,
3999 						ptr_regno, off, size,
4000 						value_regno, insn_idx);
4001 	}
4002 	return err;
4003 }
4004 
4005 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4006 				 int off, int size, enum bpf_access_type type)
4007 {
4008 	struct bpf_reg_state *regs = cur_regs(env);
4009 	struct bpf_map *map = regs[regno].map_ptr;
4010 	u32 cap = bpf_map_flags_to_cap(map);
4011 
4012 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4013 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4014 			map->value_size, off, size);
4015 		return -EACCES;
4016 	}
4017 
4018 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4019 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4020 			map->value_size, off, size);
4021 		return -EACCES;
4022 	}
4023 
4024 	return 0;
4025 }
4026 
4027 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4028 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4029 			      int off, int size, u32 mem_size,
4030 			      bool zero_size_allowed)
4031 {
4032 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4033 	struct bpf_reg_state *reg;
4034 
4035 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4036 		return 0;
4037 
4038 	reg = &cur_regs(env)[regno];
4039 	switch (reg->type) {
4040 	case PTR_TO_MAP_KEY:
4041 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4042 			mem_size, off, size);
4043 		break;
4044 	case PTR_TO_MAP_VALUE:
4045 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4046 			mem_size, off, size);
4047 		break;
4048 	case PTR_TO_PACKET:
4049 	case PTR_TO_PACKET_META:
4050 	case PTR_TO_PACKET_END:
4051 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4052 			off, size, regno, reg->id, off, mem_size);
4053 		break;
4054 	case PTR_TO_MEM:
4055 	default:
4056 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4057 			mem_size, off, size);
4058 	}
4059 
4060 	return -EACCES;
4061 }
4062 
4063 /* check read/write into a memory region with possible variable offset */
4064 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4065 				   int off, int size, u32 mem_size,
4066 				   bool zero_size_allowed)
4067 {
4068 	struct bpf_verifier_state *vstate = env->cur_state;
4069 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4070 	struct bpf_reg_state *reg = &state->regs[regno];
4071 	int err;
4072 
4073 	/* We may have adjusted the register pointing to memory region, so we
4074 	 * need to try adding each of min_value and max_value to off
4075 	 * to make sure our theoretical access will be safe.
4076 	 *
4077 	 * The minimum value is only important with signed
4078 	 * comparisons where we can't assume the floor of a
4079 	 * value is 0.  If we are using signed variables for our
4080 	 * index'es we need to make sure that whatever we use
4081 	 * will have a set floor within our range.
4082 	 */
4083 	if (reg->smin_value < 0 &&
4084 	    (reg->smin_value == S64_MIN ||
4085 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4086 	      reg->smin_value + off < 0)) {
4087 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4088 			regno);
4089 		return -EACCES;
4090 	}
4091 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4092 				 mem_size, zero_size_allowed);
4093 	if (err) {
4094 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4095 			regno);
4096 		return err;
4097 	}
4098 
4099 	/* If we haven't set a max value then we need to bail since we can't be
4100 	 * sure we won't do bad things.
4101 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4102 	 */
4103 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4104 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4105 			regno);
4106 		return -EACCES;
4107 	}
4108 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4109 				 mem_size, zero_size_allowed);
4110 	if (err) {
4111 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4112 			regno);
4113 		return err;
4114 	}
4115 
4116 	return 0;
4117 }
4118 
4119 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4120 			       const struct bpf_reg_state *reg, int regno,
4121 			       bool fixed_off_ok)
4122 {
4123 	/* Access to this pointer-typed register or passing it to a helper
4124 	 * is only allowed in its original, unmodified form.
4125 	 */
4126 
4127 	if (reg->off < 0) {
4128 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4129 			reg_type_str(env, reg->type), regno, reg->off);
4130 		return -EACCES;
4131 	}
4132 
4133 	if (!fixed_off_ok && reg->off) {
4134 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4135 			reg_type_str(env, reg->type), regno, reg->off);
4136 		return -EACCES;
4137 	}
4138 
4139 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4140 		char tn_buf[48];
4141 
4142 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4143 		verbose(env, "variable %s access var_off=%s disallowed\n",
4144 			reg_type_str(env, reg->type), tn_buf);
4145 		return -EACCES;
4146 	}
4147 
4148 	return 0;
4149 }
4150 
4151 int check_ptr_off_reg(struct bpf_verifier_env *env,
4152 		      const struct bpf_reg_state *reg, int regno)
4153 {
4154 	return __check_ptr_off_reg(env, reg, regno, false);
4155 }
4156 
4157 static int map_kptr_match_type(struct bpf_verifier_env *env,
4158 			       struct btf_field *kptr_field,
4159 			       struct bpf_reg_state *reg, u32 regno)
4160 {
4161 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4162 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
4163 	const char *reg_name = "";
4164 
4165 	/* Only unreferenced case accepts untrusted pointers */
4166 	if (kptr_field->type == BPF_KPTR_UNREF)
4167 		perm_flags |= PTR_UNTRUSTED;
4168 
4169 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4170 		goto bad_type;
4171 
4172 	if (!btf_is_kernel(reg->btf)) {
4173 		verbose(env, "R%d must point to kernel BTF\n", regno);
4174 		return -EINVAL;
4175 	}
4176 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4177 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
4178 
4179 	/* For ref_ptr case, release function check should ensure we get one
4180 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4181 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4182 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4183 	 * reg->off and reg->ref_obj_id are not needed here.
4184 	 */
4185 	if (__check_ptr_off_reg(env, reg, regno, true))
4186 		return -EACCES;
4187 
4188 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4189 	 * we also need to take into account the reg->off.
4190 	 *
4191 	 * We want to support cases like:
4192 	 *
4193 	 * struct foo {
4194 	 *         struct bar br;
4195 	 *         struct baz bz;
4196 	 * };
4197 	 *
4198 	 * struct foo *v;
4199 	 * v = func();	      // PTR_TO_BTF_ID
4200 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4201 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4202 	 *                    // first member type of struct after comparison fails
4203 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4204 	 *                    // to match type
4205 	 *
4206 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4207 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4208 	 * the struct to match type against first member of struct, i.e. reject
4209 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4210 	 * strict mode to true for type match.
4211 	 */
4212 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4213 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4214 				  kptr_field->type == BPF_KPTR_REF))
4215 		goto bad_type;
4216 	return 0;
4217 bad_type:
4218 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4219 		reg_type_str(env, reg->type), reg_name);
4220 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4221 	if (kptr_field->type == BPF_KPTR_UNREF)
4222 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4223 			targ_name);
4224 	else
4225 		verbose(env, "\n");
4226 	return -EINVAL;
4227 }
4228 
4229 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4230 				 int value_regno, int insn_idx,
4231 				 struct btf_field *kptr_field)
4232 {
4233 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4234 	int class = BPF_CLASS(insn->code);
4235 	struct bpf_reg_state *val_reg;
4236 
4237 	/* Things we already checked for in check_map_access and caller:
4238 	 *  - Reject cases where variable offset may touch kptr
4239 	 *  - size of access (must be BPF_DW)
4240 	 *  - tnum_is_const(reg->var_off)
4241 	 *  - kptr_field->offset == off + reg->var_off.value
4242 	 */
4243 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4244 	if (BPF_MODE(insn->code) != BPF_MEM) {
4245 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4246 		return -EACCES;
4247 	}
4248 
4249 	/* We only allow loading referenced kptr, since it will be marked as
4250 	 * untrusted, similar to unreferenced kptr.
4251 	 */
4252 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4253 		verbose(env, "store to referenced kptr disallowed\n");
4254 		return -EACCES;
4255 	}
4256 
4257 	if (class == BPF_LDX) {
4258 		val_reg = reg_state(env, value_regno);
4259 		/* We can simply mark the value_regno receiving the pointer
4260 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4261 		 */
4262 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4263 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4264 		/* For mark_ptr_or_null_reg */
4265 		val_reg->id = ++env->id_gen;
4266 	} else if (class == BPF_STX) {
4267 		val_reg = reg_state(env, value_regno);
4268 		if (!register_is_null(val_reg) &&
4269 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4270 			return -EACCES;
4271 	} else if (class == BPF_ST) {
4272 		if (insn->imm) {
4273 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4274 				kptr_field->offset);
4275 			return -EACCES;
4276 		}
4277 	} else {
4278 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4279 		return -EACCES;
4280 	}
4281 	return 0;
4282 }
4283 
4284 /* check read/write into a map element with possible variable offset */
4285 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4286 			    int off, int size, bool zero_size_allowed,
4287 			    enum bpf_access_src src)
4288 {
4289 	struct bpf_verifier_state *vstate = env->cur_state;
4290 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4291 	struct bpf_reg_state *reg = &state->regs[regno];
4292 	struct bpf_map *map = reg->map_ptr;
4293 	struct btf_record *rec;
4294 	int err, i;
4295 
4296 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4297 				      zero_size_allowed);
4298 	if (err)
4299 		return err;
4300 
4301 	if (IS_ERR_OR_NULL(map->record))
4302 		return 0;
4303 	rec = map->record;
4304 	for (i = 0; i < rec->cnt; i++) {
4305 		struct btf_field *field = &rec->fields[i];
4306 		u32 p = field->offset;
4307 
4308 		/* If any part of a field  can be touched by load/store, reject
4309 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4310 		 * it is sufficient to check x1 < y2 && y1 < x2.
4311 		 */
4312 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4313 		    p < reg->umax_value + off + size) {
4314 			switch (field->type) {
4315 			case BPF_KPTR_UNREF:
4316 			case BPF_KPTR_REF:
4317 				if (src != ACCESS_DIRECT) {
4318 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4319 					return -EACCES;
4320 				}
4321 				if (!tnum_is_const(reg->var_off)) {
4322 					verbose(env, "kptr access cannot have variable offset\n");
4323 					return -EACCES;
4324 				}
4325 				if (p != off + reg->var_off.value) {
4326 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4327 						p, off + reg->var_off.value);
4328 					return -EACCES;
4329 				}
4330 				if (size != bpf_size_to_bytes(BPF_DW)) {
4331 					verbose(env, "kptr access size must be BPF_DW\n");
4332 					return -EACCES;
4333 				}
4334 				break;
4335 			default:
4336 				verbose(env, "%s cannot be accessed directly by load/store\n",
4337 					btf_field_type_name(field->type));
4338 				return -EACCES;
4339 			}
4340 		}
4341 	}
4342 	return 0;
4343 }
4344 
4345 #define MAX_PACKET_OFF 0xffff
4346 
4347 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4348 				       const struct bpf_call_arg_meta *meta,
4349 				       enum bpf_access_type t)
4350 {
4351 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4352 
4353 	switch (prog_type) {
4354 	/* Program types only with direct read access go here! */
4355 	case BPF_PROG_TYPE_LWT_IN:
4356 	case BPF_PROG_TYPE_LWT_OUT:
4357 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4358 	case BPF_PROG_TYPE_SK_REUSEPORT:
4359 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4360 	case BPF_PROG_TYPE_CGROUP_SKB:
4361 		if (t == BPF_WRITE)
4362 			return false;
4363 		fallthrough;
4364 
4365 	/* Program types with direct read + write access go here! */
4366 	case BPF_PROG_TYPE_SCHED_CLS:
4367 	case BPF_PROG_TYPE_SCHED_ACT:
4368 	case BPF_PROG_TYPE_XDP:
4369 	case BPF_PROG_TYPE_LWT_XMIT:
4370 	case BPF_PROG_TYPE_SK_SKB:
4371 	case BPF_PROG_TYPE_SK_MSG:
4372 		if (meta)
4373 			return meta->pkt_access;
4374 
4375 		env->seen_direct_write = true;
4376 		return true;
4377 
4378 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4379 		if (t == BPF_WRITE)
4380 			env->seen_direct_write = true;
4381 
4382 		return true;
4383 
4384 	default:
4385 		return false;
4386 	}
4387 }
4388 
4389 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4390 			       int size, bool zero_size_allowed)
4391 {
4392 	struct bpf_reg_state *regs = cur_regs(env);
4393 	struct bpf_reg_state *reg = &regs[regno];
4394 	int err;
4395 
4396 	/* We may have added a variable offset to the packet pointer; but any
4397 	 * reg->range we have comes after that.  We are only checking the fixed
4398 	 * offset.
4399 	 */
4400 
4401 	/* We don't allow negative numbers, because we aren't tracking enough
4402 	 * detail to prove they're safe.
4403 	 */
4404 	if (reg->smin_value < 0) {
4405 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4406 			regno);
4407 		return -EACCES;
4408 	}
4409 
4410 	err = reg->range < 0 ? -EINVAL :
4411 	      __check_mem_access(env, regno, off, size, reg->range,
4412 				 zero_size_allowed);
4413 	if (err) {
4414 		verbose(env, "R%d offset is outside of the packet\n", regno);
4415 		return err;
4416 	}
4417 
4418 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4419 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4420 	 * otherwise find_good_pkt_pointers would have refused to set range info
4421 	 * that __check_mem_access would have rejected this pkt access.
4422 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4423 	 */
4424 	env->prog->aux->max_pkt_offset =
4425 		max_t(u32, env->prog->aux->max_pkt_offset,
4426 		      off + reg->umax_value + size - 1);
4427 
4428 	return err;
4429 }
4430 
4431 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4432 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4433 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4434 			    struct btf **btf, u32 *btf_id)
4435 {
4436 	struct bpf_insn_access_aux info = {
4437 		.reg_type = *reg_type,
4438 		.log = &env->log,
4439 	};
4440 
4441 	if (env->ops->is_valid_access &&
4442 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4443 		/* A non zero info.ctx_field_size indicates that this field is a
4444 		 * candidate for later verifier transformation to load the whole
4445 		 * field and then apply a mask when accessed with a narrower
4446 		 * access than actual ctx access size. A zero info.ctx_field_size
4447 		 * will only allow for whole field access and rejects any other
4448 		 * type of narrower access.
4449 		 */
4450 		*reg_type = info.reg_type;
4451 
4452 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4453 			*btf = info.btf;
4454 			*btf_id = info.btf_id;
4455 		} else {
4456 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4457 		}
4458 		/* remember the offset of last byte accessed in ctx */
4459 		if (env->prog->aux->max_ctx_offset < off + size)
4460 			env->prog->aux->max_ctx_offset = off + size;
4461 		return 0;
4462 	}
4463 
4464 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4465 	return -EACCES;
4466 }
4467 
4468 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4469 				  int size)
4470 {
4471 	if (size < 0 || off < 0 ||
4472 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4473 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4474 			off, size);
4475 		return -EACCES;
4476 	}
4477 	return 0;
4478 }
4479 
4480 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4481 			     u32 regno, int off, int size,
4482 			     enum bpf_access_type t)
4483 {
4484 	struct bpf_reg_state *regs = cur_regs(env);
4485 	struct bpf_reg_state *reg = &regs[regno];
4486 	struct bpf_insn_access_aux info = {};
4487 	bool valid;
4488 
4489 	if (reg->smin_value < 0) {
4490 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4491 			regno);
4492 		return -EACCES;
4493 	}
4494 
4495 	switch (reg->type) {
4496 	case PTR_TO_SOCK_COMMON:
4497 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4498 		break;
4499 	case PTR_TO_SOCKET:
4500 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4501 		break;
4502 	case PTR_TO_TCP_SOCK:
4503 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4504 		break;
4505 	case PTR_TO_XDP_SOCK:
4506 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4507 		break;
4508 	default:
4509 		valid = false;
4510 	}
4511 
4512 
4513 	if (valid) {
4514 		env->insn_aux_data[insn_idx].ctx_field_size =
4515 			info.ctx_field_size;
4516 		return 0;
4517 	}
4518 
4519 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4520 		regno, reg_type_str(env, reg->type), off, size);
4521 
4522 	return -EACCES;
4523 }
4524 
4525 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4526 {
4527 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4528 }
4529 
4530 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4531 {
4532 	const struct bpf_reg_state *reg = reg_state(env, regno);
4533 
4534 	return reg->type == PTR_TO_CTX;
4535 }
4536 
4537 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4538 {
4539 	const struct bpf_reg_state *reg = reg_state(env, regno);
4540 
4541 	return type_is_sk_pointer(reg->type);
4542 }
4543 
4544 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4545 {
4546 	const struct bpf_reg_state *reg = reg_state(env, regno);
4547 
4548 	return type_is_pkt_pointer(reg->type);
4549 }
4550 
4551 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4552 {
4553 	const struct bpf_reg_state *reg = reg_state(env, regno);
4554 
4555 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4556 	return reg->type == PTR_TO_FLOW_KEYS;
4557 }
4558 
4559 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4560 {
4561 	/* A referenced register is always trusted. */
4562 	if (reg->ref_obj_id)
4563 		return true;
4564 
4565 	/* If a register is not referenced, it is trusted if it has the
4566 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4567 	 * other type modifiers may be safe, but we elect to take an opt-in
4568 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4569 	 * not.
4570 	 *
4571 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4572 	 * for whether a register is trusted.
4573 	 */
4574 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4575 	       !bpf_type_has_unsafe_modifiers(reg->type);
4576 }
4577 
4578 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4579 {
4580 	return reg->type & MEM_RCU;
4581 }
4582 
4583 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4584 				   const struct bpf_reg_state *reg,
4585 				   int off, int size, bool strict)
4586 {
4587 	struct tnum reg_off;
4588 	int ip_align;
4589 
4590 	/* Byte size accesses are always allowed. */
4591 	if (!strict || size == 1)
4592 		return 0;
4593 
4594 	/* For platforms that do not have a Kconfig enabling
4595 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4596 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4597 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4598 	 * to this code only in strict mode where we want to emulate
4599 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4600 	 * unconditional IP align value of '2'.
4601 	 */
4602 	ip_align = 2;
4603 
4604 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4605 	if (!tnum_is_aligned(reg_off, size)) {
4606 		char tn_buf[48];
4607 
4608 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4609 		verbose(env,
4610 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4611 			ip_align, tn_buf, reg->off, off, size);
4612 		return -EACCES;
4613 	}
4614 
4615 	return 0;
4616 }
4617 
4618 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4619 				       const struct bpf_reg_state *reg,
4620 				       const char *pointer_desc,
4621 				       int off, int size, bool strict)
4622 {
4623 	struct tnum reg_off;
4624 
4625 	/* Byte size accesses are always allowed. */
4626 	if (!strict || size == 1)
4627 		return 0;
4628 
4629 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4630 	if (!tnum_is_aligned(reg_off, size)) {
4631 		char tn_buf[48];
4632 
4633 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4634 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4635 			pointer_desc, tn_buf, reg->off, off, size);
4636 		return -EACCES;
4637 	}
4638 
4639 	return 0;
4640 }
4641 
4642 static int check_ptr_alignment(struct bpf_verifier_env *env,
4643 			       const struct bpf_reg_state *reg, int off,
4644 			       int size, bool strict_alignment_once)
4645 {
4646 	bool strict = env->strict_alignment || strict_alignment_once;
4647 	const char *pointer_desc = "";
4648 
4649 	switch (reg->type) {
4650 	case PTR_TO_PACKET:
4651 	case PTR_TO_PACKET_META:
4652 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4653 		 * right in front, treat it the very same way.
4654 		 */
4655 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4656 	case PTR_TO_FLOW_KEYS:
4657 		pointer_desc = "flow keys ";
4658 		break;
4659 	case PTR_TO_MAP_KEY:
4660 		pointer_desc = "key ";
4661 		break;
4662 	case PTR_TO_MAP_VALUE:
4663 		pointer_desc = "value ";
4664 		break;
4665 	case PTR_TO_CTX:
4666 		pointer_desc = "context ";
4667 		break;
4668 	case PTR_TO_STACK:
4669 		pointer_desc = "stack ";
4670 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4671 		 * and check_stack_read_fixed_off() relies on stack accesses being
4672 		 * aligned.
4673 		 */
4674 		strict = true;
4675 		break;
4676 	case PTR_TO_SOCKET:
4677 		pointer_desc = "sock ";
4678 		break;
4679 	case PTR_TO_SOCK_COMMON:
4680 		pointer_desc = "sock_common ";
4681 		break;
4682 	case PTR_TO_TCP_SOCK:
4683 		pointer_desc = "tcp_sock ";
4684 		break;
4685 	case PTR_TO_XDP_SOCK:
4686 		pointer_desc = "xdp_sock ";
4687 		break;
4688 	default:
4689 		break;
4690 	}
4691 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4692 					   strict);
4693 }
4694 
4695 static int update_stack_depth(struct bpf_verifier_env *env,
4696 			      const struct bpf_func_state *func,
4697 			      int off)
4698 {
4699 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4700 
4701 	if (stack >= -off)
4702 		return 0;
4703 
4704 	/* update known max for given subprogram */
4705 	env->subprog_info[func->subprogno].stack_depth = -off;
4706 	return 0;
4707 }
4708 
4709 /* starting from main bpf function walk all instructions of the function
4710  * and recursively walk all callees that given function can call.
4711  * Ignore jump and exit insns.
4712  * Since recursion is prevented by check_cfg() this algorithm
4713  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4714  */
4715 static int check_max_stack_depth(struct bpf_verifier_env *env)
4716 {
4717 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4718 	struct bpf_subprog_info *subprog = env->subprog_info;
4719 	struct bpf_insn *insn = env->prog->insnsi;
4720 	bool tail_call_reachable = false;
4721 	int ret_insn[MAX_CALL_FRAMES];
4722 	int ret_prog[MAX_CALL_FRAMES];
4723 	int j;
4724 
4725 process_func:
4726 	/* protect against potential stack overflow that might happen when
4727 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4728 	 * depth for such case down to 256 so that the worst case scenario
4729 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4730 	 * 8k).
4731 	 *
4732 	 * To get the idea what might happen, see an example:
4733 	 * func1 -> sub rsp, 128
4734 	 *  subfunc1 -> sub rsp, 256
4735 	 *  tailcall1 -> add rsp, 256
4736 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4737 	 *   subfunc2 -> sub rsp, 64
4738 	 *   subfunc22 -> sub rsp, 128
4739 	 *   tailcall2 -> add rsp, 128
4740 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4741 	 *
4742 	 * tailcall will unwind the current stack frame but it will not get rid
4743 	 * of caller's stack as shown on the example above.
4744 	 */
4745 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4746 		verbose(env,
4747 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4748 			depth);
4749 		return -EACCES;
4750 	}
4751 	/* round up to 32-bytes, since this is granularity
4752 	 * of interpreter stack size
4753 	 */
4754 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4755 	if (depth > MAX_BPF_STACK) {
4756 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4757 			frame + 1, depth);
4758 		return -EACCES;
4759 	}
4760 continue_func:
4761 	subprog_end = subprog[idx + 1].start;
4762 	for (; i < subprog_end; i++) {
4763 		int next_insn;
4764 
4765 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4766 			continue;
4767 		/* remember insn and function to return to */
4768 		ret_insn[frame] = i + 1;
4769 		ret_prog[frame] = idx;
4770 
4771 		/* find the callee */
4772 		next_insn = i + insn[i].imm + 1;
4773 		idx = find_subprog(env, next_insn);
4774 		if (idx < 0) {
4775 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4776 				  next_insn);
4777 			return -EFAULT;
4778 		}
4779 		if (subprog[idx].is_async_cb) {
4780 			if (subprog[idx].has_tail_call) {
4781 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4782 				return -EFAULT;
4783 			}
4784 			 /* async callbacks don't increase bpf prog stack size */
4785 			continue;
4786 		}
4787 		i = next_insn;
4788 
4789 		if (subprog[idx].has_tail_call)
4790 			tail_call_reachable = true;
4791 
4792 		frame++;
4793 		if (frame >= MAX_CALL_FRAMES) {
4794 			verbose(env, "the call stack of %d frames is too deep !\n",
4795 				frame);
4796 			return -E2BIG;
4797 		}
4798 		goto process_func;
4799 	}
4800 	/* if tail call got detected across bpf2bpf calls then mark each of the
4801 	 * currently present subprog frames as tail call reachable subprogs;
4802 	 * this info will be utilized by JIT so that we will be preserving the
4803 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4804 	 */
4805 	if (tail_call_reachable)
4806 		for (j = 0; j < frame; j++)
4807 			subprog[ret_prog[j]].tail_call_reachable = true;
4808 	if (subprog[0].tail_call_reachable)
4809 		env->prog->aux->tail_call_reachable = true;
4810 
4811 	/* end of for() loop means the last insn of the 'subprog'
4812 	 * was reached. Doesn't matter whether it was JA or EXIT
4813 	 */
4814 	if (frame == 0)
4815 		return 0;
4816 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4817 	frame--;
4818 	i = ret_insn[frame];
4819 	idx = ret_prog[frame];
4820 	goto continue_func;
4821 }
4822 
4823 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4824 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4825 				  const struct bpf_insn *insn, int idx)
4826 {
4827 	int start = idx + insn->imm + 1, subprog;
4828 
4829 	subprog = find_subprog(env, start);
4830 	if (subprog < 0) {
4831 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4832 			  start);
4833 		return -EFAULT;
4834 	}
4835 	return env->subprog_info[subprog].stack_depth;
4836 }
4837 #endif
4838 
4839 static int __check_buffer_access(struct bpf_verifier_env *env,
4840 				 const char *buf_info,
4841 				 const struct bpf_reg_state *reg,
4842 				 int regno, int off, int size)
4843 {
4844 	if (off < 0) {
4845 		verbose(env,
4846 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4847 			regno, buf_info, off, size);
4848 		return -EACCES;
4849 	}
4850 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4851 		char tn_buf[48];
4852 
4853 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4854 		verbose(env,
4855 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4856 			regno, off, tn_buf);
4857 		return -EACCES;
4858 	}
4859 
4860 	return 0;
4861 }
4862 
4863 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4864 				  const struct bpf_reg_state *reg,
4865 				  int regno, int off, int size)
4866 {
4867 	int err;
4868 
4869 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4870 	if (err)
4871 		return err;
4872 
4873 	if (off + size > env->prog->aux->max_tp_access)
4874 		env->prog->aux->max_tp_access = off + size;
4875 
4876 	return 0;
4877 }
4878 
4879 static int check_buffer_access(struct bpf_verifier_env *env,
4880 			       const struct bpf_reg_state *reg,
4881 			       int regno, int off, int size,
4882 			       bool zero_size_allowed,
4883 			       u32 *max_access)
4884 {
4885 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4886 	int err;
4887 
4888 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4889 	if (err)
4890 		return err;
4891 
4892 	if (off + size > *max_access)
4893 		*max_access = off + size;
4894 
4895 	return 0;
4896 }
4897 
4898 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4899 static void zext_32_to_64(struct bpf_reg_state *reg)
4900 {
4901 	reg->var_off = tnum_subreg(reg->var_off);
4902 	__reg_assign_32_into_64(reg);
4903 }
4904 
4905 /* truncate register to smaller size (in bytes)
4906  * must be called with size < BPF_REG_SIZE
4907  */
4908 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4909 {
4910 	u64 mask;
4911 
4912 	/* clear high bits in bit representation */
4913 	reg->var_off = tnum_cast(reg->var_off, size);
4914 
4915 	/* fix arithmetic bounds */
4916 	mask = ((u64)1 << (size * 8)) - 1;
4917 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4918 		reg->umin_value &= mask;
4919 		reg->umax_value &= mask;
4920 	} else {
4921 		reg->umin_value = 0;
4922 		reg->umax_value = mask;
4923 	}
4924 	reg->smin_value = reg->umin_value;
4925 	reg->smax_value = reg->umax_value;
4926 
4927 	/* If size is smaller than 32bit register the 32bit register
4928 	 * values are also truncated so we push 64-bit bounds into
4929 	 * 32-bit bounds. Above were truncated < 32-bits already.
4930 	 */
4931 	if (size >= 4)
4932 		return;
4933 	__reg_combine_64_into_32(reg);
4934 }
4935 
4936 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4937 {
4938 	/* A map is considered read-only if the following condition are true:
4939 	 *
4940 	 * 1) BPF program side cannot change any of the map content. The
4941 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4942 	 *    and was set at map creation time.
4943 	 * 2) The map value(s) have been initialized from user space by a
4944 	 *    loader and then "frozen", such that no new map update/delete
4945 	 *    operations from syscall side are possible for the rest of
4946 	 *    the map's lifetime from that point onwards.
4947 	 * 3) Any parallel/pending map update/delete operations from syscall
4948 	 *    side have been completed. Only after that point, it's safe to
4949 	 *    assume that map value(s) are immutable.
4950 	 */
4951 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4952 	       READ_ONCE(map->frozen) &&
4953 	       !bpf_map_write_active(map);
4954 }
4955 
4956 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4957 {
4958 	void *ptr;
4959 	u64 addr;
4960 	int err;
4961 
4962 	err = map->ops->map_direct_value_addr(map, &addr, off);
4963 	if (err)
4964 		return err;
4965 	ptr = (void *)(long)addr + off;
4966 
4967 	switch (size) {
4968 	case sizeof(u8):
4969 		*val = (u64)*(u8 *)ptr;
4970 		break;
4971 	case sizeof(u16):
4972 		*val = (u64)*(u16 *)ptr;
4973 		break;
4974 	case sizeof(u32):
4975 		*val = (u64)*(u32 *)ptr;
4976 		break;
4977 	case sizeof(u64):
4978 		*val = *(u64 *)ptr;
4979 		break;
4980 	default:
4981 		return -EINVAL;
4982 	}
4983 	return 0;
4984 }
4985 
4986 #define BTF_TYPE_SAFE_NESTED(__type)  __PASTE(__type, __safe_fields)
4987 
4988 BTF_TYPE_SAFE_NESTED(struct task_struct) {
4989 	const cpumask_t *cpus_ptr;
4990 };
4991 
4992 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env,
4993 				  struct bpf_reg_state *reg,
4994 				  int off)
4995 {
4996 	/* If its parent is not trusted, it can't regain its trusted status. */
4997 	if (!is_trusted_reg(reg))
4998 		return false;
4999 
5000 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct));
5001 
5002 	return btf_nested_type_is_trusted(&env->log, reg, off);
5003 }
5004 
5005 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5006 				   struct bpf_reg_state *regs,
5007 				   int regno, int off, int size,
5008 				   enum bpf_access_type atype,
5009 				   int value_regno)
5010 {
5011 	struct bpf_reg_state *reg = regs + regno;
5012 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5013 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5014 	enum bpf_type_flag flag = 0;
5015 	u32 btf_id;
5016 	int ret;
5017 
5018 	if (!env->allow_ptr_leaks) {
5019 		verbose(env,
5020 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5021 			tname);
5022 		return -EPERM;
5023 	}
5024 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5025 		verbose(env,
5026 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5027 			tname);
5028 		return -EINVAL;
5029 	}
5030 	if (off < 0) {
5031 		verbose(env,
5032 			"R%d is ptr_%s invalid negative access: off=%d\n",
5033 			regno, tname, off);
5034 		return -EACCES;
5035 	}
5036 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5037 		char tn_buf[48];
5038 
5039 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5040 		verbose(env,
5041 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5042 			regno, tname, off, tn_buf);
5043 		return -EACCES;
5044 	}
5045 
5046 	if (reg->type & MEM_USER) {
5047 		verbose(env,
5048 			"R%d is ptr_%s access user memory: off=%d\n",
5049 			regno, tname, off);
5050 		return -EACCES;
5051 	}
5052 
5053 	if (reg->type & MEM_PERCPU) {
5054 		verbose(env,
5055 			"R%d is ptr_%s access percpu memory: off=%d\n",
5056 			regno, tname, off);
5057 		return -EACCES;
5058 	}
5059 
5060 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5061 		if (!btf_is_kernel(reg->btf)) {
5062 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5063 			return -EFAULT;
5064 		}
5065 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5066 	} else {
5067 		/* Writes are permitted with default btf_struct_access for
5068 		 * program allocated objects (which always have ref_obj_id > 0),
5069 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5070 		 */
5071 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5072 			verbose(env, "only read is supported\n");
5073 			return -EACCES;
5074 		}
5075 
5076 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5077 		    !reg->ref_obj_id) {
5078 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5079 			return -EFAULT;
5080 		}
5081 
5082 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5083 	}
5084 
5085 	if (ret < 0)
5086 		return ret;
5087 
5088 	/* If this is an untrusted pointer, all pointers formed by walking it
5089 	 * also inherit the untrusted flag.
5090 	 */
5091 	if (type_flag(reg->type) & PTR_UNTRUSTED)
5092 		flag |= PTR_UNTRUSTED;
5093 
5094 	/* By default any pointer obtained from walking a trusted pointer is no
5095 	 * longer trusted, unless the field being accessed has explicitly been
5096 	 * marked as inheriting its parent's state of trust.
5097 	 *
5098 	 * An RCU-protected pointer can also be deemed trusted if we are in an
5099 	 * RCU read region. This case is handled below.
5100 	 */
5101 	if (nested_ptr_is_trusted(env, reg, off))
5102 		flag |= PTR_TRUSTED;
5103 	else
5104 		flag &= ~PTR_TRUSTED;
5105 
5106 	if (flag & MEM_RCU) {
5107 		/* Mark value register as MEM_RCU only if it is protected by
5108 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
5109 		 * itself can already indicate trustedness inside the rcu
5110 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
5111 		 * it could be null in some cases.
5112 		 */
5113 		if (!env->cur_state->active_rcu_lock ||
5114 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
5115 			flag &= ~MEM_RCU;
5116 		else
5117 			flag |= PTR_MAYBE_NULL;
5118 	} else if (reg->type & MEM_RCU) {
5119 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
5120 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
5121 		 */
5122 		flag |= PTR_UNTRUSTED;
5123 	}
5124 
5125 	if (atype == BPF_READ && value_regno >= 0)
5126 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5127 
5128 	return 0;
5129 }
5130 
5131 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5132 				   struct bpf_reg_state *regs,
5133 				   int regno, int off, int size,
5134 				   enum bpf_access_type atype,
5135 				   int value_regno)
5136 {
5137 	struct bpf_reg_state *reg = regs + regno;
5138 	struct bpf_map *map = reg->map_ptr;
5139 	struct bpf_reg_state map_reg;
5140 	enum bpf_type_flag flag = 0;
5141 	const struct btf_type *t;
5142 	const char *tname;
5143 	u32 btf_id;
5144 	int ret;
5145 
5146 	if (!btf_vmlinux) {
5147 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5148 		return -ENOTSUPP;
5149 	}
5150 
5151 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5152 		verbose(env, "map_ptr access not supported for map type %d\n",
5153 			map->map_type);
5154 		return -ENOTSUPP;
5155 	}
5156 
5157 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5158 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5159 
5160 	if (!env->allow_ptr_leaks) {
5161 		verbose(env,
5162 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5163 			tname);
5164 		return -EPERM;
5165 	}
5166 
5167 	if (off < 0) {
5168 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5169 			regno, tname, off);
5170 		return -EACCES;
5171 	}
5172 
5173 	if (atype != BPF_READ) {
5174 		verbose(env, "only read from %s is supported\n", tname);
5175 		return -EACCES;
5176 	}
5177 
5178 	/* Simulate access to a PTR_TO_BTF_ID */
5179 	memset(&map_reg, 0, sizeof(map_reg));
5180 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5181 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5182 	if (ret < 0)
5183 		return ret;
5184 
5185 	if (value_regno >= 0)
5186 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5187 
5188 	return 0;
5189 }
5190 
5191 /* Check that the stack access at the given offset is within bounds. The
5192  * maximum valid offset is -1.
5193  *
5194  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5195  * -state->allocated_stack for reads.
5196  */
5197 static int check_stack_slot_within_bounds(int off,
5198 					  struct bpf_func_state *state,
5199 					  enum bpf_access_type t)
5200 {
5201 	int min_valid_off;
5202 
5203 	if (t == BPF_WRITE)
5204 		min_valid_off = -MAX_BPF_STACK;
5205 	else
5206 		min_valid_off = -state->allocated_stack;
5207 
5208 	if (off < min_valid_off || off > -1)
5209 		return -EACCES;
5210 	return 0;
5211 }
5212 
5213 /* Check that the stack access at 'regno + off' falls within the maximum stack
5214  * bounds.
5215  *
5216  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5217  */
5218 static int check_stack_access_within_bounds(
5219 		struct bpf_verifier_env *env,
5220 		int regno, int off, int access_size,
5221 		enum bpf_access_src src, enum bpf_access_type type)
5222 {
5223 	struct bpf_reg_state *regs = cur_regs(env);
5224 	struct bpf_reg_state *reg = regs + regno;
5225 	struct bpf_func_state *state = func(env, reg);
5226 	int min_off, max_off;
5227 	int err;
5228 	char *err_extra;
5229 
5230 	if (src == ACCESS_HELPER)
5231 		/* We don't know if helpers are reading or writing (or both). */
5232 		err_extra = " indirect access to";
5233 	else if (type == BPF_READ)
5234 		err_extra = " read from";
5235 	else
5236 		err_extra = " write to";
5237 
5238 	if (tnum_is_const(reg->var_off)) {
5239 		min_off = reg->var_off.value + off;
5240 		if (access_size > 0)
5241 			max_off = min_off + access_size - 1;
5242 		else
5243 			max_off = min_off;
5244 	} else {
5245 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5246 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5247 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5248 				err_extra, regno);
5249 			return -EACCES;
5250 		}
5251 		min_off = reg->smin_value + off;
5252 		if (access_size > 0)
5253 			max_off = reg->smax_value + off + access_size - 1;
5254 		else
5255 			max_off = min_off;
5256 	}
5257 
5258 	err = check_stack_slot_within_bounds(min_off, state, type);
5259 	if (!err)
5260 		err = check_stack_slot_within_bounds(max_off, state, type);
5261 
5262 	if (err) {
5263 		if (tnum_is_const(reg->var_off)) {
5264 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5265 				err_extra, regno, off, access_size);
5266 		} else {
5267 			char tn_buf[48];
5268 
5269 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5270 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5271 				err_extra, regno, tn_buf, access_size);
5272 		}
5273 	}
5274 	return err;
5275 }
5276 
5277 /* check whether memory at (regno + off) is accessible for t = (read | write)
5278  * if t==write, value_regno is a register which value is stored into memory
5279  * if t==read, value_regno is a register which will receive the value from memory
5280  * if t==write && value_regno==-1, some unknown value is stored into memory
5281  * if t==read && value_regno==-1, don't care what we read from memory
5282  */
5283 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5284 			    int off, int bpf_size, enum bpf_access_type t,
5285 			    int value_regno, bool strict_alignment_once)
5286 {
5287 	struct bpf_reg_state *regs = cur_regs(env);
5288 	struct bpf_reg_state *reg = regs + regno;
5289 	struct bpf_func_state *state;
5290 	int size, err = 0;
5291 
5292 	size = bpf_size_to_bytes(bpf_size);
5293 	if (size < 0)
5294 		return size;
5295 
5296 	/* alignment checks will add in reg->off themselves */
5297 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5298 	if (err)
5299 		return err;
5300 
5301 	/* for access checks, reg->off is just part of off */
5302 	off += reg->off;
5303 
5304 	if (reg->type == PTR_TO_MAP_KEY) {
5305 		if (t == BPF_WRITE) {
5306 			verbose(env, "write to change key R%d not allowed\n", regno);
5307 			return -EACCES;
5308 		}
5309 
5310 		err = check_mem_region_access(env, regno, off, size,
5311 					      reg->map_ptr->key_size, false);
5312 		if (err)
5313 			return err;
5314 		if (value_regno >= 0)
5315 			mark_reg_unknown(env, regs, value_regno);
5316 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5317 		struct btf_field *kptr_field = NULL;
5318 
5319 		if (t == BPF_WRITE && value_regno >= 0 &&
5320 		    is_pointer_value(env, value_regno)) {
5321 			verbose(env, "R%d leaks addr into map\n", value_regno);
5322 			return -EACCES;
5323 		}
5324 		err = check_map_access_type(env, regno, off, size, t);
5325 		if (err)
5326 			return err;
5327 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5328 		if (err)
5329 			return err;
5330 		if (tnum_is_const(reg->var_off))
5331 			kptr_field = btf_record_find(reg->map_ptr->record,
5332 						     off + reg->var_off.value, BPF_KPTR);
5333 		if (kptr_field) {
5334 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5335 		} else if (t == BPF_READ && value_regno >= 0) {
5336 			struct bpf_map *map = reg->map_ptr;
5337 
5338 			/* if map is read-only, track its contents as scalars */
5339 			if (tnum_is_const(reg->var_off) &&
5340 			    bpf_map_is_rdonly(map) &&
5341 			    map->ops->map_direct_value_addr) {
5342 				int map_off = off + reg->var_off.value;
5343 				u64 val = 0;
5344 
5345 				err = bpf_map_direct_read(map, map_off, size,
5346 							  &val);
5347 				if (err)
5348 					return err;
5349 
5350 				regs[value_regno].type = SCALAR_VALUE;
5351 				__mark_reg_known(&regs[value_regno], val);
5352 			} else {
5353 				mark_reg_unknown(env, regs, value_regno);
5354 			}
5355 		}
5356 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5357 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5358 
5359 		if (type_may_be_null(reg->type)) {
5360 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5361 				reg_type_str(env, reg->type));
5362 			return -EACCES;
5363 		}
5364 
5365 		if (t == BPF_WRITE && rdonly_mem) {
5366 			verbose(env, "R%d cannot write into %s\n",
5367 				regno, reg_type_str(env, reg->type));
5368 			return -EACCES;
5369 		}
5370 
5371 		if (t == BPF_WRITE && value_regno >= 0 &&
5372 		    is_pointer_value(env, value_regno)) {
5373 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5374 			return -EACCES;
5375 		}
5376 
5377 		err = check_mem_region_access(env, regno, off, size,
5378 					      reg->mem_size, false);
5379 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5380 			mark_reg_unknown(env, regs, value_regno);
5381 	} else if (reg->type == PTR_TO_CTX) {
5382 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5383 		struct btf *btf = NULL;
5384 		u32 btf_id = 0;
5385 
5386 		if (t == BPF_WRITE && value_regno >= 0 &&
5387 		    is_pointer_value(env, value_regno)) {
5388 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5389 			return -EACCES;
5390 		}
5391 
5392 		err = check_ptr_off_reg(env, reg, regno);
5393 		if (err < 0)
5394 			return err;
5395 
5396 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5397 				       &btf_id);
5398 		if (err)
5399 			verbose_linfo(env, insn_idx, "; ");
5400 		if (!err && t == BPF_READ && value_regno >= 0) {
5401 			/* ctx access returns either a scalar, or a
5402 			 * PTR_TO_PACKET[_META,_END]. In the latter
5403 			 * case, we know the offset is zero.
5404 			 */
5405 			if (reg_type == SCALAR_VALUE) {
5406 				mark_reg_unknown(env, regs, value_regno);
5407 			} else {
5408 				mark_reg_known_zero(env, regs,
5409 						    value_regno);
5410 				if (type_may_be_null(reg_type))
5411 					regs[value_regno].id = ++env->id_gen;
5412 				/* A load of ctx field could have different
5413 				 * actual load size with the one encoded in the
5414 				 * insn. When the dst is PTR, it is for sure not
5415 				 * a sub-register.
5416 				 */
5417 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5418 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5419 					regs[value_regno].btf = btf;
5420 					regs[value_regno].btf_id = btf_id;
5421 				}
5422 			}
5423 			regs[value_regno].type = reg_type;
5424 		}
5425 
5426 	} else if (reg->type == PTR_TO_STACK) {
5427 		/* Basic bounds checks. */
5428 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5429 		if (err)
5430 			return err;
5431 
5432 		state = func(env, reg);
5433 		err = update_stack_depth(env, state, off);
5434 		if (err)
5435 			return err;
5436 
5437 		if (t == BPF_READ)
5438 			err = check_stack_read(env, regno, off, size,
5439 					       value_regno);
5440 		else
5441 			err = check_stack_write(env, regno, off, size,
5442 						value_regno, insn_idx);
5443 	} else if (reg_is_pkt_pointer(reg)) {
5444 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5445 			verbose(env, "cannot write into packet\n");
5446 			return -EACCES;
5447 		}
5448 		if (t == BPF_WRITE && value_regno >= 0 &&
5449 		    is_pointer_value(env, value_regno)) {
5450 			verbose(env, "R%d leaks addr into packet\n",
5451 				value_regno);
5452 			return -EACCES;
5453 		}
5454 		err = check_packet_access(env, regno, off, size, false);
5455 		if (!err && t == BPF_READ && value_regno >= 0)
5456 			mark_reg_unknown(env, regs, value_regno);
5457 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5458 		if (t == BPF_WRITE && value_regno >= 0 &&
5459 		    is_pointer_value(env, value_regno)) {
5460 			verbose(env, "R%d leaks addr into flow keys\n",
5461 				value_regno);
5462 			return -EACCES;
5463 		}
5464 
5465 		err = check_flow_keys_access(env, off, size);
5466 		if (!err && t == BPF_READ && value_regno >= 0)
5467 			mark_reg_unknown(env, regs, value_regno);
5468 	} else if (type_is_sk_pointer(reg->type)) {
5469 		if (t == BPF_WRITE) {
5470 			verbose(env, "R%d cannot write into %s\n",
5471 				regno, reg_type_str(env, reg->type));
5472 			return -EACCES;
5473 		}
5474 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5475 		if (!err && value_regno >= 0)
5476 			mark_reg_unknown(env, regs, value_regno);
5477 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5478 		err = check_tp_buffer_access(env, reg, regno, off, size);
5479 		if (!err && t == BPF_READ && value_regno >= 0)
5480 			mark_reg_unknown(env, regs, value_regno);
5481 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5482 		   !type_may_be_null(reg->type)) {
5483 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5484 					      value_regno);
5485 	} else if (reg->type == CONST_PTR_TO_MAP) {
5486 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5487 					      value_regno);
5488 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5489 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5490 		u32 *max_access;
5491 
5492 		if (rdonly_mem) {
5493 			if (t == BPF_WRITE) {
5494 				verbose(env, "R%d cannot write into %s\n",
5495 					regno, reg_type_str(env, reg->type));
5496 				return -EACCES;
5497 			}
5498 			max_access = &env->prog->aux->max_rdonly_access;
5499 		} else {
5500 			max_access = &env->prog->aux->max_rdwr_access;
5501 		}
5502 
5503 		err = check_buffer_access(env, reg, regno, off, size, false,
5504 					  max_access);
5505 
5506 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5507 			mark_reg_unknown(env, regs, value_regno);
5508 	} else {
5509 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5510 			reg_type_str(env, reg->type));
5511 		return -EACCES;
5512 	}
5513 
5514 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5515 	    regs[value_regno].type == SCALAR_VALUE) {
5516 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5517 		coerce_reg_to_size(&regs[value_regno], size);
5518 	}
5519 	return err;
5520 }
5521 
5522 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5523 {
5524 	int load_reg;
5525 	int err;
5526 
5527 	switch (insn->imm) {
5528 	case BPF_ADD:
5529 	case BPF_ADD | BPF_FETCH:
5530 	case BPF_AND:
5531 	case BPF_AND | BPF_FETCH:
5532 	case BPF_OR:
5533 	case BPF_OR | BPF_FETCH:
5534 	case BPF_XOR:
5535 	case BPF_XOR | BPF_FETCH:
5536 	case BPF_XCHG:
5537 	case BPF_CMPXCHG:
5538 		break;
5539 	default:
5540 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5541 		return -EINVAL;
5542 	}
5543 
5544 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5545 		verbose(env, "invalid atomic operand size\n");
5546 		return -EINVAL;
5547 	}
5548 
5549 	/* check src1 operand */
5550 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5551 	if (err)
5552 		return err;
5553 
5554 	/* check src2 operand */
5555 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5556 	if (err)
5557 		return err;
5558 
5559 	if (insn->imm == BPF_CMPXCHG) {
5560 		/* Check comparison of R0 with memory location */
5561 		const u32 aux_reg = BPF_REG_0;
5562 
5563 		err = check_reg_arg(env, aux_reg, SRC_OP);
5564 		if (err)
5565 			return err;
5566 
5567 		if (is_pointer_value(env, aux_reg)) {
5568 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5569 			return -EACCES;
5570 		}
5571 	}
5572 
5573 	if (is_pointer_value(env, insn->src_reg)) {
5574 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5575 		return -EACCES;
5576 	}
5577 
5578 	if (is_ctx_reg(env, insn->dst_reg) ||
5579 	    is_pkt_reg(env, insn->dst_reg) ||
5580 	    is_flow_key_reg(env, insn->dst_reg) ||
5581 	    is_sk_reg(env, insn->dst_reg)) {
5582 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5583 			insn->dst_reg,
5584 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5585 		return -EACCES;
5586 	}
5587 
5588 	if (insn->imm & BPF_FETCH) {
5589 		if (insn->imm == BPF_CMPXCHG)
5590 			load_reg = BPF_REG_0;
5591 		else
5592 			load_reg = insn->src_reg;
5593 
5594 		/* check and record load of old value */
5595 		err = check_reg_arg(env, load_reg, DST_OP);
5596 		if (err)
5597 			return err;
5598 	} else {
5599 		/* This instruction accesses a memory location but doesn't
5600 		 * actually load it into a register.
5601 		 */
5602 		load_reg = -1;
5603 	}
5604 
5605 	/* Check whether we can read the memory, with second call for fetch
5606 	 * case to simulate the register fill.
5607 	 */
5608 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5609 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5610 	if (!err && load_reg >= 0)
5611 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5612 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5613 				       true);
5614 	if (err)
5615 		return err;
5616 
5617 	/* Check whether we can write into the same memory. */
5618 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5619 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5620 	if (err)
5621 		return err;
5622 
5623 	return 0;
5624 }
5625 
5626 /* When register 'regno' is used to read the stack (either directly or through
5627  * a helper function) make sure that it's within stack boundary and, depending
5628  * on the access type, that all elements of the stack are initialized.
5629  *
5630  * 'off' includes 'regno->off', but not its dynamic part (if any).
5631  *
5632  * All registers that have been spilled on the stack in the slots within the
5633  * read offsets are marked as read.
5634  */
5635 static int check_stack_range_initialized(
5636 		struct bpf_verifier_env *env, int regno, int off,
5637 		int access_size, bool zero_size_allowed,
5638 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5639 {
5640 	struct bpf_reg_state *reg = reg_state(env, regno);
5641 	struct bpf_func_state *state = func(env, reg);
5642 	int err, min_off, max_off, i, j, slot, spi;
5643 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5644 	enum bpf_access_type bounds_check_type;
5645 	/* Some accesses can write anything into the stack, others are
5646 	 * read-only.
5647 	 */
5648 	bool clobber = false;
5649 
5650 	if (access_size == 0 && !zero_size_allowed) {
5651 		verbose(env, "invalid zero-sized read\n");
5652 		return -EACCES;
5653 	}
5654 
5655 	if (type == ACCESS_HELPER) {
5656 		/* The bounds checks for writes are more permissive than for
5657 		 * reads. However, if raw_mode is not set, we'll do extra
5658 		 * checks below.
5659 		 */
5660 		bounds_check_type = BPF_WRITE;
5661 		clobber = true;
5662 	} else {
5663 		bounds_check_type = BPF_READ;
5664 	}
5665 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5666 					       type, bounds_check_type);
5667 	if (err)
5668 		return err;
5669 
5670 
5671 	if (tnum_is_const(reg->var_off)) {
5672 		min_off = max_off = reg->var_off.value + off;
5673 	} else {
5674 		/* Variable offset is prohibited for unprivileged mode for
5675 		 * simplicity since it requires corresponding support in
5676 		 * Spectre masking for stack ALU.
5677 		 * See also retrieve_ptr_limit().
5678 		 */
5679 		if (!env->bypass_spec_v1) {
5680 			char tn_buf[48];
5681 
5682 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5683 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5684 				regno, err_extra, tn_buf);
5685 			return -EACCES;
5686 		}
5687 		/* Only initialized buffer on stack is allowed to be accessed
5688 		 * with variable offset. With uninitialized buffer it's hard to
5689 		 * guarantee that whole memory is marked as initialized on
5690 		 * helper return since specific bounds are unknown what may
5691 		 * cause uninitialized stack leaking.
5692 		 */
5693 		if (meta && meta->raw_mode)
5694 			meta = NULL;
5695 
5696 		min_off = reg->smin_value + off;
5697 		max_off = reg->smax_value + off;
5698 	}
5699 
5700 	if (meta && meta->raw_mode) {
5701 		/* Ensure we won't be overwriting dynptrs when simulating byte
5702 		 * by byte access in check_helper_call using meta.access_size.
5703 		 * This would be a problem if we have a helper in the future
5704 		 * which takes:
5705 		 *
5706 		 *	helper(uninit_mem, len, dynptr)
5707 		 *
5708 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5709 		 * may end up writing to dynptr itself when touching memory from
5710 		 * arg 1. This can be relaxed on a case by case basis for known
5711 		 * safe cases, but reject due to the possibilitiy of aliasing by
5712 		 * default.
5713 		 */
5714 		for (i = min_off; i < max_off + access_size; i++) {
5715 			int stack_off = -i - 1;
5716 
5717 			spi = __get_spi(i);
5718 			/* raw_mode may write past allocated_stack */
5719 			if (state->allocated_stack <= stack_off)
5720 				continue;
5721 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5722 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5723 				return -EACCES;
5724 			}
5725 		}
5726 		meta->access_size = access_size;
5727 		meta->regno = regno;
5728 		return 0;
5729 	}
5730 
5731 	for (i = min_off; i < max_off + access_size; i++) {
5732 		u8 *stype;
5733 
5734 		slot = -i - 1;
5735 		spi = slot / BPF_REG_SIZE;
5736 		if (state->allocated_stack <= slot)
5737 			goto err;
5738 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5739 		if (*stype == STACK_MISC)
5740 			goto mark;
5741 		if (*stype == STACK_ZERO) {
5742 			if (clobber) {
5743 				/* helper can write anything into the stack */
5744 				*stype = STACK_MISC;
5745 			}
5746 			goto mark;
5747 		}
5748 
5749 		if (is_spilled_reg(&state->stack[spi]) &&
5750 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5751 		     env->allow_ptr_leaks)) {
5752 			if (clobber) {
5753 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5754 				for (j = 0; j < BPF_REG_SIZE; j++)
5755 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5756 			}
5757 			goto mark;
5758 		}
5759 
5760 err:
5761 		if (tnum_is_const(reg->var_off)) {
5762 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5763 				err_extra, regno, min_off, i - min_off, access_size);
5764 		} else {
5765 			char tn_buf[48];
5766 
5767 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5768 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5769 				err_extra, regno, tn_buf, i - min_off, access_size);
5770 		}
5771 		return -EACCES;
5772 mark:
5773 		/* reading any byte out of 8-byte 'spill_slot' will cause
5774 		 * the whole slot to be marked as 'read'
5775 		 */
5776 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5777 			      state->stack[spi].spilled_ptr.parent,
5778 			      REG_LIVE_READ64);
5779 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5780 		 * be sure that whether stack slot is written to or not. Hence,
5781 		 * we must still conservatively propagate reads upwards even if
5782 		 * helper may write to the entire memory range.
5783 		 */
5784 	}
5785 	return update_stack_depth(env, state, min_off);
5786 }
5787 
5788 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5789 				   int access_size, bool zero_size_allowed,
5790 				   struct bpf_call_arg_meta *meta)
5791 {
5792 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5793 	u32 *max_access;
5794 
5795 	switch (base_type(reg->type)) {
5796 	case PTR_TO_PACKET:
5797 	case PTR_TO_PACKET_META:
5798 		return check_packet_access(env, regno, reg->off, access_size,
5799 					   zero_size_allowed);
5800 	case PTR_TO_MAP_KEY:
5801 		if (meta && meta->raw_mode) {
5802 			verbose(env, "R%d cannot write into %s\n", regno,
5803 				reg_type_str(env, reg->type));
5804 			return -EACCES;
5805 		}
5806 		return check_mem_region_access(env, regno, reg->off, access_size,
5807 					       reg->map_ptr->key_size, false);
5808 	case PTR_TO_MAP_VALUE:
5809 		if (check_map_access_type(env, regno, reg->off, access_size,
5810 					  meta && meta->raw_mode ? BPF_WRITE :
5811 					  BPF_READ))
5812 			return -EACCES;
5813 		return check_map_access(env, regno, reg->off, access_size,
5814 					zero_size_allowed, ACCESS_HELPER);
5815 	case PTR_TO_MEM:
5816 		if (type_is_rdonly_mem(reg->type)) {
5817 			if (meta && meta->raw_mode) {
5818 				verbose(env, "R%d cannot write into %s\n", regno,
5819 					reg_type_str(env, reg->type));
5820 				return -EACCES;
5821 			}
5822 		}
5823 		return check_mem_region_access(env, regno, reg->off,
5824 					       access_size, reg->mem_size,
5825 					       zero_size_allowed);
5826 	case PTR_TO_BUF:
5827 		if (type_is_rdonly_mem(reg->type)) {
5828 			if (meta && meta->raw_mode) {
5829 				verbose(env, "R%d cannot write into %s\n", regno,
5830 					reg_type_str(env, reg->type));
5831 				return -EACCES;
5832 			}
5833 
5834 			max_access = &env->prog->aux->max_rdonly_access;
5835 		} else {
5836 			max_access = &env->prog->aux->max_rdwr_access;
5837 		}
5838 		return check_buffer_access(env, reg, regno, reg->off,
5839 					   access_size, zero_size_allowed,
5840 					   max_access);
5841 	case PTR_TO_STACK:
5842 		return check_stack_range_initialized(
5843 				env,
5844 				regno, reg->off, access_size,
5845 				zero_size_allowed, ACCESS_HELPER, meta);
5846 	case PTR_TO_CTX:
5847 		/* in case the function doesn't know how to access the context,
5848 		 * (because we are in a program of type SYSCALL for example), we
5849 		 * can not statically check its size.
5850 		 * Dynamically check it now.
5851 		 */
5852 		if (!env->ops->convert_ctx_access) {
5853 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5854 			int offset = access_size - 1;
5855 
5856 			/* Allow zero-byte read from PTR_TO_CTX */
5857 			if (access_size == 0)
5858 				return zero_size_allowed ? 0 : -EACCES;
5859 
5860 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5861 						atype, -1, false);
5862 		}
5863 
5864 		fallthrough;
5865 	default: /* scalar_value or invalid ptr */
5866 		/* Allow zero-byte read from NULL, regardless of pointer type */
5867 		if (zero_size_allowed && access_size == 0 &&
5868 		    register_is_null(reg))
5869 			return 0;
5870 
5871 		verbose(env, "R%d type=%s ", regno,
5872 			reg_type_str(env, reg->type));
5873 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5874 		return -EACCES;
5875 	}
5876 }
5877 
5878 static int check_mem_size_reg(struct bpf_verifier_env *env,
5879 			      struct bpf_reg_state *reg, u32 regno,
5880 			      bool zero_size_allowed,
5881 			      struct bpf_call_arg_meta *meta)
5882 {
5883 	int err;
5884 
5885 	/* This is used to refine r0 return value bounds for helpers
5886 	 * that enforce this value as an upper bound on return values.
5887 	 * See do_refine_retval_range() for helpers that can refine
5888 	 * the return value. C type of helper is u32 so we pull register
5889 	 * bound from umax_value however, if negative verifier errors
5890 	 * out. Only upper bounds can be learned because retval is an
5891 	 * int type and negative retvals are allowed.
5892 	 */
5893 	meta->msize_max_value = reg->umax_value;
5894 
5895 	/* The register is SCALAR_VALUE; the access check
5896 	 * happens using its boundaries.
5897 	 */
5898 	if (!tnum_is_const(reg->var_off))
5899 		/* For unprivileged variable accesses, disable raw
5900 		 * mode so that the program is required to
5901 		 * initialize all the memory that the helper could
5902 		 * just partially fill up.
5903 		 */
5904 		meta = NULL;
5905 
5906 	if (reg->smin_value < 0) {
5907 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5908 			regno);
5909 		return -EACCES;
5910 	}
5911 
5912 	if (reg->umin_value == 0) {
5913 		err = check_helper_mem_access(env, regno - 1, 0,
5914 					      zero_size_allowed,
5915 					      meta);
5916 		if (err)
5917 			return err;
5918 	}
5919 
5920 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5921 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5922 			regno);
5923 		return -EACCES;
5924 	}
5925 	err = check_helper_mem_access(env, regno - 1,
5926 				      reg->umax_value,
5927 				      zero_size_allowed, meta);
5928 	if (!err)
5929 		err = mark_chain_precision(env, regno);
5930 	return err;
5931 }
5932 
5933 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5934 		   u32 regno, u32 mem_size)
5935 {
5936 	bool may_be_null = type_may_be_null(reg->type);
5937 	struct bpf_reg_state saved_reg;
5938 	struct bpf_call_arg_meta meta;
5939 	int err;
5940 
5941 	if (register_is_null(reg))
5942 		return 0;
5943 
5944 	memset(&meta, 0, sizeof(meta));
5945 	/* Assuming that the register contains a value check if the memory
5946 	 * access is safe. Temporarily save and restore the register's state as
5947 	 * the conversion shouldn't be visible to a caller.
5948 	 */
5949 	if (may_be_null) {
5950 		saved_reg = *reg;
5951 		mark_ptr_not_null_reg(reg);
5952 	}
5953 
5954 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5955 	/* Check access for BPF_WRITE */
5956 	meta.raw_mode = true;
5957 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5958 
5959 	if (may_be_null)
5960 		*reg = saved_reg;
5961 
5962 	return err;
5963 }
5964 
5965 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5966 				    u32 regno)
5967 {
5968 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5969 	bool may_be_null = type_may_be_null(mem_reg->type);
5970 	struct bpf_reg_state saved_reg;
5971 	struct bpf_call_arg_meta meta;
5972 	int err;
5973 
5974 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5975 
5976 	memset(&meta, 0, sizeof(meta));
5977 
5978 	if (may_be_null) {
5979 		saved_reg = *mem_reg;
5980 		mark_ptr_not_null_reg(mem_reg);
5981 	}
5982 
5983 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5984 	/* Check access for BPF_WRITE */
5985 	meta.raw_mode = true;
5986 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5987 
5988 	if (may_be_null)
5989 		*mem_reg = saved_reg;
5990 	return err;
5991 }
5992 
5993 /* Implementation details:
5994  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5995  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5996  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5997  * Two separate bpf_obj_new will also have different reg->id.
5998  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5999  * clears reg->id after value_or_null->value transition, since the verifier only
6000  * cares about the range of access to valid map value pointer and doesn't care
6001  * about actual address of the map element.
6002  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6003  * reg->id > 0 after value_or_null->value transition. By doing so
6004  * two bpf_map_lookups will be considered two different pointers that
6005  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6006  * returned from bpf_obj_new.
6007  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6008  * dead-locks.
6009  * Since only one bpf_spin_lock is allowed the checks are simpler than
6010  * reg_is_refcounted() logic. The verifier needs to remember only
6011  * one spin_lock instead of array of acquired_refs.
6012  * cur_state->active_lock remembers which map value element or allocated
6013  * object got locked and clears it after bpf_spin_unlock.
6014  */
6015 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6016 			     bool is_lock)
6017 {
6018 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6019 	struct bpf_verifier_state *cur = env->cur_state;
6020 	bool is_const = tnum_is_const(reg->var_off);
6021 	u64 val = reg->var_off.value;
6022 	struct bpf_map *map = NULL;
6023 	struct btf *btf = NULL;
6024 	struct btf_record *rec;
6025 
6026 	if (!is_const) {
6027 		verbose(env,
6028 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6029 			regno);
6030 		return -EINVAL;
6031 	}
6032 	if (reg->type == PTR_TO_MAP_VALUE) {
6033 		map = reg->map_ptr;
6034 		if (!map->btf) {
6035 			verbose(env,
6036 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6037 				map->name);
6038 			return -EINVAL;
6039 		}
6040 	} else {
6041 		btf = reg->btf;
6042 	}
6043 
6044 	rec = reg_btf_record(reg);
6045 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6046 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6047 			map ? map->name : "kptr");
6048 		return -EINVAL;
6049 	}
6050 	if (rec->spin_lock_off != val + reg->off) {
6051 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6052 			val + reg->off, rec->spin_lock_off);
6053 		return -EINVAL;
6054 	}
6055 	if (is_lock) {
6056 		if (cur->active_lock.ptr) {
6057 			verbose(env,
6058 				"Locking two bpf_spin_locks are not allowed\n");
6059 			return -EINVAL;
6060 		}
6061 		if (map)
6062 			cur->active_lock.ptr = map;
6063 		else
6064 			cur->active_lock.ptr = btf;
6065 		cur->active_lock.id = reg->id;
6066 	} else {
6067 		void *ptr;
6068 
6069 		if (map)
6070 			ptr = map;
6071 		else
6072 			ptr = btf;
6073 
6074 		if (!cur->active_lock.ptr) {
6075 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6076 			return -EINVAL;
6077 		}
6078 		if (cur->active_lock.ptr != ptr ||
6079 		    cur->active_lock.id != reg->id) {
6080 			verbose(env, "bpf_spin_unlock of different lock\n");
6081 			return -EINVAL;
6082 		}
6083 
6084 		invalidate_non_owning_refs(env);
6085 
6086 		cur->active_lock.ptr = NULL;
6087 		cur->active_lock.id = 0;
6088 	}
6089 	return 0;
6090 }
6091 
6092 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6093 			      struct bpf_call_arg_meta *meta)
6094 {
6095 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6096 	bool is_const = tnum_is_const(reg->var_off);
6097 	struct bpf_map *map = reg->map_ptr;
6098 	u64 val = reg->var_off.value;
6099 
6100 	if (!is_const) {
6101 		verbose(env,
6102 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6103 			regno);
6104 		return -EINVAL;
6105 	}
6106 	if (!map->btf) {
6107 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6108 			map->name);
6109 		return -EINVAL;
6110 	}
6111 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6112 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6113 		return -EINVAL;
6114 	}
6115 	if (map->record->timer_off != val + reg->off) {
6116 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6117 			val + reg->off, map->record->timer_off);
6118 		return -EINVAL;
6119 	}
6120 	if (meta->map_ptr) {
6121 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6122 		return -EFAULT;
6123 	}
6124 	meta->map_uid = reg->map_uid;
6125 	meta->map_ptr = map;
6126 	return 0;
6127 }
6128 
6129 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6130 			     struct bpf_call_arg_meta *meta)
6131 {
6132 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6133 	struct bpf_map *map_ptr = reg->map_ptr;
6134 	struct btf_field *kptr_field;
6135 	u32 kptr_off;
6136 
6137 	if (!tnum_is_const(reg->var_off)) {
6138 		verbose(env,
6139 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6140 			regno);
6141 		return -EINVAL;
6142 	}
6143 	if (!map_ptr->btf) {
6144 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6145 			map_ptr->name);
6146 		return -EINVAL;
6147 	}
6148 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6149 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6150 		return -EINVAL;
6151 	}
6152 
6153 	meta->map_ptr = map_ptr;
6154 	kptr_off = reg->off + reg->var_off.value;
6155 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6156 	if (!kptr_field) {
6157 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6158 		return -EACCES;
6159 	}
6160 	if (kptr_field->type != BPF_KPTR_REF) {
6161 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6162 		return -EACCES;
6163 	}
6164 	meta->kptr_field = kptr_field;
6165 	return 0;
6166 }
6167 
6168 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6169  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6170  *
6171  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6172  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6173  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6174  *
6175  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6176  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6177  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6178  * mutate the view of the dynptr and also possibly destroy it. In the latter
6179  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6180  * memory that dynptr points to.
6181  *
6182  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6183  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6184  * readonly dynptr view yet, hence only the first case is tracked and checked.
6185  *
6186  * This is consistent with how C applies the const modifier to a struct object,
6187  * where the pointer itself inside bpf_dynptr becomes const but not what it
6188  * points to.
6189  *
6190  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6191  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6192  */
6193 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
6194 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
6195 {
6196 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6197 	int spi = 0;
6198 
6199 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6200 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6201 	 */
6202 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6203 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6204 		return -EFAULT;
6205 	}
6206 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
6207 	 * check_func_arg_reg_off's logic. We only need to check offset
6208 	 * and its alignment for PTR_TO_STACK.
6209 	 */
6210 	if (reg->type == PTR_TO_STACK) {
6211 		spi = dynptr_get_spi(env, reg);
6212 		if (spi < 0 && spi != -ERANGE)
6213 			return spi;
6214 	}
6215 
6216 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6217 	 *		 constructing a mutable bpf_dynptr object.
6218 	 *
6219 	 *		 Currently, this is only possible with PTR_TO_STACK
6220 	 *		 pointing to a region of at least 16 bytes which doesn't
6221 	 *		 contain an existing bpf_dynptr.
6222 	 *
6223 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6224 	 *		 mutated or destroyed. However, the memory it points to
6225 	 *		 may be mutated.
6226 	 *
6227 	 *  None       - Points to a initialized dynptr that can be mutated and
6228 	 *		 destroyed, including mutation of the memory it points
6229 	 *		 to.
6230 	 */
6231 	if (arg_type & MEM_UNINIT) {
6232 		if (!is_dynptr_reg_valid_uninit(env, reg, spi)) {
6233 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6234 			return -EINVAL;
6235 		}
6236 
6237 		/* We only support one dynptr being uninitialized at the moment,
6238 		 * which is sufficient for the helper functions we have right now.
6239 		 */
6240 		if (meta->uninit_dynptr_regno) {
6241 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6242 			return -EFAULT;
6243 		}
6244 
6245 		meta->uninit_dynptr_regno = regno;
6246 	} else /* MEM_RDONLY and None case from above */ {
6247 		int err;
6248 
6249 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6250 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6251 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6252 			return -EINVAL;
6253 		}
6254 
6255 		if (!is_dynptr_reg_valid_init(env, reg, spi)) {
6256 			verbose(env,
6257 				"Expected an initialized dynptr as arg #%d\n",
6258 				regno);
6259 			return -EINVAL;
6260 		}
6261 
6262 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6263 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6264 			const char *err_extra = "";
6265 
6266 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6267 			case DYNPTR_TYPE_LOCAL:
6268 				err_extra = "local";
6269 				break;
6270 			case DYNPTR_TYPE_RINGBUF:
6271 				err_extra = "ringbuf";
6272 				break;
6273 			default:
6274 				err_extra = "<unknown>";
6275 				break;
6276 			}
6277 			verbose(env,
6278 				"Expected a dynptr of type %s as arg #%d\n",
6279 				err_extra, regno);
6280 			return -EINVAL;
6281 		}
6282 
6283 		err = mark_dynptr_read(env, reg);
6284 		if (err)
6285 			return err;
6286 	}
6287 	return 0;
6288 }
6289 
6290 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6291 {
6292 	return type == ARG_CONST_SIZE ||
6293 	       type == ARG_CONST_SIZE_OR_ZERO;
6294 }
6295 
6296 static bool arg_type_is_release(enum bpf_arg_type type)
6297 {
6298 	return type & OBJ_RELEASE;
6299 }
6300 
6301 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6302 {
6303 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6304 }
6305 
6306 static int int_ptr_type_to_size(enum bpf_arg_type type)
6307 {
6308 	if (type == ARG_PTR_TO_INT)
6309 		return sizeof(u32);
6310 	else if (type == ARG_PTR_TO_LONG)
6311 		return sizeof(u64);
6312 
6313 	return -EINVAL;
6314 }
6315 
6316 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6317 				 const struct bpf_call_arg_meta *meta,
6318 				 enum bpf_arg_type *arg_type)
6319 {
6320 	if (!meta->map_ptr) {
6321 		/* kernel subsystem misconfigured verifier */
6322 		verbose(env, "invalid map_ptr to access map->type\n");
6323 		return -EACCES;
6324 	}
6325 
6326 	switch (meta->map_ptr->map_type) {
6327 	case BPF_MAP_TYPE_SOCKMAP:
6328 	case BPF_MAP_TYPE_SOCKHASH:
6329 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6330 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6331 		} else {
6332 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6333 			return -EINVAL;
6334 		}
6335 		break;
6336 	case BPF_MAP_TYPE_BLOOM_FILTER:
6337 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6338 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6339 		break;
6340 	default:
6341 		break;
6342 	}
6343 	return 0;
6344 }
6345 
6346 struct bpf_reg_types {
6347 	const enum bpf_reg_type types[10];
6348 	u32 *btf_id;
6349 };
6350 
6351 static const struct bpf_reg_types sock_types = {
6352 	.types = {
6353 		PTR_TO_SOCK_COMMON,
6354 		PTR_TO_SOCKET,
6355 		PTR_TO_TCP_SOCK,
6356 		PTR_TO_XDP_SOCK,
6357 	},
6358 };
6359 
6360 #ifdef CONFIG_NET
6361 static const struct bpf_reg_types btf_id_sock_common_types = {
6362 	.types = {
6363 		PTR_TO_SOCK_COMMON,
6364 		PTR_TO_SOCKET,
6365 		PTR_TO_TCP_SOCK,
6366 		PTR_TO_XDP_SOCK,
6367 		PTR_TO_BTF_ID,
6368 		PTR_TO_BTF_ID | PTR_TRUSTED,
6369 	},
6370 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6371 };
6372 #endif
6373 
6374 static const struct bpf_reg_types mem_types = {
6375 	.types = {
6376 		PTR_TO_STACK,
6377 		PTR_TO_PACKET,
6378 		PTR_TO_PACKET_META,
6379 		PTR_TO_MAP_KEY,
6380 		PTR_TO_MAP_VALUE,
6381 		PTR_TO_MEM,
6382 		PTR_TO_MEM | MEM_RINGBUF,
6383 		PTR_TO_BUF,
6384 	},
6385 };
6386 
6387 static const struct bpf_reg_types int_ptr_types = {
6388 	.types = {
6389 		PTR_TO_STACK,
6390 		PTR_TO_PACKET,
6391 		PTR_TO_PACKET_META,
6392 		PTR_TO_MAP_KEY,
6393 		PTR_TO_MAP_VALUE,
6394 	},
6395 };
6396 
6397 static const struct bpf_reg_types spin_lock_types = {
6398 	.types = {
6399 		PTR_TO_MAP_VALUE,
6400 		PTR_TO_BTF_ID | MEM_ALLOC,
6401 	}
6402 };
6403 
6404 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6405 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6406 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6407 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6408 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6409 static const struct bpf_reg_types btf_ptr_types = {
6410 	.types = {
6411 		PTR_TO_BTF_ID,
6412 		PTR_TO_BTF_ID | PTR_TRUSTED,
6413 		PTR_TO_BTF_ID | MEM_RCU,
6414 	},
6415 };
6416 static const struct bpf_reg_types percpu_btf_ptr_types = {
6417 	.types = {
6418 		PTR_TO_BTF_ID | MEM_PERCPU,
6419 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6420 	}
6421 };
6422 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6423 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6424 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6425 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6426 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6427 static const struct bpf_reg_types dynptr_types = {
6428 	.types = {
6429 		PTR_TO_STACK,
6430 		CONST_PTR_TO_DYNPTR,
6431 	}
6432 };
6433 
6434 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6435 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6436 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6437 	[ARG_CONST_SIZE]		= &scalar_types,
6438 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6439 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6440 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6441 	[ARG_PTR_TO_CTX]		= &context_types,
6442 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6443 #ifdef CONFIG_NET
6444 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6445 #endif
6446 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6447 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6448 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6449 	[ARG_PTR_TO_MEM]		= &mem_types,
6450 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6451 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6452 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6453 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6454 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6455 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6456 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6457 	[ARG_PTR_TO_TIMER]		= &timer_types,
6458 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6459 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6460 };
6461 
6462 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6463 			  enum bpf_arg_type arg_type,
6464 			  const u32 *arg_btf_id,
6465 			  struct bpf_call_arg_meta *meta)
6466 {
6467 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6468 	enum bpf_reg_type expected, type = reg->type;
6469 	const struct bpf_reg_types *compatible;
6470 	int i, j;
6471 
6472 	compatible = compatible_reg_types[base_type(arg_type)];
6473 	if (!compatible) {
6474 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6475 		return -EFAULT;
6476 	}
6477 
6478 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6479 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6480 	 *
6481 	 * Same for MAYBE_NULL:
6482 	 *
6483 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6484 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6485 	 *
6486 	 * Therefore we fold these flags depending on the arg_type before comparison.
6487 	 */
6488 	if (arg_type & MEM_RDONLY)
6489 		type &= ~MEM_RDONLY;
6490 	if (arg_type & PTR_MAYBE_NULL)
6491 		type &= ~PTR_MAYBE_NULL;
6492 
6493 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6494 		expected = compatible->types[i];
6495 		if (expected == NOT_INIT)
6496 			break;
6497 
6498 		if (type == expected)
6499 			goto found;
6500 	}
6501 
6502 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6503 	for (j = 0; j + 1 < i; j++)
6504 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6505 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6506 	return -EACCES;
6507 
6508 found:
6509 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6510 		/* For bpf_sk_release, it needs to match against first member
6511 		 * 'struct sock_common', hence make an exception for it. This
6512 		 * allows bpf_sk_release to work for multiple socket types.
6513 		 */
6514 		bool strict_type_match = arg_type_is_release(arg_type) &&
6515 					 meta->func_id != BPF_FUNC_sk_release;
6516 
6517 		if (!arg_btf_id) {
6518 			if (!compatible->btf_id) {
6519 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6520 				return -EFAULT;
6521 			}
6522 			arg_btf_id = compatible->btf_id;
6523 		}
6524 
6525 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6526 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6527 				return -EACCES;
6528 		} else {
6529 			if (arg_btf_id == BPF_PTR_POISON) {
6530 				verbose(env, "verifier internal error:");
6531 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6532 					regno);
6533 				return -EACCES;
6534 			}
6535 
6536 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6537 						  btf_vmlinux, *arg_btf_id,
6538 						  strict_type_match)) {
6539 				verbose(env, "R%d is of type %s but %s is expected\n",
6540 					regno, kernel_type_name(reg->btf, reg->btf_id),
6541 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6542 				return -EACCES;
6543 			}
6544 		}
6545 	} else if (type_is_alloc(reg->type)) {
6546 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6547 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6548 			return -EFAULT;
6549 		}
6550 	}
6551 
6552 	return 0;
6553 }
6554 
6555 static struct btf_field *
6556 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6557 {
6558 	struct btf_field *field;
6559 	struct btf_record *rec;
6560 
6561 	rec = reg_btf_record(reg);
6562 	if (!rec)
6563 		return NULL;
6564 
6565 	field = btf_record_find(rec, off, fields);
6566 	if (!field)
6567 		return NULL;
6568 
6569 	return field;
6570 }
6571 
6572 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6573 			   const struct bpf_reg_state *reg, int regno,
6574 			   enum bpf_arg_type arg_type)
6575 {
6576 	u32 type = reg->type;
6577 
6578 	/* When referenced register is passed to release function, its fixed
6579 	 * offset must be 0.
6580 	 *
6581 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6582 	 * meta->release_regno.
6583 	 */
6584 	if (arg_type_is_release(arg_type)) {
6585 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6586 		 * may not directly point to the object being released, but to
6587 		 * dynptr pointing to such object, which might be at some offset
6588 		 * on the stack. In that case, we simply to fallback to the
6589 		 * default handling.
6590 		 */
6591 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6592 			return 0;
6593 
6594 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6595 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6596 				return __check_ptr_off_reg(env, reg, regno, true);
6597 
6598 			verbose(env, "R%d must have zero offset when passed to release func\n",
6599 				regno);
6600 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6601 				kernel_type_name(reg->btf, reg->btf_id), reg->off);
6602 			return -EINVAL;
6603 		}
6604 
6605 		/* Doing check_ptr_off_reg check for the offset will catch this
6606 		 * because fixed_off_ok is false, but checking here allows us
6607 		 * to give the user a better error message.
6608 		 */
6609 		if (reg->off) {
6610 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6611 				regno);
6612 			return -EINVAL;
6613 		}
6614 		return __check_ptr_off_reg(env, reg, regno, false);
6615 	}
6616 
6617 	switch (type) {
6618 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6619 	case PTR_TO_STACK:
6620 	case PTR_TO_PACKET:
6621 	case PTR_TO_PACKET_META:
6622 	case PTR_TO_MAP_KEY:
6623 	case PTR_TO_MAP_VALUE:
6624 	case PTR_TO_MEM:
6625 	case PTR_TO_MEM | MEM_RDONLY:
6626 	case PTR_TO_MEM | MEM_RINGBUF:
6627 	case PTR_TO_BUF:
6628 	case PTR_TO_BUF | MEM_RDONLY:
6629 	case SCALAR_VALUE:
6630 		return 0;
6631 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6632 	 * fixed offset.
6633 	 */
6634 	case PTR_TO_BTF_ID:
6635 	case PTR_TO_BTF_ID | MEM_ALLOC:
6636 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6637 	case PTR_TO_BTF_ID | MEM_RCU:
6638 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6639 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6640 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6641 		 * its fixed offset must be 0. In the other cases, fixed offset
6642 		 * can be non-zero. This was already checked above. So pass
6643 		 * fixed_off_ok as true to allow fixed offset for all other
6644 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6645 		 * still need to do checks instead of returning.
6646 		 */
6647 		return __check_ptr_off_reg(env, reg, regno, true);
6648 	default:
6649 		return __check_ptr_off_reg(env, reg, regno, false);
6650 	}
6651 }
6652 
6653 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6654 {
6655 	struct bpf_func_state *state = func(env, reg);
6656 	int spi;
6657 
6658 	if (reg->type == CONST_PTR_TO_DYNPTR)
6659 		return reg->id;
6660 	spi = dynptr_get_spi(env, reg);
6661 	if (spi < 0)
6662 		return spi;
6663 	return state->stack[spi].spilled_ptr.id;
6664 }
6665 
6666 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6667 {
6668 	struct bpf_func_state *state = func(env, reg);
6669 	int spi;
6670 
6671 	if (reg->type == CONST_PTR_TO_DYNPTR)
6672 		return reg->ref_obj_id;
6673 	spi = dynptr_get_spi(env, reg);
6674 	if (spi < 0)
6675 		return spi;
6676 	return state->stack[spi].spilled_ptr.ref_obj_id;
6677 }
6678 
6679 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6680 			  struct bpf_call_arg_meta *meta,
6681 			  const struct bpf_func_proto *fn)
6682 {
6683 	u32 regno = BPF_REG_1 + arg;
6684 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6685 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6686 	enum bpf_reg_type type = reg->type;
6687 	u32 *arg_btf_id = NULL;
6688 	int err = 0;
6689 
6690 	if (arg_type == ARG_DONTCARE)
6691 		return 0;
6692 
6693 	err = check_reg_arg(env, regno, SRC_OP);
6694 	if (err)
6695 		return err;
6696 
6697 	if (arg_type == ARG_ANYTHING) {
6698 		if (is_pointer_value(env, regno)) {
6699 			verbose(env, "R%d leaks addr into helper function\n",
6700 				regno);
6701 			return -EACCES;
6702 		}
6703 		return 0;
6704 	}
6705 
6706 	if (type_is_pkt_pointer(type) &&
6707 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6708 		verbose(env, "helper access to the packet is not allowed\n");
6709 		return -EACCES;
6710 	}
6711 
6712 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6713 		err = resolve_map_arg_type(env, meta, &arg_type);
6714 		if (err)
6715 			return err;
6716 	}
6717 
6718 	if (register_is_null(reg) && type_may_be_null(arg_type))
6719 		/* A NULL register has a SCALAR_VALUE type, so skip
6720 		 * type checking.
6721 		 */
6722 		goto skip_type_check;
6723 
6724 	/* arg_btf_id and arg_size are in a union. */
6725 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6726 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6727 		arg_btf_id = fn->arg_btf_id[arg];
6728 
6729 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6730 	if (err)
6731 		return err;
6732 
6733 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6734 	if (err)
6735 		return err;
6736 
6737 skip_type_check:
6738 	if (arg_type_is_release(arg_type)) {
6739 		if (arg_type_is_dynptr(arg_type)) {
6740 			struct bpf_func_state *state = func(env, reg);
6741 			int spi;
6742 
6743 			/* Only dynptr created on stack can be released, thus
6744 			 * the get_spi and stack state checks for spilled_ptr
6745 			 * should only be done before process_dynptr_func for
6746 			 * PTR_TO_STACK.
6747 			 */
6748 			if (reg->type == PTR_TO_STACK) {
6749 				spi = dynptr_get_spi(env, reg);
6750 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
6751 					verbose(env, "arg %d is an unacquired reference\n", regno);
6752 					return -EINVAL;
6753 				}
6754 			} else {
6755 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6756 				return -EINVAL;
6757 			}
6758 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6759 			verbose(env, "R%d must be referenced when passed to release function\n",
6760 				regno);
6761 			return -EINVAL;
6762 		}
6763 		if (meta->release_regno) {
6764 			verbose(env, "verifier internal error: more than one release argument\n");
6765 			return -EFAULT;
6766 		}
6767 		meta->release_regno = regno;
6768 	}
6769 
6770 	if (reg->ref_obj_id) {
6771 		if (meta->ref_obj_id) {
6772 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6773 				regno, reg->ref_obj_id,
6774 				meta->ref_obj_id);
6775 			return -EFAULT;
6776 		}
6777 		meta->ref_obj_id = reg->ref_obj_id;
6778 	}
6779 
6780 	switch (base_type(arg_type)) {
6781 	case ARG_CONST_MAP_PTR:
6782 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6783 		if (meta->map_ptr) {
6784 			/* Use map_uid (which is unique id of inner map) to reject:
6785 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6786 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6787 			 * if (inner_map1 && inner_map2) {
6788 			 *     timer = bpf_map_lookup_elem(inner_map1);
6789 			 *     if (timer)
6790 			 *         // mismatch would have been allowed
6791 			 *         bpf_timer_init(timer, inner_map2);
6792 			 * }
6793 			 *
6794 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6795 			 */
6796 			if (meta->map_ptr != reg->map_ptr ||
6797 			    meta->map_uid != reg->map_uid) {
6798 				verbose(env,
6799 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6800 					meta->map_uid, reg->map_uid);
6801 				return -EINVAL;
6802 			}
6803 		}
6804 		meta->map_ptr = reg->map_ptr;
6805 		meta->map_uid = reg->map_uid;
6806 		break;
6807 	case ARG_PTR_TO_MAP_KEY:
6808 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6809 		 * check that [key, key + map->key_size) are within
6810 		 * stack limits and initialized
6811 		 */
6812 		if (!meta->map_ptr) {
6813 			/* in function declaration map_ptr must come before
6814 			 * map_key, so that it's verified and known before
6815 			 * we have to check map_key here. Otherwise it means
6816 			 * that kernel subsystem misconfigured verifier
6817 			 */
6818 			verbose(env, "invalid map_ptr to access map->key\n");
6819 			return -EACCES;
6820 		}
6821 		err = check_helper_mem_access(env, regno,
6822 					      meta->map_ptr->key_size, false,
6823 					      NULL);
6824 		break;
6825 	case ARG_PTR_TO_MAP_VALUE:
6826 		if (type_may_be_null(arg_type) && register_is_null(reg))
6827 			return 0;
6828 
6829 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6830 		 * check [value, value + map->value_size) validity
6831 		 */
6832 		if (!meta->map_ptr) {
6833 			/* kernel subsystem misconfigured verifier */
6834 			verbose(env, "invalid map_ptr to access map->value\n");
6835 			return -EACCES;
6836 		}
6837 		meta->raw_mode = arg_type & MEM_UNINIT;
6838 		err = check_helper_mem_access(env, regno,
6839 					      meta->map_ptr->value_size, false,
6840 					      meta);
6841 		break;
6842 	case ARG_PTR_TO_PERCPU_BTF_ID:
6843 		if (!reg->btf_id) {
6844 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6845 			return -EACCES;
6846 		}
6847 		meta->ret_btf = reg->btf;
6848 		meta->ret_btf_id = reg->btf_id;
6849 		break;
6850 	case ARG_PTR_TO_SPIN_LOCK:
6851 		if (in_rbtree_lock_required_cb(env)) {
6852 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
6853 			return -EACCES;
6854 		}
6855 		if (meta->func_id == BPF_FUNC_spin_lock) {
6856 			err = process_spin_lock(env, regno, true);
6857 			if (err)
6858 				return err;
6859 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6860 			err = process_spin_lock(env, regno, false);
6861 			if (err)
6862 				return err;
6863 		} else {
6864 			verbose(env, "verifier internal error\n");
6865 			return -EFAULT;
6866 		}
6867 		break;
6868 	case ARG_PTR_TO_TIMER:
6869 		err = process_timer_func(env, regno, meta);
6870 		if (err)
6871 			return err;
6872 		break;
6873 	case ARG_PTR_TO_FUNC:
6874 		meta->subprogno = reg->subprogno;
6875 		break;
6876 	case ARG_PTR_TO_MEM:
6877 		/* The access to this pointer is only checked when we hit the
6878 		 * next is_mem_size argument below.
6879 		 */
6880 		meta->raw_mode = arg_type & MEM_UNINIT;
6881 		if (arg_type & MEM_FIXED_SIZE) {
6882 			err = check_helper_mem_access(env, regno,
6883 						      fn->arg_size[arg], false,
6884 						      meta);
6885 		}
6886 		break;
6887 	case ARG_CONST_SIZE:
6888 		err = check_mem_size_reg(env, reg, regno, false, meta);
6889 		break;
6890 	case ARG_CONST_SIZE_OR_ZERO:
6891 		err = check_mem_size_reg(env, reg, regno, true, meta);
6892 		break;
6893 	case ARG_PTR_TO_DYNPTR:
6894 		err = process_dynptr_func(env, regno, arg_type, meta);
6895 		if (err)
6896 			return err;
6897 		break;
6898 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6899 		if (!tnum_is_const(reg->var_off)) {
6900 			verbose(env, "R%d is not a known constant'\n",
6901 				regno);
6902 			return -EACCES;
6903 		}
6904 		meta->mem_size = reg->var_off.value;
6905 		err = mark_chain_precision(env, regno);
6906 		if (err)
6907 			return err;
6908 		break;
6909 	case ARG_PTR_TO_INT:
6910 	case ARG_PTR_TO_LONG:
6911 	{
6912 		int size = int_ptr_type_to_size(arg_type);
6913 
6914 		err = check_helper_mem_access(env, regno, size, false, meta);
6915 		if (err)
6916 			return err;
6917 		err = check_ptr_alignment(env, reg, 0, size, true);
6918 		break;
6919 	}
6920 	case ARG_PTR_TO_CONST_STR:
6921 	{
6922 		struct bpf_map *map = reg->map_ptr;
6923 		int map_off;
6924 		u64 map_addr;
6925 		char *str_ptr;
6926 
6927 		if (!bpf_map_is_rdonly(map)) {
6928 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6929 			return -EACCES;
6930 		}
6931 
6932 		if (!tnum_is_const(reg->var_off)) {
6933 			verbose(env, "R%d is not a constant address'\n", regno);
6934 			return -EACCES;
6935 		}
6936 
6937 		if (!map->ops->map_direct_value_addr) {
6938 			verbose(env, "no direct value access support for this map type\n");
6939 			return -EACCES;
6940 		}
6941 
6942 		err = check_map_access(env, regno, reg->off,
6943 				       map->value_size - reg->off, false,
6944 				       ACCESS_HELPER);
6945 		if (err)
6946 			return err;
6947 
6948 		map_off = reg->off + reg->var_off.value;
6949 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6950 		if (err) {
6951 			verbose(env, "direct value access on string failed\n");
6952 			return err;
6953 		}
6954 
6955 		str_ptr = (char *)(long)(map_addr);
6956 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6957 			verbose(env, "string is not zero-terminated\n");
6958 			return -EINVAL;
6959 		}
6960 		break;
6961 	}
6962 	case ARG_PTR_TO_KPTR:
6963 		err = process_kptr_func(env, regno, meta);
6964 		if (err)
6965 			return err;
6966 		break;
6967 	}
6968 
6969 	return err;
6970 }
6971 
6972 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6973 {
6974 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6975 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6976 
6977 	if (func_id != BPF_FUNC_map_update_elem)
6978 		return false;
6979 
6980 	/* It's not possible to get access to a locked struct sock in these
6981 	 * contexts, so updating is safe.
6982 	 */
6983 	switch (type) {
6984 	case BPF_PROG_TYPE_TRACING:
6985 		if (eatype == BPF_TRACE_ITER)
6986 			return true;
6987 		break;
6988 	case BPF_PROG_TYPE_SOCKET_FILTER:
6989 	case BPF_PROG_TYPE_SCHED_CLS:
6990 	case BPF_PROG_TYPE_SCHED_ACT:
6991 	case BPF_PROG_TYPE_XDP:
6992 	case BPF_PROG_TYPE_SK_REUSEPORT:
6993 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6994 	case BPF_PROG_TYPE_SK_LOOKUP:
6995 		return true;
6996 	default:
6997 		break;
6998 	}
6999 
7000 	verbose(env, "cannot update sockmap in this context\n");
7001 	return false;
7002 }
7003 
7004 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7005 {
7006 	return env->prog->jit_requested &&
7007 	       bpf_jit_supports_subprog_tailcalls();
7008 }
7009 
7010 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7011 					struct bpf_map *map, int func_id)
7012 {
7013 	if (!map)
7014 		return 0;
7015 
7016 	/* We need a two way check, first is from map perspective ... */
7017 	switch (map->map_type) {
7018 	case BPF_MAP_TYPE_PROG_ARRAY:
7019 		if (func_id != BPF_FUNC_tail_call)
7020 			goto error;
7021 		break;
7022 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7023 		if (func_id != BPF_FUNC_perf_event_read &&
7024 		    func_id != BPF_FUNC_perf_event_output &&
7025 		    func_id != BPF_FUNC_skb_output &&
7026 		    func_id != BPF_FUNC_perf_event_read_value &&
7027 		    func_id != BPF_FUNC_xdp_output)
7028 			goto error;
7029 		break;
7030 	case BPF_MAP_TYPE_RINGBUF:
7031 		if (func_id != BPF_FUNC_ringbuf_output &&
7032 		    func_id != BPF_FUNC_ringbuf_reserve &&
7033 		    func_id != BPF_FUNC_ringbuf_query &&
7034 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7035 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7036 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
7037 			goto error;
7038 		break;
7039 	case BPF_MAP_TYPE_USER_RINGBUF:
7040 		if (func_id != BPF_FUNC_user_ringbuf_drain)
7041 			goto error;
7042 		break;
7043 	case BPF_MAP_TYPE_STACK_TRACE:
7044 		if (func_id != BPF_FUNC_get_stackid)
7045 			goto error;
7046 		break;
7047 	case BPF_MAP_TYPE_CGROUP_ARRAY:
7048 		if (func_id != BPF_FUNC_skb_under_cgroup &&
7049 		    func_id != BPF_FUNC_current_task_under_cgroup)
7050 			goto error;
7051 		break;
7052 	case BPF_MAP_TYPE_CGROUP_STORAGE:
7053 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7054 		if (func_id != BPF_FUNC_get_local_storage)
7055 			goto error;
7056 		break;
7057 	case BPF_MAP_TYPE_DEVMAP:
7058 	case BPF_MAP_TYPE_DEVMAP_HASH:
7059 		if (func_id != BPF_FUNC_redirect_map &&
7060 		    func_id != BPF_FUNC_map_lookup_elem)
7061 			goto error;
7062 		break;
7063 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
7064 	 * appear.
7065 	 */
7066 	case BPF_MAP_TYPE_CPUMAP:
7067 		if (func_id != BPF_FUNC_redirect_map)
7068 			goto error;
7069 		break;
7070 	case BPF_MAP_TYPE_XSKMAP:
7071 		if (func_id != BPF_FUNC_redirect_map &&
7072 		    func_id != BPF_FUNC_map_lookup_elem)
7073 			goto error;
7074 		break;
7075 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7076 	case BPF_MAP_TYPE_HASH_OF_MAPS:
7077 		if (func_id != BPF_FUNC_map_lookup_elem)
7078 			goto error;
7079 		break;
7080 	case BPF_MAP_TYPE_SOCKMAP:
7081 		if (func_id != BPF_FUNC_sk_redirect_map &&
7082 		    func_id != BPF_FUNC_sock_map_update &&
7083 		    func_id != BPF_FUNC_map_delete_elem &&
7084 		    func_id != BPF_FUNC_msg_redirect_map &&
7085 		    func_id != BPF_FUNC_sk_select_reuseport &&
7086 		    func_id != BPF_FUNC_map_lookup_elem &&
7087 		    !may_update_sockmap(env, func_id))
7088 			goto error;
7089 		break;
7090 	case BPF_MAP_TYPE_SOCKHASH:
7091 		if (func_id != BPF_FUNC_sk_redirect_hash &&
7092 		    func_id != BPF_FUNC_sock_hash_update &&
7093 		    func_id != BPF_FUNC_map_delete_elem &&
7094 		    func_id != BPF_FUNC_msg_redirect_hash &&
7095 		    func_id != BPF_FUNC_sk_select_reuseport &&
7096 		    func_id != BPF_FUNC_map_lookup_elem &&
7097 		    !may_update_sockmap(env, func_id))
7098 			goto error;
7099 		break;
7100 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7101 		if (func_id != BPF_FUNC_sk_select_reuseport)
7102 			goto error;
7103 		break;
7104 	case BPF_MAP_TYPE_QUEUE:
7105 	case BPF_MAP_TYPE_STACK:
7106 		if (func_id != BPF_FUNC_map_peek_elem &&
7107 		    func_id != BPF_FUNC_map_pop_elem &&
7108 		    func_id != BPF_FUNC_map_push_elem)
7109 			goto error;
7110 		break;
7111 	case BPF_MAP_TYPE_SK_STORAGE:
7112 		if (func_id != BPF_FUNC_sk_storage_get &&
7113 		    func_id != BPF_FUNC_sk_storage_delete)
7114 			goto error;
7115 		break;
7116 	case BPF_MAP_TYPE_INODE_STORAGE:
7117 		if (func_id != BPF_FUNC_inode_storage_get &&
7118 		    func_id != BPF_FUNC_inode_storage_delete)
7119 			goto error;
7120 		break;
7121 	case BPF_MAP_TYPE_TASK_STORAGE:
7122 		if (func_id != BPF_FUNC_task_storage_get &&
7123 		    func_id != BPF_FUNC_task_storage_delete)
7124 			goto error;
7125 		break;
7126 	case BPF_MAP_TYPE_CGRP_STORAGE:
7127 		if (func_id != BPF_FUNC_cgrp_storage_get &&
7128 		    func_id != BPF_FUNC_cgrp_storage_delete)
7129 			goto error;
7130 		break;
7131 	case BPF_MAP_TYPE_BLOOM_FILTER:
7132 		if (func_id != BPF_FUNC_map_peek_elem &&
7133 		    func_id != BPF_FUNC_map_push_elem)
7134 			goto error;
7135 		break;
7136 	default:
7137 		break;
7138 	}
7139 
7140 	/* ... and second from the function itself. */
7141 	switch (func_id) {
7142 	case BPF_FUNC_tail_call:
7143 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7144 			goto error;
7145 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7146 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7147 			return -EINVAL;
7148 		}
7149 		break;
7150 	case BPF_FUNC_perf_event_read:
7151 	case BPF_FUNC_perf_event_output:
7152 	case BPF_FUNC_perf_event_read_value:
7153 	case BPF_FUNC_skb_output:
7154 	case BPF_FUNC_xdp_output:
7155 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7156 			goto error;
7157 		break;
7158 	case BPF_FUNC_ringbuf_output:
7159 	case BPF_FUNC_ringbuf_reserve:
7160 	case BPF_FUNC_ringbuf_query:
7161 	case BPF_FUNC_ringbuf_reserve_dynptr:
7162 	case BPF_FUNC_ringbuf_submit_dynptr:
7163 	case BPF_FUNC_ringbuf_discard_dynptr:
7164 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7165 			goto error;
7166 		break;
7167 	case BPF_FUNC_user_ringbuf_drain:
7168 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7169 			goto error;
7170 		break;
7171 	case BPF_FUNC_get_stackid:
7172 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7173 			goto error;
7174 		break;
7175 	case BPF_FUNC_current_task_under_cgroup:
7176 	case BPF_FUNC_skb_under_cgroup:
7177 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7178 			goto error;
7179 		break;
7180 	case BPF_FUNC_redirect_map:
7181 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7182 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7183 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
7184 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
7185 			goto error;
7186 		break;
7187 	case BPF_FUNC_sk_redirect_map:
7188 	case BPF_FUNC_msg_redirect_map:
7189 	case BPF_FUNC_sock_map_update:
7190 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7191 			goto error;
7192 		break;
7193 	case BPF_FUNC_sk_redirect_hash:
7194 	case BPF_FUNC_msg_redirect_hash:
7195 	case BPF_FUNC_sock_hash_update:
7196 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7197 			goto error;
7198 		break;
7199 	case BPF_FUNC_get_local_storage:
7200 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7201 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7202 			goto error;
7203 		break;
7204 	case BPF_FUNC_sk_select_reuseport:
7205 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7206 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7207 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
7208 			goto error;
7209 		break;
7210 	case BPF_FUNC_map_pop_elem:
7211 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7212 		    map->map_type != BPF_MAP_TYPE_STACK)
7213 			goto error;
7214 		break;
7215 	case BPF_FUNC_map_peek_elem:
7216 	case BPF_FUNC_map_push_elem:
7217 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7218 		    map->map_type != BPF_MAP_TYPE_STACK &&
7219 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7220 			goto error;
7221 		break;
7222 	case BPF_FUNC_map_lookup_percpu_elem:
7223 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7224 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7225 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7226 			goto error;
7227 		break;
7228 	case BPF_FUNC_sk_storage_get:
7229 	case BPF_FUNC_sk_storage_delete:
7230 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7231 			goto error;
7232 		break;
7233 	case BPF_FUNC_inode_storage_get:
7234 	case BPF_FUNC_inode_storage_delete:
7235 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7236 			goto error;
7237 		break;
7238 	case BPF_FUNC_task_storage_get:
7239 	case BPF_FUNC_task_storage_delete:
7240 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7241 			goto error;
7242 		break;
7243 	case BPF_FUNC_cgrp_storage_get:
7244 	case BPF_FUNC_cgrp_storage_delete:
7245 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7246 			goto error;
7247 		break;
7248 	default:
7249 		break;
7250 	}
7251 
7252 	return 0;
7253 error:
7254 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
7255 		map->map_type, func_id_name(func_id), func_id);
7256 	return -EINVAL;
7257 }
7258 
7259 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7260 {
7261 	int count = 0;
7262 
7263 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7264 		count++;
7265 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7266 		count++;
7267 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7268 		count++;
7269 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7270 		count++;
7271 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7272 		count++;
7273 
7274 	/* We only support one arg being in raw mode at the moment,
7275 	 * which is sufficient for the helper functions we have
7276 	 * right now.
7277 	 */
7278 	return count <= 1;
7279 }
7280 
7281 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7282 {
7283 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7284 	bool has_size = fn->arg_size[arg] != 0;
7285 	bool is_next_size = false;
7286 
7287 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7288 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7289 
7290 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7291 		return is_next_size;
7292 
7293 	return has_size == is_next_size || is_next_size == is_fixed;
7294 }
7295 
7296 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7297 {
7298 	/* bpf_xxx(..., buf, len) call will access 'len'
7299 	 * bytes from memory 'buf'. Both arg types need
7300 	 * to be paired, so make sure there's no buggy
7301 	 * helper function specification.
7302 	 */
7303 	if (arg_type_is_mem_size(fn->arg1_type) ||
7304 	    check_args_pair_invalid(fn, 0) ||
7305 	    check_args_pair_invalid(fn, 1) ||
7306 	    check_args_pair_invalid(fn, 2) ||
7307 	    check_args_pair_invalid(fn, 3) ||
7308 	    check_args_pair_invalid(fn, 4))
7309 		return false;
7310 
7311 	return true;
7312 }
7313 
7314 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7315 {
7316 	int i;
7317 
7318 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7319 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7320 			return !!fn->arg_btf_id[i];
7321 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7322 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7323 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7324 		    /* arg_btf_id and arg_size are in a union. */
7325 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7326 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7327 			return false;
7328 	}
7329 
7330 	return true;
7331 }
7332 
7333 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7334 {
7335 	return check_raw_mode_ok(fn) &&
7336 	       check_arg_pair_ok(fn) &&
7337 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7338 }
7339 
7340 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7341  * are now invalid, so turn them into unknown SCALAR_VALUE.
7342  */
7343 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7344 {
7345 	struct bpf_func_state *state;
7346 	struct bpf_reg_state *reg;
7347 
7348 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7349 		if (reg_is_pkt_pointer_any(reg))
7350 			__mark_reg_unknown(env, reg);
7351 	}));
7352 }
7353 
7354 enum {
7355 	AT_PKT_END = -1,
7356 	BEYOND_PKT_END = -2,
7357 };
7358 
7359 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7360 {
7361 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7362 	struct bpf_reg_state *reg = &state->regs[regn];
7363 
7364 	if (reg->type != PTR_TO_PACKET)
7365 		/* PTR_TO_PACKET_META is not supported yet */
7366 		return;
7367 
7368 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7369 	 * How far beyond pkt_end it goes is unknown.
7370 	 * if (!range_open) it's the case of pkt >= pkt_end
7371 	 * if (range_open) it's the case of pkt > pkt_end
7372 	 * hence this pointer is at least 1 byte bigger than pkt_end
7373 	 */
7374 	if (range_open)
7375 		reg->range = BEYOND_PKT_END;
7376 	else
7377 		reg->range = AT_PKT_END;
7378 }
7379 
7380 /* The pointer with the specified id has released its reference to kernel
7381  * resources. Identify all copies of the same pointer and clear the reference.
7382  */
7383 static int release_reference(struct bpf_verifier_env *env,
7384 			     int ref_obj_id)
7385 {
7386 	struct bpf_func_state *state;
7387 	struct bpf_reg_state *reg;
7388 	int err;
7389 
7390 	err = release_reference_state(cur_func(env), ref_obj_id);
7391 	if (err)
7392 		return err;
7393 
7394 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7395 		if (reg->ref_obj_id == ref_obj_id) {
7396 			if (!env->allow_ptr_leaks)
7397 				__mark_reg_not_init(env, reg);
7398 			else
7399 				__mark_reg_unknown(env, reg);
7400 		}
7401 	}));
7402 
7403 	return 0;
7404 }
7405 
7406 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7407 {
7408 	struct bpf_func_state *unused;
7409 	struct bpf_reg_state *reg;
7410 
7411 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7412 		if (type_is_non_owning_ref(reg->type))
7413 			__mark_reg_unknown(env, reg);
7414 	}));
7415 }
7416 
7417 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7418 				    struct bpf_reg_state *regs)
7419 {
7420 	int i;
7421 
7422 	/* after the call registers r0 - r5 were scratched */
7423 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7424 		mark_reg_not_init(env, regs, caller_saved[i]);
7425 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7426 	}
7427 }
7428 
7429 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7430 				   struct bpf_func_state *caller,
7431 				   struct bpf_func_state *callee,
7432 				   int insn_idx);
7433 
7434 static int set_callee_state(struct bpf_verifier_env *env,
7435 			    struct bpf_func_state *caller,
7436 			    struct bpf_func_state *callee, int insn_idx);
7437 
7438 static bool is_callback_calling_kfunc(u32 btf_id);
7439 
7440 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7441 			     int *insn_idx, int subprog,
7442 			     set_callee_state_fn set_callee_state_cb)
7443 {
7444 	struct bpf_verifier_state *state = env->cur_state;
7445 	struct bpf_func_info_aux *func_info_aux;
7446 	struct bpf_func_state *caller, *callee;
7447 	int err;
7448 	bool is_global = false;
7449 
7450 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7451 		verbose(env, "the call stack of %d frames is too deep\n",
7452 			state->curframe + 2);
7453 		return -E2BIG;
7454 	}
7455 
7456 	caller = state->frame[state->curframe];
7457 	if (state->frame[state->curframe + 1]) {
7458 		verbose(env, "verifier bug. Frame %d already allocated\n",
7459 			state->curframe + 1);
7460 		return -EFAULT;
7461 	}
7462 
7463 	func_info_aux = env->prog->aux->func_info_aux;
7464 	if (func_info_aux)
7465 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7466 	err = btf_check_subprog_call(env, subprog, caller->regs);
7467 	if (err == -EFAULT)
7468 		return err;
7469 	if (is_global) {
7470 		if (err) {
7471 			verbose(env, "Caller passes invalid args into func#%d\n",
7472 				subprog);
7473 			return err;
7474 		} else {
7475 			if (env->log.level & BPF_LOG_LEVEL)
7476 				verbose(env,
7477 					"Func#%d is global and valid. Skipping.\n",
7478 					subprog);
7479 			clear_caller_saved_regs(env, caller->regs);
7480 
7481 			/* All global functions return a 64-bit SCALAR_VALUE */
7482 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7483 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7484 
7485 			/* continue with next insn after call */
7486 			return 0;
7487 		}
7488 	}
7489 
7490 	/* set_callee_state is used for direct subprog calls, but we are
7491 	 * interested in validating only BPF helpers that can call subprogs as
7492 	 * callbacks
7493 	 */
7494 	if (set_callee_state_cb != set_callee_state) {
7495 		if (bpf_pseudo_kfunc_call(insn) &&
7496 		    !is_callback_calling_kfunc(insn->imm)) {
7497 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7498 				func_id_name(insn->imm), insn->imm);
7499 			return -EFAULT;
7500 		} else if (!bpf_pseudo_kfunc_call(insn) &&
7501 			   !is_callback_calling_function(insn->imm)) { /* helper */
7502 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7503 				func_id_name(insn->imm), insn->imm);
7504 			return -EFAULT;
7505 		}
7506 	}
7507 
7508 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7509 	    insn->src_reg == 0 &&
7510 	    insn->imm == BPF_FUNC_timer_set_callback) {
7511 		struct bpf_verifier_state *async_cb;
7512 
7513 		/* there is no real recursion here. timer callbacks are async */
7514 		env->subprog_info[subprog].is_async_cb = true;
7515 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7516 					 *insn_idx, subprog);
7517 		if (!async_cb)
7518 			return -EFAULT;
7519 		callee = async_cb->frame[0];
7520 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7521 
7522 		/* Convert bpf_timer_set_callback() args into timer callback args */
7523 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7524 		if (err)
7525 			return err;
7526 
7527 		clear_caller_saved_regs(env, caller->regs);
7528 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7529 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7530 		/* continue with next insn after call */
7531 		return 0;
7532 	}
7533 
7534 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7535 	if (!callee)
7536 		return -ENOMEM;
7537 	state->frame[state->curframe + 1] = callee;
7538 
7539 	/* callee cannot access r0, r6 - r9 for reading and has to write
7540 	 * into its own stack before reading from it.
7541 	 * callee can read/write into caller's stack
7542 	 */
7543 	init_func_state(env, callee,
7544 			/* remember the callsite, it will be used by bpf_exit */
7545 			*insn_idx /* callsite */,
7546 			state->curframe + 1 /* frameno within this callchain */,
7547 			subprog /* subprog number within this prog */);
7548 
7549 	/* Transfer references to the callee */
7550 	err = copy_reference_state(callee, caller);
7551 	if (err)
7552 		goto err_out;
7553 
7554 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7555 	if (err)
7556 		goto err_out;
7557 
7558 	clear_caller_saved_regs(env, caller->regs);
7559 
7560 	/* only increment it after check_reg_arg() finished */
7561 	state->curframe++;
7562 
7563 	/* and go analyze first insn of the callee */
7564 	*insn_idx = env->subprog_info[subprog].start - 1;
7565 
7566 	if (env->log.level & BPF_LOG_LEVEL) {
7567 		verbose(env, "caller:\n");
7568 		print_verifier_state(env, caller, true);
7569 		verbose(env, "callee:\n");
7570 		print_verifier_state(env, callee, true);
7571 	}
7572 	return 0;
7573 
7574 err_out:
7575 	free_func_state(callee);
7576 	state->frame[state->curframe + 1] = NULL;
7577 	return err;
7578 }
7579 
7580 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7581 				   struct bpf_func_state *caller,
7582 				   struct bpf_func_state *callee)
7583 {
7584 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7585 	 *      void *callback_ctx, u64 flags);
7586 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7587 	 *      void *callback_ctx);
7588 	 */
7589 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7590 
7591 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7592 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7593 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7594 
7595 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7596 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7597 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7598 
7599 	/* pointer to stack or null */
7600 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7601 
7602 	/* unused */
7603 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7604 	return 0;
7605 }
7606 
7607 static int set_callee_state(struct bpf_verifier_env *env,
7608 			    struct bpf_func_state *caller,
7609 			    struct bpf_func_state *callee, int insn_idx)
7610 {
7611 	int i;
7612 
7613 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7614 	 * pointers, which connects us up to the liveness chain
7615 	 */
7616 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7617 		callee->regs[i] = caller->regs[i];
7618 	return 0;
7619 }
7620 
7621 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7622 			   int *insn_idx)
7623 {
7624 	int subprog, target_insn;
7625 
7626 	target_insn = *insn_idx + insn->imm + 1;
7627 	subprog = find_subprog(env, target_insn);
7628 	if (subprog < 0) {
7629 		verbose(env, "verifier bug. No program starts at insn %d\n",
7630 			target_insn);
7631 		return -EFAULT;
7632 	}
7633 
7634 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7635 }
7636 
7637 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7638 				       struct bpf_func_state *caller,
7639 				       struct bpf_func_state *callee,
7640 				       int insn_idx)
7641 {
7642 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7643 	struct bpf_map *map;
7644 	int err;
7645 
7646 	if (bpf_map_ptr_poisoned(insn_aux)) {
7647 		verbose(env, "tail_call abusing map_ptr\n");
7648 		return -EINVAL;
7649 	}
7650 
7651 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7652 	if (!map->ops->map_set_for_each_callback_args ||
7653 	    !map->ops->map_for_each_callback) {
7654 		verbose(env, "callback function not allowed for map\n");
7655 		return -ENOTSUPP;
7656 	}
7657 
7658 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7659 	if (err)
7660 		return err;
7661 
7662 	callee->in_callback_fn = true;
7663 	callee->callback_ret_range = tnum_range(0, 1);
7664 	return 0;
7665 }
7666 
7667 static int set_loop_callback_state(struct bpf_verifier_env *env,
7668 				   struct bpf_func_state *caller,
7669 				   struct bpf_func_state *callee,
7670 				   int insn_idx)
7671 {
7672 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7673 	 *	    u64 flags);
7674 	 * callback_fn(u32 index, void *callback_ctx);
7675 	 */
7676 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7677 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7678 
7679 	/* unused */
7680 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7681 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7682 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7683 
7684 	callee->in_callback_fn = true;
7685 	callee->callback_ret_range = tnum_range(0, 1);
7686 	return 0;
7687 }
7688 
7689 static int set_timer_callback_state(struct bpf_verifier_env *env,
7690 				    struct bpf_func_state *caller,
7691 				    struct bpf_func_state *callee,
7692 				    int insn_idx)
7693 {
7694 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7695 
7696 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7697 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7698 	 */
7699 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7700 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7701 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7702 
7703 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7704 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7705 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7706 
7707 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7708 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7709 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7710 
7711 	/* unused */
7712 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7713 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7714 	callee->in_async_callback_fn = true;
7715 	callee->callback_ret_range = tnum_range(0, 1);
7716 	return 0;
7717 }
7718 
7719 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7720 				       struct bpf_func_state *caller,
7721 				       struct bpf_func_state *callee,
7722 				       int insn_idx)
7723 {
7724 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7725 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7726 	 * (callback_fn)(struct task_struct *task,
7727 	 *               struct vm_area_struct *vma, void *callback_ctx);
7728 	 */
7729 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7730 
7731 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7732 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7733 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7734 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7735 
7736 	/* pointer to stack or null */
7737 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7738 
7739 	/* unused */
7740 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7741 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7742 	callee->in_callback_fn = true;
7743 	callee->callback_ret_range = tnum_range(0, 1);
7744 	return 0;
7745 }
7746 
7747 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7748 					   struct bpf_func_state *caller,
7749 					   struct bpf_func_state *callee,
7750 					   int insn_idx)
7751 {
7752 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7753 	 *			  callback_ctx, u64 flags);
7754 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7755 	 */
7756 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7757 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7758 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7759 
7760 	/* unused */
7761 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7762 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7763 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7764 
7765 	callee->in_callback_fn = true;
7766 	callee->callback_ret_range = tnum_range(0, 1);
7767 	return 0;
7768 }
7769 
7770 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
7771 					 struct bpf_func_state *caller,
7772 					 struct bpf_func_state *callee,
7773 					 int insn_idx)
7774 {
7775 	/* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
7776 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
7777 	 *
7778 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
7779 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
7780 	 * by this point, so look at 'root'
7781 	 */
7782 	struct btf_field *field;
7783 
7784 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
7785 				      BPF_RB_ROOT);
7786 	if (!field || !field->graph_root.value_btf_id)
7787 		return -EFAULT;
7788 
7789 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
7790 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
7791 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
7792 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
7793 
7794 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7795 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7796 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7797 	callee->in_callback_fn = true;
7798 	callee->callback_ret_range = tnum_range(0, 1);
7799 	return 0;
7800 }
7801 
7802 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
7803 
7804 /* Are we currently verifying the callback for a rbtree helper that must
7805  * be called with lock held? If so, no need to complain about unreleased
7806  * lock
7807  */
7808 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
7809 {
7810 	struct bpf_verifier_state *state = env->cur_state;
7811 	struct bpf_insn *insn = env->prog->insnsi;
7812 	struct bpf_func_state *callee;
7813 	int kfunc_btf_id;
7814 
7815 	if (!state->curframe)
7816 		return false;
7817 
7818 	callee = state->frame[state->curframe];
7819 
7820 	if (!callee->in_callback_fn)
7821 		return false;
7822 
7823 	kfunc_btf_id = insn[callee->callsite].imm;
7824 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
7825 }
7826 
7827 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7828 {
7829 	struct bpf_verifier_state *state = env->cur_state;
7830 	struct bpf_func_state *caller, *callee;
7831 	struct bpf_reg_state *r0;
7832 	int err;
7833 
7834 	callee = state->frame[state->curframe];
7835 	r0 = &callee->regs[BPF_REG_0];
7836 	if (r0->type == PTR_TO_STACK) {
7837 		/* technically it's ok to return caller's stack pointer
7838 		 * (or caller's caller's pointer) back to the caller,
7839 		 * since these pointers are valid. Only current stack
7840 		 * pointer will be invalid as soon as function exits,
7841 		 * but let's be conservative
7842 		 */
7843 		verbose(env, "cannot return stack pointer to the caller\n");
7844 		return -EINVAL;
7845 	}
7846 
7847 	caller = state->frame[state->curframe - 1];
7848 	if (callee->in_callback_fn) {
7849 		/* enforce R0 return value range [0, 1]. */
7850 		struct tnum range = callee->callback_ret_range;
7851 
7852 		if (r0->type != SCALAR_VALUE) {
7853 			verbose(env, "R0 not a scalar value\n");
7854 			return -EACCES;
7855 		}
7856 		if (!tnum_in(range, r0->var_off)) {
7857 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7858 			return -EINVAL;
7859 		}
7860 	} else {
7861 		/* return to the caller whatever r0 had in the callee */
7862 		caller->regs[BPF_REG_0] = *r0;
7863 	}
7864 
7865 	/* callback_fn frame should have released its own additions to parent's
7866 	 * reference state at this point, or check_reference_leak would
7867 	 * complain, hence it must be the same as the caller. There is no need
7868 	 * to copy it back.
7869 	 */
7870 	if (!callee->in_callback_fn) {
7871 		/* Transfer references to the caller */
7872 		err = copy_reference_state(caller, callee);
7873 		if (err)
7874 			return err;
7875 	}
7876 
7877 	*insn_idx = callee->callsite + 1;
7878 	if (env->log.level & BPF_LOG_LEVEL) {
7879 		verbose(env, "returning from callee:\n");
7880 		print_verifier_state(env, callee, true);
7881 		verbose(env, "to caller at %d:\n", *insn_idx);
7882 		print_verifier_state(env, caller, true);
7883 	}
7884 	/* clear everything in the callee */
7885 	free_func_state(callee);
7886 	state->frame[state->curframe--] = NULL;
7887 	return 0;
7888 }
7889 
7890 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7891 				   int func_id,
7892 				   struct bpf_call_arg_meta *meta)
7893 {
7894 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7895 
7896 	if (ret_type != RET_INTEGER ||
7897 	    (func_id != BPF_FUNC_get_stack &&
7898 	     func_id != BPF_FUNC_get_task_stack &&
7899 	     func_id != BPF_FUNC_probe_read_str &&
7900 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7901 	     func_id != BPF_FUNC_probe_read_user_str))
7902 		return;
7903 
7904 	ret_reg->smax_value = meta->msize_max_value;
7905 	ret_reg->s32_max_value = meta->msize_max_value;
7906 	ret_reg->smin_value = -MAX_ERRNO;
7907 	ret_reg->s32_min_value = -MAX_ERRNO;
7908 	reg_bounds_sync(ret_reg);
7909 }
7910 
7911 static int
7912 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7913 		int func_id, int insn_idx)
7914 {
7915 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7916 	struct bpf_map *map = meta->map_ptr;
7917 
7918 	if (func_id != BPF_FUNC_tail_call &&
7919 	    func_id != BPF_FUNC_map_lookup_elem &&
7920 	    func_id != BPF_FUNC_map_update_elem &&
7921 	    func_id != BPF_FUNC_map_delete_elem &&
7922 	    func_id != BPF_FUNC_map_push_elem &&
7923 	    func_id != BPF_FUNC_map_pop_elem &&
7924 	    func_id != BPF_FUNC_map_peek_elem &&
7925 	    func_id != BPF_FUNC_for_each_map_elem &&
7926 	    func_id != BPF_FUNC_redirect_map &&
7927 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7928 		return 0;
7929 
7930 	if (map == NULL) {
7931 		verbose(env, "kernel subsystem misconfigured verifier\n");
7932 		return -EINVAL;
7933 	}
7934 
7935 	/* In case of read-only, some additional restrictions
7936 	 * need to be applied in order to prevent altering the
7937 	 * state of the map from program side.
7938 	 */
7939 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7940 	    (func_id == BPF_FUNC_map_delete_elem ||
7941 	     func_id == BPF_FUNC_map_update_elem ||
7942 	     func_id == BPF_FUNC_map_push_elem ||
7943 	     func_id == BPF_FUNC_map_pop_elem)) {
7944 		verbose(env, "write into map forbidden\n");
7945 		return -EACCES;
7946 	}
7947 
7948 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7949 		bpf_map_ptr_store(aux, meta->map_ptr,
7950 				  !meta->map_ptr->bypass_spec_v1);
7951 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7952 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7953 				  !meta->map_ptr->bypass_spec_v1);
7954 	return 0;
7955 }
7956 
7957 static int
7958 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7959 		int func_id, int insn_idx)
7960 {
7961 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7962 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7963 	struct bpf_map *map = meta->map_ptr;
7964 	u64 val, max;
7965 	int err;
7966 
7967 	if (func_id != BPF_FUNC_tail_call)
7968 		return 0;
7969 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7970 		verbose(env, "kernel subsystem misconfigured verifier\n");
7971 		return -EINVAL;
7972 	}
7973 
7974 	reg = &regs[BPF_REG_3];
7975 	val = reg->var_off.value;
7976 	max = map->max_entries;
7977 
7978 	if (!(register_is_const(reg) && val < max)) {
7979 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7980 		return 0;
7981 	}
7982 
7983 	err = mark_chain_precision(env, BPF_REG_3);
7984 	if (err)
7985 		return err;
7986 	if (bpf_map_key_unseen(aux))
7987 		bpf_map_key_store(aux, val);
7988 	else if (!bpf_map_key_poisoned(aux) &&
7989 		  bpf_map_key_immediate(aux) != val)
7990 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7991 	return 0;
7992 }
7993 
7994 static int check_reference_leak(struct bpf_verifier_env *env)
7995 {
7996 	struct bpf_func_state *state = cur_func(env);
7997 	bool refs_lingering = false;
7998 	int i;
7999 
8000 	if (state->frameno && !state->in_callback_fn)
8001 		return 0;
8002 
8003 	for (i = 0; i < state->acquired_refs; i++) {
8004 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8005 			continue;
8006 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8007 			state->refs[i].id, state->refs[i].insn_idx);
8008 		refs_lingering = true;
8009 	}
8010 	return refs_lingering ? -EINVAL : 0;
8011 }
8012 
8013 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8014 				   struct bpf_reg_state *regs)
8015 {
8016 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8017 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8018 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
8019 	struct bpf_bprintf_data data = {};
8020 	int err, fmt_map_off, num_args;
8021 	u64 fmt_addr;
8022 	char *fmt;
8023 
8024 	/* data must be an array of u64 */
8025 	if (data_len_reg->var_off.value % 8)
8026 		return -EINVAL;
8027 	num_args = data_len_reg->var_off.value / 8;
8028 
8029 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8030 	 * and map_direct_value_addr is set.
8031 	 */
8032 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8033 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8034 						  fmt_map_off);
8035 	if (err) {
8036 		verbose(env, "verifier bug\n");
8037 		return -EFAULT;
8038 	}
8039 	fmt = (char *)(long)fmt_addr + fmt_map_off;
8040 
8041 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8042 	 * can focus on validating the format specifiers.
8043 	 */
8044 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8045 	if (err < 0)
8046 		verbose(env, "Invalid format string\n");
8047 
8048 	return err;
8049 }
8050 
8051 static int check_get_func_ip(struct bpf_verifier_env *env)
8052 {
8053 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8054 	int func_id = BPF_FUNC_get_func_ip;
8055 
8056 	if (type == BPF_PROG_TYPE_TRACING) {
8057 		if (!bpf_prog_has_trampoline(env->prog)) {
8058 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8059 				func_id_name(func_id), func_id);
8060 			return -ENOTSUPP;
8061 		}
8062 		return 0;
8063 	} else if (type == BPF_PROG_TYPE_KPROBE) {
8064 		return 0;
8065 	}
8066 
8067 	verbose(env, "func %s#%d not supported for program type %d\n",
8068 		func_id_name(func_id), func_id, type);
8069 	return -ENOTSUPP;
8070 }
8071 
8072 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8073 {
8074 	return &env->insn_aux_data[env->insn_idx];
8075 }
8076 
8077 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8078 {
8079 	struct bpf_reg_state *regs = cur_regs(env);
8080 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
8081 	bool reg_is_null = register_is_null(reg);
8082 
8083 	if (reg_is_null)
8084 		mark_chain_precision(env, BPF_REG_4);
8085 
8086 	return reg_is_null;
8087 }
8088 
8089 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8090 {
8091 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8092 
8093 	if (!state->initialized) {
8094 		state->initialized = 1;
8095 		state->fit_for_inline = loop_flag_is_zero(env);
8096 		state->callback_subprogno = subprogno;
8097 		return;
8098 	}
8099 
8100 	if (!state->fit_for_inline)
8101 		return;
8102 
8103 	state->fit_for_inline = (loop_flag_is_zero(env) &&
8104 				 state->callback_subprogno == subprogno);
8105 }
8106 
8107 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8108 			     int *insn_idx_p)
8109 {
8110 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8111 	const struct bpf_func_proto *fn = NULL;
8112 	enum bpf_return_type ret_type;
8113 	enum bpf_type_flag ret_flag;
8114 	struct bpf_reg_state *regs;
8115 	struct bpf_call_arg_meta meta;
8116 	int insn_idx = *insn_idx_p;
8117 	bool changes_data;
8118 	int i, err, func_id;
8119 
8120 	/* find function prototype */
8121 	func_id = insn->imm;
8122 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8123 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8124 			func_id);
8125 		return -EINVAL;
8126 	}
8127 
8128 	if (env->ops->get_func_proto)
8129 		fn = env->ops->get_func_proto(func_id, env->prog);
8130 	if (!fn) {
8131 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8132 			func_id);
8133 		return -EINVAL;
8134 	}
8135 
8136 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
8137 	if (!env->prog->gpl_compatible && fn->gpl_only) {
8138 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8139 		return -EINVAL;
8140 	}
8141 
8142 	if (fn->allowed && !fn->allowed(env->prog)) {
8143 		verbose(env, "helper call is not allowed in probe\n");
8144 		return -EINVAL;
8145 	}
8146 
8147 	if (!env->prog->aux->sleepable && fn->might_sleep) {
8148 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
8149 		return -EINVAL;
8150 	}
8151 
8152 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
8153 	changes_data = bpf_helper_changes_pkt_data(fn->func);
8154 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8155 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8156 			func_id_name(func_id), func_id);
8157 		return -EINVAL;
8158 	}
8159 
8160 	memset(&meta, 0, sizeof(meta));
8161 	meta.pkt_access = fn->pkt_access;
8162 
8163 	err = check_func_proto(fn, func_id);
8164 	if (err) {
8165 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8166 			func_id_name(func_id), func_id);
8167 		return err;
8168 	}
8169 
8170 	if (env->cur_state->active_rcu_lock) {
8171 		if (fn->might_sleep) {
8172 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8173 				func_id_name(func_id), func_id);
8174 			return -EINVAL;
8175 		}
8176 
8177 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8178 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8179 	}
8180 
8181 	meta.func_id = func_id;
8182 	/* check args */
8183 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8184 		err = check_func_arg(env, i, &meta, fn);
8185 		if (err)
8186 			return err;
8187 	}
8188 
8189 	err = record_func_map(env, &meta, func_id, insn_idx);
8190 	if (err)
8191 		return err;
8192 
8193 	err = record_func_key(env, &meta, func_id, insn_idx);
8194 	if (err)
8195 		return err;
8196 
8197 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
8198 	 * is inferred from register state.
8199 	 */
8200 	for (i = 0; i < meta.access_size; i++) {
8201 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8202 				       BPF_WRITE, -1, false);
8203 		if (err)
8204 			return err;
8205 	}
8206 
8207 	regs = cur_regs(env);
8208 
8209 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8210 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
8211 	 * is safe to do directly.
8212 	 */
8213 	if (meta.uninit_dynptr_regno) {
8214 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
8215 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
8216 			return -EFAULT;
8217 		}
8218 		/* we write BPF_DW bits (8 bytes) at a time */
8219 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8220 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
8221 					       i, BPF_DW, BPF_WRITE, -1, false);
8222 			if (err)
8223 				return err;
8224 		}
8225 
8226 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
8227 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
8228 					      insn_idx);
8229 		if (err)
8230 			return err;
8231 	}
8232 
8233 	if (meta.release_regno) {
8234 		err = -EINVAL;
8235 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8236 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8237 		 * is safe to do directly.
8238 		 */
8239 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8240 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8241 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8242 				return -EFAULT;
8243 			}
8244 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8245 		} else if (meta.ref_obj_id) {
8246 			err = release_reference(env, meta.ref_obj_id);
8247 		} else if (register_is_null(&regs[meta.release_regno])) {
8248 			/* meta.ref_obj_id can only be 0 if register that is meant to be
8249 			 * released is NULL, which must be > R0.
8250 			 */
8251 			err = 0;
8252 		}
8253 		if (err) {
8254 			verbose(env, "func %s#%d reference has not been acquired before\n",
8255 				func_id_name(func_id), func_id);
8256 			return err;
8257 		}
8258 	}
8259 
8260 	switch (func_id) {
8261 	case BPF_FUNC_tail_call:
8262 		err = check_reference_leak(env);
8263 		if (err) {
8264 			verbose(env, "tail_call would lead to reference leak\n");
8265 			return err;
8266 		}
8267 		break;
8268 	case BPF_FUNC_get_local_storage:
8269 		/* check that flags argument in get_local_storage(map, flags) is 0,
8270 		 * this is required because get_local_storage() can't return an error.
8271 		 */
8272 		if (!register_is_null(&regs[BPF_REG_2])) {
8273 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8274 			return -EINVAL;
8275 		}
8276 		break;
8277 	case BPF_FUNC_for_each_map_elem:
8278 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8279 					set_map_elem_callback_state);
8280 		break;
8281 	case BPF_FUNC_timer_set_callback:
8282 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8283 					set_timer_callback_state);
8284 		break;
8285 	case BPF_FUNC_find_vma:
8286 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8287 					set_find_vma_callback_state);
8288 		break;
8289 	case BPF_FUNC_snprintf:
8290 		err = check_bpf_snprintf_call(env, regs);
8291 		break;
8292 	case BPF_FUNC_loop:
8293 		update_loop_inline_state(env, meta.subprogno);
8294 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8295 					set_loop_callback_state);
8296 		break;
8297 	case BPF_FUNC_dynptr_from_mem:
8298 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8299 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8300 				reg_type_str(env, regs[BPF_REG_1].type));
8301 			return -EACCES;
8302 		}
8303 		break;
8304 	case BPF_FUNC_set_retval:
8305 		if (prog_type == BPF_PROG_TYPE_LSM &&
8306 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8307 			if (!env->prog->aux->attach_func_proto->type) {
8308 				/* Make sure programs that attach to void
8309 				 * hooks don't try to modify return value.
8310 				 */
8311 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8312 				return -EINVAL;
8313 			}
8314 		}
8315 		break;
8316 	case BPF_FUNC_dynptr_data:
8317 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8318 			if (arg_type_is_dynptr(fn->arg_type[i])) {
8319 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
8320 				int id, ref_obj_id;
8321 
8322 				if (meta.dynptr_id) {
8323 					verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8324 					return -EFAULT;
8325 				}
8326 
8327 				if (meta.ref_obj_id) {
8328 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8329 					return -EFAULT;
8330 				}
8331 
8332 				id = dynptr_id(env, reg);
8333 				if (id < 0) {
8334 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8335 					return id;
8336 				}
8337 
8338 				ref_obj_id = dynptr_ref_obj_id(env, reg);
8339 				if (ref_obj_id < 0) {
8340 					verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8341 					return ref_obj_id;
8342 				}
8343 
8344 				meta.dynptr_id = id;
8345 				meta.ref_obj_id = ref_obj_id;
8346 				break;
8347 			}
8348 		}
8349 		if (i == MAX_BPF_FUNC_REG_ARGS) {
8350 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
8351 			return -EFAULT;
8352 		}
8353 		break;
8354 	case BPF_FUNC_user_ringbuf_drain:
8355 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8356 					set_user_ringbuf_callback_state);
8357 		break;
8358 	}
8359 
8360 	if (err)
8361 		return err;
8362 
8363 	/* reset caller saved regs */
8364 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8365 		mark_reg_not_init(env, regs, caller_saved[i]);
8366 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8367 	}
8368 
8369 	/* helper call returns 64-bit value. */
8370 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8371 
8372 	/* update return register (already marked as written above) */
8373 	ret_type = fn->ret_type;
8374 	ret_flag = type_flag(ret_type);
8375 
8376 	switch (base_type(ret_type)) {
8377 	case RET_INTEGER:
8378 		/* sets type to SCALAR_VALUE */
8379 		mark_reg_unknown(env, regs, BPF_REG_0);
8380 		break;
8381 	case RET_VOID:
8382 		regs[BPF_REG_0].type = NOT_INIT;
8383 		break;
8384 	case RET_PTR_TO_MAP_VALUE:
8385 		/* There is no offset yet applied, variable or fixed */
8386 		mark_reg_known_zero(env, regs, BPF_REG_0);
8387 		/* remember map_ptr, so that check_map_access()
8388 		 * can check 'value_size' boundary of memory access
8389 		 * to map element returned from bpf_map_lookup_elem()
8390 		 */
8391 		if (meta.map_ptr == NULL) {
8392 			verbose(env,
8393 				"kernel subsystem misconfigured verifier\n");
8394 			return -EINVAL;
8395 		}
8396 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
8397 		regs[BPF_REG_0].map_uid = meta.map_uid;
8398 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8399 		if (!type_may_be_null(ret_type) &&
8400 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8401 			regs[BPF_REG_0].id = ++env->id_gen;
8402 		}
8403 		break;
8404 	case RET_PTR_TO_SOCKET:
8405 		mark_reg_known_zero(env, regs, BPF_REG_0);
8406 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8407 		break;
8408 	case RET_PTR_TO_SOCK_COMMON:
8409 		mark_reg_known_zero(env, regs, BPF_REG_0);
8410 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8411 		break;
8412 	case RET_PTR_TO_TCP_SOCK:
8413 		mark_reg_known_zero(env, regs, BPF_REG_0);
8414 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8415 		break;
8416 	case RET_PTR_TO_MEM:
8417 		mark_reg_known_zero(env, regs, BPF_REG_0);
8418 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8419 		regs[BPF_REG_0].mem_size = meta.mem_size;
8420 		break;
8421 	case RET_PTR_TO_MEM_OR_BTF_ID:
8422 	{
8423 		const struct btf_type *t;
8424 
8425 		mark_reg_known_zero(env, regs, BPF_REG_0);
8426 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8427 		if (!btf_type_is_struct(t)) {
8428 			u32 tsize;
8429 			const struct btf_type *ret;
8430 			const char *tname;
8431 
8432 			/* resolve the type size of ksym. */
8433 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8434 			if (IS_ERR(ret)) {
8435 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8436 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8437 					tname, PTR_ERR(ret));
8438 				return -EINVAL;
8439 			}
8440 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8441 			regs[BPF_REG_0].mem_size = tsize;
8442 		} else {
8443 			/* MEM_RDONLY may be carried from ret_flag, but it
8444 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8445 			 * it will confuse the check of PTR_TO_BTF_ID in
8446 			 * check_mem_access().
8447 			 */
8448 			ret_flag &= ~MEM_RDONLY;
8449 
8450 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8451 			regs[BPF_REG_0].btf = meta.ret_btf;
8452 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8453 		}
8454 		break;
8455 	}
8456 	case RET_PTR_TO_BTF_ID:
8457 	{
8458 		struct btf *ret_btf;
8459 		int ret_btf_id;
8460 
8461 		mark_reg_known_zero(env, regs, BPF_REG_0);
8462 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8463 		if (func_id == BPF_FUNC_kptr_xchg) {
8464 			ret_btf = meta.kptr_field->kptr.btf;
8465 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8466 		} else {
8467 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8468 				verbose(env, "verifier internal error:");
8469 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8470 					func_id_name(func_id));
8471 				return -EINVAL;
8472 			}
8473 			ret_btf = btf_vmlinux;
8474 			ret_btf_id = *fn->ret_btf_id;
8475 		}
8476 		if (ret_btf_id == 0) {
8477 			verbose(env, "invalid return type %u of func %s#%d\n",
8478 				base_type(ret_type), func_id_name(func_id),
8479 				func_id);
8480 			return -EINVAL;
8481 		}
8482 		regs[BPF_REG_0].btf = ret_btf;
8483 		regs[BPF_REG_0].btf_id = ret_btf_id;
8484 		break;
8485 	}
8486 	default:
8487 		verbose(env, "unknown return type %u of func %s#%d\n",
8488 			base_type(ret_type), func_id_name(func_id), func_id);
8489 		return -EINVAL;
8490 	}
8491 
8492 	if (type_may_be_null(regs[BPF_REG_0].type))
8493 		regs[BPF_REG_0].id = ++env->id_gen;
8494 
8495 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8496 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8497 			func_id_name(func_id), func_id);
8498 		return -EFAULT;
8499 	}
8500 
8501 	if (is_dynptr_ref_function(func_id))
8502 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8503 
8504 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8505 		/* For release_reference() */
8506 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8507 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8508 		int id = acquire_reference_state(env, insn_idx);
8509 
8510 		if (id < 0)
8511 			return id;
8512 		/* For mark_ptr_or_null_reg() */
8513 		regs[BPF_REG_0].id = id;
8514 		/* For release_reference() */
8515 		regs[BPF_REG_0].ref_obj_id = id;
8516 	}
8517 
8518 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8519 
8520 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8521 	if (err)
8522 		return err;
8523 
8524 	if ((func_id == BPF_FUNC_get_stack ||
8525 	     func_id == BPF_FUNC_get_task_stack) &&
8526 	    !env->prog->has_callchain_buf) {
8527 		const char *err_str;
8528 
8529 #ifdef CONFIG_PERF_EVENTS
8530 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8531 		err_str = "cannot get callchain buffer for func %s#%d\n";
8532 #else
8533 		err = -ENOTSUPP;
8534 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8535 #endif
8536 		if (err) {
8537 			verbose(env, err_str, func_id_name(func_id), func_id);
8538 			return err;
8539 		}
8540 
8541 		env->prog->has_callchain_buf = true;
8542 	}
8543 
8544 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8545 		env->prog->call_get_stack = true;
8546 
8547 	if (func_id == BPF_FUNC_get_func_ip) {
8548 		if (check_get_func_ip(env))
8549 			return -ENOTSUPP;
8550 		env->prog->call_get_func_ip = true;
8551 	}
8552 
8553 	if (changes_data)
8554 		clear_all_pkt_pointers(env);
8555 	return 0;
8556 }
8557 
8558 /* mark_btf_func_reg_size() is used when the reg size is determined by
8559  * the BTF func_proto's return value size and argument.
8560  */
8561 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8562 				   size_t reg_size)
8563 {
8564 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8565 
8566 	if (regno == BPF_REG_0) {
8567 		/* Function return value */
8568 		reg->live |= REG_LIVE_WRITTEN;
8569 		reg->subreg_def = reg_size == sizeof(u64) ?
8570 			DEF_NOT_SUBREG : env->insn_idx + 1;
8571 	} else {
8572 		/* Function argument */
8573 		if (reg_size == sizeof(u64)) {
8574 			mark_insn_zext(env, reg);
8575 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8576 		} else {
8577 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8578 		}
8579 	}
8580 }
8581 
8582 struct bpf_kfunc_call_arg_meta {
8583 	/* In parameters */
8584 	struct btf *btf;
8585 	u32 func_id;
8586 	u32 kfunc_flags;
8587 	const struct btf_type *func_proto;
8588 	const char *func_name;
8589 	/* Out parameters */
8590 	u32 ref_obj_id;
8591 	u8 release_regno;
8592 	bool r0_rdonly;
8593 	u32 ret_btf_id;
8594 	u64 r0_size;
8595 	u32 subprogno;
8596 	struct {
8597 		u64 value;
8598 		bool found;
8599 	} arg_constant;
8600 	struct {
8601 		struct btf *btf;
8602 		u32 btf_id;
8603 	} arg_obj_drop;
8604 	struct {
8605 		struct btf_field *field;
8606 	} arg_list_head;
8607 	struct {
8608 		struct btf_field *field;
8609 	} arg_rbtree_root;
8610 };
8611 
8612 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8613 {
8614 	return meta->kfunc_flags & KF_ACQUIRE;
8615 }
8616 
8617 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8618 {
8619 	return meta->kfunc_flags & KF_RET_NULL;
8620 }
8621 
8622 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8623 {
8624 	return meta->kfunc_flags & KF_RELEASE;
8625 }
8626 
8627 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8628 {
8629 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8630 }
8631 
8632 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8633 {
8634 	return meta->kfunc_flags & KF_SLEEPABLE;
8635 }
8636 
8637 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8638 {
8639 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8640 }
8641 
8642 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8643 {
8644 	return meta->kfunc_flags & KF_RCU;
8645 }
8646 
8647 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8648 {
8649 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8650 }
8651 
8652 static bool __kfunc_param_match_suffix(const struct btf *btf,
8653 				       const struct btf_param *arg,
8654 				       const char *suffix)
8655 {
8656 	int suffix_len = strlen(suffix), len;
8657 	const char *param_name;
8658 
8659 	/* In the future, this can be ported to use BTF tagging */
8660 	param_name = btf_name_by_offset(btf, arg->name_off);
8661 	if (str_is_empty(param_name))
8662 		return false;
8663 	len = strlen(param_name);
8664 	if (len < suffix_len)
8665 		return false;
8666 	param_name += len - suffix_len;
8667 	return !strncmp(param_name, suffix, suffix_len);
8668 }
8669 
8670 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8671 				  const struct btf_param *arg,
8672 				  const struct bpf_reg_state *reg)
8673 {
8674 	const struct btf_type *t;
8675 
8676 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8677 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8678 		return false;
8679 
8680 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8681 }
8682 
8683 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8684 {
8685 	return __kfunc_param_match_suffix(btf, arg, "__k");
8686 }
8687 
8688 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8689 {
8690 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8691 }
8692 
8693 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8694 {
8695 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8696 }
8697 
8698 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8699 					  const struct btf_param *arg,
8700 					  const char *name)
8701 {
8702 	int len, target_len = strlen(name);
8703 	const char *param_name;
8704 
8705 	param_name = btf_name_by_offset(btf, arg->name_off);
8706 	if (str_is_empty(param_name))
8707 		return false;
8708 	len = strlen(param_name);
8709 	if (len != target_len)
8710 		return false;
8711 	if (strcmp(param_name, name))
8712 		return false;
8713 
8714 	return true;
8715 }
8716 
8717 enum {
8718 	KF_ARG_DYNPTR_ID,
8719 	KF_ARG_LIST_HEAD_ID,
8720 	KF_ARG_LIST_NODE_ID,
8721 	KF_ARG_RB_ROOT_ID,
8722 	KF_ARG_RB_NODE_ID,
8723 };
8724 
8725 BTF_ID_LIST(kf_arg_btf_ids)
8726 BTF_ID(struct, bpf_dynptr_kern)
8727 BTF_ID(struct, bpf_list_head)
8728 BTF_ID(struct, bpf_list_node)
8729 BTF_ID(struct, bpf_rb_root)
8730 BTF_ID(struct, bpf_rb_node)
8731 
8732 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8733 				    const struct btf_param *arg, int type)
8734 {
8735 	const struct btf_type *t;
8736 	u32 res_id;
8737 
8738 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8739 	if (!t)
8740 		return false;
8741 	if (!btf_type_is_ptr(t))
8742 		return false;
8743 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8744 	if (!t)
8745 		return false;
8746 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8747 }
8748 
8749 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8750 {
8751 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8752 }
8753 
8754 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8755 {
8756 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8757 }
8758 
8759 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8760 {
8761 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8762 }
8763 
8764 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
8765 {
8766 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
8767 }
8768 
8769 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
8770 {
8771 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
8772 }
8773 
8774 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
8775 				  const struct btf_param *arg)
8776 {
8777 	const struct btf_type *t;
8778 
8779 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
8780 	if (!t)
8781 		return false;
8782 
8783 	return true;
8784 }
8785 
8786 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8787 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8788 					const struct btf *btf,
8789 					const struct btf_type *t, int rec)
8790 {
8791 	const struct btf_type *member_type;
8792 	const struct btf_member *member;
8793 	u32 i;
8794 
8795 	if (!btf_type_is_struct(t))
8796 		return false;
8797 
8798 	for_each_member(i, t, member) {
8799 		const struct btf_array *array;
8800 
8801 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8802 		if (btf_type_is_struct(member_type)) {
8803 			if (rec >= 3) {
8804 				verbose(env, "max struct nesting depth exceeded\n");
8805 				return false;
8806 			}
8807 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8808 				return false;
8809 			continue;
8810 		}
8811 		if (btf_type_is_array(member_type)) {
8812 			array = btf_array(member_type);
8813 			if (!array->nelems)
8814 				return false;
8815 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8816 			if (!btf_type_is_scalar(member_type))
8817 				return false;
8818 			continue;
8819 		}
8820 		if (!btf_type_is_scalar(member_type))
8821 			return false;
8822 	}
8823 	return true;
8824 }
8825 
8826 
8827 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8828 #ifdef CONFIG_NET
8829 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8830 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8831 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8832 #endif
8833 };
8834 
8835 enum kfunc_ptr_arg_type {
8836 	KF_ARG_PTR_TO_CTX,
8837 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8838 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8839 	KF_ARG_PTR_TO_DYNPTR,
8840 	KF_ARG_PTR_TO_LIST_HEAD,
8841 	KF_ARG_PTR_TO_LIST_NODE,
8842 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8843 	KF_ARG_PTR_TO_MEM,
8844 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8845 	KF_ARG_PTR_TO_CALLBACK,
8846 	KF_ARG_PTR_TO_RB_ROOT,
8847 	KF_ARG_PTR_TO_RB_NODE,
8848 };
8849 
8850 enum special_kfunc_type {
8851 	KF_bpf_obj_new_impl,
8852 	KF_bpf_obj_drop_impl,
8853 	KF_bpf_list_push_front,
8854 	KF_bpf_list_push_back,
8855 	KF_bpf_list_pop_front,
8856 	KF_bpf_list_pop_back,
8857 	KF_bpf_cast_to_kern_ctx,
8858 	KF_bpf_rdonly_cast,
8859 	KF_bpf_rcu_read_lock,
8860 	KF_bpf_rcu_read_unlock,
8861 	KF_bpf_rbtree_remove,
8862 	KF_bpf_rbtree_add,
8863 	KF_bpf_rbtree_first,
8864 };
8865 
8866 BTF_SET_START(special_kfunc_set)
8867 BTF_ID(func, bpf_obj_new_impl)
8868 BTF_ID(func, bpf_obj_drop_impl)
8869 BTF_ID(func, bpf_list_push_front)
8870 BTF_ID(func, bpf_list_push_back)
8871 BTF_ID(func, bpf_list_pop_front)
8872 BTF_ID(func, bpf_list_pop_back)
8873 BTF_ID(func, bpf_cast_to_kern_ctx)
8874 BTF_ID(func, bpf_rdonly_cast)
8875 BTF_ID(func, bpf_rbtree_remove)
8876 BTF_ID(func, bpf_rbtree_add)
8877 BTF_ID(func, bpf_rbtree_first)
8878 BTF_SET_END(special_kfunc_set)
8879 
8880 BTF_ID_LIST(special_kfunc_list)
8881 BTF_ID(func, bpf_obj_new_impl)
8882 BTF_ID(func, bpf_obj_drop_impl)
8883 BTF_ID(func, bpf_list_push_front)
8884 BTF_ID(func, bpf_list_push_back)
8885 BTF_ID(func, bpf_list_pop_front)
8886 BTF_ID(func, bpf_list_pop_back)
8887 BTF_ID(func, bpf_cast_to_kern_ctx)
8888 BTF_ID(func, bpf_rdonly_cast)
8889 BTF_ID(func, bpf_rcu_read_lock)
8890 BTF_ID(func, bpf_rcu_read_unlock)
8891 BTF_ID(func, bpf_rbtree_remove)
8892 BTF_ID(func, bpf_rbtree_add)
8893 BTF_ID(func, bpf_rbtree_first)
8894 
8895 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8896 {
8897 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8898 }
8899 
8900 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8901 {
8902 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8903 }
8904 
8905 static enum kfunc_ptr_arg_type
8906 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8907 		       struct bpf_kfunc_call_arg_meta *meta,
8908 		       const struct btf_type *t, const struct btf_type *ref_t,
8909 		       const char *ref_tname, const struct btf_param *args,
8910 		       int argno, int nargs)
8911 {
8912 	u32 regno = argno + 1;
8913 	struct bpf_reg_state *regs = cur_regs(env);
8914 	struct bpf_reg_state *reg = &regs[regno];
8915 	bool arg_mem_size = false;
8916 
8917 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8918 		return KF_ARG_PTR_TO_CTX;
8919 
8920 	/* In this function, we verify the kfunc's BTF as per the argument type,
8921 	 * leaving the rest of the verification with respect to the register
8922 	 * type to our caller. When a set of conditions hold in the BTF type of
8923 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8924 	 */
8925 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8926 		return KF_ARG_PTR_TO_CTX;
8927 
8928 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8929 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8930 
8931 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8932 		if (!btf_type_is_ptr(ref_t)) {
8933 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8934 			return -EINVAL;
8935 		}
8936 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8937 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8938 		if (!btf_type_is_struct(ref_t)) {
8939 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8940 				meta->func_name, btf_type_str(ref_t), ref_tname);
8941 			return -EINVAL;
8942 		}
8943 		return KF_ARG_PTR_TO_KPTR;
8944 	}
8945 
8946 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8947 		return KF_ARG_PTR_TO_DYNPTR;
8948 
8949 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8950 		return KF_ARG_PTR_TO_LIST_HEAD;
8951 
8952 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8953 		return KF_ARG_PTR_TO_LIST_NODE;
8954 
8955 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
8956 		return KF_ARG_PTR_TO_RB_ROOT;
8957 
8958 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
8959 		return KF_ARG_PTR_TO_RB_NODE;
8960 
8961 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8962 		if (!btf_type_is_struct(ref_t)) {
8963 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8964 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8965 			return -EINVAL;
8966 		}
8967 		return KF_ARG_PTR_TO_BTF_ID;
8968 	}
8969 
8970 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
8971 		return KF_ARG_PTR_TO_CALLBACK;
8972 
8973 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8974 		arg_mem_size = true;
8975 
8976 	/* This is the catch all argument type of register types supported by
8977 	 * check_helper_mem_access. However, we only allow when argument type is
8978 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8979 	 * arg_mem_size is true, the pointer can be void *.
8980 	 */
8981 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8982 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8983 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8984 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8985 		return -EINVAL;
8986 	}
8987 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8988 }
8989 
8990 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8991 					struct bpf_reg_state *reg,
8992 					const struct btf_type *ref_t,
8993 					const char *ref_tname, u32 ref_id,
8994 					struct bpf_kfunc_call_arg_meta *meta,
8995 					int argno)
8996 {
8997 	const struct btf_type *reg_ref_t;
8998 	bool strict_type_match = false;
8999 	const struct btf *reg_btf;
9000 	const char *reg_ref_tname;
9001 	u32 reg_ref_id;
9002 
9003 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
9004 		reg_btf = reg->btf;
9005 		reg_ref_id = reg->btf_id;
9006 	} else {
9007 		reg_btf = btf_vmlinux;
9008 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9009 	}
9010 
9011 	/* Enforce strict type matching for calls to kfuncs that are acquiring
9012 	 * or releasing a reference, or are no-cast aliases. We do _not_
9013 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9014 	 * as we want to enable BPF programs to pass types that are bitwise
9015 	 * equivalent without forcing them to explicitly cast with something
9016 	 * like bpf_cast_to_kern_ctx().
9017 	 *
9018 	 * For example, say we had a type like the following:
9019 	 *
9020 	 * struct bpf_cpumask {
9021 	 *	cpumask_t cpumask;
9022 	 *	refcount_t usage;
9023 	 * };
9024 	 *
9025 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9026 	 * to a struct cpumask, so it would be safe to pass a struct
9027 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9028 	 *
9029 	 * The philosophy here is similar to how we allow scalars of different
9030 	 * types to be passed to kfuncs as long as the size is the same. The
9031 	 * only difference here is that we're simply allowing
9032 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9033 	 * resolve types.
9034 	 */
9035 	if (is_kfunc_acquire(meta) ||
9036 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
9037 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9038 		strict_type_match = true;
9039 
9040 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9041 
9042 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9043 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9044 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9045 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9046 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9047 			btf_type_str(reg_ref_t), reg_ref_tname);
9048 		return -EINVAL;
9049 	}
9050 	return 0;
9051 }
9052 
9053 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9054 				      struct bpf_reg_state *reg,
9055 				      const struct btf_type *ref_t,
9056 				      const char *ref_tname,
9057 				      struct bpf_kfunc_call_arg_meta *meta,
9058 				      int argno)
9059 {
9060 	struct btf_field *kptr_field;
9061 
9062 	/* check_func_arg_reg_off allows var_off for
9063 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9064 	 * off_desc.
9065 	 */
9066 	if (!tnum_is_const(reg->var_off)) {
9067 		verbose(env, "arg#0 must have constant offset\n");
9068 		return -EINVAL;
9069 	}
9070 
9071 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9072 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9073 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9074 			reg->off + reg->var_off.value);
9075 		return -EINVAL;
9076 	}
9077 
9078 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9079 				  kptr_field->kptr.btf_id, true)) {
9080 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9081 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9082 		return -EINVAL;
9083 	}
9084 	return 0;
9085 }
9086 
9087 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9088 {
9089 	struct bpf_verifier_state *state = env->cur_state;
9090 
9091 	if (!state->active_lock.ptr) {
9092 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9093 		return -EFAULT;
9094 	}
9095 
9096 	if (type_flag(reg->type) & NON_OWN_REF) {
9097 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9098 		return -EFAULT;
9099 	}
9100 
9101 	reg->type |= NON_OWN_REF;
9102 	return 0;
9103 }
9104 
9105 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9106 {
9107 	struct bpf_func_state *state, *unused;
9108 	struct bpf_reg_state *reg;
9109 	int i;
9110 
9111 	state = cur_func(env);
9112 
9113 	if (!ref_obj_id) {
9114 		verbose(env, "verifier internal error: ref_obj_id is zero for "
9115 			     "owning -> non-owning conversion\n");
9116 		return -EFAULT;
9117 	}
9118 
9119 	for (i = 0; i < state->acquired_refs; i++) {
9120 		if (state->refs[i].id != ref_obj_id)
9121 			continue;
9122 
9123 		/* Clear ref_obj_id here so release_reference doesn't clobber
9124 		 * the whole reg
9125 		 */
9126 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9127 			if (reg->ref_obj_id == ref_obj_id) {
9128 				reg->ref_obj_id = 0;
9129 				ref_set_non_owning(env, reg);
9130 			}
9131 		}));
9132 		return 0;
9133 	}
9134 
9135 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9136 	return -EFAULT;
9137 }
9138 
9139 /* Implementation details:
9140  *
9141  * Each register points to some region of memory, which we define as an
9142  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9143  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9144  * allocation. The lock and the data it protects are colocated in the same
9145  * memory region.
9146  *
9147  * Hence, everytime a register holds a pointer value pointing to such
9148  * allocation, the verifier preserves a unique reg->id for it.
9149  *
9150  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9151  * bpf_spin_lock is called.
9152  *
9153  * To enable this, lock state in the verifier captures two values:
9154  *	active_lock.ptr = Register's type specific pointer
9155  *	active_lock.id  = A unique ID for each register pointer value
9156  *
9157  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9158  * supported register types.
9159  *
9160  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9161  * allocated objects is the reg->btf pointer.
9162  *
9163  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9164  * can establish the provenance of the map value statically for each distinct
9165  * lookup into such maps. They always contain a single map value hence unique
9166  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9167  *
9168  * So, in case of global variables, they use array maps with max_entries = 1,
9169  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9170  * into the same map value as max_entries is 1, as described above).
9171  *
9172  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9173  * outer map pointer (in verifier context), but each lookup into an inner map
9174  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9175  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9176  * will get different reg->id assigned to each lookup, hence different
9177  * active_lock.id.
9178  *
9179  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9180  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9181  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9182  */
9183 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9184 {
9185 	void *ptr;
9186 	u32 id;
9187 
9188 	switch ((int)reg->type) {
9189 	case PTR_TO_MAP_VALUE:
9190 		ptr = reg->map_ptr;
9191 		break;
9192 	case PTR_TO_BTF_ID | MEM_ALLOC:
9193 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
9194 		ptr = reg->btf;
9195 		break;
9196 	default:
9197 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
9198 		return -EFAULT;
9199 	}
9200 	id = reg->id;
9201 
9202 	if (!env->cur_state->active_lock.ptr)
9203 		return -EINVAL;
9204 	if (env->cur_state->active_lock.ptr != ptr ||
9205 	    env->cur_state->active_lock.id != id) {
9206 		verbose(env, "held lock and object are not in the same allocation\n");
9207 		return -EINVAL;
9208 	}
9209 	return 0;
9210 }
9211 
9212 static bool is_bpf_list_api_kfunc(u32 btf_id)
9213 {
9214 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9215 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9216 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9217 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9218 }
9219 
9220 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9221 {
9222 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9223 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9224 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9225 }
9226 
9227 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9228 {
9229 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9230 }
9231 
9232 static bool is_callback_calling_kfunc(u32 btf_id)
9233 {
9234 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9235 }
9236 
9237 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9238 {
9239 	return is_bpf_rbtree_api_kfunc(btf_id);
9240 }
9241 
9242 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9243 					  enum btf_field_type head_field_type,
9244 					  u32 kfunc_btf_id)
9245 {
9246 	bool ret;
9247 
9248 	switch (head_field_type) {
9249 	case BPF_LIST_HEAD:
9250 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9251 		break;
9252 	case BPF_RB_ROOT:
9253 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9254 		break;
9255 	default:
9256 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9257 			btf_field_type_name(head_field_type));
9258 		return false;
9259 	}
9260 
9261 	if (!ret)
9262 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9263 			btf_field_type_name(head_field_type));
9264 	return ret;
9265 }
9266 
9267 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9268 					  enum btf_field_type node_field_type,
9269 					  u32 kfunc_btf_id)
9270 {
9271 	bool ret;
9272 
9273 	switch (node_field_type) {
9274 	case BPF_LIST_NODE:
9275 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9276 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9277 		break;
9278 	case BPF_RB_NODE:
9279 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9280 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9281 		break;
9282 	default:
9283 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9284 			btf_field_type_name(node_field_type));
9285 		return false;
9286 	}
9287 
9288 	if (!ret)
9289 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9290 			btf_field_type_name(node_field_type));
9291 	return ret;
9292 }
9293 
9294 static int
9295 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9296 				   struct bpf_reg_state *reg, u32 regno,
9297 				   struct bpf_kfunc_call_arg_meta *meta,
9298 				   enum btf_field_type head_field_type,
9299 				   struct btf_field **head_field)
9300 {
9301 	const char *head_type_name;
9302 	struct btf_field *field;
9303 	struct btf_record *rec;
9304 	u32 head_off;
9305 
9306 	if (meta->btf != btf_vmlinux) {
9307 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9308 		return -EFAULT;
9309 	}
9310 
9311 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9312 		return -EFAULT;
9313 
9314 	head_type_name = btf_field_type_name(head_field_type);
9315 	if (!tnum_is_const(reg->var_off)) {
9316 		verbose(env,
9317 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9318 			regno, head_type_name);
9319 		return -EINVAL;
9320 	}
9321 
9322 	rec = reg_btf_record(reg);
9323 	head_off = reg->off + reg->var_off.value;
9324 	field = btf_record_find(rec, head_off, head_field_type);
9325 	if (!field) {
9326 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9327 		return -EINVAL;
9328 	}
9329 
9330 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9331 	if (check_reg_allocation_locked(env, reg)) {
9332 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9333 			rec->spin_lock_off, head_type_name);
9334 		return -EINVAL;
9335 	}
9336 
9337 	if (*head_field) {
9338 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9339 		return -EFAULT;
9340 	}
9341 	*head_field = field;
9342 	return 0;
9343 }
9344 
9345 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9346 					   struct bpf_reg_state *reg, u32 regno,
9347 					   struct bpf_kfunc_call_arg_meta *meta)
9348 {
9349 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9350 							  &meta->arg_list_head.field);
9351 }
9352 
9353 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9354 					     struct bpf_reg_state *reg, u32 regno,
9355 					     struct bpf_kfunc_call_arg_meta *meta)
9356 {
9357 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9358 							  &meta->arg_rbtree_root.field);
9359 }
9360 
9361 static int
9362 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9363 				   struct bpf_reg_state *reg, u32 regno,
9364 				   struct bpf_kfunc_call_arg_meta *meta,
9365 				   enum btf_field_type head_field_type,
9366 				   enum btf_field_type node_field_type,
9367 				   struct btf_field **node_field)
9368 {
9369 	const char *node_type_name;
9370 	const struct btf_type *et, *t;
9371 	struct btf_field *field;
9372 	u32 node_off;
9373 
9374 	if (meta->btf != btf_vmlinux) {
9375 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9376 		return -EFAULT;
9377 	}
9378 
9379 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9380 		return -EFAULT;
9381 
9382 	node_type_name = btf_field_type_name(node_field_type);
9383 	if (!tnum_is_const(reg->var_off)) {
9384 		verbose(env,
9385 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9386 			regno, node_type_name);
9387 		return -EINVAL;
9388 	}
9389 
9390 	node_off = reg->off + reg->var_off.value;
9391 	field = reg_find_field_offset(reg, node_off, node_field_type);
9392 	if (!field || field->offset != node_off) {
9393 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9394 		return -EINVAL;
9395 	}
9396 
9397 	field = *node_field;
9398 
9399 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9400 	t = btf_type_by_id(reg->btf, reg->btf_id);
9401 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9402 				  field->graph_root.value_btf_id, true)) {
9403 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9404 			"in struct %s, but arg is at offset=%d in struct %s\n",
9405 			btf_field_type_name(head_field_type),
9406 			btf_field_type_name(node_field_type),
9407 			field->graph_root.node_offset,
9408 			btf_name_by_offset(field->graph_root.btf, et->name_off),
9409 			node_off, btf_name_by_offset(reg->btf, t->name_off));
9410 		return -EINVAL;
9411 	}
9412 
9413 	if (node_off != field->graph_root.node_offset) {
9414 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9415 			node_off, btf_field_type_name(node_field_type),
9416 			field->graph_root.node_offset,
9417 			btf_name_by_offset(field->graph_root.btf, et->name_off));
9418 		return -EINVAL;
9419 	}
9420 
9421 	return 0;
9422 }
9423 
9424 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9425 					   struct bpf_reg_state *reg, u32 regno,
9426 					   struct bpf_kfunc_call_arg_meta *meta)
9427 {
9428 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9429 						  BPF_LIST_HEAD, BPF_LIST_NODE,
9430 						  &meta->arg_list_head.field);
9431 }
9432 
9433 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9434 					     struct bpf_reg_state *reg, u32 regno,
9435 					     struct bpf_kfunc_call_arg_meta *meta)
9436 {
9437 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9438 						  BPF_RB_ROOT, BPF_RB_NODE,
9439 						  &meta->arg_rbtree_root.field);
9440 }
9441 
9442 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
9443 {
9444 	const char *func_name = meta->func_name, *ref_tname;
9445 	const struct btf *btf = meta->btf;
9446 	const struct btf_param *args;
9447 	u32 i, nargs;
9448 	int ret;
9449 
9450 	args = (const struct btf_param *)(meta->func_proto + 1);
9451 	nargs = btf_type_vlen(meta->func_proto);
9452 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9453 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9454 			MAX_BPF_FUNC_REG_ARGS);
9455 		return -EINVAL;
9456 	}
9457 
9458 	/* Check that BTF function arguments match actual types that the
9459 	 * verifier sees.
9460 	 */
9461 	for (i = 0; i < nargs; i++) {
9462 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9463 		const struct btf_type *t, *ref_t, *resolve_ret;
9464 		enum bpf_arg_type arg_type = ARG_DONTCARE;
9465 		u32 regno = i + 1, ref_id, type_size;
9466 		bool is_ret_buf_sz = false;
9467 		int kf_arg_type;
9468 
9469 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9470 
9471 		if (is_kfunc_arg_ignore(btf, &args[i]))
9472 			continue;
9473 
9474 		if (btf_type_is_scalar(t)) {
9475 			if (reg->type != SCALAR_VALUE) {
9476 				verbose(env, "R%d is not a scalar\n", regno);
9477 				return -EINVAL;
9478 			}
9479 
9480 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9481 				if (meta->arg_constant.found) {
9482 					verbose(env, "verifier internal error: only one constant argument permitted\n");
9483 					return -EFAULT;
9484 				}
9485 				if (!tnum_is_const(reg->var_off)) {
9486 					verbose(env, "R%d must be a known constant\n", regno);
9487 					return -EINVAL;
9488 				}
9489 				ret = mark_chain_precision(env, regno);
9490 				if (ret < 0)
9491 					return ret;
9492 				meta->arg_constant.found = true;
9493 				meta->arg_constant.value = reg->var_off.value;
9494 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9495 				meta->r0_rdonly = true;
9496 				is_ret_buf_sz = true;
9497 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9498 				is_ret_buf_sz = true;
9499 			}
9500 
9501 			if (is_ret_buf_sz) {
9502 				if (meta->r0_size) {
9503 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9504 					return -EINVAL;
9505 				}
9506 
9507 				if (!tnum_is_const(reg->var_off)) {
9508 					verbose(env, "R%d is not a const\n", regno);
9509 					return -EINVAL;
9510 				}
9511 
9512 				meta->r0_size = reg->var_off.value;
9513 				ret = mark_chain_precision(env, regno);
9514 				if (ret)
9515 					return ret;
9516 			}
9517 			continue;
9518 		}
9519 
9520 		if (!btf_type_is_ptr(t)) {
9521 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9522 			return -EINVAL;
9523 		}
9524 
9525 		if (is_kfunc_trusted_args(meta) &&
9526 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
9527 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9528 			return -EACCES;
9529 		}
9530 
9531 		if (reg->ref_obj_id) {
9532 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
9533 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9534 					regno, reg->ref_obj_id,
9535 					meta->ref_obj_id);
9536 				return -EFAULT;
9537 			}
9538 			meta->ref_obj_id = reg->ref_obj_id;
9539 			if (is_kfunc_release(meta))
9540 				meta->release_regno = regno;
9541 		}
9542 
9543 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9544 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9545 
9546 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9547 		if (kf_arg_type < 0)
9548 			return kf_arg_type;
9549 
9550 		switch (kf_arg_type) {
9551 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9552 		case KF_ARG_PTR_TO_BTF_ID:
9553 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9554 				break;
9555 
9556 			if (!is_trusted_reg(reg)) {
9557 				if (!is_kfunc_rcu(meta)) {
9558 					verbose(env, "R%d must be referenced or trusted\n", regno);
9559 					return -EINVAL;
9560 				}
9561 				if (!is_rcu_reg(reg)) {
9562 					verbose(env, "R%d must be a rcu pointer\n", regno);
9563 					return -EINVAL;
9564 				}
9565 			}
9566 
9567 			fallthrough;
9568 		case KF_ARG_PTR_TO_CTX:
9569 			/* Trusted arguments have the same offset checks as release arguments */
9570 			arg_type |= OBJ_RELEASE;
9571 			break;
9572 		case KF_ARG_PTR_TO_KPTR:
9573 		case KF_ARG_PTR_TO_DYNPTR:
9574 		case KF_ARG_PTR_TO_LIST_HEAD:
9575 		case KF_ARG_PTR_TO_LIST_NODE:
9576 		case KF_ARG_PTR_TO_RB_ROOT:
9577 		case KF_ARG_PTR_TO_RB_NODE:
9578 		case KF_ARG_PTR_TO_MEM:
9579 		case KF_ARG_PTR_TO_MEM_SIZE:
9580 		case KF_ARG_PTR_TO_CALLBACK:
9581 			/* Trusted by default */
9582 			break;
9583 		default:
9584 			WARN_ON_ONCE(1);
9585 			return -EFAULT;
9586 		}
9587 
9588 		if (is_kfunc_release(meta) && reg->ref_obj_id)
9589 			arg_type |= OBJ_RELEASE;
9590 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9591 		if (ret < 0)
9592 			return ret;
9593 
9594 		switch (kf_arg_type) {
9595 		case KF_ARG_PTR_TO_CTX:
9596 			if (reg->type != PTR_TO_CTX) {
9597 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9598 				return -EINVAL;
9599 			}
9600 
9601 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9602 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9603 				if (ret < 0)
9604 					return -EINVAL;
9605 				meta->ret_btf_id  = ret;
9606 			}
9607 			break;
9608 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9609 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9610 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9611 				return -EINVAL;
9612 			}
9613 			if (!reg->ref_obj_id) {
9614 				verbose(env, "allocated object must be referenced\n");
9615 				return -EINVAL;
9616 			}
9617 			if (meta->btf == btf_vmlinux &&
9618 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9619 				meta->arg_obj_drop.btf = reg->btf;
9620 				meta->arg_obj_drop.btf_id = reg->btf_id;
9621 			}
9622 			break;
9623 		case KF_ARG_PTR_TO_KPTR:
9624 			if (reg->type != PTR_TO_MAP_VALUE) {
9625 				verbose(env, "arg#0 expected pointer to map value\n");
9626 				return -EINVAL;
9627 			}
9628 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9629 			if (ret < 0)
9630 				return ret;
9631 			break;
9632 		case KF_ARG_PTR_TO_DYNPTR:
9633 			if (reg->type != PTR_TO_STACK &&
9634 			    reg->type != CONST_PTR_TO_DYNPTR) {
9635 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9636 				return -EINVAL;
9637 			}
9638 
9639 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
9640 			if (ret < 0)
9641 				return ret;
9642 			break;
9643 		case KF_ARG_PTR_TO_LIST_HEAD:
9644 			if (reg->type != PTR_TO_MAP_VALUE &&
9645 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9646 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9647 				return -EINVAL;
9648 			}
9649 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9650 				verbose(env, "allocated object must be referenced\n");
9651 				return -EINVAL;
9652 			}
9653 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9654 			if (ret < 0)
9655 				return ret;
9656 			break;
9657 		case KF_ARG_PTR_TO_RB_ROOT:
9658 			if (reg->type != PTR_TO_MAP_VALUE &&
9659 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9660 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9661 				return -EINVAL;
9662 			}
9663 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9664 				verbose(env, "allocated object must be referenced\n");
9665 				return -EINVAL;
9666 			}
9667 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9668 			if (ret < 0)
9669 				return ret;
9670 			break;
9671 		case KF_ARG_PTR_TO_LIST_NODE:
9672 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9673 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9674 				return -EINVAL;
9675 			}
9676 			if (!reg->ref_obj_id) {
9677 				verbose(env, "allocated object must be referenced\n");
9678 				return -EINVAL;
9679 			}
9680 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9681 			if (ret < 0)
9682 				return ret;
9683 			break;
9684 		case KF_ARG_PTR_TO_RB_NODE:
9685 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9686 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9687 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
9688 					return -EINVAL;
9689 				}
9690 				if (in_rbtree_lock_required_cb(env)) {
9691 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9692 					return -EINVAL;
9693 				}
9694 			} else {
9695 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9696 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
9697 					return -EINVAL;
9698 				}
9699 				if (!reg->ref_obj_id) {
9700 					verbose(env, "allocated object must be referenced\n");
9701 					return -EINVAL;
9702 				}
9703 			}
9704 
9705 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
9706 			if (ret < 0)
9707 				return ret;
9708 			break;
9709 		case KF_ARG_PTR_TO_BTF_ID:
9710 			/* Only base_type is checked, further checks are done here */
9711 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9712 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9713 			    !reg2btf_ids[base_type(reg->type)]) {
9714 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9715 				verbose(env, "expected %s or socket\n",
9716 					reg_type_str(env, base_type(reg->type) |
9717 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9718 				return -EINVAL;
9719 			}
9720 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9721 			if (ret < 0)
9722 				return ret;
9723 			break;
9724 		case KF_ARG_PTR_TO_MEM:
9725 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9726 			if (IS_ERR(resolve_ret)) {
9727 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9728 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9729 				return -EINVAL;
9730 			}
9731 			ret = check_mem_reg(env, reg, regno, type_size);
9732 			if (ret < 0)
9733 				return ret;
9734 			break;
9735 		case KF_ARG_PTR_TO_MEM_SIZE:
9736 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9737 			if (ret < 0) {
9738 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9739 				return ret;
9740 			}
9741 			/* Skip next '__sz' argument */
9742 			i++;
9743 			break;
9744 		case KF_ARG_PTR_TO_CALLBACK:
9745 			meta->subprogno = reg->subprogno;
9746 			break;
9747 		}
9748 	}
9749 
9750 	if (is_kfunc_release(meta) && !meta->release_regno) {
9751 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9752 			func_name);
9753 		return -EINVAL;
9754 	}
9755 
9756 	return 0;
9757 }
9758 
9759 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9760 			    int *insn_idx_p)
9761 {
9762 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9763 	u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
9764 	struct bpf_reg_state *regs = cur_regs(env);
9765 	const char *func_name, *ptr_type_name;
9766 	bool sleepable, rcu_lock, rcu_unlock;
9767 	struct bpf_kfunc_call_arg_meta meta;
9768 	int err, insn_idx = *insn_idx_p;
9769 	const struct btf_param *args;
9770 	const struct btf_type *ret_t;
9771 	struct btf *desc_btf;
9772 	u32 *kfunc_flags;
9773 
9774 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9775 	if (!insn->imm)
9776 		return 0;
9777 
9778 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9779 	if (IS_ERR(desc_btf))
9780 		return PTR_ERR(desc_btf);
9781 
9782 	func_id = insn->imm;
9783 	func = btf_type_by_id(desc_btf, func_id);
9784 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9785 	func_proto = btf_type_by_id(desc_btf, func->type);
9786 
9787 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9788 	if (!kfunc_flags) {
9789 		verbose(env, "calling kernel function %s is not allowed\n",
9790 			func_name);
9791 		return -EACCES;
9792 	}
9793 
9794 	/* Prepare kfunc call metadata */
9795 	memset(&meta, 0, sizeof(meta));
9796 	meta.btf = desc_btf;
9797 	meta.func_id = func_id;
9798 	meta.kfunc_flags = *kfunc_flags;
9799 	meta.func_proto = func_proto;
9800 	meta.func_name = func_name;
9801 
9802 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9803 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9804 		return -EACCES;
9805 	}
9806 
9807 	sleepable = is_kfunc_sleepable(&meta);
9808 	if (sleepable && !env->prog->aux->sleepable) {
9809 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9810 		return -EACCES;
9811 	}
9812 
9813 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9814 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9815 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9816 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9817 		return -EACCES;
9818 	}
9819 
9820 	if (env->cur_state->active_rcu_lock) {
9821 		struct bpf_func_state *state;
9822 		struct bpf_reg_state *reg;
9823 
9824 		if (rcu_lock) {
9825 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9826 			return -EINVAL;
9827 		} else if (rcu_unlock) {
9828 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9829 				if (reg->type & MEM_RCU) {
9830 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9831 					reg->type |= PTR_UNTRUSTED;
9832 				}
9833 			}));
9834 			env->cur_state->active_rcu_lock = false;
9835 		} else if (sleepable) {
9836 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9837 			return -EACCES;
9838 		}
9839 	} else if (rcu_lock) {
9840 		env->cur_state->active_rcu_lock = true;
9841 	} else if (rcu_unlock) {
9842 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9843 		return -EINVAL;
9844 	}
9845 
9846 	/* Check the arguments */
9847 	err = check_kfunc_args(env, &meta);
9848 	if (err < 0)
9849 		return err;
9850 	/* In case of release function, we get register number of refcounted
9851 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9852 	 */
9853 	if (meta.release_regno) {
9854 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9855 		if (err) {
9856 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9857 				func_name, func_id);
9858 			return err;
9859 		}
9860 	}
9861 
9862 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
9863 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
9864 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9865 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
9866 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
9867 		if (err) {
9868 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
9869 				func_name, func_id);
9870 			return err;
9871 		}
9872 
9873 		err = release_reference(env, release_ref_obj_id);
9874 		if (err) {
9875 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9876 				func_name, func_id);
9877 			return err;
9878 		}
9879 	}
9880 
9881 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9882 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9883 					set_rbtree_add_callback_state);
9884 		if (err) {
9885 			verbose(env, "kfunc %s#%d failed callback verification\n",
9886 				func_name, func_id);
9887 			return err;
9888 		}
9889 	}
9890 
9891 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9892 		mark_reg_not_init(env, regs, caller_saved[i]);
9893 
9894 	/* Check return type */
9895 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9896 
9897 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9898 		/* Only exception is bpf_obj_new_impl */
9899 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9900 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9901 			return -EINVAL;
9902 		}
9903 	}
9904 
9905 	if (btf_type_is_scalar(t)) {
9906 		mark_reg_unknown(env, regs, BPF_REG_0);
9907 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9908 	} else if (btf_type_is_ptr(t)) {
9909 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9910 
9911 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9912 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9913 				struct btf *ret_btf;
9914 				u32 ret_btf_id;
9915 
9916 				if (unlikely(!bpf_global_ma_set))
9917 					return -ENOMEM;
9918 
9919 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9920 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9921 					return -EINVAL;
9922 				}
9923 
9924 				ret_btf = env->prog->aux->btf;
9925 				ret_btf_id = meta.arg_constant.value;
9926 
9927 				/* This may be NULL due to user not supplying a BTF */
9928 				if (!ret_btf) {
9929 					verbose(env, "bpf_obj_new requires prog BTF\n");
9930 					return -EINVAL;
9931 				}
9932 
9933 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9934 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9935 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9936 					return -EINVAL;
9937 				}
9938 
9939 				mark_reg_known_zero(env, regs, BPF_REG_0);
9940 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9941 				regs[BPF_REG_0].btf = ret_btf;
9942 				regs[BPF_REG_0].btf_id = ret_btf_id;
9943 
9944 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9945 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9946 					btf_find_struct_meta(ret_btf, ret_btf_id);
9947 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9948 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9949 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9950 							     meta.arg_obj_drop.btf_id);
9951 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9952 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9953 				struct btf_field *field = meta.arg_list_head.field;
9954 
9955 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9956 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9957 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
9958 				struct btf_field *field = meta.arg_rbtree_root.field;
9959 
9960 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9961 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9962 				mark_reg_known_zero(env, regs, BPF_REG_0);
9963 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9964 				regs[BPF_REG_0].btf = desc_btf;
9965 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9966 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9967 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9968 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9969 					verbose(env,
9970 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9971 					return -EINVAL;
9972 				}
9973 
9974 				mark_reg_known_zero(env, regs, BPF_REG_0);
9975 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9976 				regs[BPF_REG_0].btf = desc_btf;
9977 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9978 			} else {
9979 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9980 					meta.func_name);
9981 				return -EFAULT;
9982 			}
9983 		} else if (!__btf_type_is_struct(ptr_type)) {
9984 			if (!meta.r0_size) {
9985 				ptr_type_name = btf_name_by_offset(desc_btf,
9986 								   ptr_type->name_off);
9987 				verbose(env,
9988 					"kernel function %s returns pointer type %s %s is not supported\n",
9989 					func_name,
9990 					btf_type_str(ptr_type),
9991 					ptr_type_name);
9992 				return -EINVAL;
9993 			}
9994 
9995 			mark_reg_known_zero(env, regs, BPF_REG_0);
9996 			regs[BPF_REG_0].type = PTR_TO_MEM;
9997 			regs[BPF_REG_0].mem_size = meta.r0_size;
9998 
9999 			if (meta.r0_rdonly)
10000 				regs[BPF_REG_0].type |= MEM_RDONLY;
10001 
10002 			/* Ensures we don't access the memory after a release_reference() */
10003 			if (meta.ref_obj_id)
10004 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10005 		} else {
10006 			mark_reg_known_zero(env, regs, BPF_REG_0);
10007 			regs[BPF_REG_0].btf = desc_btf;
10008 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10009 			regs[BPF_REG_0].btf_id = ptr_type_id;
10010 		}
10011 
10012 		if (is_kfunc_ret_null(&meta)) {
10013 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10014 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10015 			regs[BPF_REG_0].id = ++env->id_gen;
10016 		}
10017 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10018 		if (is_kfunc_acquire(&meta)) {
10019 			int id = acquire_reference_state(env, insn_idx);
10020 
10021 			if (id < 0)
10022 				return id;
10023 			if (is_kfunc_ret_null(&meta))
10024 				regs[BPF_REG_0].id = id;
10025 			regs[BPF_REG_0].ref_obj_id = id;
10026 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10027 			ref_set_non_owning(env, &regs[BPF_REG_0]);
10028 		}
10029 
10030 		if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10031 			invalidate_non_owning_refs(env);
10032 
10033 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10034 			regs[BPF_REG_0].id = ++env->id_gen;
10035 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10036 
10037 	nargs = btf_type_vlen(func_proto);
10038 	args = (const struct btf_param *)(func_proto + 1);
10039 	for (i = 0; i < nargs; i++) {
10040 		u32 regno = i + 1;
10041 
10042 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10043 		if (btf_type_is_ptr(t))
10044 			mark_btf_func_reg_size(env, regno, sizeof(void *));
10045 		else
10046 			/* scalar. ensured by btf_check_kfunc_arg_match() */
10047 			mark_btf_func_reg_size(env, regno, t->size);
10048 	}
10049 
10050 	return 0;
10051 }
10052 
10053 static bool signed_add_overflows(s64 a, s64 b)
10054 {
10055 	/* Do the add in u64, where overflow is well-defined */
10056 	s64 res = (s64)((u64)a + (u64)b);
10057 
10058 	if (b < 0)
10059 		return res > a;
10060 	return res < a;
10061 }
10062 
10063 static bool signed_add32_overflows(s32 a, s32 b)
10064 {
10065 	/* Do the add in u32, where overflow is well-defined */
10066 	s32 res = (s32)((u32)a + (u32)b);
10067 
10068 	if (b < 0)
10069 		return res > a;
10070 	return res < a;
10071 }
10072 
10073 static bool signed_sub_overflows(s64 a, s64 b)
10074 {
10075 	/* Do the sub in u64, where overflow is well-defined */
10076 	s64 res = (s64)((u64)a - (u64)b);
10077 
10078 	if (b < 0)
10079 		return res < a;
10080 	return res > a;
10081 }
10082 
10083 static bool signed_sub32_overflows(s32 a, s32 b)
10084 {
10085 	/* Do the sub in u32, where overflow is well-defined */
10086 	s32 res = (s32)((u32)a - (u32)b);
10087 
10088 	if (b < 0)
10089 		return res < a;
10090 	return res > a;
10091 }
10092 
10093 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10094 				  const struct bpf_reg_state *reg,
10095 				  enum bpf_reg_type type)
10096 {
10097 	bool known = tnum_is_const(reg->var_off);
10098 	s64 val = reg->var_off.value;
10099 	s64 smin = reg->smin_value;
10100 
10101 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10102 		verbose(env, "math between %s pointer and %lld is not allowed\n",
10103 			reg_type_str(env, type), val);
10104 		return false;
10105 	}
10106 
10107 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10108 		verbose(env, "%s pointer offset %d is not allowed\n",
10109 			reg_type_str(env, type), reg->off);
10110 		return false;
10111 	}
10112 
10113 	if (smin == S64_MIN) {
10114 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10115 			reg_type_str(env, type));
10116 		return false;
10117 	}
10118 
10119 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10120 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
10121 			smin, reg_type_str(env, type));
10122 		return false;
10123 	}
10124 
10125 	return true;
10126 }
10127 
10128 enum {
10129 	REASON_BOUNDS	= -1,
10130 	REASON_TYPE	= -2,
10131 	REASON_PATHS	= -3,
10132 	REASON_LIMIT	= -4,
10133 	REASON_STACK	= -5,
10134 };
10135 
10136 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10137 			      u32 *alu_limit, bool mask_to_left)
10138 {
10139 	u32 max = 0, ptr_limit = 0;
10140 
10141 	switch (ptr_reg->type) {
10142 	case PTR_TO_STACK:
10143 		/* Offset 0 is out-of-bounds, but acceptable start for the
10144 		 * left direction, see BPF_REG_FP. Also, unknown scalar
10145 		 * offset where we would need to deal with min/max bounds is
10146 		 * currently prohibited for unprivileged.
10147 		 */
10148 		max = MAX_BPF_STACK + mask_to_left;
10149 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10150 		break;
10151 	case PTR_TO_MAP_VALUE:
10152 		max = ptr_reg->map_ptr->value_size;
10153 		ptr_limit = (mask_to_left ?
10154 			     ptr_reg->smin_value :
10155 			     ptr_reg->umax_value) + ptr_reg->off;
10156 		break;
10157 	default:
10158 		return REASON_TYPE;
10159 	}
10160 
10161 	if (ptr_limit >= max)
10162 		return REASON_LIMIT;
10163 	*alu_limit = ptr_limit;
10164 	return 0;
10165 }
10166 
10167 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10168 				    const struct bpf_insn *insn)
10169 {
10170 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10171 }
10172 
10173 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10174 				       u32 alu_state, u32 alu_limit)
10175 {
10176 	/* If we arrived here from different branches with different
10177 	 * state or limits to sanitize, then this won't work.
10178 	 */
10179 	if (aux->alu_state &&
10180 	    (aux->alu_state != alu_state ||
10181 	     aux->alu_limit != alu_limit))
10182 		return REASON_PATHS;
10183 
10184 	/* Corresponding fixup done in do_misc_fixups(). */
10185 	aux->alu_state = alu_state;
10186 	aux->alu_limit = alu_limit;
10187 	return 0;
10188 }
10189 
10190 static int sanitize_val_alu(struct bpf_verifier_env *env,
10191 			    struct bpf_insn *insn)
10192 {
10193 	struct bpf_insn_aux_data *aux = cur_aux(env);
10194 
10195 	if (can_skip_alu_sanitation(env, insn))
10196 		return 0;
10197 
10198 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10199 }
10200 
10201 static bool sanitize_needed(u8 opcode)
10202 {
10203 	return opcode == BPF_ADD || opcode == BPF_SUB;
10204 }
10205 
10206 struct bpf_sanitize_info {
10207 	struct bpf_insn_aux_data aux;
10208 	bool mask_to_left;
10209 };
10210 
10211 static struct bpf_verifier_state *
10212 sanitize_speculative_path(struct bpf_verifier_env *env,
10213 			  const struct bpf_insn *insn,
10214 			  u32 next_idx, u32 curr_idx)
10215 {
10216 	struct bpf_verifier_state *branch;
10217 	struct bpf_reg_state *regs;
10218 
10219 	branch = push_stack(env, next_idx, curr_idx, true);
10220 	if (branch && insn) {
10221 		regs = branch->frame[branch->curframe]->regs;
10222 		if (BPF_SRC(insn->code) == BPF_K) {
10223 			mark_reg_unknown(env, regs, insn->dst_reg);
10224 		} else if (BPF_SRC(insn->code) == BPF_X) {
10225 			mark_reg_unknown(env, regs, insn->dst_reg);
10226 			mark_reg_unknown(env, regs, insn->src_reg);
10227 		}
10228 	}
10229 	return branch;
10230 }
10231 
10232 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10233 			    struct bpf_insn *insn,
10234 			    const struct bpf_reg_state *ptr_reg,
10235 			    const struct bpf_reg_state *off_reg,
10236 			    struct bpf_reg_state *dst_reg,
10237 			    struct bpf_sanitize_info *info,
10238 			    const bool commit_window)
10239 {
10240 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10241 	struct bpf_verifier_state *vstate = env->cur_state;
10242 	bool off_is_imm = tnum_is_const(off_reg->var_off);
10243 	bool off_is_neg = off_reg->smin_value < 0;
10244 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
10245 	u8 opcode = BPF_OP(insn->code);
10246 	u32 alu_state, alu_limit;
10247 	struct bpf_reg_state tmp;
10248 	bool ret;
10249 	int err;
10250 
10251 	if (can_skip_alu_sanitation(env, insn))
10252 		return 0;
10253 
10254 	/* We already marked aux for masking from non-speculative
10255 	 * paths, thus we got here in the first place. We only care
10256 	 * to explore bad access from here.
10257 	 */
10258 	if (vstate->speculative)
10259 		goto do_sim;
10260 
10261 	if (!commit_window) {
10262 		if (!tnum_is_const(off_reg->var_off) &&
10263 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10264 			return REASON_BOUNDS;
10265 
10266 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
10267 				     (opcode == BPF_SUB && !off_is_neg);
10268 	}
10269 
10270 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10271 	if (err < 0)
10272 		return err;
10273 
10274 	if (commit_window) {
10275 		/* In commit phase we narrow the masking window based on
10276 		 * the observed pointer move after the simulated operation.
10277 		 */
10278 		alu_state = info->aux.alu_state;
10279 		alu_limit = abs(info->aux.alu_limit - alu_limit);
10280 	} else {
10281 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10282 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10283 		alu_state |= ptr_is_dst_reg ?
10284 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10285 
10286 		/* Limit pruning on unknown scalars to enable deep search for
10287 		 * potential masking differences from other program paths.
10288 		 */
10289 		if (!off_is_imm)
10290 			env->explore_alu_limits = true;
10291 	}
10292 
10293 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10294 	if (err < 0)
10295 		return err;
10296 do_sim:
10297 	/* If we're in commit phase, we're done here given we already
10298 	 * pushed the truncated dst_reg into the speculative verification
10299 	 * stack.
10300 	 *
10301 	 * Also, when register is a known constant, we rewrite register-based
10302 	 * operation to immediate-based, and thus do not need masking (and as
10303 	 * a consequence, do not need to simulate the zero-truncation either).
10304 	 */
10305 	if (commit_window || off_is_imm)
10306 		return 0;
10307 
10308 	/* Simulate and find potential out-of-bounds access under
10309 	 * speculative execution from truncation as a result of
10310 	 * masking when off was not within expected range. If off
10311 	 * sits in dst, then we temporarily need to move ptr there
10312 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
10313 	 * for cases where we use K-based arithmetic in one direction
10314 	 * and truncated reg-based in the other in order to explore
10315 	 * bad access.
10316 	 */
10317 	if (!ptr_is_dst_reg) {
10318 		tmp = *dst_reg;
10319 		copy_register_state(dst_reg, ptr_reg);
10320 	}
10321 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10322 					env->insn_idx);
10323 	if (!ptr_is_dst_reg && ret)
10324 		*dst_reg = tmp;
10325 	return !ret ? REASON_STACK : 0;
10326 }
10327 
10328 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10329 {
10330 	struct bpf_verifier_state *vstate = env->cur_state;
10331 
10332 	/* If we simulate paths under speculation, we don't update the
10333 	 * insn as 'seen' such that when we verify unreachable paths in
10334 	 * the non-speculative domain, sanitize_dead_code() can still
10335 	 * rewrite/sanitize them.
10336 	 */
10337 	if (!vstate->speculative)
10338 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10339 }
10340 
10341 static int sanitize_err(struct bpf_verifier_env *env,
10342 			const struct bpf_insn *insn, int reason,
10343 			const struct bpf_reg_state *off_reg,
10344 			const struct bpf_reg_state *dst_reg)
10345 {
10346 	static const char *err = "pointer arithmetic with it prohibited for !root";
10347 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10348 	u32 dst = insn->dst_reg, src = insn->src_reg;
10349 
10350 	switch (reason) {
10351 	case REASON_BOUNDS:
10352 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10353 			off_reg == dst_reg ? dst : src, err);
10354 		break;
10355 	case REASON_TYPE:
10356 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10357 			off_reg == dst_reg ? src : dst, err);
10358 		break;
10359 	case REASON_PATHS:
10360 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10361 			dst, op, err);
10362 		break;
10363 	case REASON_LIMIT:
10364 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10365 			dst, op, err);
10366 		break;
10367 	case REASON_STACK:
10368 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10369 			dst, err);
10370 		break;
10371 	default:
10372 		verbose(env, "verifier internal error: unknown reason (%d)\n",
10373 			reason);
10374 		break;
10375 	}
10376 
10377 	return -EACCES;
10378 }
10379 
10380 /* check that stack access falls within stack limits and that 'reg' doesn't
10381  * have a variable offset.
10382  *
10383  * Variable offset is prohibited for unprivileged mode for simplicity since it
10384  * requires corresponding support in Spectre masking for stack ALU.  See also
10385  * retrieve_ptr_limit().
10386  *
10387  *
10388  * 'off' includes 'reg->off'.
10389  */
10390 static int check_stack_access_for_ptr_arithmetic(
10391 				struct bpf_verifier_env *env,
10392 				int regno,
10393 				const struct bpf_reg_state *reg,
10394 				int off)
10395 {
10396 	if (!tnum_is_const(reg->var_off)) {
10397 		char tn_buf[48];
10398 
10399 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10400 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10401 			regno, tn_buf, off);
10402 		return -EACCES;
10403 	}
10404 
10405 	if (off >= 0 || off < -MAX_BPF_STACK) {
10406 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
10407 			"prohibited for !root; off=%d\n", regno, off);
10408 		return -EACCES;
10409 	}
10410 
10411 	return 0;
10412 }
10413 
10414 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10415 				 const struct bpf_insn *insn,
10416 				 const struct bpf_reg_state *dst_reg)
10417 {
10418 	u32 dst = insn->dst_reg;
10419 
10420 	/* For unprivileged we require that resulting offset must be in bounds
10421 	 * in order to be able to sanitize access later on.
10422 	 */
10423 	if (env->bypass_spec_v1)
10424 		return 0;
10425 
10426 	switch (dst_reg->type) {
10427 	case PTR_TO_STACK:
10428 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10429 					dst_reg->off + dst_reg->var_off.value))
10430 			return -EACCES;
10431 		break;
10432 	case PTR_TO_MAP_VALUE:
10433 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10434 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10435 				"prohibited for !root\n", dst);
10436 			return -EACCES;
10437 		}
10438 		break;
10439 	default:
10440 		break;
10441 	}
10442 
10443 	return 0;
10444 }
10445 
10446 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10447  * Caller should also handle BPF_MOV case separately.
10448  * If we return -EACCES, caller may want to try again treating pointer as a
10449  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10450  */
10451 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10452 				   struct bpf_insn *insn,
10453 				   const struct bpf_reg_state *ptr_reg,
10454 				   const struct bpf_reg_state *off_reg)
10455 {
10456 	struct bpf_verifier_state *vstate = env->cur_state;
10457 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10458 	struct bpf_reg_state *regs = state->regs, *dst_reg;
10459 	bool known = tnum_is_const(off_reg->var_off);
10460 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10461 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10462 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10463 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10464 	struct bpf_sanitize_info info = {};
10465 	u8 opcode = BPF_OP(insn->code);
10466 	u32 dst = insn->dst_reg;
10467 	int ret;
10468 
10469 	dst_reg = &regs[dst];
10470 
10471 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10472 	    smin_val > smax_val || umin_val > umax_val) {
10473 		/* Taint dst register if offset had invalid bounds derived from
10474 		 * e.g. dead branches.
10475 		 */
10476 		__mark_reg_unknown(env, dst_reg);
10477 		return 0;
10478 	}
10479 
10480 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
10481 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
10482 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10483 			__mark_reg_unknown(env, dst_reg);
10484 			return 0;
10485 		}
10486 
10487 		verbose(env,
10488 			"R%d 32-bit pointer arithmetic prohibited\n",
10489 			dst);
10490 		return -EACCES;
10491 	}
10492 
10493 	if (ptr_reg->type & PTR_MAYBE_NULL) {
10494 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10495 			dst, reg_type_str(env, ptr_reg->type));
10496 		return -EACCES;
10497 	}
10498 
10499 	switch (base_type(ptr_reg->type)) {
10500 	case CONST_PTR_TO_MAP:
10501 		/* smin_val represents the known value */
10502 		if (known && smin_val == 0 && opcode == BPF_ADD)
10503 			break;
10504 		fallthrough;
10505 	case PTR_TO_PACKET_END:
10506 	case PTR_TO_SOCKET:
10507 	case PTR_TO_SOCK_COMMON:
10508 	case PTR_TO_TCP_SOCK:
10509 	case PTR_TO_XDP_SOCK:
10510 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10511 			dst, reg_type_str(env, ptr_reg->type));
10512 		return -EACCES;
10513 	default:
10514 		break;
10515 	}
10516 
10517 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10518 	 * The id may be overwritten later if we create a new variable offset.
10519 	 */
10520 	dst_reg->type = ptr_reg->type;
10521 	dst_reg->id = ptr_reg->id;
10522 
10523 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10524 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10525 		return -EINVAL;
10526 
10527 	/* pointer types do not carry 32-bit bounds at the moment. */
10528 	__mark_reg32_unbounded(dst_reg);
10529 
10530 	if (sanitize_needed(opcode)) {
10531 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10532 				       &info, false);
10533 		if (ret < 0)
10534 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10535 	}
10536 
10537 	switch (opcode) {
10538 	case BPF_ADD:
10539 		/* We can take a fixed offset as long as it doesn't overflow
10540 		 * the s32 'off' field
10541 		 */
10542 		if (known && (ptr_reg->off + smin_val ==
10543 			      (s64)(s32)(ptr_reg->off + smin_val))) {
10544 			/* pointer += K.  Accumulate it into fixed offset */
10545 			dst_reg->smin_value = smin_ptr;
10546 			dst_reg->smax_value = smax_ptr;
10547 			dst_reg->umin_value = umin_ptr;
10548 			dst_reg->umax_value = umax_ptr;
10549 			dst_reg->var_off = ptr_reg->var_off;
10550 			dst_reg->off = ptr_reg->off + smin_val;
10551 			dst_reg->raw = ptr_reg->raw;
10552 			break;
10553 		}
10554 		/* A new variable offset is created.  Note that off_reg->off
10555 		 * == 0, since it's a scalar.
10556 		 * dst_reg gets the pointer type and since some positive
10557 		 * integer value was added to the pointer, give it a new 'id'
10558 		 * if it's a PTR_TO_PACKET.
10559 		 * this creates a new 'base' pointer, off_reg (variable) gets
10560 		 * added into the variable offset, and we copy the fixed offset
10561 		 * from ptr_reg.
10562 		 */
10563 		if (signed_add_overflows(smin_ptr, smin_val) ||
10564 		    signed_add_overflows(smax_ptr, smax_val)) {
10565 			dst_reg->smin_value = S64_MIN;
10566 			dst_reg->smax_value = S64_MAX;
10567 		} else {
10568 			dst_reg->smin_value = smin_ptr + smin_val;
10569 			dst_reg->smax_value = smax_ptr + smax_val;
10570 		}
10571 		if (umin_ptr + umin_val < umin_ptr ||
10572 		    umax_ptr + umax_val < umax_ptr) {
10573 			dst_reg->umin_value = 0;
10574 			dst_reg->umax_value = U64_MAX;
10575 		} else {
10576 			dst_reg->umin_value = umin_ptr + umin_val;
10577 			dst_reg->umax_value = umax_ptr + umax_val;
10578 		}
10579 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10580 		dst_reg->off = ptr_reg->off;
10581 		dst_reg->raw = ptr_reg->raw;
10582 		if (reg_is_pkt_pointer(ptr_reg)) {
10583 			dst_reg->id = ++env->id_gen;
10584 			/* something was added to pkt_ptr, set range to zero */
10585 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10586 		}
10587 		break;
10588 	case BPF_SUB:
10589 		if (dst_reg == off_reg) {
10590 			/* scalar -= pointer.  Creates an unknown scalar */
10591 			verbose(env, "R%d tried to subtract pointer from scalar\n",
10592 				dst);
10593 			return -EACCES;
10594 		}
10595 		/* We don't allow subtraction from FP, because (according to
10596 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
10597 		 * be able to deal with it.
10598 		 */
10599 		if (ptr_reg->type == PTR_TO_STACK) {
10600 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
10601 				dst);
10602 			return -EACCES;
10603 		}
10604 		if (known && (ptr_reg->off - smin_val ==
10605 			      (s64)(s32)(ptr_reg->off - smin_val))) {
10606 			/* pointer -= K.  Subtract it from fixed offset */
10607 			dst_reg->smin_value = smin_ptr;
10608 			dst_reg->smax_value = smax_ptr;
10609 			dst_reg->umin_value = umin_ptr;
10610 			dst_reg->umax_value = umax_ptr;
10611 			dst_reg->var_off = ptr_reg->var_off;
10612 			dst_reg->id = ptr_reg->id;
10613 			dst_reg->off = ptr_reg->off - smin_val;
10614 			dst_reg->raw = ptr_reg->raw;
10615 			break;
10616 		}
10617 		/* A new variable offset is created.  If the subtrahend is known
10618 		 * nonnegative, then any reg->range we had before is still good.
10619 		 */
10620 		if (signed_sub_overflows(smin_ptr, smax_val) ||
10621 		    signed_sub_overflows(smax_ptr, smin_val)) {
10622 			/* Overflow possible, we know nothing */
10623 			dst_reg->smin_value = S64_MIN;
10624 			dst_reg->smax_value = S64_MAX;
10625 		} else {
10626 			dst_reg->smin_value = smin_ptr - smax_val;
10627 			dst_reg->smax_value = smax_ptr - smin_val;
10628 		}
10629 		if (umin_ptr < umax_val) {
10630 			/* Overflow possible, we know nothing */
10631 			dst_reg->umin_value = 0;
10632 			dst_reg->umax_value = U64_MAX;
10633 		} else {
10634 			/* Cannot overflow (as long as bounds are consistent) */
10635 			dst_reg->umin_value = umin_ptr - umax_val;
10636 			dst_reg->umax_value = umax_ptr - umin_val;
10637 		}
10638 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10639 		dst_reg->off = ptr_reg->off;
10640 		dst_reg->raw = ptr_reg->raw;
10641 		if (reg_is_pkt_pointer(ptr_reg)) {
10642 			dst_reg->id = ++env->id_gen;
10643 			/* something was added to pkt_ptr, set range to zero */
10644 			if (smin_val < 0)
10645 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10646 		}
10647 		break;
10648 	case BPF_AND:
10649 	case BPF_OR:
10650 	case BPF_XOR:
10651 		/* bitwise ops on pointers are troublesome, prohibit. */
10652 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
10653 			dst, bpf_alu_string[opcode >> 4]);
10654 		return -EACCES;
10655 	default:
10656 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
10657 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
10658 			dst, bpf_alu_string[opcode >> 4]);
10659 		return -EACCES;
10660 	}
10661 
10662 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
10663 		return -EINVAL;
10664 	reg_bounds_sync(dst_reg);
10665 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
10666 		return -EACCES;
10667 	if (sanitize_needed(opcode)) {
10668 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
10669 				       &info, true);
10670 		if (ret < 0)
10671 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10672 	}
10673 
10674 	return 0;
10675 }
10676 
10677 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
10678 				 struct bpf_reg_state *src_reg)
10679 {
10680 	s32 smin_val = src_reg->s32_min_value;
10681 	s32 smax_val = src_reg->s32_max_value;
10682 	u32 umin_val = src_reg->u32_min_value;
10683 	u32 umax_val = src_reg->u32_max_value;
10684 
10685 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
10686 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
10687 		dst_reg->s32_min_value = S32_MIN;
10688 		dst_reg->s32_max_value = S32_MAX;
10689 	} else {
10690 		dst_reg->s32_min_value += smin_val;
10691 		dst_reg->s32_max_value += smax_val;
10692 	}
10693 	if (dst_reg->u32_min_value + umin_val < umin_val ||
10694 	    dst_reg->u32_max_value + umax_val < umax_val) {
10695 		dst_reg->u32_min_value = 0;
10696 		dst_reg->u32_max_value = U32_MAX;
10697 	} else {
10698 		dst_reg->u32_min_value += umin_val;
10699 		dst_reg->u32_max_value += umax_val;
10700 	}
10701 }
10702 
10703 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
10704 			       struct bpf_reg_state *src_reg)
10705 {
10706 	s64 smin_val = src_reg->smin_value;
10707 	s64 smax_val = src_reg->smax_value;
10708 	u64 umin_val = src_reg->umin_value;
10709 	u64 umax_val = src_reg->umax_value;
10710 
10711 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
10712 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
10713 		dst_reg->smin_value = S64_MIN;
10714 		dst_reg->smax_value = S64_MAX;
10715 	} else {
10716 		dst_reg->smin_value += smin_val;
10717 		dst_reg->smax_value += smax_val;
10718 	}
10719 	if (dst_reg->umin_value + umin_val < umin_val ||
10720 	    dst_reg->umax_value + umax_val < umax_val) {
10721 		dst_reg->umin_value = 0;
10722 		dst_reg->umax_value = U64_MAX;
10723 	} else {
10724 		dst_reg->umin_value += umin_val;
10725 		dst_reg->umax_value += umax_val;
10726 	}
10727 }
10728 
10729 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10730 				 struct bpf_reg_state *src_reg)
10731 {
10732 	s32 smin_val = src_reg->s32_min_value;
10733 	s32 smax_val = src_reg->s32_max_value;
10734 	u32 umin_val = src_reg->u32_min_value;
10735 	u32 umax_val = src_reg->u32_max_value;
10736 
10737 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10738 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10739 		/* Overflow possible, we know nothing */
10740 		dst_reg->s32_min_value = S32_MIN;
10741 		dst_reg->s32_max_value = S32_MAX;
10742 	} else {
10743 		dst_reg->s32_min_value -= smax_val;
10744 		dst_reg->s32_max_value -= smin_val;
10745 	}
10746 	if (dst_reg->u32_min_value < umax_val) {
10747 		/* Overflow possible, we know nothing */
10748 		dst_reg->u32_min_value = 0;
10749 		dst_reg->u32_max_value = U32_MAX;
10750 	} else {
10751 		/* Cannot overflow (as long as bounds are consistent) */
10752 		dst_reg->u32_min_value -= umax_val;
10753 		dst_reg->u32_max_value -= umin_val;
10754 	}
10755 }
10756 
10757 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10758 			       struct bpf_reg_state *src_reg)
10759 {
10760 	s64 smin_val = src_reg->smin_value;
10761 	s64 smax_val = src_reg->smax_value;
10762 	u64 umin_val = src_reg->umin_value;
10763 	u64 umax_val = src_reg->umax_value;
10764 
10765 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10766 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10767 		/* Overflow possible, we know nothing */
10768 		dst_reg->smin_value = S64_MIN;
10769 		dst_reg->smax_value = S64_MAX;
10770 	} else {
10771 		dst_reg->smin_value -= smax_val;
10772 		dst_reg->smax_value -= smin_val;
10773 	}
10774 	if (dst_reg->umin_value < umax_val) {
10775 		/* Overflow possible, we know nothing */
10776 		dst_reg->umin_value = 0;
10777 		dst_reg->umax_value = U64_MAX;
10778 	} else {
10779 		/* Cannot overflow (as long as bounds are consistent) */
10780 		dst_reg->umin_value -= umax_val;
10781 		dst_reg->umax_value -= umin_val;
10782 	}
10783 }
10784 
10785 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10786 				 struct bpf_reg_state *src_reg)
10787 {
10788 	s32 smin_val = src_reg->s32_min_value;
10789 	u32 umin_val = src_reg->u32_min_value;
10790 	u32 umax_val = src_reg->u32_max_value;
10791 
10792 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10793 		/* Ain't nobody got time to multiply that sign */
10794 		__mark_reg32_unbounded(dst_reg);
10795 		return;
10796 	}
10797 	/* Both values are positive, so we can work with unsigned and
10798 	 * copy the result to signed (unless it exceeds S32_MAX).
10799 	 */
10800 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10801 		/* Potential overflow, we know nothing */
10802 		__mark_reg32_unbounded(dst_reg);
10803 		return;
10804 	}
10805 	dst_reg->u32_min_value *= umin_val;
10806 	dst_reg->u32_max_value *= umax_val;
10807 	if (dst_reg->u32_max_value > S32_MAX) {
10808 		/* Overflow possible, we know nothing */
10809 		dst_reg->s32_min_value = S32_MIN;
10810 		dst_reg->s32_max_value = S32_MAX;
10811 	} else {
10812 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10813 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10814 	}
10815 }
10816 
10817 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10818 			       struct bpf_reg_state *src_reg)
10819 {
10820 	s64 smin_val = src_reg->smin_value;
10821 	u64 umin_val = src_reg->umin_value;
10822 	u64 umax_val = src_reg->umax_value;
10823 
10824 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10825 		/* Ain't nobody got time to multiply that sign */
10826 		__mark_reg64_unbounded(dst_reg);
10827 		return;
10828 	}
10829 	/* Both values are positive, so we can work with unsigned and
10830 	 * copy the result to signed (unless it exceeds S64_MAX).
10831 	 */
10832 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10833 		/* Potential overflow, we know nothing */
10834 		__mark_reg64_unbounded(dst_reg);
10835 		return;
10836 	}
10837 	dst_reg->umin_value *= umin_val;
10838 	dst_reg->umax_value *= umax_val;
10839 	if (dst_reg->umax_value > S64_MAX) {
10840 		/* Overflow possible, we know nothing */
10841 		dst_reg->smin_value = S64_MIN;
10842 		dst_reg->smax_value = S64_MAX;
10843 	} else {
10844 		dst_reg->smin_value = dst_reg->umin_value;
10845 		dst_reg->smax_value = dst_reg->umax_value;
10846 	}
10847 }
10848 
10849 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10850 				 struct bpf_reg_state *src_reg)
10851 {
10852 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10853 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10854 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10855 	s32 smin_val = src_reg->s32_min_value;
10856 	u32 umax_val = src_reg->u32_max_value;
10857 
10858 	if (src_known && dst_known) {
10859 		__mark_reg32_known(dst_reg, var32_off.value);
10860 		return;
10861 	}
10862 
10863 	/* We get our minimum from the var_off, since that's inherently
10864 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10865 	 */
10866 	dst_reg->u32_min_value = var32_off.value;
10867 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10868 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10869 		/* Lose signed bounds when ANDing negative numbers,
10870 		 * ain't nobody got time for that.
10871 		 */
10872 		dst_reg->s32_min_value = S32_MIN;
10873 		dst_reg->s32_max_value = S32_MAX;
10874 	} else {
10875 		/* ANDing two positives gives a positive, so safe to
10876 		 * cast result into s64.
10877 		 */
10878 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10879 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10880 	}
10881 }
10882 
10883 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10884 			       struct bpf_reg_state *src_reg)
10885 {
10886 	bool src_known = tnum_is_const(src_reg->var_off);
10887 	bool dst_known = tnum_is_const(dst_reg->var_off);
10888 	s64 smin_val = src_reg->smin_value;
10889 	u64 umax_val = src_reg->umax_value;
10890 
10891 	if (src_known && dst_known) {
10892 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10893 		return;
10894 	}
10895 
10896 	/* We get our minimum from the var_off, since that's inherently
10897 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10898 	 */
10899 	dst_reg->umin_value = dst_reg->var_off.value;
10900 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10901 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10902 		/* Lose signed bounds when ANDing negative numbers,
10903 		 * ain't nobody got time for that.
10904 		 */
10905 		dst_reg->smin_value = S64_MIN;
10906 		dst_reg->smax_value = S64_MAX;
10907 	} else {
10908 		/* ANDing two positives gives a positive, so safe to
10909 		 * cast result into s64.
10910 		 */
10911 		dst_reg->smin_value = dst_reg->umin_value;
10912 		dst_reg->smax_value = dst_reg->umax_value;
10913 	}
10914 	/* We may learn something more from the var_off */
10915 	__update_reg_bounds(dst_reg);
10916 }
10917 
10918 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10919 				struct bpf_reg_state *src_reg)
10920 {
10921 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10922 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10923 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10924 	s32 smin_val = src_reg->s32_min_value;
10925 	u32 umin_val = src_reg->u32_min_value;
10926 
10927 	if (src_known && dst_known) {
10928 		__mark_reg32_known(dst_reg, var32_off.value);
10929 		return;
10930 	}
10931 
10932 	/* We get our maximum from the var_off, and our minimum is the
10933 	 * maximum of the operands' minima
10934 	 */
10935 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10936 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10937 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10938 		/* Lose signed bounds when ORing negative numbers,
10939 		 * ain't nobody got time for that.
10940 		 */
10941 		dst_reg->s32_min_value = S32_MIN;
10942 		dst_reg->s32_max_value = S32_MAX;
10943 	} else {
10944 		/* ORing two positives gives a positive, so safe to
10945 		 * cast result into s64.
10946 		 */
10947 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10948 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10949 	}
10950 }
10951 
10952 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10953 			      struct bpf_reg_state *src_reg)
10954 {
10955 	bool src_known = tnum_is_const(src_reg->var_off);
10956 	bool dst_known = tnum_is_const(dst_reg->var_off);
10957 	s64 smin_val = src_reg->smin_value;
10958 	u64 umin_val = src_reg->umin_value;
10959 
10960 	if (src_known && dst_known) {
10961 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10962 		return;
10963 	}
10964 
10965 	/* We get our maximum from the var_off, and our minimum is the
10966 	 * maximum of the operands' minima
10967 	 */
10968 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10969 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10970 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10971 		/* Lose signed bounds when ORing negative numbers,
10972 		 * ain't nobody got time for that.
10973 		 */
10974 		dst_reg->smin_value = S64_MIN;
10975 		dst_reg->smax_value = S64_MAX;
10976 	} else {
10977 		/* ORing two positives gives a positive, so safe to
10978 		 * cast result into s64.
10979 		 */
10980 		dst_reg->smin_value = dst_reg->umin_value;
10981 		dst_reg->smax_value = dst_reg->umax_value;
10982 	}
10983 	/* We may learn something more from the var_off */
10984 	__update_reg_bounds(dst_reg);
10985 }
10986 
10987 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10988 				 struct bpf_reg_state *src_reg)
10989 {
10990 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10991 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10992 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10993 	s32 smin_val = src_reg->s32_min_value;
10994 
10995 	if (src_known && dst_known) {
10996 		__mark_reg32_known(dst_reg, var32_off.value);
10997 		return;
10998 	}
10999 
11000 	/* We get both minimum and maximum from the var32_off. */
11001 	dst_reg->u32_min_value = var32_off.value;
11002 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11003 
11004 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11005 		/* XORing two positive sign numbers gives a positive,
11006 		 * so safe to cast u32 result into s32.
11007 		 */
11008 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11009 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11010 	} else {
11011 		dst_reg->s32_min_value = S32_MIN;
11012 		dst_reg->s32_max_value = S32_MAX;
11013 	}
11014 }
11015 
11016 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11017 			       struct bpf_reg_state *src_reg)
11018 {
11019 	bool src_known = tnum_is_const(src_reg->var_off);
11020 	bool dst_known = tnum_is_const(dst_reg->var_off);
11021 	s64 smin_val = src_reg->smin_value;
11022 
11023 	if (src_known && dst_known) {
11024 		/* dst_reg->var_off.value has been updated earlier */
11025 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11026 		return;
11027 	}
11028 
11029 	/* We get both minimum and maximum from the var_off. */
11030 	dst_reg->umin_value = dst_reg->var_off.value;
11031 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11032 
11033 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11034 		/* XORing two positive sign numbers gives a positive,
11035 		 * so safe to cast u64 result into s64.
11036 		 */
11037 		dst_reg->smin_value = dst_reg->umin_value;
11038 		dst_reg->smax_value = dst_reg->umax_value;
11039 	} else {
11040 		dst_reg->smin_value = S64_MIN;
11041 		dst_reg->smax_value = S64_MAX;
11042 	}
11043 
11044 	__update_reg_bounds(dst_reg);
11045 }
11046 
11047 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11048 				   u64 umin_val, u64 umax_val)
11049 {
11050 	/* We lose all sign bit information (except what we can pick
11051 	 * up from var_off)
11052 	 */
11053 	dst_reg->s32_min_value = S32_MIN;
11054 	dst_reg->s32_max_value = S32_MAX;
11055 	/* If we might shift our top bit out, then we know nothing */
11056 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11057 		dst_reg->u32_min_value = 0;
11058 		dst_reg->u32_max_value = U32_MAX;
11059 	} else {
11060 		dst_reg->u32_min_value <<= umin_val;
11061 		dst_reg->u32_max_value <<= umax_val;
11062 	}
11063 }
11064 
11065 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11066 				 struct bpf_reg_state *src_reg)
11067 {
11068 	u32 umax_val = src_reg->u32_max_value;
11069 	u32 umin_val = src_reg->u32_min_value;
11070 	/* u32 alu operation will zext upper bits */
11071 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11072 
11073 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11074 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11075 	/* Not required but being careful mark reg64 bounds as unknown so
11076 	 * that we are forced to pick them up from tnum and zext later and
11077 	 * if some path skips this step we are still safe.
11078 	 */
11079 	__mark_reg64_unbounded(dst_reg);
11080 	__update_reg32_bounds(dst_reg);
11081 }
11082 
11083 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11084 				   u64 umin_val, u64 umax_val)
11085 {
11086 	/* Special case <<32 because it is a common compiler pattern to sign
11087 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11088 	 * positive we know this shift will also be positive so we can track
11089 	 * bounds correctly. Otherwise we lose all sign bit information except
11090 	 * what we can pick up from var_off. Perhaps we can generalize this
11091 	 * later to shifts of any length.
11092 	 */
11093 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11094 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11095 	else
11096 		dst_reg->smax_value = S64_MAX;
11097 
11098 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11099 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11100 	else
11101 		dst_reg->smin_value = S64_MIN;
11102 
11103 	/* If we might shift our top bit out, then we know nothing */
11104 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11105 		dst_reg->umin_value = 0;
11106 		dst_reg->umax_value = U64_MAX;
11107 	} else {
11108 		dst_reg->umin_value <<= umin_val;
11109 		dst_reg->umax_value <<= umax_val;
11110 	}
11111 }
11112 
11113 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11114 			       struct bpf_reg_state *src_reg)
11115 {
11116 	u64 umax_val = src_reg->umax_value;
11117 	u64 umin_val = src_reg->umin_value;
11118 
11119 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
11120 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11121 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11122 
11123 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11124 	/* We may learn something more from the var_off */
11125 	__update_reg_bounds(dst_reg);
11126 }
11127 
11128 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11129 				 struct bpf_reg_state *src_reg)
11130 {
11131 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11132 	u32 umax_val = src_reg->u32_max_value;
11133 	u32 umin_val = src_reg->u32_min_value;
11134 
11135 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11136 	 * be negative, then either:
11137 	 * 1) src_reg might be zero, so the sign bit of the result is
11138 	 *    unknown, so we lose our signed bounds
11139 	 * 2) it's known negative, thus the unsigned bounds capture the
11140 	 *    signed bounds
11141 	 * 3) the signed bounds cross zero, so they tell us nothing
11142 	 *    about the result
11143 	 * If the value in dst_reg is known nonnegative, then again the
11144 	 * unsigned bounds capture the signed bounds.
11145 	 * Thus, in all cases it suffices to blow away our signed bounds
11146 	 * and rely on inferring new ones from the unsigned bounds and
11147 	 * var_off of the result.
11148 	 */
11149 	dst_reg->s32_min_value = S32_MIN;
11150 	dst_reg->s32_max_value = S32_MAX;
11151 
11152 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
11153 	dst_reg->u32_min_value >>= umax_val;
11154 	dst_reg->u32_max_value >>= umin_val;
11155 
11156 	__mark_reg64_unbounded(dst_reg);
11157 	__update_reg32_bounds(dst_reg);
11158 }
11159 
11160 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11161 			       struct bpf_reg_state *src_reg)
11162 {
11163 	u64 umax_val = src_reg->umax_value;
11164 	u64 umin_val = src_reg->umin_value;
11165 
11166 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11167 	 * be negative, then either:
11168 	 * 1) src_reg might be zero, so the sign bit of the result is
11169 	 *    unknown, so we lose our signed bounds
11170 	 * 2) it's known negative, thus the unsigned bounds capture the
11171 	 *    signed bounds
11172 	 * 3) the signed bounds cross zero, so they tell us nothing
11173 	 *    about the result
11174 	 * If the value in dst_reg is known nonnegative, then again the
11175 	 * unsigned bounds capture the signed bounds.
11176 	 * Thus, in all cases it suffices to blow away our signed bounds
11177 	 * and rely on inferring new ones from the unsigned bounds and
11178 	 * var_off of the result.
11179 	 */
11180 	dst_reg->smin_value = S64_MIN;
11181 	dst_reg->smax_value = S64_MAX;
11182 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11183 	dst_reg->umin_value >>= umax_val;
11184 	dst_reg->umax_value >>= umin_val;
11185 
11186 	/* Its not easy to operate on alu32 bounds here because it depends
11187 	 * on bits being shifted in. Take easy way out and mark unbounded
11188 	 * so we can recalculate later from tnum.
11189 	 */
11190 	__mark_reg32_unbounded(dst_reg);
11191 	__update_reg_bounds(dst_reg);
11192 }
11193 
11194 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11195 				  struct bpf_reg_state *src_reg)
11196 {
11197 	u64 umin_val = src_reg->u32_min_value;
11198 
11199 	/* Upon reaching here, src_known is true and
11200 	 * umax_val is equal to umin_val.
11201 	 */
11202 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11203 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11204 
11205 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11206 
11207 	/* blow away the dst_reg umin_value/umax_value and rely on
11208 	 * dst_reg var_off to refine the result.
11209 	 */
11210 	dst_reg->u32_min_value = 0;
11211 	dst_reg->u32_max_value = U32_MAX;
11212 
11213 	__mark_reg64_unbounded(dst_reg);
11214 	__update_reg32_bounds(dst_reg);
11215 }
11216 
11217 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11218 				struct bpf_reg_state *src_reg)
11219 {
11220 	u64 umin_val = src_reg->umin_value;
11221 
11222 	/* Upon reaching here, src_known is true and umax_val is equal
11223 	 * to umin_val.
11224 	 */
11225 	dst_reg->smin_value >>= umin_val;
11226 	dst_reg->smax_value >>= umin_val;
11227 
11228 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11229 
11230 	/* blow away the dst_reg umin_value/umax_value and rely on
11231 	 * dst_reg var_off to refine the result.
11232 	 */
11233 	dst_reg->umin_value = 0;
11234 	dst_reg->umax_value = U64_MAX;
11235 
11236 	/* Its not easy to operate on alu32 bounds here because it depends
11237 	 * on bits being shifted in from upper 32-bits. Take easy way out
11238 	 * and mark unbounded so we can recalculate later from tnum.
11239 	 */
11240 	__mark_reg32_unbounded(dst_reg);
11241 	__update_reg_bounds(dst_reg);
11242 }
11243 
11244 /* WARNING: This function does calculations on 64-bit values, but the actual
11245  * execution may occur on 32-bit values. Therefore, things like bitshifts
11246  * need extra checks in the 32-bit case.
11247  */
11248 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11249 				      struct bpf_insn *insn,
11250 				      struct bpf_reg_state *dst_reg,
11251 				      struct bpf_reg_state src_reg)
11252 {
11253 	struct bpf_reg_state *regs = cur_regs(env);
11254 	u8 opcode = BPF_OP(insn->code);
11255 	bool src_known;
11256 	s64 smin_val, smax_val;
11257 	u64 umin_val, umax_val;
11258 	s32 s32_min_val, s32_max_val;
11259 	u32 u32_min_val, u32_max_val;
11260 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11261 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11262 	int ret;
11263 
11264 	smin_val = src_reg.smin_value;
11265 	smax_val = src_reg.smax_value;
11266 	umin_val = src_reg.umin_value;
11267 	umax_val = src_reg.umax_value;
11268 
11269 	s32_min_val = src_reg.s32_min_value;
11270 	s32_max_val = src_reg.s32_max_value;
11271 	u32_min_val = src_reg.u32_min_value;
11272 	u32_max_val = src_reg.u32_max_value;
11273 
11274 	if (alu32) {
11275 		src_known = tnum_subreg_is_const(src_reg.var_off);
11276 		if ((src_known &&
11277 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11278 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11279 			/* Taint dst register if offset had invalid bounds
11280 			 * derived from e.g. dead branches.
11281 			 */
11282 			__mark_reg_unknown(env, dst_reg);
11283 			return 0;
11284 		}
11285 	} else {
11286 		src_known = tnum_is_const(src_reg.var_off);
11287 		if ((src_known &&
11288 		     (smin_val != smax_val || umin_val != umax_val)) ||
11289 		    smin_val > smax_val || umin_val > umax_val) {
11290 			/* Taint dst register if offset had invalid bounds
11291 			 * derived from e.g. dead branches.
11292 			 */
11293 			__mark_reg_unknown(env, dst_reg);
11294 			return 0;
11295 		}
11296 	}
11297 
11298 	if (!src_known &&
11299 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11300 		__mark_reg_unknown(env, dst_reg);
11301 		return 0;
11302 	}
11303 
11304 	if (sanitize_needed(opcode)) {
11305 		ret = sanitize_val_alu(env, insn);
11306 		if (ret < 0)
11307 			return sanitize_err(env, insn, ret, NULL, NULL);
11308 	}
11309 
11310 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11311 	 * There are two classes of instructions: The first class we track both
11312 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
11313 	 * greatest amount of precision when alu operations are mixed with jmp32
11314 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11315 	 * and BPF_OR. This is possible because these ops have fairly easy to
11316 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11317 	 * See alu32 verifier tests for examples. The second class of
11318 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11319 	 * with regards to tracking sign/unsigned bounds because the bits may
11320 	 * cross subreg boundaries in the alu64 case. When this happens we mark
11321 	 * the reg unbounded in the subreg bound space and use the resulting
11322 	 * tnum to calculate an approximation of the sign/unsigned bounds.
11323 	 */
11324 	switch (opcode) {
11325 	case BPF_ADD:
11326 		scalar32_min_max_add(dst_reg, &src_reg);
11327 		scalar_min_max_add(dst_reg, &src_reg);
11328 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11329 		break;
11330 	case BPF_SUB:
11331 		scalar32_min_max_sub(dst_reg, &src_reg);
11332 		scalar_min_max_sub(dst_reg, &src_reg);
11333 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11334 		break;
11335 	case BPF_MUL:
11336 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11337 		scalar32_min_max_mul(dst_reg, &src_reg);
11338 		scalar_min_max_mul(dst_reg, &src_reg);
11339 		break;
11340 	case BPF_AND:
11341 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11342 		scalar32_min_max_and(dst_reg, &src_reg);
11343 		scalar_min_max_and(dst_reg, &src_reg);
11344 		break;
11345 	case BPF_OR:
11346 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11347 		scalar32_min_max_or(dst_reg, &src_reg);
11348 		scalar_min_max_or(dst_reg, &src_reg);
11349 		break;
11350 	case BPF_XOR:
11351 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11352 		scalar32_min_max_xor(dst_reg, &src_reg);
11353 		scalar_min_max_xor(dst_reg, &src_reg);
11354 		break;
11355 	case BPF_LSH:
11356 		if (umax_val >= insn_bitness) {
11357 			/* Shifts greater than 31 or 63 are undefined.
11358 			 * This includes shifts by a negative number.
11359 			 */
11360 			mark_reg_unknown(env, regs, insn->dst_reg);
11361 			break;
11362 		}
11363 		if (alu32)
11364 			scalar32_min_max_lsh(dst_reg, &src_reg);
11365 		else
11366 			scalar_min_max_lsh(dst_reg, &src_reg);
11367 		break;
11368 	case BPF_RSH:
11369 		if (umax_val >= insn_bitness) {
11370 			/* Shifts greater than 31 or 63 are undefined.
11371 			 * This includes shifts by a negative number.
11372 			 */
11373 			mark_reg_unknown(env, regs, insn->dst_reg);
11374 			break;
11375 		}
11376 		if (alu32)
11377 			scalar32_min_max_rsh(dst_reg, &src_reg);
11378 		else
11379 			scalar_min_max_rsh(dst_reg, &src_reg);
11380 		break;
11381 	case BPF_ARSH:
11382 		if (umax_val >= insn_bitness) {
11383 			/* Shifts greater than 31 or 63 are undefined.
11384 			 * This includes shifts by a negative number.
11385 			 */
11386 			mark_reg_unknown(env, regs, insn->dst_reg);
11387 			break;
11388 		}
11389 		if (alu32)
11390 			scalar32_min_max_arsh(dst_reg, &src_reg);
11391 		else
11392 			scalar_min_max_arsh(dst_reg, &src_reg);
11393 		break;
11394 	default:
11395 		mark_reg_unknown(env, regs, insn->dst_reg);
11396 		break;
11397 	}
11398 
11399 	/* ALU32 ops are zero extended into 64bit register */
11400 	if (alu32)
11401 		zext_32_to_64(dst_reg);
11402 	reg_bounds_sync(dst_reg);
11403 	return 0;
11404 }
11405 
11406 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11407  * and var_off.
11408  */
11409 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11410 				   struct bpf_insn *insn)
11411 {
11412 	struct bpf_verifier_state *vstate = env->cur_state;
11413 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11414 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11415 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11416 	u8 opcode = BPF_OP(insn->code);
11417 	int err;
11418 
11419 	dst_reg = &regs[insn->dst_reg];
11420 	src_reg = NULL;
11421 	if (dst_reg->type != SCALAR_VALUE)
11422 		ptr_reg = dst_reg;
11423 	else
11424 		/* Make sure ID is cleared otherwise dst_reg min/max could be
11425 		 * incorrectly propagated into other registers by find_equal_scalars()
11426 		 */
11427 		dst_reg->id = 0;
11428 	if (BPF_SRC(insn->code) == BPF_X) {
11429 		src_reg = &regs[insn->src_reg];
11430 		if (src_reg->type != SCALAR_VALUE) {
11431 			if (dst_reg->type != SCALAR_VALUE) {
11432 				/* Combining two pointers by any ALU op yields
11433 				 * an arbitrary scalar. Disallow all math except
11434 				 * pointer subtraction
11435 				 */
11436 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11437 					mark_reg_unknown(env, regs, insn->dst_reg);
11438 					return 0;
11439 				}
11440 				verbose(env, "R%d pointer %s pointer prohibited\n",
11441 					insn->dst_reg,
11442 					bpf_alu_string[opcode >> 4]);
11443 				return -EACCES;
11444 			} else {
11445 				/* scalar += pointer
11446 				 * This is legal, but we have to reverse our
11447 				 * src/dest handling in computing the range
11448 				 */
11449 				err = mark_chain_precision(env, insn->dst_reg);
11450 				if (err)
11451 					return err;
11452 				return adjust_ptr_min_max_vals(env, insn,
11453 							       src_reg, dst_reg);
11454 			}
11455 		} else if (ptr_reg) {
11456 			/* pointer += scalar */
11457 			err = mark_chain_precision(env, insn->src_reg);
11458 			if (err)
11459 				return err;
11460 			return adjust_ptr_min_max_vals(env, insn,
11461 						       dst_reg, src_reg);
11462 		} else if (dst_reg->precise) {
11463 			/* if dst_reg is precise, src_reg should be precise as well */
11464 			err = mark_chain_precision(env, insn->src_reg);
11465 			if (err)
11466 				return err;
11467 		}
11468 	} else {
11469 		/* Pretend the src is a reg with a known value, since we only
11470 		 * need to be able to read from this state.
11471 		 */
11472 		off_reg.type = SCALAR_VALUE;
11473 		__mark_reg_known(&off_reg, insn->imm);
11474 		src_reg = &off_reg;
11475 		if (ptr_reg) /* pointer += K */
11476 			return adjust_ptr_min_max_vals(env, insn,
11477 						       ptr_reg, src_reg);
11478 	}
11479 
11480 	/* Got here implies adding two SCALAR_VALUEs */
11481 	if (WARN_ON_ONCE(ptr_reg)) {
11482 		print_verifier_state(env, state, true);
11483 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
11484 		return -EINVAL;
11485 	}
11486 	if (WARN_ON(!src_reg)) {
11487 		print_verifier_state(env, state, true);
11488 		verbose(env, "verifier internal error: no src_reg\n");
11489 		return -EINVAL;
11490 	}
11491 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11492 }
11493 
11494 /* check validity of 32-bit and 64-bit arithmetic operations */
11495 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11496 {
11497 	struct bpf_reg_state *regs = cur_regs(env);
11498 	u8 opcode = BPF_OP(insn->code);
11499 	int err;
11500 
11501 	if (opcode == BPF_END || opcode == BPF_NEG) {
11502 		if (opcode == BPF_NEG) {
11503 			if (BPF_SRC(insn->code) != BPF_K ||
11504 			    insn->src_reg != BPF_REG_0 ||
11505 			    insn->off != 0 || insn->imm != 0) {
11506 				verbose(env, "BPF_NEG uses reserved fields\n");
11507 				return -EINVAL;
11508 			}
11509 		} else {
11510 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11511 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11512 			    BPF_CLASS(insn->code) == BPF_ALU64) {
11513 				verbose(env, "BPF_END uses reserved fields\n");
11514 				return -EINVAL;
11515 			}
11516 		}
11517 
11518 		/* check src operand */
11519 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11520 		if (err)
11521 			return err;
11522 
11523 		if (is_pointer_value(env, insn->dst_reg)) {
11524 			verbose(env, "R%d pointer arithmetic prohibited\n",
11525 				insn->dst_reg);
11526 			return -EACCES;
11527 		}
11528 
11529 		/* check dest operand */
11530 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
11531 		if (err)
11532 			return err;
11533 
11534 	} else if (opcode == BPF_MOV) {
11535 
11536 		if (BPF_SRC(insn->code) == BPF_X) {
11537 			if (insn->imm != 0 || insn->off != 0) {
11538 				verbose(env, "BPF_MOV uses reserved fields\n");
11539 				return -EINVAL;
11540 			}
11541 
11542 			/* check src operand */
11543 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11544 			if (err)
11545 				return err;
11546 		} else {
11547 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11548 				verbose(env, "BPF_MOV uses reserved fields\n");
11549 				return -EINVAL;
11550 			}
11551 		}
11552 
11553 		/* check dest operand, mark as required later */
11554 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11555 		if (err)
11556 			return err;
11557 
11558 		if (BPF_SRC(insn->code) == BPF_X) {
11559 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
11560 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11561 
11562 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11563 				/* case: R1 = R2
11564 				 * copy register state to dest reg
11565 				 */
11566 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11567 					/* Assign src and dst registers the same ID
11568 					 * that will be used by find_equal_scalars()
11569 					 * to propagate min/max range.
11570 					 */
11571 					src_reg->id = ++env->id_gen;
11572 				copy_register_state(dst_reg, src_reg);
11573 				dst_reg->live |= REG_LIVE_WRITTEN;
11574 				dst_reg->subreg_def = DEF_NOT_SUBREG;
11575 			} else {
11576 				/* R1 = (u32) R2 */
11577 				if (is_pointer_value(env, insn->src_reg)) {
11578 					verbose(env,
11579 						"R%d partial copy of pointer\n",
11580 						insn->src_reg);
11581 					return -EACCES;
11582 				} else if (src_reg->type == SCALAR_VALUE) {
11583 					copy_register_state(dst_reg, src_reg);
11584 					/* Make sure ID is cleared otherwise
11585 					 * dst_reg min/max could be incorrectly
11586 					 * propagated into src_reg by find_equal_scalars()
11587 					 */
11588 					dst_reg->id = 0;
11589 					dst_reg->live |= REG_LIVE_WRITTEN;
11590 					dst_reg->subreg_def = env->insn_idx + 1;
11591 				} else {
11592 					mark_reg_unknown(env, regs,
11593 							 insn->dst_reg);
11594 				}
11595 				zext_32_to_64(dst_reg);
11596 				reg_bounds_sync(dst_reg);
11597 			}
11598 		} else {
11599 			/* case: R = imm
11600 			 * remember the value we stored into this reg
11601 			 */
11602 			/* clear any state __mark_reg_known doesn't set */
11603 			mark_reg_unknown(env, regs, insn->dst_reg);
11604 			regs[insn->dst_reg].type = SCALAR_VALUE;
11605 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11606 				__mark_reg_known(regs + insn->dst_reg,
11607 						 insn->imm);
11608 			} else {
11609 				__mark_reg_known(regs + insn->dst_reg,
11610 						 (u32)insn->imm);
11611 			}
11612 		}
11613 
11614 	} else if (opcode > BPF_END) {
11615 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11616 		return -EINVAL;
11617 
11618 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
11619 
11620 		if (BPF_SRC(insn->code) == BPF_X) {
11621 			if (insn->imm != 0 || insn->off != 0) {
11622 				verbose(env, "BPF_ALU uses reserved fields\n");
11623 				return -EINVAL;
11624 			}
11625 			/* check src1 operand */
11626 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11627 			if (err)
11628 				return err;
11629 		} else {
11630 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11631 				verbose(env, "BPF_ALU uses reserved fields\n");
11632 				return -EINVAL;
11633 			}
11634 		}
11635 
11636 		/* check src2 operand */
11637 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11638 		if (err)
11639 			return err;
11640 
11641 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11642 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11643 			verbose(env, "div by zero\n");
11644 			return -EINVAL;
11645 		}
11646 
11647 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11648 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11649 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11650 
11651 			if (insn->imm < 0 || insn->imm >= size) {
11652 				verbose(env, "invalid shift %d\n", insn->imm);
11653 				return -EINVAL;
11654 			}
11655 		}
11656 
11657 		/* check dest operand */
11658 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11659 		if (err)
11660 			return err;
11661 
11662 		return adjust_reg_min_max_vals(env, insn);
11663 	}
11664 
11665 	return 0;
11666 }
11667 
11668 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
11669 				   struct bpf_reg_state *dst_reg,
11670 				   enum bpf_reg_type type,
11671 				   bool range_right_open)
11672 {
11673 	struct bpf_func_state *state;
11674 	struct bpf_reg_state *reg;
11675 	int new_range;
11676 
11677 	if (dst_reg->off < 0 ||
11678 	    (dst_reg->off == 0 && range_right_open))
11679 		/* This doesn't give us any range */
11680 		return;
11681 
11682 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
11683 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
11684 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
11685 		 * than pkt_end, but that's because it's also less than pkt.
11686 		 */
11687 		return;
11688 
11689 	new_range = dst_reg->off;
11690 	if (range_right_open)
11691 		new_range++;
11692 
11693 	/* Examples for register markings:
11694 	 *
11695 	 * pkt_data in dst register:
11696 	 *
11697 	 *   r2 = r3;
11698 	 *   r2 += 8;
11699 	 *   if (r2 > pkt_end) goto <handle exception>
11700 	 *   <access okay>
11701 	 *
11702 	 *   r2 = r3;
11703 	 *   r2 += 8;
11704 	 *   if (r2 < pkt_end) goto <access okay>
11705 	 *   <handle exception>
11706 	 *
11707 	 *   Where:
11708 	 *     r2 == dst_reg, pkt_end == src_reg
11709 	 *     r2=pkt(id=n,off=8,r=0)
11710 	 *     r3=pkt(id=n,off=0,r=0)
11711 	 *
11712 	 * pkt_data in src register:
11713 	 *
11714 	 *   r2 = r3;
11715 	 *   r2 += 8;
11716 	 *   if (pkt_end >= r2) goto <access okay>
11717 	 *   <handle exception>
11718 	 *
11719 	 *   r2 = r3;
11720 	 *   r2 += 8;
11721 	 *   if (pkt_end <= r2) goto <handle exception>
11722 	 *   <access okay>
11723 	 *
11724 	 *   Where:
11725 	 *     pkt_end == dst_reg, r2 == src_reg
11726 	 *     r2=pkt(id=n,off=8,r=0)
11727 	 *     r3=pkt(id=n,off=0,r=0)
11728 	 *
11729 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11730 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11731 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11732 	 * the check.
11733 	 */
11734 
11735 	/* If our ids match, then we must have the same max_value.  And we
11736 	 * don't care about the other reg's fixed offset, since if it's too big
11737 	 * the range won't allow anything.
11738 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11739 	 */
11740 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11741 		if (reg->type == type && reg->id == dst_reg->id)
11742 			/* keep the maximum range already checked */
11743 			reg->range = max(reg->range, new_range);
11744 	}));
11745 }
11746 
11747 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11748 {
11749 	struct tnum subreg = tnum_subreg(reg->var_off);
11750 	s32 sval = (s32)val;
11751 
11752 	switch (opcode) {
11753 	case BPF_JEQ:
11754 		if (tnum_is_const(subreg))
11755 			return !!tnum_equals_const(subreg, val);
11756 		break;
11757 	case BPF_JNE:
11758 		if (tnum_is_const(subreg))
11759 			return !tnum_equals_const(subreg, val);
11760 		break;
11761 	case BPF_JSET:
11762 		if ((~subreg.mask & subreg.value) & val)
11763 			return 1;
11764 		if (!((subreg.mask | subreg.value) & val))
11765 			return 0;
11766 		break;
11767 	case BPF_JGT:
11768 		if (reg->u32_min_value > val)
11769 			return 1;
11770 		else if (reg->u32_max_value <= val)
11771 			return 0;
11772 		break;
11773 	case BPF_JSGT:
11774 		if (reg->s32_min_value > sval)
11775 			return 1;
11776 		else if (reg->s32_max_value <= sval)
11777 			return 0;
11778 		break;
11779 	case BPF_JLT:
11780 		if (reg->u32_max_value < val)
11781 			return 1;
11782 		else if (reg->u32_min_value >= val)
11783 			return 0;
11784 		break;
11785 	case BPF_JSLT:
11786 		if (reg->s32_max_value < sval)
11787 			return 1;
11788 		else if (reg->s32_min_value >= sval)
11789 			return 0;
11790 		break;
11791 	case BPF_JGE:
11792 		if (reg->u32_min_value >= val)
11793 			return 1;
11794 		else if (reg->u32_max_value < val)
11795 			return 0;
11796 		break;
11797 	case BPF_JSGE:
11798 		if (reg->s32_min_value >= sval)
11799 			return 1;
11800 		else if (reg->s32_max_value < sval)
11801 			return 0;
11802 		break;
11803 	case BPF_JLE:
11804 		if (reg->u32_max_value <= val)
11805 			return 1;
11806 		else if (reg->u32_min_value > val)
11807 			return 0;
11808 		break;
11809 	case BPF_JSLE:
11810 		if (reg->s32_max_value <= sval)
11811 			return 1;
11812 		else if (reg->s32_min_value > sval)
11813 			return 0;
11814 		break;
11815 	}
11816 
11817 	return -1;
11818 }
11819 
11820 
11821 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11822 {
11823 	s64 sval = (s64)val;
11824 
11825 	switch (opcode) {
11826 	case BPF_JEQ:
11827 		if (tnum_is_const(reg->var_off))
11828 			return !!tnum_equals_const(reg->var_off, val);
11829 		break;
11830 	case BPF_JNE:
11831 		if (tnum_is_const(reg->var_off))
11832 			return !tnum_equals_const(reg->var_off, val);
11833 		break;
11834 	case BPF_JSET:
11835 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11836 			return 1;
11837 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11838 			return 0;
11839 		break;
11840 	case BPF_JGT:
11841 		if (reg->umin_value > val)
11842 			return 1;
11843 		else if (reg->umax_value <= val)
11844 			return 0;
11845 		break;
11846 	case BPF_JSGT:
11847 		if (reg->smin_value > sval)
11848 			return 1;
11849 		else if (reg->smax_value <= sval)
11850 			return 0;
11851 		break;
11852 	case BPF_JLT:
11853 		if (reg->umax_value < val)
11854 			return 1;
11855 		else if (reg->umin_value >= val)
11856 			return 0;
11857 		break;
11858 	case BPF_JSLT:
11859 		if (reg->smax_value < sval)
11860 			return 1;
11861 		else if (reg->smin_value >= sval)
11862 			return 0;
11863 		break;
11864 	case BPF_JGE:
11865 		if (reg->umin_value >= val)
11866 			return 1;
11867 		else if (reg->umax_value < val)
11868 			return 0;
11869 		break;
11870 	case BPF_JSGE:
11871 		if (reg->smin_value >= sval)
11872 			return 1;
11873 		else if (reg->smax_value < sval)
11874 			return 0;
11875 		break;
11876 	case BPF_JLE:
11877 		if (reg->umax_value <= val)
11878 			return 1;
11879 		else if (reg->umin_value > val)
11880 			return 0;
11881 		break;
11882 	case BPF_JSLE:
11883 		if (reg->smax_value <= sval)
11884 			return 1;
11885 		else if (reg->smin_value > sval)
11886 			return 0;
11887 		break;
11888 	}
11889 
11890 	return -1;
11891 }
11892 
11893 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11894  * and return:
11895  *  1 - branch will be taken and "goto target" will be executed
11896  *  0 - branch will not be taken and fall-through to next insn
11897  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11898  *      range [0,10]
11899  */
11900 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11901 			   bool is_jmp32)
11902 {
11903 	if (__is_pointer_value(false, reg)) {
11904 		if (!reg_type_not_null(reg->type))
11905 			return -1;
11906 
11907 		/* If pointer is valid tests against zero will fail so we can
11908 		 * use this to direct branch taken.
11909 		 */
11910 		if (val != 0)
11911 			return -1;
11912 
11913 		switch (opcode) {
11914 		case BPF_JEQ:
11915 			return 0;
11916 		case BPF_JNE:
11917 			return 1;
11918 		default:
11919 			return -1;
11920 		}
11921 	}
11922 
11923 	if (is_jmp32)
11924 		return is_branch32_taken(reg, val, opcode);
11925 	return is_branch64_taken(reg, val, opcode);
11926 }
11927 
11928 static int flip_opcode(u32 opcode)
11929 {
11930 	/* How can we transform "a <op> b" into "b <op> a"? */
11931 	static const u8 opcode_flip[16] = {
11932 		/* these stay the same */
11933 		[BPF_JEQ  >> 4] = BPF_JEQ,
11934 		[BPF_JNE  >> 4] = BPF_JNE,
11935 		[BPF_JSET >> 4] = BPF_JSET,
11936 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11937 		[BPF_JGE  >> 4] = BPF_JLE,
11938 		[BPF_JGT  >> 4] = BPF_JLT,
11939 		[BPF_JLE  >> 4] = BPF_JGE,
11940 		[BPF_JLT  >> 4] = BPF_JGT,
11941 		[BPF_JSGE >> 4] = BPF_JSLE,
11942 		[BPF_JSGT >> 4] = BPF_JSLT,
11943 		[BPF_JSLE >> 4] = BPF_JSGE,
11944 		[BPF_JSLT >> 4] = BPF_JSGT
11945 	};
11946 	return opcode_flip[opcode >> 4];
11947 }
11948 
11949 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11950 				   struct bpf_reg_state *src_reg,
11951 				   u8 opcode)
11952 {
11953 	struct bpf_reg_state *pkt;
11954 
11955 	if (src_reg->type == PTR_TO_PACKET_END) {
11956 		pkt = dst_reg;
11957 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11958 		pkt = src_reg;
11959 		opcode = flip_opcode(opcode);
11960 	} else {
11961 		return -1;
11962 	}
11963 
11964 	if (pkt->range >= 0)
11965 		return -1;
11966 
11967 	switch (opcode) {
11968 	case BPF_JLE:
11969 		/* pkt <= pkt_end */
11970 		fallthrough;
11971 	case BPF_JGT:
11972 		/* pkt > pkt_end */
11973 		if (pkt->range == BEYOND_PKT_END)
11974 			/* pkt has at last one extra byte beyond pkt_end */
11975 			return opcode == BPF_JGT;
11976 		break;
11977 	case BPF_JLT:
11978 		/* pkt < pkt_end */
11979 		fallthrough;
11980 	case BPF_JGE:
11981 		/* pkt >= pkt_end */
11982 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11983 			return opcode == BPF_JGE;
11984 		break;
11985 	}
11986 	return -1;
11987 }
11988 
11989 /* Adjusts the register min/max values in the case that the dst_reg is the
11990  * variable register that we are working on, and src_reg is a constant or we're
11991  * simply doing a BPF_K check.
11992  * In JEQ/JNE cases we also adjust the var_off values.
11993  */
11994 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11995 			    struct bpf_reg_state *false_reg,
11996 			    u64 val, u32 val32,
11997 			    u8 opcode, bool is_jmp32)
11998 {
11999 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
12000 	struct tnum false_64off = false_reg->var_off;
12001 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
12002 	struct tnum true_64off = true_reg->var_off;
12003 	s64 sval = (s64)val;
12004 	s32 sval32 = (s32)val32;
12005 
12006 	/* If the dst_reg is a pointer, we can't learn anything about its
12007 	 * variable offset from the compare (unless src_reg were a pointer into
12008 	 * the same object, but we don't bother with that.
12009 	 * Since false_reg and true_reg have the same type by construction, we
12010 	 * only need to check one of them for pointerness.
12011 	 */
12012 	if (__is_pointer_value(false, false_reg))
12013 		return;
12014 
12015 	switch (opcode) {
12016 	/* JEQ/JNE comparison doesn't change the register equivalence.
12017 	 *
12018 	 * r1 = r2;
12019 	 * if (r1 == 42) goto label;
12020 	 * ...
12021 	 * label: // here both r1 and r2 are known to be 42.
12022 	 *
12023 	 * Hence when marking register as known preserve it's ID.
12024 	 */
12025 	case BPF_JEQ:
12026 		if (is_jmp32) {
12027 			__mark_reg32_known(true_reg, val32);
12028 			true_32off = tnum_subreg(true_reg->var_off);
12029 		} else {
12030 			___mark_reg_known(true_reg, val);
12031 			true_64off = true_reg->var_off;
12032 		}
12033 		break;
12034 	case BPF_JNE:
12035 		if (is_jmp32) {
12036 			__mark_reg32_known(false_reg, val32);
12037 			false_32off = tnum_subreg(false_reg->var_off);
12038 		} else {
12039 			___mark_reg_known(false_reg, val);
12040 			false_64off = false_reg->var_off;
12041 		}
12042 		break;
12043 	case BPF_JSET:
12044 		if (is_jmp32) {
12045 			false_32off = tnum_and(false_32off, tnum_const(~val32));
12046 			if (is_power_of_2(val32))
12047 				true_32off = tnum_or(true_32off,
12048 						     tnum_const(val32));
12049 		} else {
12050 			false_64off = tnum_and(false_64off, tnum_const(~val));
12051 			if (is_power_of_2(val))
12052 				true_64off = tnum_or(true_64off,
12053 						     tnum_const(val));
12054 		}
12055 		break;
12056 	case BPF_JGE:
12057 	case BPF_JGT:
12058 	{
12059 		if (is_jmp32) {
12060 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12061 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12062 
12063 			false_reg->u32_max_value = min(false_reg->u32_max_value,
12064 						       false_umax);
12065 			true_reg->u32_min_value = max(true_reg->u32_min_value,
12066 						      true_umin);
12067 		} else {
12068 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12069 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12070 
12071 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
12072 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
12073 		}
12074 		break;
12075 	}
12076 	case BPF_JSGE:
12077 	case BPF_JSGT:
12078 	{
12079 		if (is_jmp32) {
12080 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12081 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12082 
12083 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12084 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12085 		} else {
12086 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12087 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12088 
12089 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
12090 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
12091 		}
12092 		break;
12093 	}
12094 	case BPF_JLE:
12095 	case BPF_JLT:
12096 	{
12097 		if (is_jmp32) {
12098 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12099 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12100 
12101 			false_reg->u32_min_value = max(false_reg->u32_min_value,
12102 						       false_umin);
12103 			true_reg->u32_max_value = min(true_reg->u32_max_value,
12104 						      true_umax);
12105 		} else {
12106 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12107 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12108 
12109 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
12110 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
12111 		}
12112 		break;
12113 	}
12114 	case BPF_JSLE:
12115 	case BPF_JSLT:
12116 	{
12117 		if (is_jmp32) {
12118 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12119 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12120 
12121 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12122 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12123 		} else {
12124 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12125 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12126 
12127 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
12128 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
12129 		}
12130 		break;
12131 	}
12132 	default:
12133 		return;
12134 	}
12135 
12136 	if (is_jmp32) {
12137 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12138 					     tnum_subreg(false_32off));
12139 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12140 					    tnum_subreg(true_32off));
12141 		__reg_combine_32_into_64(false_reg);
12142 		__reg_combine_32_into_64(true_reg);
12143 	} else {
12144 		false_reg->var_off = false_64off;
12145 		true_reg->var_off = true_64off;
12146 		__reg_combine_64_into_32(false_reg);
12147 		__reg_combine_64_into_32(true_reg);
12148 	}
12149 }
12150 
12151 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12152  * the variable reg.
12153  */
12154 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12155 				struct bpf_reg_state *false_reg,
12156 				u64 val, u32 val32,
12157 				u8 opcode, bool is_jmp32)
12158 {
12159 	opcode = flip_opcode(opcode);
12160 	/* This uses zero as "not present in table"; luckily the zero opcode,
12161 	 * BPF_JA, can't get here.
12162 	 */
12163 	if (opcode)
12164 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12165 }
12166 
12167 /* Regs are known to be equal, so intersect their min/max/var_off */
12168 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12169 				  struct bpf_reg_state *dst_reg)
12170 {
12171 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12172 							dst_reg->umin_value);
12173 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12174 							dst_reg->umax_value);
12175 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12176 							dst_reg->smin_value);
12177 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12178 							dst_reg->smax_value);
12179 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12180 							     dst_reg->var_off);
12181 	reg_bounds_sync(src_reg);
12182 	reg_bounds_sync(dst_reg);
12183 }
12184 
12185 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12186 				struct bpf_reg_state *true_dst,
12187 				struct bpf_reg_state *false_src,
12188 				struct bpf_reg_state *false_dst,
12189 				u8 opcode)
12190 {
12191 	switch (opcode) {
12192 	case BPF_JEQ:
12193 		__reg_combine_min_max(true_src, true_dst);
12194 		break;
12195 	case BPF_JNE:
12196 		__reg_combine_min_max(false_src, false_dst);
12197 		break;
12198 	}
12199 }
12200 
12201 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12202 				 struct bpf_reg_state *reg, u32 id,
12203 				 bool is_null)
12204 {
12205 	if (type_may_be_null(reg->type) && reg->id == id &&
12206 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12207 		/* Old offset (both fixed and variable parts) should have been
12208 		 * known-zero, because we don't allow pointer arithmetic on
12209 		 * pointers that might be NULL. If we see this happening, don't
12210 		 * convert the register.
12211 		 *
12212 		 * But in some cases, some helpers that return local kptrs
12213 		 * advance offset for the returned pointer. In those cases, it
12214 		 * is fine to expect to see reg->off.
12215 		 */
12216 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12217 			return;
12218 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12219 		    WARN_ON_ONCE(reg->off))
12220 			return;
12221 
12222 		if (is_null) {
12223 			reg->type = SCALAR_VALUE;
12224 			/* We don't need id and ref_obj_id from this point
12225 			 * onwards anymore, thus we should better reset it,
12226 			 * so that state pruning has chances to take effect.
12227 			 */
12228 			reg->id = 0;
12229 			reg->ref_obj_id = 0;
12230 
12231 			return;
12232 		}
12233 
12234 		mark_ptr_not_null_reg(reg);
12235 
12236 		if (!reg_may_point_to_spin_lock(reg)) {
12237 			/* For not-NULL ptr, reg->ref_obj_id will be reset
12238 			 * in release_reference().
12239 			 *
12240 			 * reg->id is still used by spin_lock ptr. Other
12241 			 * than spin_lock ptr type, reg->id can be reset.
12242 			 */
12243 			reg->id = 0;
12244 		}
12245 	}
12246 }
12247 
12248 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12249  * be folded together at some point.
12250  */
12251 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12252 				  bool is_null)
12253 {
12254 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12255 	struct bpf_reg_state *regs = state->regs, *reg;
12256 	u32 ref_obj_id = regs[regno].ref_obj_id;
12257 	u32 id = regs[regno].id;
12258 
12259 	if (ref_obj_id && ref_obj_id == id && is_null)
12260 		/* regs[regno] is in the " == NULL" branch.
12261 		 * No one could have freed the reference state before
12262 		 * doing the NULL check.
12263 		 */
12264 		WARN_ON_ONCE(release_reference_state(state, id));
12265 
12266 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12267 		mark_ptr_or_null_reg(state, reg, id, is_null);
12268 	}));
12269 }
12270 
12271 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12272 				   struct bpf_reg_state *dst_reg,
12273 				   struct bpf_reg_state *src_reg,
12274 				   struct bpf_verifier_state *this_branch,
12275 				   struct bpf_verifier_state *other_branch)
12276 {
12277 	if (BPF_SRC(insn->code) != BPF_X)
12278 		return false;
12279 
12280 	/* Pointers are always 64-bit. */
12281 	if (BPF_CLASS(insn->code) == BPF_JMP32)
12282 		return false;
12283 
12284 	switch (BPF_OP(insn->code)) {
12285 	case BPF_JGT:
12286 		if ((dst_reg->type == PTR_TO_PACKET &&
12287 		     src_reg->type == PTR_TO_PACKET_END) ||
12288 		    (dst_reg->type == PTR_TO_PACKET_META &&
12289 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12290 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12291 			find_good_pkt_pointers(this_branch, dst_reg,
12292 					       dst_reg->type, false);
12293 			mark_pkt_end(other_branch, insn->dst_reg, true);
12294 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12295 			    src_reg->type == PTR_TO_PACKET) ||
12296 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12297 			    src_reg->type == PTR_TO_PACKET_META)) {
12298 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
12299 			find_good_pkt_pointers(other_branch, src_reg,
12300 					       src_reg->type, true);
12301 			mark_pkt_end(this_branch, insn->src_reg, false);
12302 		} else {
12303 			return false;
12304 		}
12305 		break;
12306 	case BPF_JLT:
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(other_branch, dst_reg,
12313 					       dst_reg->type, true);
12314 			mark_pkt_end(this_branch, insn->dst_reg, false);
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(this_branch, src_reg,
12321 					       src_reg->type, false);
12322 			mark_pkt_end(other_branch, insn->src_reg, true);
12323 		} else {
12324 			return false;
12325 		}
12326 		break;
12327 	case BPF_JGE:
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(this_branch, dst_reg,
12334 					       dst_reg->type, true);
12335 			mark_pkt_end(other_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(other_branch, src_reg,
12342 					       src_reg->type, false);
12343 			mark_pkt_end(this_branch, insn->src_reg, true);
12344 		} else {
12345 			return false;
12346 		}
12347 		break;
12348 	case BPF_JLE:
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(other_branch, dst_reg,
12355 					       dst_reg->type, false);
12356 			mark_pkt_end(this_branch, insn->dst_reg, true);
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(this_branch, src_reg,
12363 					       src_reg->type, true);
12364 			mark_pkt_end(other_branch, insn->src_reg, false);
12365 		} else {
12366 			return false;
12367 		}
12368 		break;
12369 	default:
12370 		return false;
12371 	}
12372 
12373 	return true;
12374 }
12375 
12376 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12377 			       struct bpf_reg_state *known_reg)
12378 {
12379 	struct bpf_func_state *state;
12380 	struct bpf_reg_state *reg;
12381 
12382 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12383 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12384 			copy_register_state(reg, known_reg);
12385 	}));
12386 }
12387 
12388 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12389 			     struct bpf_insn *insn, int *insn_idx)
12390 {
12391 	struct bpf_verifier_state *this_branch = env->cur_state;
12392 	struct bpf_verifier_state *other_branch;
12393 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12394 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12395 	struct bpf_reg_state *eq_branch_regs;
12396 	u8 opcode = BPF_OP(insn->code);
12397 	bool is_jmp32;
12398 	int pred = -1;
12399 	int err;
12400 
12401 	/* Only conditional jumps are expected to reach here. */
12402 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
12403 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12404 		return -EINVAL;
12405 	}
12406 
12407 	if (BPF_SRC(insn->code) == BPF_X) {
12408 		if (insn->imm != 0) {
12409 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12410 			return -EINVAL;
12411 		}
12412 
12413 		/* check src1 operand */
12414 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12415 		if (err)
12416 			return err;
12417 
12418 		if (is_pointer_value(env, insn->src_reg)) {
12419 			verbose(env, "R%d pointer comparison prohibited\n",
12420 				insn->src_reg);
12421 			return -EACCES;
12422 		}
12423 		src_reg = &regs[insn->src_reg];
12424 	} else {
12425 		if (insn->src_reg != BPF_REG_0) {
12426 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12427 			return -EINVAL;
12428 		}
12429 	}
12430 
12431 	/* check src2 operand */
12432 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12433 	if (err)
12434 		return err;
12435 
12436 	dst_reg = &regs[insn->dst_reg];
12437 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12438 
12439 	if (BPF_SRC(insn->code) == BPF_K) {
12440 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12441 	} else if (src_reg->type == SCALAR_VALUE &&
12442 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12443 		pred = is_branch_taken(dst_reg,
12444 				       tnum_subreg(src_reg->var_off).value,
12445 				       opcode,
12446 				       is_jmp32);
12447 	} else if (src_reg->type == SCALAR_VALUE &&
12448 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12449 		pred = is_branch_taken(dst_reg,
12450 				       src_reg->var_off.value,
12451 				       opcode,
12452 				       is_jmp32);
12453 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
12454 		   reg_is_pkt_pointer_any(src_reg) &&
12455 		   !is_jmp32) {
12456 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12457 	}
12458 
12459 	if (pred >= 0) {
12460 		/* If we get here with a dst_reg pointer type it is because
12461 		 * above is_branch_taken() special cased the 0 comparison.
12462 		 */
12463 		if (!__is_pointer_value(false, dst_reg))
12464 			err = mark_chain_precision(env, insn->dst_reg);
12465 		if (BPF_SRC(insn->code) == BPF_X && !err &&
12466 		    !__is_pointer_value(false, src_reg))
12467 			err = mark_chain_precision(env, insn->src_reg);
12468 		if (err)
12469 			return err;
12470 	}
12471 
12472 	if (pred == 1) {
12473 		/* Only follow the goto, ignore fall-through. If needed, push
12474 		 * the fall-through branch for simulation under speculative
12475 		 * execution.
12476 		 */
12477 		if (!env->bypass_spec_v1 &&
12478 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
12479 					       *insn_idx))
12480 			return -EFAULT;
12481 		*insn_idx += insn->off;
12482 		return 0;
12483 	} else if (pred == 0) {
12484 		/* Only follow the fall-through branch, since that's where the
12485 		 * program will go. If needed, push the goto branch for
12486 		 * simulation under speculative execution.
12487 		 */
12488 		if (!env->bypass_spec_v1 &&
12489 		    !sanitize_speculative_path(env, insn,
12490 					       *insn_idx + insn->off + 1,
12491 					       *insn_idx))
12492 			return -EFAULT;
12493 		return 0;
12494 	}
12495 
12496 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12497 				  false);
12498 	if (!other_branch)
12499 		return -EFAULT;
12500 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12501 
12502 	/* detect if we are comparing against a constant value so we can adjust
12503 	 * our min/max values for our dst register.
12504 	 * this is only legit if both are scalars (or pointers to the same
12505 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12506 	 * because otherwise the different base pointers mean the offsets aren't
12507 	 * comparable.
12508 	 */
12509 	if (BPF_SRC(insn->code) == BPF_X) {
12510 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12511 
12512 		if (dst_reg->type == SCALAR_VALUE &&
12513 		    src_reg->type == SCALAR_VALUE) {
12514 			if (tnum_is_const(src_reg->var_off) ||
12515 			    (is_jmp32 &&
12516 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
12517 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
12518 						dst_reg,
12519 						src_reg->var_off.value,
12520 						tnum_subreg(src_reg->var_off).value,
12521 						opcode, is_jmp32);
12522 			else if (tnum_is_const(dst_reg->var_off) ||
12523 				 (is_jmp32 &&
12524 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
12525 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12526 						    src_reg,
12527 						    dst_reg->var_off.value,
12528 						    tnum_subreg(dst_reg->var_off).value,
12529 						    opcode, is_jmp32);
12530 			else if (!is_jmp32 &&
12531 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
12532 				/* Comparing for equality, we can combine knowledge */
12533 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
12534 						    &other_branch_regs[insn->dst_reg],
12535 						    src_reg, dst_reg, opcode);
12536 			if (src_reg->id &&
12537 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12538 				find_equal_scalars(this_branch, src_reg);
12539 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12540 			}
12541 
12542 		}
12543 	} else if (dst_reg->type == SCALAR_VALUE) {
12544 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
12545 					dst_reg, insn->imm, (u32)insn->imm,
12546 					opcode, is_jmp32);
12547 	}
12548 
12549 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12550 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12551 		find_equal_scalars(this_branch, dst_reg);
12552 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12553 	}
12554 
12555 	/* if one pointer register is compared to another pointer
12556 	 * register check if PTR_MAYBE_NULL could be lifted.
12557 	 * E.g. register A - maybe null
12558 	 *      register B - not null
12559 	 * for JNE A, B, ... - A is not null in the false branch;
12560 	 * for JEQ A, B, ... - A is not null in the true branch.
12561 	 *
12562 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
12563 	 * not need to be null checked by the BPF program, i.e.,
12564 	 * could be null even without PTR_MAYBE_NULL marking, so
12565 	 * only propagate nullness when neither reg is that type.
12566 	 */
12567 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12568 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12569 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12570 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
12571 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12572 		eq_branch_regs = NULL;
12573 		switch (opcode) {
12574 		case BPF_JEQ:
12575 			eq_branch_regs = other_branch_regs;
12576 			break;
12577 		case BPF_JNE:
12578 			eq_branch_regs = regs;
12579 			break;
12580 		default:
12581 			/* do nothing */
12582 			break;
12583 		}
12584 		if (eq_branch_regs) {
12585 			if (type_may_be_null(src_reg->type))
12586 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12587 			else
12588 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12589 		}
12590 	}
12591 
12592 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12593 	 * NOTE: these optimizations below are related with pointer comparison
12594 	 *       which will never be JMP32.
12595 	 */
12596 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12597 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12598 	    type_may_be_null(dst_reg->type)) {
12599 		/* Mark all identical registers in each branch as either
12600 		 * safe or unknown depending R == 0 or R != 0 conditional.
12601 		 */
12602 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12603 				      opcode == BPF_JNE);
12604 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12605 				      opcode == BPF_JEQ);
12606 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12607 					   this_branch, other_branch) &&
12608 		   is_pointer_value(env, insn->dst_reg)) {
12609 		verbose(env, "R%d pointer comparison prohibited\n",
12610 			insn->dst_reg);
12611 		return -EACCES;
12612 	}
12613 	if (env->log.level & BPF_LOG_LEVEL)
12614 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
12615 	return 0;
12616 }
12617 
12618 /* verify BPF_LD_IMM64 instruction */
12619 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12620 {
12621 	struct bpf_insn_aux_data *aux = cur_aux(env);
12622 	struct bpf_reg_state *regs = cur_regs(env);
12623 	struct bpf_reg_state *dst_reg;
12624 	struct bpf_map *map;
12625 	int err;
12626 
12627 	if (BPF_SIZE(insn->code) != BPF_DW) {
12628 		verbose(env, "invalid BPF_LD_IMM insn\n");
12629 		return -EINVAL;
12630 	}
12631 	if (insn->off != 0) {
12632 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12633 		return -EINVAL;
12634 	}
12635 
12636 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
12637 	if (err)
12638 		return err;
12639 
12640 	dst_reg = &regs[insn->dst_reg];
12641 	if (insn->src_reg == 0) {
12642 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12643 
12644 		dst_reg->type = SCALAR_VALUE;
12645 		__mark_reg_known(&regs[insn->dst_reg], imm);
12646 		return 0;
12647 	}
12648 
12649 	/* All special src_reg cases are listed below. From this point onwards
12650 	 * we either succeed and assign a corresponding dst_reg->type after
12651 	 * zeroing the offset, or fail and reject the program.
12652 	 */
12653 	mark_reg_known_zero(env, regs, insn->dst_reg);
12654 
12655 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
12656 		dst_reg->type = aux->btf_var.reg_type;
12657 		switch (base_type(dst_reg->type)) {
12658 		case PTR_TO_MEM:
12659 			dst_reg->mem_size = aux->btf_var.mem_size;
12660 			break;
12661 		case PTR_TO_BTF_ID:
12662 			dst_reg->btf = aux->btf_var.btf;
12663 			dst_reg->btf_id = aux->btf_var.btf_id;
12664 			break;
12665 		default:
12666 			verbose(env, "bpf verifier is misconfigured\n");
12667 			return -EFAULT;
12668 		}
12669 		return 0;
12670 	}
12671 
12672 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
12673 		struct bpf_prog_aux *aux = env->prog->aux;
12674 		u32 subprogno = find_subprog(env,
12675 					     env->insn_idx + insn->imm + 1);
12676 
12677 		if (!aux->func_info) {
12678 			verbose(env, "missing btf func_info\n");
12679 			return -EINVAL;
12680 		}
12681 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
12682 			verbose(env, "callback function not static\n");
12683 			return -EINVAL;
12684 		}
12685 
12686 		dst_reg->type = PTR_TO_FUNC;
12687 		dst_reg->subprogno = subprogno;
12688 		return 0;
12689 	}
12690 
12691 	map = env->used_maps[aux->map_index];
12692 	dst_reg->map_ptr = map;
12693 
12694 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
12695 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
12696 		dst_reg->type = PTR_TO_MAP_VALUE;
12697 		dst_reg->off = aux->map_off;
12698 		WARN_ON_ONCE(map->max_entries != 1);
12699 		/* We want reg->id to be same (0) as map_value is not distinct */
12700 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
12701 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
12702 		dst_reg->type = CONST_PTR_TO_MAP;
12703 	} else {
12704 		verbose(env, "bpf verifier is misconfigured\n");
12705 		return -EINVAL;
12706 	}
12707 
12708 	return 0;
12709 }
12710 
12711 static bool may_access_skb(enum bpf_prog_type type)
12712 {
12713 	switch (type) {
12714 	case BPF_PROG_TYPE_SOCKET_FILTER:
12715 	case BPF_PROG_TYPE_SCHED_CLS:
12716 	case BPF_PROG_TYPE_SCHED_ACT:
12717 		return true;
12718 	default:
12719 		return false;
12720 	}
12721 }
12722 
12723 /* verify safety of LD_ABS|LD_IND instructions:
12724  * - they can only appear in the programs where ctx == skb
12725  * - since they are wrappers of function calls, they scratch R1-R5 registers,
12726  *   preserve R6-R9, and store return value into R0
12727  *
12728  * Implicit input:
12729  *   ctx == skb == R6 == CTX
12730  *
12731  * Explicit input:
12732  *   SRC == any register
12733  *   IMM == 32-bit immediate
12734  *
12735  * Output:
12736  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12737  */
12738 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12739 {
12740 	struct bpf_reg_state *regs = cur_regs(env);
12741 	static const int ctx_reg = BPF_REG_6;
12742 	u8 mode = BPF_MODE(insn->code);
12743 	int i, err;
12744 
12745 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12746 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12747 		return -EINVAL;
12748 	}
12749 
12750 	if (!env->ops->gen_ld_abs) {
12751 		verbose(env, "bpf verifier is misconfigured\n");
12752 		return -EINVAL;
12753 	}
12754 
12755 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12756 	    BPF_SIZE(insn->code) == BPF_DW ||
12757 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12758 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12759 		return -EINVAL;
12760 	}
12761 
12762 	/* check whether implicit source operand (register R6) is readable */
12763 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12764 	if (err)
12765 		return err;
12766 
12767 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12768 	 * gen_ld_abs() may terminate the program at runtime, leading to
12769 	 * reference leak.
12770 	 */
12771 	err = check_reference_leak(env);
12772 	if (err) {
12773 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12774 		return err;
12775 	}
12776 
12777 	if (env->cur_state->active_lock.ptr) {
12778 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12779 		return -EINVAL;
12780 	}
12781 
12782 	if (env->cur_state->active_rcu_lock) {
12783 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12784 		return -EINVAL;
12785 	}
12786 
12787 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12788 		verbose(env,
12789 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12790 		return -EINVAL;
12791 	}
12792 
12793 	if (mode == BPF_IND) {
12794 		/* check explicit source operand */
12795 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12796 		if (err)
12797 			return err;
12798 	}
12799 
12800 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12801 	if (err < 0)
12802 		return err;
12803 
12804 	/* reset caller saved regs to unreadable */
12805 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12806 		mark_reg_not_init(env, regs, caller_saved[i]);
12807 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12808 	}
12809 
12810 	/* mark destination R0 register as readable, since it contains
12811 	 * the value fetched from the packet.
12812 	 * Already marked as written above.
12813 	 */
12814 	mark_reg_unknown(env, regs, BPF_REG_0);
12815 	/* ld_abs load up to 32-bit skb data. */
12816 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12817 	return 0;
12818 }
12819 
12820 static int check_return_code(struct bpf_verifier_env *env)
12821 {
12822 	struct tnum enforce_attach_type_range = tnum_unknown;
12823 	const struct bpf_prog *prog = env->prog;
12824 	struct bpf_reg_state *reg;
12825 	struct tnum range = tnum_range(0, 1);
12826 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12827 	int err;
12828 	struct bpf_func_state *frame = env->cur_state->frame[0];
12829 	const bool is_subprog = frame->subprogno;
12830 
12831 	/* LSM and struct_ops func-ptr's return type could be "void" */
12832 	if (!is_subprog) {
12833 		switch (prog_type) {
12834 		case BPF_PROG_TYPE_LSM:
12835 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12836 				/* See below, can be 0 or 0-1 depending on hook. */
12837 				break;
12838 			fallthrough;
12839 		case BPF_PROG_TYPE_STRUCT_OPS:
12840 			if (!prog->aux->attach_func_proto->type)
12841 				return 0;
12842 			break;
12843 		default:
12844 			break;
12845 		}
12846 	}
12847 
12848 	/* eBPF calling convention is such that R0 is used
12849 	 * to return the value from eBPF program.
12850 	 * Make sure that it's readable at this time
12851 	 * of bpf_exit, which means that program wrote
12852 	 * something into it earlier
12853 	 */
12854 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12855 	if (err)
12856 		return err;
12857 
12858 	if (is_pointer_value(env, BPF_REG_0)) {
12859 		verbose(env, "R0 leaks addr as return value\n");
12860 		return -EACCES;
12861 	}
12862 
12863 	reg = cur_regs(env) + BPF_REG_0;
12864 
12865 	if (frame->in_async_callback_fn) {
12866 		/* enforce return zero from async callbacks like timer */
12867 		if (reg->type != SCALAR_VALUE) {
12868 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12869 				reg_type_str(env, reg->type));
12870 			return -EINVAL;
12871 		}
12872 
12873 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12874 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12875 			return -EINVAL;
12876 		}
12877 		return 0;
12878 	}
12879 
12880 	if (is_subprog) {
12881 		if (reg->type != SCALAR_VALUE) {
12882 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12883 				reg_type_str(env, reg->type));
12884 			return -EINVAL;
12885 		}
12886 		return 0;
12887 	}
12888 
12889 	switch (prog_type) {
12890 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12891 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12892 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12893 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12894 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12895 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12896 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12897 			range = tnum_range(1, 1);
12898 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12899 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12900 			range = tnum_range(0, 3);
12901 		break;
12902 	case BPF_PROG_TYPE_CGROUP_SKB:
12903 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12904 			range = tnum_range(0, 3);
12905 			enforce_attach_type_range = tnum_range(2, 3);
12906 		}
12907 		break;
12908 	case BPF_PROG_TYPE_CGROUP_SOCK:
12909 	case BPF_PROG_TYPE_SOCK_OPS:
12910 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12911 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12912 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12913 		break;
12914 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12915 		if (!env->prog->aux->attach_btf_id)
12916 			return 0;
12917 		range = tnum_const(0);
12918 		break;
12919 	case BPF_PROG_TYPE_TRACING:
12920 		switch (env->prog->expected_attach_type) {
12921 		case BPF_TRACE_FENTRY:
12922 		case BPF_TRACE_FEXIT:
12923 			range = tnum_const(0);
12924 			break;
12925 		case BPF_TRACE_RAW_TP:
12926 		case BPF_MODIFY_RETURN:
12927 			return 0;
12928 		case BPF_TRACE_ITER:
12929 			break;
12930 		default:
12931 			return -ENOTSUPP;
12932 		}
12933 		break;
12934 	case BPF_PROG_TYPE_SK_LOOKUP:
12935 		range = tnum_range(SK_DROP, SK_PASS);
12936 		break;
12937 
12938 	case BPF_PROG_TYPE_LSM:
12939 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12940 			/* Regular BPF_PROG_TYPE_LSM programs can return
12941 			 * any value.
12942 			 */
12943 			return 0;
12944 		}
12945 		if (!env->prog->aux->attach_func_proto->type) {
12946 			/* Make sure programs that attach to void
12947 			 * hooks don't try to modify return value.
12948 			 */
12949 			range = tnum_range(1, 1);
12950 		}
12951 		break;
12952 
12953 	case BPF_PROG_TYPE_EXT:
12954 		/* freplace program can return anything as its return value
12955 		 * depends on the to-be-replaced kernel func or bpf program.
12956 		 */
12957 	default:
12958 		return 0;
12959 	}
12960 
12961 	if (reg->type != SCALAR_VALUE) {
12962 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12963 			reg_type_str(env, reg->type));
12964 		return -EINVAL;
12965 	}
12966 
12967 	if (!tnum_in(range, reg->var_off)) {
12968 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12969 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12970 		    prog_type == BPF_PROG_TYPE_LSM &&
12971 		    !prog->aux->attach_func_proto->type)
12972 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12973 		return -EINVAL;
12974 	}
12975 
12976 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12977 	    tnum_in(enforce_attach_type_range, reg->var_off))
12978 		env->prog->enforce_expected_attach_type = 1;
12979 	return 0;
12980 }
12981 
12982 /* non-recursive DFS pseudo code
12983  * 1  procedure DFS-iterative(G,v):
12984  * 2      label v as discovered
12985  * 3      let S be a stack
12986  * 4      S.push(v)
12987  * 5      while S is not empty
12988  * 6            t <- S.peek()
12989  * 7            if t is what we're looking for:
12990  * 8                return t
12991  * 9            for all edges e in G.adjacentEdges(t) do
12992  * 10               if edge e is already labelled
12993  * 11                   continue with the next edge
12994  * 12               w <- G.adjacentVertex(t,e)
12995  * 13               if vertex w is not discovered and not explored
12996  * 14                   label e as tree-edge
12997  * 15                   label w as discovered
12998  * 16                   S.push(w)
12999  * 17                   continue at 5
13000  * 18               else if vertex w is discovered
13001  * 19                   label e as back-edge
13002  * 20               else
13003  * 21                   // vertex w is explored
13004  * 22                   label e as forward- or cross-edge
13005  * 23           label t as explored
13006  * 24           S.pop()
13007  *
13008  * convention:
13009  * 0x10 - discovered
13010  * 0x11 - discovered and fall-through edge labelled
13011  * 0x12 - discovered and fall-through and branch edges labelled
13012  * 0x20 - explored
13013  */
13014 
13015 enum {
13016 	DISCOVERED = 0x10,
13017 	EXPLORED = 0x20,
13018 	FALLTHROUGH = 1,
13019 	BRANCH = 2,
13020 };
13021 
13022 static u32 state_htab_size(struct bpf_verifier_env *env)
13023 {
13024 	return env->prog->len;
13025 }
13026 
13027 static struct bpf_verifier_state_list **explored_state(
13028 					struct bpf_verifier_env *env,
13029 					int idx)
13030 {
13031 	struct bpf_verifier_state *cur = env->cur_state;
13032 	struct bpf_func_state *state = cur->frame[cur->curframe];
13033 
13034 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13035 }
13036 
13037 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13038 {
13039 	env->insn_aux_data[idx].prune_point = true;
13040 }
13041 
13042 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13043 {
13044 	return env->insn_aux_data[insn_idx].prune_point;
13045 }
13046 
13047 enum {
13048 	DONE_EXPLORING = 0,
13049 	KEEP_EXPLORING = 1,
13050 };
13051 
13052 /* t, w, e - match pseudo-code above:
13053  * t - index of current instruction
13054  * w - next instruction
13055  * e - edge
13056  */
13057 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13058 		     bool loop_ok)
13059 {
13060 	int *insn_stack = env->cfg.insn_stack;
13061 	int *insn_state = env->cfg.insn_state;
13062 
13063 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13064 		return DONE_EXPLORING;
13065 
13066 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13067 		return DONE_EXPLORING;
13068 
13069 	if (w < 0 || w >= env->prog->len) {
13070 		verbose_linfo(env, t, "%d: ", t);
13071 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
13072 		return -EINVAL;
13073 	}
13074 
13075 	if (e == BRANCH) {
13076 		/* mark branch target for state pruning */
13077 		mark_prune_point(env, w);
13078 		mark_jmp_point(env, w);
13079 	}
13080 
13081 	if (insn_state[w] == 0) {
13082 		/* tree-edge */
13083 		insn_state[t] = DISCOVERED | e;
13084 		insn_state[w] = DISCOVERED;
13085 		if (env->cfg.cur_stack >= env->prog->len)
13086 			return -E2BIG;
13087 		insn_stack[env->cfg.cur_stack++] = w;
13088 		return KEEP_EXPLORING;
13089 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13090 		if (loop_ok && env->bpf_capable)
13091 			return DONE_EXPLORING;
13092 		verbose_linfo(env, t, "%d: ", t);
13093 		verbose_linfo(env, w, "%d: ", w);
13094 		verbose(env, "back-edge from insn %d to %d\n", t, w);
13095 		return -EINVAL;
13096 	} else if (insn_state[w] == EXPLORED) {
13097 		/* forward- or cross-edge */
13098 		insn_state[t] = DISCOVERED | e;
13099 	} else {
13100 		verbose(env, "insn state internal bug\n");
13101 		return -EFAULT;
13102 	}
13103 	return DONE_EXPLORING;
13104 }
13105 
13106 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13107 				struct bpf_verifier_env *env,
13108 				bool visit_callee)
13109 {
13110 	int ret;
13111 
13112 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13113 	if (ret)
13114 		return ret;
13115 
13116 	mark_prune_point(env, t + 1);
13117 	/* when we exit from subprog, we need to record non-linear history */
13118 	mark_jmp_point(env, t + 1);
13119 
13120 	if (visit_callee) {
13121 		mark_prune_point(env, t);
13122 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13123 				/* It's ok to allow recursion from CFG point of
13124 				 * view. __check_func_call() will do the actual
13125 				 * check.
13126 				 */
13127 				bpf_pseudo_func(insns + t));
13128 	}
13129 	return ret;
13130 }
13131 
13132 /* Visits the instruction at index t and returns one of the following:
13133  *  < 0 - an error occurred
13134  *  DONE_EXPLORING - the instruction was fully explored
13135  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
13136  */
13137 static int visit_insn(int t, struct bpf_verifier_env *env)
13138 {
13139 	struct bpf_insn *insns = env->prog->insnsi;
13140 	int ret;
13141 
13142 	if (bpf_pseudo_func(insns + t))
13143 		return visit_func_call_insn(t, insns, env, true);
13144 
13145 	/* All non-branch instructions have a single fall-through edge. */
13146 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
13147 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
13148 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
13149 
13150 	switch (BPF_OP(insns[t].code)) {
13151 	case BPF_EXIT:
13152 		return DONE_EXPLORING;
13153 
13154 	case BPF_CALL:
13155 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
13156 			/* Mark this call insn as a prune point to trigger
13157 			 * is_state_visited() check before call itself is
13158 			 * processed by __check_func_call(). Otherwise new
13159 			 * async state will be pushed for further exploration.
13160 			 */
13161 			mark_prune_point(env, t);
13162 		return visit_func_call_insn(t, insns, env,
13163 					    insns[t].src_reg == BPF_PSEUDO_CALL);
13164 
13165 	case BPF_JA:
13166 		if (BPF_SRC(insns[t].code) != BPF_K)
13167 			return -EINVAL;
13168 
13169 		/* unconditional jump with single edge */
13170 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
13171 				true);
13172 		if (ret)
13173 			return ret;
13174 
13175 		mark_prune_point(env, t + insns[t].off + 1);
13176 		mark_jmp_point(env, t + insns[t].off + 1);
13177 
13178 		return ret;
13179 
13180 	default:
13181 		/* conditional jump with two edges */
13182 		mark_prune_point(env, t);
13183 
13184 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13185 		if (ret)
13186 			return ret;
13187 
13188 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
13189 	}
13190 }
13191 
13192 /* non-recursive depth-first-search to detect loops in BPF program
13193  * loop == back-edge in directed graph
13194  */
13195 static int check_cfg(struct bpf_verifier_env *env)
13196 {
13197 	int insn_cnt = env->prog->len;
13198 	int *insn_stack, *insn_state;
13199 	int ret = 0;
13200 	int i;
13201 
13202 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13203 	if (!insn_state)
13204 		return -ENOMEM;
13205 
13206 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13207 	if (!insn_stack) {
13208 		kvfree(insn_state);
13209 		return -ENOMEM;
13210 	}
13211 
13212 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13213 	insn_stack[0] = 0; /* 0 is the first instruction */
13214 	env->cfg.cur_stack = 1;
13215 
13216 	while (env->cfg.cur_stack > 0) {
13217 		int t = insn_stack[env->cfg.cur_stack - 1];
13218 
13219 		ret = visit_insn(t, env);
13220 		switch (ret) {
13221 		case DONE_EXPLORING:
13222 			insn_state[t] = EXPLORED;
13223 			env->cfg.cur_stack--;
13224 			break;
13225 		case KEEP_EXPLORING:
13226 			break;
13227 		default:
13228 			if (ret > 0) {
13229 				verbose(env, "visit_insn internal bug\n");
13230 				ret = -EFAULT;
13231 			}
13232 			goto err_free;
13233 		}
13234 	}
13235 
13236 	if (env->cfg.cur_stack < 0) {
13237 		verbose(env, "pop stack internal bug\n");
13238 		ret = -EFAULT;
13239 		goto err_free;
13240 	}
13241 
13242 	for (i = 0; i < insn_cnt; i++) {
13243 		if (insn_state[i] != EXPLORED) {
13244 			verbose(env, "unreachable insn %d\n", i);
13245 			ret = -EINVAL;
13246 			goto err_free;
13247 		}
13248 	}
13249 	ret = 0; /* cfg looks good */
13250 
13251 err_free:
13252 	kvfree(insn_state);
13253 	kvfree(insn_stack);
13254 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
13255 	return ret;
13256 }
13257 
13258 static int check_abnormal_return(struct bpf_verifier_env *env)
13259 {
13260 	int i;
13261 
13262 	for (i = 1; i < env->subprog_cnt; i++) {
13263 		if (env->subprog_info[i].has_ld_abs) {
13264 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13265 			return -EINVAL;
13266 		}
13267 		if (env->subprog_info[i].has_tail_call) {
13268 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13269 			return -EINVAL;
13270 		}
13271 	}
13272 	return 0;
13273 }
13274 
13275 /* The minimum supported BTF func info size */
13276 #define MIN_BPF_FUNCINFO_SIZE	8
13277 #define MAX_FUNCINFO_REC_SIZE	252
13278 
13279 static int check_btf_func(struct bpf_verifier_env *env,
13280 			  const union bpf_attr *attr,
13281 			  bpfptr_t uattr)
13282 {
13283 	const struct btf_type *type, *func_proto, *ret_type;
13284 	u32 i, nfuncs, urec_size, min_size;
13285 	u32 krec_size = sizeof(struct bpf_func_info);
13286 	struct bpf_func_info *krecord;
13287 	struct bpf_func_info_aux *info_aux = NULL;
13288 	struct bpf_prog *prog;
13289 	const struct btf *btf;
13290 	bpfptr_t urecord;
13291 	u32 prev_offset = 0;
13292 	bool scalar_return;
13293 	int ret = -ENOMEM;
13294 
13295 	nfuncs = attr->func_info_cnt;
13296 	if (!nfuncs) {
13297 		if (check_abnormal_return(env))
13298 			return -EINVAL;
13299 		return 0;
13300 	}
13301 
13302 	if (nfuncs != env->subprog_cnt) {
13303 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13304 		return -EINVAL;
13305 	}
13306 
13307 	urec_size = attr->func_info_rec_size;
13308 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13309 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
13310 	    urec_size % sizeof(u32)) {
13311 		verbose(env, "invalid func info rec size %u\n", urec_size);
13312 		return -EINVAL;
13313 	}
13314 
13315 	prog = env->prog;
13316 	btf = prog->aux->btf;
13317 
13318 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13319 	min_size = min_t(u32, krec_size, urec_size);
13320 
13321 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13322 	if (!krecord)
13323 		return -ENOMEM;
13324 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13325 	if (!info_aux)
13326 		goto err_free;
13327 
13328 	for (i = 0; i < nfuncs; i++) {
13329 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13330 		if (ret) {
13331 			if (ret == -E2BIG) {
13332 				verbose(env, "nonzero tailing record in func info");
13333 				/* set the size kernel expects so loader can zero
13334 				 * out the rest of the record.
13335 				 */
13336 				if (copy_to_bpfptr_offset(uattr,
13337 							  offsetof(union bpf_attr, func_info_rec_size),
13338 							  &min_size, sizeof(min_size)))
13339 					ret = -EFAULT;
13340 			}
13341 			goto err_free;
13342 		}
13343 
13344 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13345 			ret = -EFAULT;
13346 			goto err_free;
13347 		}
13348 
13349 		/* check insn_off */
13350 		ret = -EINVAL;
13351 		if (i == 0) {
13352 			if (krecord[i].insn_off) {
13353 				verbose(env,
13354 					"nonzero insn_off %u for the first func info record",
13355 					krecord[i].insn_off);
13356 				goto err_free;
13357 			}
13358 		} else if (krecord[i].insn_off <= prev_offset) {
13359 			verbose(env,
13360 				"same or smaller insn offset (%u) than previous func info record (%u)",
13361 				krecord[i].insn_off, prev_offset);
13362 			goto err_free;
13363 		}
13364 
13365 		if (env->subprog_info[i].start != krecord[i].insn_off) {
13366 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13367 			goto err_free;
13368 		}
13369 
13370 		/* check type_id */
13371 		type = btf_type_by_id(btf, krecord[i].type_id);
13372 		if (!type || !btf_type_is_func(type)) {
13373 			verbose(env, "invalid type id %d in func info",
13374 				krecord[i].type_id);
13375 			goto err_free;
13376 		}
13377 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13378 
13379 		func_proto = btf_type_by_id(btf, type->type);
13380 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13381 			/* btf_func_check() already verified it during BTF load */
13382 			goto err_free;
13383 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13384 		scalar_return =
13385 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13386 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13387 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13388 			goto err_free;
13389 		}
13390 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13391 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13392 			goto err_free;
13393 		}
13394 
13395 		prev_offset = krecord[i].insn_off;
13396 		bpfptr_add(&urecord, urec_size);
13397 	}
13398 
13399 	prog->aux->func_info = krecord;
13400 	prog->aux->func_info_cnt = nfuncs;
13401 	prog->aux->func_info_aux = info_aux;
13402 	return 0;
13403 
13404 err_free:
13405 	kvfree(krecord);
13406 	kfree(info_aux);
13407 	return ret;
13408 }
13409 
13410 static void adjust_btf_func(struct bpf_verifier_env *env)
13411 {
13412 	struct bpf_prog_aux *aux = env->prog->aux;
13413 	int i;
13414 
13415 	if (!aux->func_info)
13416 		return;
13417 
13418 	for (i = 0; i < env->subprog_cnt; i++)
13419 		aux->func_info[i].insn_off = env->subprog_info[i].start;
13420 }
13421 
13422 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
13423 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
13424 
13425 static int check_btf_line(struct bpf_verifier_env *env,
13426 			  const union bpf_attr *attr,
13427 			  bpfptr_t uattr)
13428 {
13429 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13430 	struct bpf_subprog_info *sub;
13431 	struct bpf_line_info *linfo;
13432 	struct bpf_prog *prog;
13433 	const struct btf *btf;
13434 	bpfptr_t ulinfo;
13435 	int err;
13436 
13437 	nr_linfo = attr->line_info_cnt;
13438 	if (!nr_linfo)
13439 		return 0;
13440 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13441 		return -EINVAL;
13442 
13443 	rec_size = attr->line_info_rec_size;
13444 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13445 	    rec_size > MAX_LINEINFO_REC_SIZE ||
13446 	    rec_size & (sizeof(u32) - 1))
13447 		return -EINVAL;
13448 
13449 	/* Need to zero it in case the userspace may
13450 	 * pass in a smaller bpf_line_info object.
13451 	 */
13452 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13453 			 GFP_KERNEL | __GFP_NOWARN);
13454 	if (!linfo)
13455 		return -ENOMEM;
13456 
13457 	prog = env->prog;
13458 	btf = prog->aux->btf;
13459 
13460 	s = 0;
13461 	sub = env->subprog_info;
13462 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13463 	expected_size = sizeof(struct bpf_line_info);
13464 	ncopy = min_t(u32, expected_size, rec_size);
13465 	for (i = 0; i < nr_linfo; i++) {
13466 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13467 		if (err) {
13468 			if (err == -E2BIG) {
13469 				verbose(env, "nonzero tailing record in line_info");
13470 				if (copy_to_bpfptr_offset(uattr,
13471 							  offsetof(union bpf_attr, line_info_rec_size),
13472 							  &expected_size, sizeof(expected_size)))
13473 					err = -EFAULT;
13474 			}
13475 			goto err_free;
13476 		}
13477 
13478 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13479 			err = -EFAULT;
13480 			goto err_free;
13481 		}
13482 
13483 		/*
13484 		 * Check insn_off to ensure
13485 		 * 1) strictly increasing AND
13486 		 * 2) bounded by prog->len
13487 		 *
13488 		 * The linfo[0].insn_off == 0 check logically falls into
13489 		 * the later "missing bpf_line_info for func..." case
13490 		 * because the first linfo[0].insn_off must be the
13491 		 * first sub also and the first sub must have
13492 		 * subprog_info[0].start == 0.
13493 		 */
13494 		if ((i && linfo[i].insn_off <= prev_offset) ||
13495 		    linfo[i].insn_off >= prog->len) {
13496 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13497 				i, linfo[i].insn_off, prev_offset,
13498 				prog->len);
13499 			err = -EINVAL;
13500 			goto err_free;
13501 		}
13502 
13503 		if (!prog->insnsi[linfo[i].insn_off].code) {
13504 			verbose(env,
13505 				"Invalid insn code at line_info[%u].insn_off\n",
13506 				i);
13507 			err = -EINVAL;
13508 			goto err_free;
13509 		}
13510 
13511 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13512 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13513 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13514 			err = -EINVAL;
13515 			goto err_free;
13516 		}
13517 
13518 		if (s != env->subprog_cnt) {
13519 			if (linfo[i].insn_off == sub[s].start) {
13520 				sub[s].linfo_idx = i;
13521 				s++;
13522 			} else if (sub[s].start < linfo[i].insn_off) {
13523 				verbose(env, "missing bpf_line_info for func#%u\n", s);
13524 				err = -EINVAL;
13525 				goto err_free;
13526 			}
13527 		}
13528 
13529 		prev_offset = linfo[i].insn_off;
13530 		bpfptr_add(&ulinfo, rec_size);
13531 	}
13532 
13533 	if (s != env->subprog_cnt) {
13534 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13535 			env->subprog_cnt - s, s);
13536 		err = -EINVAL;
13537 		goto err_free;
13538 	}
13539 
13540 	prog->aux->linfo = linfo;
13541 	prog->aux->nr_linfo = nr_linfo;
13542 
13543 	return 0;
13544 
13545 err_free:
13546 	kvfree(linfo);
13547 	return err;
13548 }
13549 
13550 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
13551 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
13552 
13553 static int check_core_relo(struct bpf_verifier_env *env,
13554 			   const union bpf_attr *attr,
13555 			   bpfptr_t uattr)
13556 {
13557 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13558 	struct bpf_core_relo core_relo = {};
13559 	struct bpf_prog *prog = env->prog;
13560 	const struct btf *btf = prog->aux->btf;
13561 	struct bpf_core_ctx ctx = {
13562 		.log = &env->log,
13563 		.btf = btf,
13564 	};
13565 	bpfptr_t u_core_relo;
13566 	int err;
13567 
13568 	nr_core_relo = attr->core_relo_cnt;
13569 	if (!nr_core_relo)
13570 		return 0;
13571 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13572 		return -EINVAL;
13573 
13574 	rec_size = attr->core_relo_rec_size;
13575 	if (rec_size < MIN_CORE_RELO_SIZE ||
13576 	    rec_size > MAX_CORE_RELO_SIZE ||
13577 	    rec_size % sizeof(u32))
13578 		return -EINVAL;
13579 
13580 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13581 	expected_size = sizeof(struct bpf_core_relo);
13582 	ncopy = min_t(u32, expected_size, rec_size);
13583 
13584 	/* Unlike func_info and line_info, copy and apply each CO-RE
13585 	 * relocation record one at a time.
13586 	 */
13587 	for (i = 0; i < nr_core_relo; i++) {
13588 		/* future proofing when sizeof(bpf_core_relo) changes */
13589 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13590 		if (err) {
13591 			if (err == -E2BIG) {
13592 				verbose(env, "nonzero tailing record in core_relo");
13593 				if (copy_to_bpfptr_offset(uattr,
13594 							  offsetof(union bpf_attr, core_relo_rec_size),
13595 							  &expected_size, sizeof(expected_size)))
13596 					err = -EFAULT;
13597 			}
13598 			break;
13599 		}
13600 
13601 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13602 			err = -EFAULT;
13603 			break;
13604 		}
13605 
13606 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13607 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13608 				i, core_relo.insn_off, prog->len);
13609 			err = -EINVAL;
13610 			break;
13611 		}
13612 
13613 		err = bpf_core_apply(&ctx, &core_relo, i,
13614 				     &prog->insnsi[core_relo.insn_off / 8]);
13615 		if (err)
13616 			break;
13617 		bpfptr_add(&u_core_relo, rec_size);
13618 	}
13619 	return err;
13620 }
13621 
13622 static int check_btf_info(struct bpf_verifier_env *env,
13623 			  const union bpf_attr *attr,
13624 			  bpfptr_t uattr)
13625 {
13626 	struct btf *btf;
13627 	int err;
13628 
13629 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
13630 		if (check_abnormal_return(env))
13631 			return -EINVAL;
13632 		return 0;
13633 	}
13634 
13635 	btf = btf_get_by_fd(attr->prog_btf_fd);
13636 	if (IS_ERR(btf))
13637 		return PTR_ERR(btf);
13638 	if (btf_is_kernel(btf)) {
13639 		btf_put(btf);
13640 		return -EACCES;
13641 	}
13642 	env->prog->aux->btf = btf;
13643 
13644 	err = check_btf_func(env, attr, uattr);
13645 	if (err)
13646 		return err;
13647 
13648 	err = check_btf_line(env, attr, uattr);
13649 	if (err)
13650 		return err;
13651 
13652 	err = check_core_relo(env, attr, uattr);
13653 	if (err)
13654 		return err;
13655 
13656 	return 0;
13657 }
13658 
13659 /* check %cur's range satisfies %old's */
13660 static bool range_within(struct bpf_reg_state *old,
13661 			 struct bpf_reg_state *cur)
13662 {
13663 	return old->umin_value <= cur->umin_value &&
13664 	       old->umax_value >= cur->umax_value &&
13665 	       old->smin_value <= cur->smin_value &&
13666 	       old->smax_value >= cur->smax_value &&
13667 	       old->u32_min_value <= cur->u32_min_value &&
13668 	       old->u32_max_value >= cur->u32_max_value &&
13669 	       old->s32_min_value <= cur->s32_min_value &&
13670 	       old->s32_max_value >= cur->s32_max_value;
13671 }
13672 
13673 /* If in the old state two registers had the same id, then they need to have
13674  * the same id in the new state as well.  But that id could be different from
13675  * the old state, so we need to track the mapping from old to new ids.
13676  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
13677  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
13678  * regs with a different old id could still have new id 9, we don't care about
13679  * that.
13680  * So we look through our idmap to see if this old id has been seen before.  If
13681  * so, we require the new id to match; otherwise, we add the id pair to the map.
13682  */
13683 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
13684 {
13685 	unsigned int i;
13686 
13687 	/* either both IDs should be set or both should be zero */
13688 	if (!!old_id != !!cur_id)
13689 		return false;
13690 
13691 	if (old_id == 0) /* cur_id == 0 as well */
13692 		return true;
13693 
13694 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
13695 		if (!idmap[i].old) {
13696 			/* Reached an empty slot; haven't seen this id before */
13697 			idmap[i].old = old_id;
13698 			idmap[i].cur = cur_id;
13699 			return true;
13700 		}
13701 		if (idmap[i].old == old_id)
13702 			return idmap[i].cur == cur_id;
13703 	}
13704 	/* We ran out of idmap slots, which should be impossible */
13705 	WARN_ON_ONCE(1);
13706 	return false;
13707 }
13708 
13709 static void clean_func_state(struct bpf_verifier_env *env,
13710 			     struct bpf_func_state *st)
13711 {
13712 	enum bpf_reg_liveness live;
13713 	int i, j;
13714 
13715 	for (i = 0; i < BPF_REG_FP; i++) {
13716 		live = st->regs[i].live;
13717 		/* liveness must not touch this register anymore */
13718 		st->regs[i].live |= REG_LIVE_DONE;
13719 		if (!(live & REG_LIVE_READ))
13720 			/* since the register is unused, clear its state
13721 			 * to make further comparison simpler
13722 			 */
13723 			__mark_reg_not_init(env, &st->regs[i]);
13724 	}
13725 
13726 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
13727 		live = st->stack[i].spilled_ptr.live;
13728 		/* liveness must not touch this stack slot anymore */
13729 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13730 		if (!(live & REG_LIVE_READ)) {
13731 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13732 			for (j = 0; j < BPF_REG_SIZE; j++)
13733 				st->stack[i].slot_type[j] = STACK_INVALID;
13734 		}
13735 	}
13736 }
13737 
13738 static void clean_verifier_state(struct bpf_verifier_env *env,
13739 				 struct bpf_verifier_state *st)
13740 {
13741 	int i;
13742 
13743 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13744 		/* all regs in this state in all frames were already marked */
13745 		return;
13746 
13747 	for (i = 0; i <= st->curframe; i++)
13748 		clean_func_state(env, st->frame[i]);
13749 }
13750 
13751 /* the parentage chains form a tree.
13752  * the verifier states are added to state lists at given insn and
13753  * pushed into state stack for future exploration.
13754  * when the verifier reaches bpf_exit insn some of the verifer states
13755  * stored in the state lists have their final liveness state already,
13756  * but a lot of states will get revised from liveness point of view when
13757  * the verifier explores other branches.
13758  * Example:
13759  * 1: r0 = 1
13760  * 2: if r1 == 100 goto pc+1
13761  * 3: r0 = 2
13762  * 4: exit
13763  * when the verifier reaches exit insn the register r0 in the state list of
13764  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13765  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13766  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13767  *
13768  * Since the verifier pushes the branch states as it sees them while exploring
13769  * the program the condition of walking the branch instruction for the second
13770  * time means that all states below this branch were already explored and
13771  * their final liveness marks are already propagated.
13772  * Hence when the verifier completes the search of state list in is_state_visited()
13773  * we can call this clean_live_states() function to mark all liveness states
13774  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13775  * will not be used.
13776  * This function also clears the registers and stack for states that !READ
13777  * to simplify state merging.
13778  *
13779  * Important note here that walking the same branch instruction in the callee
13780  * doesn't meant that the states are DONE. The verifier has to compare
13781  * the callsites
13782  */
13783 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13784 			      struct bpf_verifier_state *cur)
13785 {
13786 	struct bpf_verifier_state_list *sl;
13787 	int i;
13788 
13789 	sl = *explored_state(env, insn);
13790 	while (sl) {
13791 		if (sl->state.branches)
13792 			goto next;
13793 		if (sl->state.insn_idx != insn ||
13794 		    sl->state.curframe != cur->curframe)
13795 			goto next;
13796 		for (i = 0; i <= cur->curframe; i++)
13797 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13798 				goto next;
13799 		clean_verifier_state(env, &sl->state);
13800 next:
13801 		sl = sl->next;
13802 	}
13803 }
13804 
13805 static bool regs_exact(const struct bpf_reg_state *rold,
13806 		       const struct bpf_reg_state *rcur,
13807 		       struct bpf_id_pair *idmap)
13808 {
13809 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13810 	       check_ids(rold->id, rcur->id, idmap) &&
13811 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13812 }
13813 
13814 /* Returns true if (rold safe implies rcur safe) */
13815 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13816 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13817 {
13818 	if (!(rold->live & REG_LIVE_READ))
13819 		/* explored state didn't use this */
13820 		return true;
13821 	if (rold->type == NOT_INIT)
13822 		/* explored state can't have used this */
13823 		return true;
13824 	if (rcur->type == NOT_INIT)
13825 		return false;
13826 
13827 	/* Enforce that register types have to match exactly, including their
13828 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13829 	 * rule.
13830 	 *
13831 	 * One can make a point that using a pointer register as unbounded
13832 	 * SCALAR would be technically acceptable, but this could lead to
13833 	 * pointer leaks because scalars are allowed to leak while pointers
13834 	 * are not. We could make this safe in special cases if root is
13835 	 * calling us, but it's probably not worth the hassle.
13836 	 *
13837 	 * Also, register types that are *not* MAYBE_NULL could technically be
13838 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13839 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13840 	 * to the same map).
13841 	 * However, if the old MAYBE_NULL register then got NULL checked,
13842 	 * doing so could have affected others with the same id, and we can't
13843 	 * check for that because we lost the id when we converted to
13844 	 * a non-MAYBE_NULL variant.
13845 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13846 	 * non-MAYBE_NULL registers as well.
13847 	 */
13848 	if (rold->type != rcur->type)
13849 		return false;
13850 
13851 	switch (base_type(rold->type)) {
13852 	case SCALAR_VALUE:
13853 		if (regs_exact(rold, rcur, idmap))
13854 			return true;
13855 		if (env->explore_alu_limits)
13856 			return false;
13857 		if (!rold->precise)
13858 			return true;
13859 		/* new val must satisfy old val knowledge */
13860 		return range_within(rold, rcur) &&
13861 		       tnum_in(rold->var_off, rcur->var_off);
13862 	case PTR_TO_MAP_KEY:
13863 	case PTR_TO_MAP_VALUE:
13864 		/* If the new min/max/var_off satisfy the old ones and
13865 		 * everything else matches, we are OK.
13866 		 */
13867 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13868 		       range_within(rold, rcur) &&
13869 		       tnum_in(rold->var_off, rcur->var_off) &&
13870 		       check_ids(rold->id, rcur->id, idmap);
13871 	case PTR_TO_PACKET_META:
13872 	case PTR_TO_PACKET:
13873 		/* We must have at least as much range as the old ptr
13874 		 * did, so that any accesses which were safe before are
13875 		 * still safe.  This is true even if old range < old off,
13876 		 * since someone could have accessed through (ptr - k), or
13877 		 * even done ptr -= k in a register, to get a safe access.
13878 		 */
13879 		if (rold->range > rcur->range)
13880 			return false;
13881 		/* If the offsets don't match, we can't trust our alignment;
13882 		 * nor can we be sure that we won't fall out of range.
13883 		 */
13884 		if (rold->off != rcur->off)
13885 			return false;
13886 		/* id relations must be preserved */
13887 		if (!check_ids(rold->id, rcur->id, idmap))
13888 			return false;
13889 		/* new val must satisfy old val knowledge */
13890 		return range_within(rold, rcur) &&
13891 		       tnum_in(rold->var_off, rcur->var_off);
13892 	case PTR_TO_STACK:
13893 		/* two stack pointers are equal only if they're pointing to
13894 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13895 		 */
13896 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13897 	default:
13898 		return regs_exact(rold, rcur, idmap);
13899 	}
13900 }
13901 
13902 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13903 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13904 {
13905 	int i, spi;
13906 
13907 	/* walk slots of the explored stack and ignore any additional
13908 	 * slots in the current stack, since explored(safe) state
13909 	 * didn't use them
13910 	 */
13911 	for (i = 0; i < old->allocated_stack; i++) {
13912 		spi = i / BPF_REG_SIZE;
13913 
13914 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13915 			i += BPF_REG_SIZE - 1;
13916 			/* explored state didn't use this */
13917 			continue;
13918 		}
13919 
13920 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13921 			continue;
13922 
13923 		/* explored stack has more populated slots than current stack
13924 		 * and these slots were used
13925 		 */
13926 		if (i >= cur->allocated_stack)
13927 			return false;
13928 
13929 		/* if old state was safe with misc data in the stack
13930 		 * it will be safe with zero-initialized stack.
13931 		 * The opposite is not true
13932 		 */
13933 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13934 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13935 			continue;
13936 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13937 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13938 			/* Ex: old explored (safe) state has STACK_SPILL in
13939 			 * this stack slot, but current has STACK_MISC ->
13940 			 * this verifier states are not equivalent,
13941 			 * return false to continue verification of this path
13942 			 */
13943 			return false;
13944 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13945 			continue;
13946 		/* Both old and cur are having same slot_type */
13947 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
13948 		case STACK_SPILL:
13949 			/* when explored and current stack slot are both storing
13950 			 * spilled registers, check that stored pointers types
13951 			 * are the same as well.
13952 			 * Ex: explored safe path could have stored
13953 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13954 			 * but current path has stored:
13955 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13956 			 * such verifier states are not equivalent.
13957 			 * return false to continue verification of this path
13958 			 */
13959 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
13960 				     &cur->stack[spi].spilled_ptr, idmap))
13961 				return false;
13962 			break;
13963 		case STACK_DYNPTR:
13964 		{
13965 			const struct bpf_reg_state *old_reg, *cur_reg;
13966 
13967 			old_reg = &old->stack[spi].spilled_ptr;
13968 			cur_reg = &cur->stack[spi].spilled_ptr;
13969 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
13970 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
13971 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
13972 				return false;
13973 			break;
13974 		}
13975 		case STACK_MISC:
13976 		case STACK_ZERO:
13977 		case STACK_INVALID:
13978 			continue;
13979 		/* Ensure that new unhandled slot types return false by default */
13980 		default:
13981 			return false;
13982 		}
13983 	}
13984 	return true;
13985 }
13986 
13987 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
13988 		    struct bpf_id_pair *idmap)
13989 {
13990 	int i;
13991 
13992 	if (old->acquired_refs != cur->acquired_refs)
13993 		return false;
13994 
13995 	for (i = 0; i < old->acquired_refs; i++) {
13996 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
13997 			return false;
13998 	}
13999 
14000 	return true;
14001 }
14002 
14003 /* compare two verifier states
14004  *
14005  * all states stored in state_list are known to be valid, since
14006  * verifier reached 'bpf_exit' instruction through them
14007  *
14008  * this function is called when verifier exploring different branches of
14009  * execution popped from the state stack. If it sees an old state that has
14010  * more strict register state and more strict stack state then this execution
14011  * branch doesn't need to be explored further, since verifier already
14012  * concluded that more strict state leads to valid finish.
14013  *
14014  * Therefore two states are equivalent if register state is more conservative
14015  * and explored stack state is more conservative than the current one.
14016  * Example:
14017  *       explored                   current
14018  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14019  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14020  *
14021  * In other words if current stack state (one being explored) has more
14022  * valid slots than old one that already passed validation, it means
14023  * the verifier can stop exploring and conclude that current state is valid too
14024  *
14025  * Similarly with registers. If explored state has register type as invalid
14026  * whereas register type in current state is meaningful, it means that
14027  * the current state will reach 'bpf_exit' instruction safely
14028  */
14029 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14030 			      struct bpf_func_state *cur)
14031 {
14032 	int i;
14033 
14034 	for (i = 0; i < MAX_BPF_REG; i++)
14035 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
14036 			     env->idmap_scratch))
14037 			return false;
14038 
14039 	if (!stacksafe(env, old, cur, env->idmap_scratch))
14040 		return false;
14041 
14042 	if (!refsafe(old, cur, env->idmap_scratch))
14043 		return false;
14044 
14045 	return true;
14046 }
14047 
14048 static bool states_equal(struct bpf_verifier_env *env,
14049 			 struct bpf_verifier_state *old,
14050 			 struct bpf_verifier_state *cur)
14051 {
14052 	int i;
14053 
14054 	if (old->curframe != cur->curframe)
14055 		return false;
14056 
14057 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14058 
14059 	/* Verification state from speculative execution simulation
14060 	 * must never prune a non-speculative execution one.
14061 	 */
14062 	if (old->speculative && !cur->speculative)
14063 		return false;
14064 
14065 	if (old->active_lock.ptr != cur->active_lock.ptr)
14066 		return false;
14067 
14068 	/* Old and cur active_lock's have to be either both present
14069 	 * or both absent.
14070 	 */
14071 	if (!!old->active_lock.id != !!cur->active_lock.id)
14072 		return false;
14073 
14074 	if (old->active_lock.id &&
14075 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14076 		return false;
14077 
14078 	if (old->active_rcu_lock != cur->active_rcu_lock)
14079 		return false;
14080 
14081 	/* for states to be equal callsites have to be the same
14082 	 * and all frame states need to be equivalent
14083 	 */
14084 	for (i = 0; i <= old->curframe; i++) {
14085 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
14086 			return false;
14087 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14088 			return false;
14089 	}
14090 	return true;
14091 }
14092 
14093 /* Return 0 if no propagation happened. Return negative error code if error
14094  * happened. Otherwise, return the propagated bit.
14095  */
14096 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14097 				  struct bpf_reg_state *reg,
14098 				  struct bpf_reg_state *parent_reg)
14099 {
14100 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14101 	u8 flag = reg->live & REG_LIVE_READ;
14102 	int err;
14103 
14104 	/* When comes here, read flags of PARENT_REG or REG could be any of
14105 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14106 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14107 	 */
14108 	if (parent_flag == REG_LIVE_READ64 ||
14109 	    /* Or if there is no read flag from REG. */
14110 	    !flag ||
14111 	    /* Or if the read flag from REG is the same as PARENT_REG. */
14112 	    parent_flag == flag)
14113 		return 0;
14114 
14115 	err = mark_reg_read(env, reg, parent_reg, flag);
14116 	if (err)
14117 		return err;
14118 
14119 	return flag;
14120 }
14121 
14122 /* A write screens off any subsequent reads; but write marks come from the
14123  * straight-line code between a state and its parent.  When we arrive at an
14124  * equivalent state (jump target or such) we didn't arrive by the straight-line
14125  * code, so read marks in the state must propagate to the parent regardless
14126  * of the state's write marks. That's what 'parent == state->parent' comparison
14127  * in mark_reg_read() is for.
14128  */
14129 static int propagate_liveness(struct bpf_verifier_env *env,
14130 			      const struct bpf_verifier_state *vstate,
14131 			      struct bpf_verifier_state *vparent)
14132 {
14133 	struct bpf_reg_state *state_reg, *parent_reg;
14134 	struct bpf_func_state *state, *parent;
14135 	int i, frame, err = 0;
14136 
14137 	if (vparent->curframe != vstate->curframe) {
14138 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
14139 		     vparent->curframe, vstate->curframe);
14140 		return -EFAULT;
14141 	}
14142 	/* Propagate read liveness of registers... */
14143 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14144 	for (frame = 0; frame <= vstate->curframe; frame++) {
14145 		parent = vparent->frame[frame];
14146 		state = vstate->frame[frame];
14147 		parent_reg = parent->regs;
14148 		state_reg = state->regs;
14149 		/* We don't need to worry about FP liveness, it's read-only */
14150 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14151 			err = propagate_liveness_reg(env, &state_reg[i],
14152 						     &parent_reg[i]);
14153 			if (err < 0)
14154 				return err;
14155 			if (err == REG_LIVE_READ64)
14156 				mark_insn_zext(env, &parent_reg[i]);
14157 		}
14158 
14159 		/* Propagate stack slots. */
14160 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14161 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14162 			parent_reg = &parent->stack[i].spilled_ptr;
14163 			state_reg = &state->stack[i].spilled_ptr;
14164 			err = propagate_liveness_reg(env, state_reg,
14165 						     parent_reg);
14166 			if (err < 0)
14167 				return err;
14168 		}
14169 	}
14170 	return 0;
14171 }
14172 
14173 /* find precise scalars in the previous equivalent state and
14174  * propagate them into the current state
14175  */
14176 static int propagate_precision(struct bpf_verifier_env *env,
14177 			       const struct bpf_verifier_state *old)
14178 {
14179 	struct bpf_reg_state *state_reg;
14180 	struct bpf_func_state *state;
14181 	int i, err = 0, fr;
14182 
14183 	for (fr = old->curframe; fr >= 0; fr--) {
14184 		state = old->frame[fr];
14185 		state_reg = state->regs;
14186 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14187 			if (state_reg->type != SCALAR_VALUE ||
14188 			    !state_reg->precise)
14189 				continue;
14190 			if (env->log.level & BPF_LOG_LEVEL2)
14191 				verbose(env, "frame %d: propagating r%d\n", i, fr);
14192 			err = mark_chain_precision_frame(env, fr, i);
14193 			if (err < 0)
14194 				return err;
14195 		}
14196 
14197 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14198 			if (!is_spilled_reg(&state->stack[i]))
14199 				continue;
14200 			state_reg = &state->stack[i].spilled_ptr;
14201 			if (state_reg->type != SCALAR_VALUE ||
14202 			    !state_reg->precise)
14203 				continue;
14204 			if (env->log.level & BPF_LOG_LEVEL2)
14205 				verbose(env, "frame %d: propagating fp%d\n",
14206 					(-i - 1) * BPF_REG_SIZE, fr);
14207 			err = mark_chain_precision_stack_frame(env, fr, i);
14208 			if (err < 0)
14209 				return err;
14210 		}
14211 	}
14212 	return 0;
14213 }
14214 
14215 static bool states_maybe_looping(struct bpf_verifier_state *old,
14216 				 struct bpf_verifier_state *cur)
14217 {
14218 	struct bpf_func_state *fold, *fcur;
14219 	int i, fr = cur->curframe;
14220 
14221 	if (old->curframe != fr)
14222 		return false;
14223 
14224 	fold = old->frame[fr];
14225 	fcur = cur->frame[fr];
14226 	for (i = 0; i < MAX_BPF_REG; i++)
14227 		if (memcmp(&fold->regs[i], &fcur->regs[i],
14228 			   offsetof(struct bpf_reg_state, parent)))
14229 			return false;
14230 	return true;
14231 }
14232 
14233 
14234 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14235 {
14236 	struct bpf_verifier_state_list *new_sl;
14237 	struct bpf_verifier_state_list *sl, **pprev;
14238 	struct bpf_verifier_state *cur = env->cur_state, *new;
14239 	int i, j, err, states_cnt = 0;
14240 	bool add_new_state = env->test_state_freq ? true : false;
14241 
14242 	/* bpf progs typically have pruning point every 4 instructions
14243 	 * http://vger.kernel.org/bpfconf2019.html#session-1
14244 	 * Do not add new state for future pruning if the verifier hasn't seen
14245 	 * at least 2 jumps and at least 8 instructions.
14246 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14247 	 * In tests that amounts to up to 50% reduction into total verifier
14248 	 * memory consumption and 20% verifier time speedup.
14249 	 */
14250 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14251 	    env->insn_processed - env->prev_insn_processed >= 8)
14252 		add_new_state = true;
14253 
14254 	pprev = explored_state(env, insn_idx);
14255 	sl = *pprev;
14256 
14257 	clean_live_states(env, insn_idx, cur);
14258 
14259 	while (sl) {
14260 		states_cnt++;
14261 		if (sl->state.insn_idx != insn_idx)
14262 			goto next;
14263 
14264 		if (sl->state.branches) {
14265 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14266 
14267 			if (frame->in_async_callback_fn &&
14268 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14269 				/* Different async_entry_cnt means that the verifier is
14270 				 * processing another entry into async callback.
14271 				 * Seeing the same state is not an indication of infinite
14272 				 * loop or infinite recursion.
14273 				 * But finding the same state doesn't mean that it's safe
14274 				 * to stop processing the current state. The previous state
14275 				 * hasn't yet reached bpf_exit, since state.branches > 0.
14276 				 * Checking in_async_callback_fn alone is not enough either.
14277 				 * Since the verifier still needs to catch infinite loops
14278 				 * inside async callbacks.
14279 				 */
14280 			} else if (states_maybe_looping(&sl->state, cur) &&
14281 				   states_equal(env, &sl->state, cur)) {
14282 				verbose_linfo(env, insn_idx, "; ");
14283 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14284 				return -EINVAL;
14285 			}
14286 			/* if the verifier is processing a loop, avoid adding new state
14287 			 * too often, since different loop iterations have distinct
14288 			 * states and may not help future pruning.
14289 			 * This threshold shouldn't be too low to make sure that
14290 			 * a loop with large bound will be rejected quickly.
14291 			 * The most abusive loop will be:
14292 			 * r1 += 1
14293 			 * if r1 < 1000000 goto pc-2
14294 			 * 1M insn_procssed limit / 100 == 10k peak states.
14295 			 * This threshold shouldn't be too high either, since states
14296 			 * at the end of the loop are likely to be useful in pruning.
14297 			 */
14298 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
14299 			    env->insn_processed - env->prev_insn_processed < 100)
14300 				add_new_state = false;
14301 			goto miss;
14302 		}
14303 		if (states_equal(env, &sl->state, cur)) {
14304 			sl->hit_cnt++;
14305 			/* reached equivalent register/stack state,
14306 			 * prune the search.
14307 			 * Registers read by the continuation are read by us.
14308 			 * If we have any write marks in env->cur_state, they
14309 			 * will prevent corresponding reads in the continuation
14310 			 * from reaching our parent (an explored_state).  Our
14311 			 * own state will get the read marks recorded, but
14312 			 * they'll be immediately forgotten as we're pruning
14313 			 * this state and will pop a new one.
14314 			 */
14315 			err = propagate_liveness(env, &sl->state, cur);
14316 
14317 			/* if previous state reached the exit with precision and
14318 			 * current state is equivalent to it (except precsion marks)
14319 			 * the precision needs to be propagated back in
14320 			 * the current state.
14321 			 */
14322 			err = err ? : push_jmp_history(env, cur);
14323 			err = err ? : propagate_precision(env, &sl->state);
14324 			if (err)
14325 				return err;
14326 			return 1;
14327 		}
14328 miss:
14329 		/* when new state is not going to be added do not increase miss count.
14330 		 * Otherwise several loop iterations will remove the state
14331 		 * recorded earlier. The goal of these heuristics is to have
14332 		 * states from some iterations of the loop (some in the beginning
14333 		 * and some at the end) to help pruning.
14334 		 */
14335 		if (add_new_state)
14336 			sl->miss_cnt++;
14337 		/* heuristic to determine whether this state is beneficial
14338 		 * to keep checking from state equivalence point of view.
14339 		 * Higher numbers increase max_states_per_insn and verification time,
14340 		 * but do not meaningfully decrease insn_processed.
14341 		 */
14342 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14343 			/* the state is unlikely to be useful. Remove it to
14344 			 * speed up verification
14345 			 */
14346 			*pprev = sl->next;
14347 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14348 				u32 br = sl->state.branches;
14349 
14350 				WARN_ONCE(br,
14351 					  "BUG live_done but branches_to_explore %d\n",
14352 					  br);
14353 				free_verifier_state(&sl->state, false);
14354 				kfree(sl);
14355 				env->peak_states--;
14356 			} else {
14357 				/* cannot free this state, since parentage chain may
14358 				 * walk it later. Add it for free_list instead to
14359 				 * be freed at the end of verification
14360 				 */
14361 				sl->next = env->free_list;
14362 				env->free_list = sl;
14363 			}
14364 			sl = *pprev;
14365 			continue;
14366 		}
14367 next:
14368 		pprev = &sl->next;
14369 		sl = *pprev;
14370 	}
14371 
14372 	if (env->max_states_per_insn < states_cnt)
14373 		env->max_states_per_insn = states_cnt;
14374 
14375 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14376 		return 0;
14377 
14378 	if (!add_new_state)
14379 		return 0;
14380 
14381 	/* There were no equivalent states, remember the current one.
14382 	 * Technically the current state is not proven to be safe yet,
14383 	 * but it will either reach outer most bpf_exit (which means it's safe)
14384 	 * or it will be rejected. When there are no loops the verifier won't be
14385 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14386 	 * again on the way to bpf_exit.
14387 	 * When looping the sl->state.branches will be > 0 and this state
14388 	 * will not be considered for equivalence until branches == 0.
14389 	 */
14390 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14391 	if (!new_sl)
14392 		return -ENOMEM;
14393 	env->total_states++;
14394 	env->peak_states++;
14395 	env->prev_jmps_processed = env->jmps_processed;
14396 	env->prev_insn_processed = env->insn_processed;
14397 
14398 	/* forget precise markings we inherited, see __mark_chain_precision */
14399 	if (env->bpf_capable)
14400 		mark_all_scalars_imprecise(env, cur);
14401 
14402 	/* add new state to the head of linked list */
14403 	new = &new_sl->state;
14404 	err = copy_verifier_state(new, cur);
14405 	if (err) {
14406 		free_verifier_state(new, false);
14407 		kfree(new_sl);
14408 		return err;
14409 	}
14410 	new->insn_idx = insn_idx;
14411 	WARN_ONCE(new->branches != 1,
14412 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14413 
14414 	cur->parent = new;
14415 	cur->first_insn_idx = insn_idx;
14416 	clear_jmp_history(cur);
14417 	new_sl->next = *explored_state(env, insn_idx);
14418 	*explored_state(env, insn_idx) = new_sl;
14419 	/* connect new state to parentage chain. Current frame needs all
14420 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
14421 	 * to the stack implicitly by JITs) so in callers' frames connect just
14422 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14423 	 * the state of the call instruction (with WRITTEN set), and r0 comes
14424 	 * from callee with its full parentage chain, anyway.
14425 	 */
14426 	/* clear write marks in current state: the writes we did are not writes
14427 	 * our child did, so they don't screen off its reads from us.
14428 	 * (There are no read marks in current state, because reads always mark
14429 	 * their parent and current state never has children yet.  Only
14430 	 * explored_states can get read marks.)
14431 	 */
14432 	for (j = 0; j <= cur->curframe; j++) {
14433 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14434 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14435 		for (i = 0; i < BPF_REG_FP; i++)
14436 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14437 	}
14438 
14439 	/* all stack frames are accessible from callee, clear them all */
14440 	for (j = 0; j <= cur->curframe; j++) {
14441 		struct bpf_func_state *frame = cur->frame[j];
14442 		struct bpf_func_state *newframe = new->frame[j];
14443 
14444 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14445 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14446 			frame->stack[i].spilled_ptr.parent =
14447 						&newframe->stack[i].spilled_ptr;
14448 		}
14449 	}
14450 	return 0;
14451 }
14452 
14453 /* Return true if it's OK to have the same insn return a different type. */
14454 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14455 {
14456 	switch (base_type(type)) {
14457 	case PTR_TO_CTX:
14458 	case PTR_TO_SOCKET:
14459 	case PTR_TO_SOCK_COMMON:
14460 	case PTR_TO_TCP_SOCK:
14461 	case PTR_TO_XDP_SOCK:
14462 	case PTR_TO_BTF_ID:
14463 		return false;
14464 	default:
14465 		return true;
14466 	}
14467 }
14468 
14469 /* If an instruction was previously used with particular pointer types, then we
14470  * need to be careful to avoid cases such as the below, where it may be ok
14471  * for one branch accessing the pointer, but not ok for the other branch:
14472  *
14473  * R1 = sock_ptr
14474  * goto X;
14475  * ...
14476  * R1 = some_other_valid_ptr;
14477  * goto X;
14478  * ...
14479  * R2 = *(u32 *)(R1 + 0);
14480  */
14481 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14482 {
14483 	return src != prev && (!reg_type_mismatch_ok(src) ||
14484 			       !reg_type_mismatch_ok(prev));
14485 }
14486 
14487 static int do_check(struct bpf_verifier_env *env)
14488 {
14489 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14490 	struct bpf_verifier_state *state = env->cur_state;
14491 	struct bpf_insn *insns = env->prog->insnsi;
14492 	struct bpf_reg_state *regs;
14493 	int insn_cnt = env->prog->len;
14494 	bool do_print_state = false;
14495 	int prev_insn_idx = -1;
14496 
14497 	for (;;) {
14498 		struct bpf_insn *insn;
14499 		u8 class;
14500 		int err;
14501 
14502 		env->prev_insn_idx = prev_insn_idx;
14503 		if (env->insn_idx >= insn_cnt) {
14504 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
14505 				env->insn_idx, insn_cnt);
14506 			return -EFAULT;
14507 		}
14508 
14509 		insn = &insns[env->insn_idx];
14510 		class = BPF_CLASS(insn->code);
14511 
14512 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14513 			verbose(env,
14514 				"BPF program is too large. Processed %d insn\n",
14515 				env->insn_processed);
14516 			return -E2BIG;
14517 		}
14518 
14519 		state->last_insn_idx = env->prev_insn_idx;
14520 
14521 		if (is_prune_point(env, env->insn_idx)) {
14522 			err = is_state_visited(env, env->insn_idx);
14523 			if (err < 0)
14524 				return err;
14525 			if (err == 1) {
14526 				/* found equivalent state, can prune the search */
14527 				if (env->log.level & BPF_LOG_LEVEL) {
14528 					if (do_print_state)
14529 						verbose(env, "\nfrom %d to %d%s: safe\n",
14530 							env->prev_insn_idx, env->insn_idx,
14531 							env->cur_state->speculative ?
14532 							" (speculative execution)" : "");
14533 					else
14534 						verbose(env, "%d: safe\n", env->insn_idx);
14535 				}
14536 				goto process_bpf_exit;
14537 			}
14538 		}
14539 
14540 		if (is_jmp_point(env, env->insn_idx)) {
14541 			err = push_jmp_history(env, state);
14542 			if (err)
14543 				return err;
14544 		}
14545 
14546 		if (signal_pending(current))
14547 			return -EAGAIN;
14548 
14549 		if (need_resched())
14550 			cond_resched();
14551 
14552 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14553 			verbose(env, "\nfrom %d to %d%s:",
14554 				env->prev_insn_idx, env->insn_idx,
14555 				env->cur_state->speculative ?
14556 				" (speculative execution)" : "");
14557 			print_verifier_state(env, state->frame[state->curframe], true);
14558 			do_print_state = false;
14559 		}
14560 
14561 		if (env->log.level & BPF_LOG_LEVEL) {
14562 			const struct bpf_insn_cbs cbs = {
14563 				.cb_call	= disasm_kfunc_name,
14564 				.cb_print	= verbose,
14565 				.private_data	= env,
14566 			};
14567 
14568 			if (verifier_state_scratched(env))
14569 				print_insn_state(env, state->frame[state->curframe]);
14570 
14571 			verbose_linfo(env, env->insn_idx, "; ");
14572 			env->prev_log_len = env->log.len_used;
14573 			verbose(env, "%d: ", env->insn_idx);
14574 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14575 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14576 			env->prev_log_len = env->log.len_used;
14577 		}
14578 
14579 		if (bpf_prog_is_offloaded(env->prog->aux)) {
14580 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14581 							   env->prev_insn_idx);
14582 			if (err)
14583 				return err;
14584 		}
14585 
14586 		regs = cur_regs(env);
14587 		sanitize_mark_insn_seen(env);
14588 		prev_insn_idx = env->insn_idx;
14589 
14590 		if (class == BPF_ALU || class == BPF_ALU64) {
14591 			err = check_alu_op(env, insn);
14592 			if (err)
14593 				return err;
14594 
14595 		} else if (class == BPF_LDX) {
14596 			enum bpf_reg_type *prev_src_type, src_reg_type;
14597 
14598 			/* check for reserved fields is already done */
14599 
14600 			/* check src operand */
14601 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14602 			if (err)
14603 				return err;
14604 
14605 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14606 			if (err)
14607 				return err;
14608 
14609 			src_reg_type = regs[insn->src_reg].type;
14610 
14611 			/* check that memory (src_reg + off) is readable,
14612 			 * the state of dst_reg will be updated by this func
14613 			 */
14614 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
14615 					       insn->off, BPF_SIZE(insn->code),
14616 					       BPF_READ, insn->dst_reg, false);
14617 			if (err)
14618 				return err;
14619 
14620 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14621 
14622 			if (*prev_src_type == NOT_INIT) {
14623 				/* saw a valid insn
14624 				 * dst_reg = *(u32 *)(src_reg + off)
14625 				 * save type to validate intersecting paths
14626 				 */
14627 				*prev_src_type = src_reg_type;
14628 
14629 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
14630 				/* ABuser program is trying to use the same insn
14631 				 * dst_reg = *(u32*) (src_reg + off)
14632 				 * with different pointer types:
14633 				 * src_reg == ctx in one branch and
14634 				 * src_reg == stack|map in some other branch.
14635 				 * Reject it.
14636 				 */
14637 				verbose(env, "same insn cannot be used with different pointers\n");
14638 				return -EINVAL;
14639 			}
14640 
14641 		} else if (class == BPF_STX) {
14642 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
14643 
14644 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
14645 				err = check_atomic(env, env->insn_idx, insn);
14646 				if (err)
14647 					return err;
14648 				env->insn_idx++;
14649 				continue;
14650 			}
14651 
14652 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
14653 				verbose(env, "BPF_STX uses reserved fields\n");
14654 				return -EINVAL;
14655 			}
14656 
14657 			/* check src1 operand */
14658 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14659 			if (err)
14660 				return err;
14661 			/* check src2 operand */
14662 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14663 			if (err)
14664 				return err;
14665 
14666 			dst_reg_type = regs[insn->dst_reg].type;
14667 
14668 			/* check that memory (dst_reg + off) is writeable */
14669 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14670 					       insn->off, BPF_SIZE(insn->code),
14671 					       BPF_WRITE, insn->src_reg, false);
14672 			if (err)
14673 				return err;
14674 
14675 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14676 
14677 			if (*prev_dst_type == NOT_INIT) {
14678 				*prev_dst_type = dst_reg_type;
14679 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
14680 				verbose(env, "same insn cannot be used with different pointers\n");
14681 				return -EINVAL;
14682 			}
14683 
14684 		} else if (class == BPF_ST) {
14685 			if (BPF_MODE(insn->code) != BPF_MEM ||
14686 			    insn->src_reg != BPF_REG_0) {
14687 				verbose(env, "BPF_ST uses reserved fields\n");
14688 				return -EINVAL;
14689 			}
14690 			/* check src operand */
14691 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14692 			if (err)
14693 				return err;
14694 
14695 			if (is_ctx_reg(env, insn->dst_reg)) {
14696 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
14697 					insn->dst_reg,
14698 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
14699 				return -EACCES;
14700 			}
14701 
14702 			/* check that memory (dst_reg + off) is writeable */
14703 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14704 					       insn->off, BPF_SIZE(insn->code),
14705 					       BPF_WRITE, -1, false);
14706 			if (err)
14707 				return err;
14708 
14709 		} else if (class == BPF_JMP || class == BPF_JMP32) {
14710 			u8 opcode = BPF_OP(insn->code);
14711 
14712 			env->jmps_processed++;
14713 			if (opcode == BPF_CALL) {
14714 				if (BPF_SRC(insn->code) != BPF_K ||
14715 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
14716 				     && insn->off != 0) ||
14717 				    (insn->src_reg != BPF_REG_0 &&
14718 				     insn->src_reg != BPF_PSEUDO_CALL &&
14719 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
14720 				    insn->dst_reg != BPF_REG_0 ||
14721 				    class == BPF_JMP32) {
14722 					verbose(env, "BPF_CALL uses reserved fields\n");
14723 					return -EINVAL;
14724 				}
14725 
14726 				if (env->cur_state->active_lock.ptr) {
14727 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
14728 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
14729 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
14730 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
14731 						verbose(env, "function calls are not allowed while holding a lock\n");
14732 						return -EINVAL;
14733 					}
14734 				}
14735 				if (insn->src_reg == BPF_PSEUDO_CALL)
14736 					err = check_func_call(env, insn, &env->insn_idx);
14737 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
14738 					err = check_kfunc_call(env, insn, &env->insn_idx);
14739 				else
14740 					err = check_helper_call(env, insn, &env->insn_idx);
14741 				if (err)
14742 					return err;
14743 			} else if (opcode == BPF_JA) {
14744 				if (BPF_SRC(insn->code) != BPF_K ||
14745 				    insn->imm != 0 ||
14746 				    insn->src_reg != BPF_REG_0 ||
14747 				    insn->dst_reg != BPF_REG_0 ||
14748 				    class == BPF_JMP32) {
14749 					verbose(env, "BPF_JA uses reserved fields\n");
14750 					return -EINVAL;
14751 				}
14752 
14753 				env->insn_idx += insn->off + 1;
14754 				continue;
14755 
14756 			} else if (opcode == BPF_EXIT) {
14757 				if (BPF_SRC(insn->code) != BPF_K ||
14758 				    insn->imm != 0 ||
14759 				    insn->src_reg != BPF_REG_0 ||
14760 				    insn->dst_reg != BPF_REG_0 ||
14761 				    class == BPF_JMP32) {
14762 					verbose(env, "BPF_EXIT uses reserved fields\n");
14763 					return -EINVAL;
14764 				}
14765 
14766 				if (env->cur_state->active_lock.ptr &&
14767 				    !in_rbtree_lock_required_cb(env)) {
14768 					verbose(env, "bpf_spin_unlock is missing\n");
14769 					return -EINVAL;
14770 				}
14771 
14772 				if (env->cur_state->active_rcu_lock) {
14773 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14774 					return -EINVAL;
14775 				}
14776 
14777 				/* We must do check_reference_leak here before
14778 				 * prepare_func_exit to handle the case when
14779 				 * state->curframe > 0, it may be a callback
14780 				 * function, for which reference_state must
14781 				 * match caller reference state when it exits.
14782 				 */
14783 				err = check_reference_leak(env);
14784 				if (err)
14785 					return err;
14786 
14787 				if (state->curframe) {
14788 					/* exit from nested function */
14789 					err = prepare_func_exit(env, &env->insn_idx);
14790 					if (err)
14791 						return err;
14792 					do_print_state = true;
14793 					continue;
14794 				}
14795 
14796 				err = check_return_code(env);
14797 				if (err)
14798 					return err;
14799 process_bpf_exit:
14800 				mark_verifier_state_scratched(env);
14801 				update_branch_counts(env, env->cur_state);
14802 				err = pop_stack(env, &prev_insn_idx,
14803 						&env->insn_idx, pop_log);
14804 				if (err < 0) {
14805 					if (err != -ENOENT)
14806 						return err;
14807 					break;
14808 				} else {
14809 					do_print_state = true;
14810 					continue;
14811 				}
14812 			} else {
14813 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14814 				if (err)
14815 					return err;
14816 			}
14817 		} else if (class == BPF_LD) {
14818 			u8 mode = BPF_MODE(insn->code);
14819 
14820 			if (mode == BPF_ABS || mode == BPF_IND) {
14821 				err = check_ld_abs(env, insn);
14822 				if (err)
14823 					return err;
14824 
14825 			} else if (mode == BPF_IMM) {
14826 				err = check_ld_imm(env, insn);
14827 				if (err)
14828 					return err;
14829 
14830 				env->insn_idx++;
14831 				sanitize_mark_insn_seen(env);
14832 			} else {
14833 				verbose(env, "invalid BPF_LD mode\n");
14834 				return -EINVAL;
14835 			}
14836 		} else {
14837 			verbose(env, "unknown insn class %d\n", class);
14838 			return -EINVAL;
14839 		}
14840 
14841 		env->insn_idx++;
14842 	}
14843 
14844 	return 0;
14845 }
14846 
14847 static int find_btf_percpu_datasec(struct btf *btf)
14848 {
14849 	const struct btf_type *t;
14850 	const char *tname;
14851 	int i, n;
14852 
14853 	/*
14854 	 * Both vmlinux and module each have their own ".data..percpu"
14855 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14856 	 * types to look at only module's own BTF types.
14857 	 */
14858 	n = btf_nr_types(btf);
14859 	if (btf_is_module(btf))
14860 		i = btf_nr_types(btf_vmlinux);
14861 	else
14862 		i = 1;
14863 
14864 	for(; i < n; i++) {
14865 		t = btf_type_by_id(btf, i);
14866 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14867 			continue;
14868 
14869 		tname = btf_name_by_offset(btf, t->name_off);
14870 		if (!strcmp(tname, ".data..percpu"))
14871 			return i;
14872 	}
14873 
14874 	return -ENOENT;
14875 }
14876 
14877 /* replace pseudo btf_id with kernel symbol address */
14878 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14879 			       struct bpf_insn *insn,
14880 			       struct bpf_insn_aux_data *aux)
14881 {
14882 	const struct btf_var_secinfo *vsi;
14883 	const struct btf_type *datasec;
14884 	struct btf_mod_pair *btf_mod;
14885 	const struct btf_type *t;
14886 	const char *sym_name;
14887 	bool percpu = false;
14888 	u32 type, id = insn->imm;
14889 	struct btf *btf;
14890 	s32 datasec_id;
14891 	u64 addr;
14892 	int i, btf_fd, err;
14893 
14894 	btf_fd = insn[1].imm;
14895 	if (btf_fd) {
14896 		btf = btf_get_by_fd(btf_fd);
14897 		if (IS_ERR(btf)) {
14898 			verbose(env, "invalid module BTF object FD specified.\n");
14899 			return -EINVAL;
14900 		}
14901 	} else {
14902 		if (!btf_vmlinux) {
14903 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14904 			return -EINVAL;
14905 		}
14906 		btf = btf_vmlinux;
14907 		btf_get(btf);
14908 	}
14909 
14910 	t = btf_type_by_id(btf, id);
14911 	if (!t) {
14912 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14913 		err = -ENOENT;
14914 		goto err_put;
14915 	}
14916 
14917 	if (!btf_type_is_var(t)) {
14918 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14919 		err = -EINVAL;
14920 		goto err_put;
14921 	}
14922 
14923 	sym_name = btf_name_by_offset(btf, t->name_off);
14924 	addr = kallsyms_lookup_name(sym_name);
14925 	if (!addr) {
14926 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14927 			sym_name);
14928 		err = -ENOENT;
14929 		goto err_put;
14930 	}
14931 
14932 	datasec_id = find_btf_percpu_datasec(btf);
14933 	if (datasec_id > 0) {
14934 		datasec = btf_type_by_id(btf, datasec_id);
14935 		for_each_vsi(i, datasec, vsi) {
14936 			if (vsi->type == id) {
14937 				percpu = true;
14938 				break;
14939 			}
14940 		}
14941 	}
14942 
14943 	insn[0].imm = (u32)addr;
14944 	insn[1].imm = addr >> 32;
14945 
14946 	type = t->type;
14947 	t = btf_type_skip_modifiers(btf, type, NULL);
14948 	if (percpu) {
14949 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14950 		aux->btf_var.btf = btf;
14951 		aux->btf_var.btf_id = type;
14952 	} else if (!btf_type_is_struct(t)) {
14953 		const struct btf_type *ret;
14954 		const char *tname;
14955 		u32 tsize;
14956 
14957 		/* resolve the type size of ksym. */
14958 		ret = btf_resolve_size(btf, t, &tsize);
14959 		if (IS_ERR(ret)) {
14960 			tname = btf_name_by_offset(btf, t->name_off);
14961 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14962 				tname, PTR_ERR(ret));
14963 			err = -EINVAL;
14964 			goto err_put;
14965 		}
14966 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14967 		aux->btf_var.mem_size = tsize;
14968 	} else {
14969 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14970 		aux->btf_var.btf = btf;
14971 		aux->btf_var.btf_id = type;
14972 	}
14973 
14974 	/* check whether we recorded this BTF (and maybe module) already */
14975 	for (i = 0; i < env->used_btf_cnt; i++) {
14976 		if (env->used_btfs[i].btf == btf) {
14977 			btf_put(btf);
14978 			return 0;
14979 		}
14980 	}
14981 
14982 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14983 		err = -E2BIG;
14984 		goto err_put;
14985 	}
14986 
14987 	btf_mod = &env->used_btfs[env->used_btf_cnt];
14988 	btf_mod->btf = btf;
14989 	btf_mod->module = NULL;
14990 
14991 	/* if we reference variables from kernel module, bump its refcount */
14992 	if (btf_is_module(btf)) {
14993 		btf_mod->module = btf_try_get_module(btf);
14994 		if (!btf_mod->module) {
14995 			err = -ENXIO;
14996 			goto err_put;
14997 		}
14998 	}
14999 
15000 	env->used_btf_cnt++;
15001 
15002 	return 0;
15003 err_put:
15004 	btf_put(btf);
15005 	return err;
15006 }
15007 
15008 static bool is_tracing_prog_type(enum bpf_prog_type type)
15009 {
15010 	switch (type) {
15011 	case BPF_PROG_TYPE_KPROBE:
15012 	case BPF_PROG_TYPE_TRACEPOINT:
15013 	case BPF_PROG_TYPE_PERF_EVENT:
15014 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15015 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15016 		return true;
15017 	default:
15018 		return false;
15019 	}
15020 }
15021 
15022 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15023 					struct bpf_map *map,
15024 					struct bpf_prog *prog)
15025 
15026 {
15027 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15028 
15029 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15030 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
15031 		if (is_tracing_prog_type(prog_type)) {
15032 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15033 			return -EINVAL;
15034 		}
15035 	}
15036 
15037 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15038 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15039 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15040 			return -EINVAL;
15041 		}
15042 
15043 		if (is_tracing_prog_type(prog_type)) {
15044 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15045 			return -EINVAL;
15046 		}
15047 
15048 		if (prog->aux->sleepable) {
15049 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15050 			return -EINVAL;
15051 		}
15052 	}
15053 
15054 	if (btf_record_has_field(map->record, BPF_TIMER)) {
15055 		if (is_tracing_prog_type(prog_type)) {
15056 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
15057 			return -EINVAL;
15058 		}
15059 	}
15060 
15061 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15062 	    !bpf_offload_prog_map_match(prog, map)) {
15063 		verbose(env, "offload device mismatch between prog and map\n");
15064 		return -EINVAL;
15065 	}
15066 
15067 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15068 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15069 		return -EINVAL;
15070 	}
15071 
15072 	if (prog->aux->sleepable)
15073 		switch (map->map_type) {
15074 		case BPF_MAP_TYPE_HASH:
15075 		case BPF_MAP_TYPE_LRU_HASH:
15076 		case BPF_MAP_TYPE_ARRAY:
15077 		case BPF_MAP_TYPE_PERCPU_HASH:
15078 		case BPF_MAP_TYPE_PERCPU_ARRAY:
15079 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15080 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15081 		case BPF_MAP_TYPE_HASH_OF_MAPS:
15082 		case BPF_MAP_TYPE_RINGBUF:
15083 		case BPF_MAP_TYPE_USER_RINGBUF:
15084 		case BPF_MAP_TYPE_INODE_STORAGE:
15085 		case BPF_MAP_TYPE_SK_STORAGE:
15086 		case BPF_MAP_TYPE_TASK_STORAGE:
15087 		case BPF_MAP_TYPE_CGRP_STORAGE:
15088 			break;
15089 		default:
15090 			verbose(env,
15091 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15092 			return -EINVAL;
15093 		}
15094 
15095 	return 0;
15096 }
15097 
15098 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15099 {
15100 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15101 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15102 }
15103 
15104 /* find and rewrite pseudo imm in ld_imm64 instructions:
15105  *
15106  * 1. if it accesses map FD, replace it with actual map pointer.
15107  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15108  *
15109  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15110  */
15111 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15112 {
15113 	struct bpf_insn *insn = env->prog->insnsi;
15114 	int insn_cnt = env->prog->len;
15115 	int i, j, err;
15116 
15117 	err = bpf_prog_calc_tag(env->prog);
15118 	if (err)
15119 		return err;
15120 
15121 	for (i = 0; i < insn_cnt; i++, insn++) {
15122 		if (BPF_CLASS(insn->code) == BPF_LDX &&
15123 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15124 			verbose(env, "BPF_LDX uses reserved fields\n");
15125 			return -EINVAL;
15126 		}
15127 
15128 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15129 			struct bpf_insn_aux_data *aux;
15130 			struct bpf_map *map;
15131 			struct fd f;
15132 			u64 addr;
15133 			u32 fd;
15134 
15135 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
15136 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15137 			    insn[1].off != 0) {
15138 				verbose(env, "invalid bpf_ld_imm64 insn\n");
15139 				return -EINVAL;
15140 			}
15141 
15142 			if (insn[0].src_reg == 0)
15143 				/* valid generic load 64-bit imm */
15144 				goto next_insn;
15145 
15146 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15147 				aux = &env->insn_aux_data[i];
15148 				err = check_pseudo_btf_id(env, insn, aux);
15149 				if (err)
15150 					return err;
15151 				goto next_insn;
15152 			}
15153 
15154 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15155 				aux = &env->insn_aux_data[i];
15156 				aux->ptr_type = PTR_TO_FUNC;
15157 				goto next_insn;
15158 			}
15159 
15160 			/* In final convert_pseudo_ld_imm64() step, this is
15161 			 * converted into regular 64-bit imm load insn.
15162 			 */
15163 			switch (insn[0].src_reg) {
15164 			case BPF_PSEUDO_MAP_VALUE:
15165 			case BPF_PSEUDO_MAP_IDX_VALUE:
15166 				break;
15167 			case BPF_PSEUDO_MAP_FD:
15168 			case BPF_PSEUDO_MAP_IDX:
15169 				if (insn[1].imm == 0)
15170 					break;
15171 				fallthrough;
15172 			default:
15173 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15174 				return -EINVAL;
15175 			}
15176 
15177 			switch (insn[0].src_reg) {
15178 			case BPF_PSEUDO_MAP_IDX_VALUE:
15179 			case BPF_PSEUDO_MAP_IDX:
15180 				if (bpfptr_is_null(env->fd_array)) {
15181 					verbose(env, "fd_idx without fd_array is invalid\n");
15182 					return -EPROTO;
15183 				}
15184 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
15185 							    insn[0].imm * sizeof(fd),
15186 							    sizeof(fd)))
15187 					return -EFAULT;
15188 				break;
15189 			default:
15190 				fd = insn[0].imm;
15191 				break;
15192 			}
15193 
15194 			f = fdget(fd);
15195 			map = __bpf_map_get(f);
15196 			if (IS_ERR(map)) {
15197 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
15198 					insn[0].imm);
15199 				return PTR_ERR(map);
15200 			}
15201 
15202 			err = check_map_prog_compatibility(env, map, env->prog);
15203 			if (err) {
15204 				fdput(f);
15205 				return err;
15206 			}
15207 
15208 			aux = &env->insn_aux_data[i];
15209 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15210 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15211 				addr = (unsigned long)map;
15212 			} else {
15213 				u32 off = insn[1].imm;
15214 
15215 				if (off >= BPF_MAX_VAR_OFF) {
15216 					verbose(env, "direct value offset of %u is not allowed\n", off);
15217 					fdput(f);
15218 					return -EINVAL;
15219 				}
15220 
15221 				if (!map->ops->map_direct_value_addr) {
15222 					verbose(env, "no direct value access support for this map type\n");
15223 					fdput(f);
15224 					return -EINVAL;
15225 				}
15226 
15227 				err = map->ops->map_direct_value_addr(map, &addr, off);
15228 				if (err) {
15229 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15230 						map->value_size, off);
15231 					fdput(f);
15232 					return err;
15233 				}
15234 
15235 				aux->map_off = off;
15236 				addr += off;
15237 			}
15238 
15239 			insn[0].imm = (u32)addr;
15240 			insn[1].imm = addr >> 32;
15241 
15242 			/* check whether we recorded this map already */
15243 			for (j = 0; j < env->used_map_cnt; j++) {
15244 				if (env->used_maps[j] == map) {
15245 					aux->map_index = j;
15246 					fdput(f);
15247 					goto next_insn;
15248 				}
15249 			}
15250 
15251 			if (env->used_map_cnt >= MAX_USED_MAPS) {
15252 				fdput(f);
15253 				return -E2BIG;
15254 			}
15255 
15256 			/* hold the map. If the program is rejected by verifier,
15257 			 * the map will be released by release_maps() or it
15258 			 * will be used by the valid program until it's unloaded
15259 			 * and all maps are released in free_used_maps()
15260 			 */
15261 			bpf_map_inc(map);
15262 
15263 			aux->map_index = env->used_map_cnt;
15264 			env->used_maps[env->used_map_cnt++] = map;
15265 
15266 			if (bpf_map_is_cgroup_storage(map) &&
15267 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
15268 				verbose(env, "only one cgroup storage of each type is allowed\n");
15269 				fdput(f);
15270 				return -EBUSY;
15271 			}
15272 
15273 			fdput(f);
15274 next_insn:
15275 			insn++;
15276 			i++;
15277 			continue;
15278 		}
15279 
15280 		/* Basic sanity check before we invest more work here. */
15281 		if (!bpf_opcode_in_insntable(insn->code)) {
15282 			verbose(env, "unknown opcode %02x\n", insn->code);
15283 			return -EINVAL;
15284 		}
15285 	}
15286 
15287 	/* now all pseudo BPF_LD_IMM64 instructions load valid
15288 	 * 'struct bpf_map *' into a register instead of user map_fd.
15289 	 * These pointers will be used later by verifier to validate map access.
15290 	 */
15291 	return 0;
15292 }
15293 
15294 /* drop refcnt of maps used by the rejected program */
15295 static void release_maps(struct bpf_verifier_env *env)
15296 {
15297 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
15298 			     env->used_map_cnt);
15299 }
15300 
15301 /* drop refcnt of maps used by the rejected program */
15302 static void release_btfs(struct bpf_verifier_env *env)
15303 {
15304 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15305 			     env->used_btf_cnt);
15306 }
15307 
15308 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15309 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15310 {
15311 	struct bpf_insn *insn = env->prog->insnsi;
15312 	int insn_cnt = env->prog->len;
15313 	int i;
15314 
15315 	for (i = 0; i < insn_cnt; i++, insn++) {
15316 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15317 			continue;
15318 		if (insn->src_reg == BPF_PSEUDO_FUNC)
15319 			continue;
15320 		insn->src_reg = 0;
15321 	}
15322 }
15323 
15324 /* single env->prog->insni[off] instruction was replaced with the range
15325  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
15326  * [0, off) and [off, end) to new locations, so the patched range stays zero
15327  */
15328 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15329 				 struct bpf_insn_aux_data *new_data,
15330 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
15331 {
15332 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15333 	struct bpf_insn *insn = new_prog->insnsi;
15334 	u32 old_seen = old_data[off].seen;
15335 	u32 prog_len;
15336 	int i;
15337 
15338 	/* aux info at OFF always needs adjustment, no matter fast path
15339 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15340 	 * original insn at old prog.
15341 	 */
15342 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15343 
15344 	if (cnt == 1)
15345 		return;
15346 	prog_len = new_prog->len;
15347 
15348 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15349 	memcpy(new_data + off + cnt - 1, old_data + off,
15350 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15351 	for (i = off; i < off + cnt - 1; i++) {
15352 		/* Expand insni[off]'s seen count to the patched range. */
15353 		new_data[i].seen = old_seen;
15354 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
15355 	}
15356 	env->insn_aux_data = new_data;
15357 	vfree(old_data);
15358 }
15359 
15360 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15361 {
15362 	int i;
15363 
15364 	if (len == 1)
15365 		return;
15366 	/* NOTE: fake 'exit' subprog should be updated as well. */
15367 	for (i = 0; i <= env->subprog_cnt; i++) {
15368 		if (env->subprog_info[i].start <= off)
15369 			continue;
15370 		env->subprog_info[i].start += len - 1;
15371 	}
15372 }
15373 
15374 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15375 {
15376 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15377 	int i, sz = prog->aux->size_poke_tab;
15378 	struct bpf_jit_poke_descriptor *desc;
15379 
15380 	for (i = 0; i < sz; i++) {
15381 		desc = &tab[i];
15382 		if (desc->insn_idx <= off)
15383 			continue;
15384 		desc->insn_idx += len - 1;
15385 	}
15386 }
15387 
15388 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15389 					    const struct bpf_insn *patch, u32 len)
15390 {
15391 	struct bpf_prog *new_prog;
15392 	struct bpf_insn_aux_data *new_data = NULL;
15393 
15394 	if (len > 1) {
15395 		new_data = vzalloc(array_size(env->prog->len + len - 1,
15396 					      sizeof(struct bpf_insn_aux_data)));
15397 		if (!new_data)
15398 			return NULL;
15399 	}
15400 
15401 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15402 	if (IS_ERR(new_prog)) {
15403 		if (PTR_ERR(new_prog) == -ERANGE)
15404 			verbose(env,
15405 				"insn %d cannot be patched due to 16-bit range\n",
15406 				env->insn_aux_data[off].orig_idx);
15407 		vfree(new_data);
15408 		return NULL;
15409 	}
15410 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
15411 	adjust_subprog_starts(env, off, len);
15412 	adjust_poke_descs(new_prog, off, len);
15413 	return new_prog;
15414 }
15415 
15416 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15417 					      u32 off, u32 cnt)
15418 {
15419 	int i, j;
15420 
15421 	/* find first prog starting at or after off (first to remove) */
15422 	for (i = 0; i < env->subprog_cnt; i++)
15423 		if (env->subprog_info[i].start >= off)
15424 			break;
15425 	/* find first prog starting at or after off + cnt (first to stay) */
15426 	for (j = i; j < env->subprog_cnt; j++)
15427 		if (env->subprog_info[j].start >= off + cnt)
15428 			break;
15429 	/* if j doesn't start exactly at off + cnt, we are just removing
15430 	 * the front of previous prog
15431 	 */
15432 	if (env->subprog_info[j].start != off + cnt)
15433 		j--;
15434 
15435 	if (j > i) {
15436 		struct bpf_prog_aux *aux = env->prog->aux;
15437 		int move;
15438 
15439 		/* move fake 'exit' subprog as well */
15440 		move = env->subprog_cnt + 1 - j;
15441 
15442 		memmove(env->subprog_info + i,
15443 			env->subprog_info + j,
15444 			sizeof(*env->subprog_info) * move);
15445 		env->subprog_cnt -= j - i;
15446 
15447 		/* remove func_info */
15448 		if (aux->func_info) {
15449 			move = aux->func_info_cnt - j;
15450 
15451 			memmove(aux->func_info + i,
15452 				aux->func_info + j,
15453 				sizeof(*aux->func_info) * move);
15454 			aux->func_info_cnt -= j - i;
15455 			/* func_info->insn_off is set after all code rewrites,
15456 			 * in adjust_btf_func() - no need to adjust
15457 			 */
15458 		}
15459 	} else {
15460 		/* convert i from "first prog to remove" to "first to adjust" */
15461 		if (env->subprog_info[i].start == off)
15462 			i++;
15463 	}
15464 
15465 	/* update fake 'exit' subprog as well */
15466 	for (; i <= env->subprog_cnt; i++)
15467 		env->subprog_info[i].start -= cnt;
15468 
15469 	return 0;
15470 }
15471 
15472 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15473 				      u32 cnt)
15474 {
15475 	struct bpf_prog *prog = env->prog;
15476 	u32 i, l_off, l_cnt, nr_linfo;
15477 	struct bpf_line_info *linfo;
15478 
15479 	nr_linfo = prog->aux->nr_linfo;
15480 	if (!nr_linfo)
15481 		return 0;
15482 
15483 	linfo = prog->aux->linfo;
15484 
15485 	/* find first line info to remove, count lines to be removed */
15486 	for (i = 0; i < nr_linfo; i++)
15487 		if (linfo[i].insn_off >= off)
15488 			break;
15489 
15490 	l_off = i;
15491 	l_cnt = 0;
15492 	for (; i < nr_linfo; i++)
15493 		if (linfo[i].insn_off < off + cnt)
15494 			l_cnt++;
15495 		else
15496 			break;
15497 
15498 	/* First live insn doesn't match first live linfo, it needs to "inherit"
15499 	 * last removed linfo.  prog is already modified, so prog->len == off
15500 	 * means no live instructions after (tail of the program was removed).
15501 	 */
15502 	if (prog->len != off && l_cnt &&
15503 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15504 		l_cnt--;
15505 		linfo[--i].insn_off = off + cnt;
15506 	}
15507 
15508 	/* remove the line info which refer to the removed instructions */
15509 	if (l_cnt) {
15510 		memmove(linfo + l_off, linfo + i,
15511 			sizeof(*linfo) * (nr_linfo - i));
15512 
15513 		prog->aux->nr_linfo -= l_cnt;
15514 		nr_linfo = prog->aux->nr_linfo;
15515 	}
15516 
15517 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
15518 	for (i = l_off; i < nr_linfo; i++)
15519 		linfo[i].insn_off -= cnt;
15520 
15521 	/* fix up all subprogs (incl. 'exit') which start >= off */
15522 	for (i = 0; i <= env->subprog_cnt; i++)
15523 		if (env->subprog_info[i].linfo_idx > l_off) {
15524 			/* program may have started in the removed region but
15525 			 * may not be fully removed
15526 			 */
15527 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15528 				env->subprog_info[i].linfo_idx -= l_cnt;
15529 			else
15530 				env->subprog_info[i].linfo_idx = l_off;
15531 		}
15532 
15533 	return 0;
15534 }
15535 
15536 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15537 {
15538 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15539 	unsigned int orig_prog_len = env->prog->len;
15540 	int err;
15541 
15542 	if (bpf_prog_is_offloaded(env->prog->aux))
15543 		bpf_prog_offload_remove_insns(env, off, cnt);
15544 
15545 	err = bpf_remove_insns(env->prog, off, cnt);
15546 	if (err)
15547 		return err;
15548 
15549 	err = adjust_subprog_starts_after_remove(env, off, cnt);
15550 	if (err)
15551 		return err;
15552 
15553 	err = bpf_adj_linfo_after_remove(env, off, cnt);
15554 	if (err)
15555 		return err;
15556 
15557 	memmove(aux_data + off,	aux_data + off + cnt,
15558 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
15559 
15560 	return 0;
15561 }
15562 
15563 /* The verifier does more data flow analysis than llvm and will not
15564  * explore branches that are dead at run time. Malicious programs can
15565  * have dead code too. Therefore replace all dead at-run-time code
15566  * with 'ja -1'.
15567  *
15568  * Just nops are not optimal, e.g. if they would sit at the end of the
15569  * program and through another bug we would manage to jump there, then
15570  * we'd execute beyond program memory otherwise. Returning exception
15571  * code also wouldn't work since we can have subprogs where the dead
15572  * code could be located.
15573  */
15574 static void sanitize_dead_code(struct bpf_verifier_env *env)
15575 {
15576 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15577 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15578 	struct bpf_insn *insn = env->prog->insnsi;
15579 	const int insn_cnt = env->prog->len;
15580 	int i;
15581 
15582 	for (i = 0; i < insn_cnt; i++) {
15583 		if (aux_data[i].seen)
15584 			continue;
15585 		memcpy(insn + i, &trap, sizeof(trap));
15586 		aux_data[i].zext_dst = false;
15587 	}
15588 }
15589 
15590 static bool insn_is_cond_jump(u8 code)
15591 {
15592 	u8 op;
15593 
15594 	if (BPF_CLASS(code) == BPF_JMP32)
15595 		return true;
15596 
15597 	if (BPF_CLASS(code) != BPF_JMP)
15598 		return false;
15599 
15600 	op = BPF_OP(code);
15601 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15602 }
15603 
15604 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15605 {
15606 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15607 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15608 	struct bpf_insn *insn = env->prog->insnsi;
15609 	const int insn_cnt = env->prog->len;
15610 	int i;
15611 
15612 	for (i = 0; i < insn_cnt; i++, insn++) {
15613 		if (!insn_is_cond_jump(insn->code))
15614 			continue;
15615 
15616 		if (!aux_data[i + 1].seen)
15617 			ja.off = insn->off;
15618 		else if (!aux_data[i + 1 + insn->off].seen)
15619 			ja.off = 0;
15620 		else
15621 			continue;
15622 
15623 		if (bpf_prog_is_offloaded(env->prog->aux))
15624 			bpf_prog_offload_replace_insn(env, i, &ja);
15625 
15626 		memcpy(insn, &ja, sizeof(ja));
15627 	}
15628 }
15629 
15630 static int opt_remove_dead_code(struct bpf_verifier_env *env)
15631 {
15632 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15633 	int insn_cnt = env->prog->len;
15634 	int i, err;
15635 
15636 	for (i = 0; i < insn_cnt; i++) {
15637 		int j;
15638 
15639 		j = 0;
15640 		while (i + j < insn_cnt && !aux_data[i + j].seen)
15641 			j++;
15642 		if (!j)
15643 			continue;
15644 
15645 		err = verifier_remove_insns(env, i, j);
15646 		if (err)
15647 			return err;
15648 		insn_cnt = env->prog->len;
15649 	}
15650 
15651 	return 0;
15652 }
15653 
15654 static int opt_remove_nops(struct bpf_verifier_env *env)
15655 {
15656 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15657 	struct bpf_insn *insn = env->prog->insnsi;
15658 	int insn_cnt = env->prog->len;
15659 	int i, err;
15660 
15661 	for (i = 0; i < insn_cnt; i++) {
15662 		if (memcmp(&insn[i], &ja, sizeof(ja)))
15663 			continue;
15664 
15665 		err = verifier_remove_insns(env, i, 1);
15666 		if (err)
15667 			return err;
15668 		insn_cnt--;
15669 		i--;
15670 	}
15671 
15672 	return 0;
15673 }
15674 
15675 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
15676 					 const union bpf_attr *attr)
15677 {
15678 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
15679 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15680 	int i, patch_len, delta = 0, len = env->prog->len;
15681 	struct bpf_insn *insns = env->prog->insnsi;
15682 	struct bpf_prog *new_prog;
15683 	bool rnd_hi32;
15684 
15685 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
15686 	zext_patch[1] = BPF_ZEXT_REG(0);
15687 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
15688 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
15689 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
15690 	for (i = 0; i < len; i++) {
15691 		int adj_idx = i + delta;
15692 		struct bpf_insn insn;
15693 		int load_reg;
15694 
15695 		insn = insns[adj_idx];
15696 		load_reg = insn_def_regno(&insn);
15697 		if (!aux[adj_idx].zext_dst) {
15698 			u8 code, class;
15699 			u32 imm_rnd;
15700 
15701 			if (!rnd_hi32)
15702 				continue;
15703 
15704 			code = insn.code;
15705 			class = BPF_CLASS(code);
15706 			if (load_reg == -1)
15707 				continue;
15708 
15709 			/* NOTE: arg "reg" (the fourth one) is only used for
15710 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
15711 			 *       here.
15712 			 */
15713 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
15714 				if (class == BPF_LD &&
15715 				    BPF_MODE(code) == BPF_IMM)
15716 					i++;
15717 				continue;
15718 			}
15719 
15720 			/* ctx load could be transformed into wider load. */
15721 			if (class == BPF_LDX &&
15722 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
15723 				continue;
15724 
15725 			imm_rnd = get_random_u32();
15726 			rnd_hi32_patch[0] = insn;
15727 			rnd_hi32_patch[1].imm = imm_rnd;
15728 			rnd_hi32_patch[3].dst_reg = load_reg;
15729 			patch = rnd_hi32_patch;
15730 			patch_len = 4;
15731 			goto apply_patch_buffer;
15732 		}
15733 
15734 		/* Add in an zero-extend instruction if a) the JIT has requested
15735 		 * it or b) it's a CMPXCHG.
15736 		 *
15737 		 * The latter is because: BPF_CMPXCHG always loads a value into
15738 		 * R0, therefore always zero-extends. However some archs'
15739 		 * equivalent instruction only does this load when the
15740 		 * comparison is successful. This detail of CMPXCHG is
15741 		 * orthogonal to the general zero-extension behaviour of the
15742 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
15743 		 */
15744 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
15745 			continue;
15746 
15747 		/* Zero-extension is done by the caller. */
15748 		if (bpf_pseudo_kfunc_call(&insn))
15749 			continue;
15750 
15751 		if (WARN_ON(load_reg == -1)) {
15752 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15753 			return -EFAULT;
15754 		}
15755 
15756 		zext_patch[0] = insn;
15757 		zext_patch[1].dst_reg = load_reg;
15758 		zext_patch[1].src_reg = load_reg;
15759 		patch = zext_patch;
15760 		patch_len = 2;
15761 apply_patch_buffer:
15762 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15763 		if (!new_prog)
15764 			return -ENOMEM;
15765 		env->prog = new_prog;
15766 		insns = new_prog->insnsi;
15767 		aux = env->insn_aux_data;
15768 		delta += patch_len - 1;
15769 	}
15770 
15771 	return 0;
15772 }
15773 
15774 /* convert load instructions that access fields of a context type into a
15775  * sequence of instructions that access fields of the underlying structure:
15776  *     struct __sk_buff    -> struct sk_buff
15777  *     struct bpf_sock_ops -> struct sock
15778  */
15779 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15780 {
15781 	const struct bpf_verifier_ops *ops = env->ops;
15782 	int i, cnt, size, ctx_field_size, delta = 0;
15783 	const int insn_cnt = env->prog->len;
15784 	struct bpf_insn insn_buf[16], *insn;
15785 	u32 target_size, size_default, off;
15786 	struct bpf_prog *new_prog;
15787 	enum bpf_access_type type;
15788 	bool is_narrower_load;
15789 
15790 	if (ops->gen_prologue || env->seen_direct_write) {
15791 		if (!ops->gen_prologue) {
15792 			verbose(env, "bpf verifier is misconfigured\n");
15793 			return -EINVAL;
15794 		}
15795 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15796 					env->prog);
15797 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15798 			verbose(env, "bpf verifier is misconfigured\n");
15799 			return -EINVAL;
15800 		} else if (cnt) {
15801 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15802 			if (!new_prog)
15803 				return -ENOMEM;
15804 
15805 			env->prog = new_prog;
15806 			delta += cnt - 1;
15807 		}
15808 	}
15809 
15810 	if (bpf_prog_is_offloaded(env->prog->aux))
15811 		return 0;
15812 
15813 	insn = env->prog->insnsi + delta;
15814 
15815 	for (i = 0; i < insn_cnt; i++, insn++) {
15816 		bpf_convert_ctx_access_t convert_ctx_access;
15817 		bool ctx_access;
15818 
15819 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15820 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15821 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15822 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15823 			type = BPF_READ;
15824 			ctx_access = true;
15825 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15826 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15827 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15828 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15829 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15830 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15831 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15832 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15833 			type = BPF_WRITE;
15834 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15835 		} else {
15836 			continue;
15837 		}
15838 
15839 		if (type == BPF_WRITE &&
15840 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15841 			struct bpf_insn patch[] = {
15842 				*insn,
15843 				BPF_ST_NOSPEC(),
15844 			};
15845 
15846 			cnt = ARRAY_SIZE(patch);
15847 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15848 			if (!new_prog)
15849 				return -ENOMEM;
15850 
15851 			delta    += cnt - 1;
15852 			env->prog = new_prog;
15853 			insn      = new_prog->insnsi + i + delta;
15854 			continue;
15855 		}
15856 
15857 		if (!ctx_access)
15858 			continue;
15859 
15860 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15861 		case PTR_TO_CTX:
15862 			if (!ops->convert_ctx_access)
15863 				continue;
15864 			convert_ctx_access = ops->convert_ctx_access;
15865 			break;
15866 		case PTR_TO_SOCKET:
15867 		case PTR_TO_SOCK_COMMON:
15868 			convert_ctx_access = bpf_sock_convert_ctx_access;
15869 			break;
15870 		case PTR_TO_TCP_SOCK:
15871 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15872 			break;
15873 		case PTR_TO_XDP_SOCK:
15874 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15875 			break;
15876 		case PTR_TO_BTF_ID:
15877 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15878 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15879 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15880 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15881 		 * any faults for loads into such types. BPF_WRITE is disallowed
15882 		 * for this case.
15883 		 */
15884 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15885 			if (type == BPF_READ) {
15886 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15887 					BPF_SIZE((insn)->code);
15888 				env->prog->aux->num_exentries++;
15889 			}
15890 			continue;
15891 		default:
15892 			continue;
15893 		}
15894 
15895 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15896 		size = BPF_LDST_BYTES(insn);
15897 
15898 		/* If the read access is a narrower load of the field,
15899 		 * convert to a 4/8-byte load, to minimum program type specific
15900 		 * convert_ctx_access changes. If conversion is successful,
15901 		 * we will apply proper mask to the result.
15902 		 */
15903 		is_narrower_load = size < ctx_field_size;
15904 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15905 		off = insn->off;
15906 		if (is_narrower_load) {
15907 			u8 size_code;
15908 
15909 			if (type == BPF_WRITE) {
15910 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15911 				return -EINVAL;
15912 			}
15913 
15914 			size_code = BPF_H;
15915 			if (ctx_field_size == 4)
15916 				size_code = BPF_W;
15917 			else if (ctx_field_size == 8)
15918 				size_code = BPF_DW;
15919 
15920 			insn->off = off & ~(size_default - 1);
15921 			insn->code = BPF_LDX | BPF_MEM | size_code;
15922 		}
15923 
15924 		target_size = 0;
15925 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15926 					 &target_size);
15927 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15928 		    (ctx_field_size && !target_size)) {
15929 			verbose(env, "bpf verifier is misconfigured\n");
15930 			return -EINVAL;
15931 		}
15932 
15933 		if (is_narrower_load && size < target_size) {
15934 			u8 shift = bpf_ctx_narrow_access_offset(
15935 				off, size, size_default) * 8;
15936 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15937 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15938 				return -EINVAL;
15939 			}
15940 			if (ctx_field_size <= 4) {
15941 				if (shift)
15942 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15943 									insn->dst_reg,
15944 									shift);
15945 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15946 								(1 << size * 8) - 1);
15947 			} else {
15948 				if (shift)
15949 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15950 									insn->dst_reg,
15951 									shift);
15952 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15953 								(1ULL << size * 8) - 1);
15954 			}
15955 		}
15956 
15957 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15958 		if (!new_prog)
15959 			return -ENOMEM;
15960 
15961 		delta += cnt - 1;
15962 
15963 		/* keep walking new program and skip insns we just inserted */
15964 		env->prog = new_prog;
15965 		insn      = new_prog->insnsi + i + delta;
15966 	}
15967 
15968 	return 0;
15969 }
15970 
15971 static int jit_subprogs(struct bpf_verifier_env *env)
15972 {
15973 	struct bpf_prog *prog = env->prog, **func, *tmp;
15974 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15975 	struct bpf_map *map_ptr;
15976 	struct bpf_insn *insn;
15977 	void *old_bpf_func;
15978 	int err, num_exentries;
15979 
15980 	if (env->subprog_cnt <= 1)
15981 		return 0;
15982 
15983 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15984 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15985 			continue;
15986 
15987 		/* Upon error here we cannot fall back to interpreter but
15988 		 * need a hard reject of the program. Thus -EFAULT is
15989 		 * propagated in any case.
15990 		 */
15991 		subprog = find_subprog(env, i + insn->imm + 1);
15992 		if (subprog < 0) {
15993 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15994 				  i + insn->imm + 1);
15995 			return -EFAULT;
15996 		}
15997 		/* temporarily remember subprog id inside insn instead of
15998 		 * aux_data, since next loop will split up all insns into funcs
15999 		 */
16000 		insn->off = subprog;
16001 		/* remember original imm in case JIT fails and fallback
16002 		 * to interpreter will be needed
16003 		 */
16004 		env->insn_aux_data[i].call_imm = insn->imm;
16005 		/* point imm to __bpf_call_base+1 from JITs point of view */
16006 		insn->imm = 1;
16007 		if (bpf_pseudo_func(insn))
16008 			/* jit (e.g. x86_64) may emit fewer instructions
16009 			 * if it learns a u32 imm is the same as a u64 imm.
16010 			 * Force a non zero here.
16011 			 */
16012 			insn[1].imm = 1;
16013 	}
16014 
16015 	err = bpf_prog_alloc_jited_linfo(prog);
16016 	if (err)
16017 		goto out_undo_insn;
16018 
16019 	err = -ENOMEM;
16020 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16021 	if (!func)
16022 		goto out_undo_insn;
16023 
16024 	for (i = 0; i < env->subprog_cnt; i++) {
16025 		subprog_start = subprog_end;
16026 		subprog_end = env->subprog_info[i + 1].start;
16027 
16028 		len = subprog_end - subprog_start;
16029 		/* bpf_prog_run() doesn't call subprogs directly,
16030 		 * hence main prog stats include the runtime of subprogs.
16031 		 * subprogs don't have IDs and not reachable via prog_get_next_id
16032 		 * func[i]->stats will never be accessed and stays NULL
16033 		 */
16034 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16035 		if (!func[i])
16036 			goto out_free;
16037 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16038 		       len * sizeof(struct bpf_insn));
16039 		func[i]->type = prog->type;
16040 		func[i]->len = len;
16041 		if (bpf_prog_calc_tag(func[i]))
16042 			goto out_free;
16043 		func[i]->is_func = 1;
16044 		func[i]->aux->func_idx = i;
16045 		/* Below members will be freed only at prog->aux */
16046 		func[i]->aux->btf = prog->aux->btf;
16047 		func[i]->aux->func_info = prog->aux->func_info;
16048 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16049 		func[i]->aux->poke_tab = prog->aux->poke_tab;
16050 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16051 
16052 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
16053 			struct bpf_jit_poke_descriptor *poke;
16054 
16055 			poke = &prog->aux->poke_tab[j];
16056 			if (poke->insn_idx < subprog_end &&
16057 			    poke->insn_idx >= subprog_start)
16058 				poke->aux = func[i]->aux;
16059 		}
16060 
16061 		func[i]->aux->name[0] = 'F';
16062 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16063 		func[i]->jit_requested = 1;
16064 		func[i]->blinding_requested = prog->blinding_requested;
16065 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16066 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16067 		func[i]->aux->linfo = prog->aux->linfo;
16068 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16069 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16070 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16071 		num_exentries = 0;
16072 		insn = func[i]->insnsi;
16073 		for (j = 0; j < func[i]->len; j++, insn++) {
16074 			if (BPF_CLASS(insn->code) == BPF_LDX &&
16075 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
16076 				num_exentries++;
16077 		}
16078 		func[i]->aux->num_exentries = num_exentries;
16079 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16080 		func[i] = bpf_int_jit_compile(func[i]);
16081 		if (!func[i]->jited) {
16082 			err = -ENOTSUPP;
16083 			goto out_free;
16084 		}
16085 		cond_resched();
16086 	}
16087 
16088 	/* at this point all bpf functions were successfully JITed
16089 	 * now populate all bpf_calls with correct addresses and
16090 	 * run last pass of JIT
16091 	 */
16092 	for (i = 0; i < env->subprog_cnt; i++) {
16093 		insn = func[i]->insnsi;
16094 		for (j = 0; j < func[i]->len; j++, insn++) {
16095 			if (bpf_pseudo_func(insn)) {
16096 				subprog = insn->off;
16097 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16098 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16099 				continue;
16100 			}
16101 			if (!bpf_pseudo_call(insn))
16102 				continue;
16103 			subprog = insn->off;
16104 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16105 		}
16106 
16107 		/* we use the aux data to keep a list of the start addresses
16108 		 * of the JITed images for each function in the program
16109 		 *
16110 		 * for some architectures, such as powerpc64, the imm field
16111 		 * might not be large enough to hold the offset of the start
16112 		 * address of the callee's JITed image from __bpf_call_base
16113 		 *
16114 		 * in such cases, we can lookup the start address of a callee
16115 		 * by using its subprog id, available from the off field of
16116 		 * the call instruction, as an index for this list
16117 		 */
16118 		func[i]->aux->func = func;
16119 		func[i]->aux->func_cnt = env->subprog_cnt;
16120 	}
16121 	for (i = 0; i < env->subprog_cnt; i++) {
16122 		old_bpf_func = func[i]->bpf_func;
16123 		tmp = bpf_int_jit_compile(func[i]);
16124 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16125 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16126 			err = -ENOTSUPP;
16127 			goto out_free;
16128 		}
16129 		cond_resched();
16130 	}
16131 
16132 	/* finally lock prog and jit images for all functions and
16133 	 * populate kallsysm
16134 	 */
16135 	for (i = 0; i < env->subprog_cnt; i++) {
16136 		bpf_prog_lock_ro(func[i]);
16137 		bpf_prog_kallsyms_add(func[i]);
16138 	}
16139 
16140 	/* Last step: make now unused interpreter insns from main
16141 	 * prog consistent for later dump requests, so they can
16142 	 * later look the same as if they were interpreted only.
16143 	 */
16144 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16145 		if (bpf_pseudo_func(insn)) {
16146 			insn[0].imm = env->insn_aux_data[i].call_imm;
16147 			insn[1].imm = insn->off;
16148 			insn->off = 0;
16149 			continue;
16150 		}
16151 		if (!bpf_pseudo_call(insn))
16152 			continue;
16153 		insn->off = env->insn_aux_data[i].call_imm;
16154 		subprog = find_subprog(env, i + insn->off + 1);
16155 		insn->imm = subprog;
16156 	}
16157 
16158 	prog->jited = 1;
16159 	prog->bpf_func = func[0]->bpf_func;
16160 	prog->jited_len = func[0]->jited_len;
16161 	prog->aux->func = func;
16162 	prog->aux->func_cnt = env->subprog_cnt;
16163 	bpf_prog_jit_attempt_done(prog);
16164 	return 0;
16165 out_free:
16166 	/* We failed JIT'ing, so at this point we need to unregister poke
16167 	 * descriptors from subprogs, so that kernel is not attempting to
16168 	 * patch it anymore as we're freeing the subprog JIT memory.
16169 	 */
16170 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16171 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16172 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16173 	}
16174 	/* At this point we're guaranteed that poke descriptors are not
16175 	 * live anymore. We can just unlink its descriptor table as it's
16176 	 * released with the main prog.
16177 	 */
16178 	for (i = 0; i < env->subprog_cnt; i++) {
16179 		if (!func[i])
16180 			continue;
16181 		func[i]->aux->poke_tab = NULL;
16182 		bpf_jit_free(func[i]);
16183 	}
16184 	kfree(func);
16185 out_undo_insn:
16186 	/* cleanup main prog to be interpreted */
16187 	prog->jit_requested = 0;
16188 	prog->blinding_requested = 0;
16189 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16190 		if (!bpf_pseudo_call(insn))
16191 			continue;
16192 		insn->off = 0;
16193 		insn->imm = env->insn_aux_data[i].call_imm;
16194 	}
16195 	bpf_prog_jit_attempt_done(prog);
16196 	return err;
16197 }
16198 
16199 static int fixup_call_args(struct bpf_verifier_env *env)
16200 {
16201 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16202 	struct bpf_prog *prog = env->prog;
16203 	struct bpf_insn *insn = prog->insnsi;
16204 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16205 	int i, depth;
16206 #endif
16207 	int err = 0;
16208 
16209 	if (env->prog->jit_requested &&
16210 	    !bpf_prog_is_offloaded(env->prog->aux)) {
16211 		err = jit_subprogs(env);
16212 		if (err == 0)
16213 			return 0;
16214 		if (err == -EFAULT)
16215 			return err;
16216 	}
16217 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16218 	if (has_kfunc_call) {
16219 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16220 		return -EINVAL;
16221 	}
16222 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16223 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
16224 		 * have to be rejected, since interpreter doesn't support them yet.
16225 		 */
16226 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16227 		return -EINVAL;
16228 	}
16229 	for (i = 0; i < prog->len; i++, insn++) {
16230 		if (bpf_pseudo_func(insn)) {
16231 			/* When JIT fails the progs with callback calls
16232 			 * have to be rejected, since interpreter doesn't support them yet.
16233 			 */
16234 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
16235 			return -EINVAL;
16236 		}
16237 
16238 		if (!bpf_pseudo_call(insn))
16239 			continue;
16240 		depth = get_callee_stack_depth(env, insn, i);
16241 		if (depth < 0)
16242 			return depth;
16243 		bpf_patch_call_args(insn, depth);
16244 	}
16245 	err = 0;
16246 #endif
16247 	return err;
16248 }
16249 
16250 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16251 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16252 {
16253 	const struct bpf_kfunc_desc *desc;
16254 	void *xdp_kfunc;
16255 
16256 	if (!insn->imm) {
16257 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16258 		return -EINVAL;
16259 	}
16260 
16261 	*cnt = 0;
16262 
16263 	if (bpf_dev_bound_kfunc_id(insn->imm)) {
16264 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16265 		if (xdp_kfunc) {
16266 			insn->imm = BPF_CALL_IMM(xdp_kfunc);
16267 			return 0;
16268 		}
16269 
16270 		/* fallback to default kfunc when not supported by netdev */
16271 	}
16272 
16273 	/* insn->imm has the btf func_id. Replace it with
16274 	 * an address (relative to __bpf_call_base).
16275 	 */
16276 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16277 	if (!desc) {
16278 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16279 			insn->imm);
16280 		return -EFAULT;
16281 	}
16282 
16283 	insn->imm = desc->imm;
16284 	if (insn->off)
16285 		return 0;
16286 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16287 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16288 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16289 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16290 
16291 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16292 		insn_buf[1] = addr[0];
16293 		insn_buf[2] = addr[1];
16294 		insn_buf[3] = *insn;
16295 		*cnt = 4;
16296 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16297 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16298 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16299 
16300 		insn_buf[0] = addr[0];
16301 		insn_buf[1] = addr[1];
16302 		insn_buf[2] = *insn;
16303 		*cnt = 3;
16304 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16305 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16306 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16307 		*cnt = 1;
16308 	}
16309 	return 0;
16310 }
16311 
16312 /* Do various post-verification rewrites in a single program pass.
16313  * These rewrites simplify JIT and interpreter implementations.
16314  */
16315 static int do_misc_fixups(struct bpf_verifier_env *env)
16316 {
16317 	struct bpf_prog *prog = env->prog;
16318 	enum bpf_attach_type eatype = prog->expected_attach_type;
16319 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16320 	struct bpf_insn *insn = prog->insnsi;
16321 	const struct bpf_func_proto *fn;
16322 	const int insn_cnt = prog->len;
16323 	const struct bpf_map_ops *ops;
16324 	struct bpf_insn_aux_data *aux;
16325 	struct bpf_insn insn_buf[16];
16326 	struct bpf_prog *new_prog;
16327 	struct bpf_map *map_ptr;
16328 	int i, ret, cnt, delta = 0;
16329 
16330 	for (i = 0; i < insn_cnt; i++, insn++) {
16331 		/* Make divide-by-zero exceptions impossible. */
16332 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16333 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16334 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16335 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16336 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16337 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16338 			struct bpf_insn *patchlet;
16339 			struct bpf_insn chk_and_div[] = {
16340 				/* [R,W]x div 0 -> 0 */
16341 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16342 					     BPF_JNE | BPF_K, insn->src_reg,
16343 					     0, 2, 0),
16344 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16345 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16346 				*insn,
16347 			};
16348 			struct bpf_insn chk_and_mod[] = {
16349 				/* [R,W]x mod 0 -> [R,W]x */
16350 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16351 					     BPF_JEQ | BPF_K, insn->src_reg,
16352 					     0, 1 + (is64 ? 0 : 1), 0),
16353 				*insn,
16354 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16355 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16356 			};
16357 
16358 			patchlet = isdiv ? chk_and_div : chk_and_mod;
16359 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16360 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16361 
16362 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16363 			if (!new_prog)
16364 				return -ENOMEM;
16365 
16366 			delta    += cnt - 1;
16367 			env->prog = prog = new_prog;
16368 			insn      = new_prog->insnsi + i + delta;
16369 			continue;
16370 		}
16371 
16372 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16373 		if (BPF_CLASS(insn->code) == BPF_LD &&
16374 		    (BPF_MODE(insn->code) == BPF_ABS ||
16375 		     BPF_MODE(insn->code) == BPF_IND)) {
16376 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
16377 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16378 				verbose(env, "bpf verifier is misconfigured\n");
16379 				return -EINVAL;
16380 			}
16381 
16382 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16383 			if (!new_prog)
16384 				return -ENOMEM;
16385 
16386 			delta    += cnt - 1;
16387 			env->prog = prog = new_prog;
16388 			insn      = new_prog->insnsi + i + delta;
16389 			continue;
16390 		}
16391 
16392 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
16393 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16394 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16395 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16396 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16397 			struct bpf_insn *patch = &insn_buf[0];
16398 			bool issrc, isneg, isimm;
16399 			u32 off_reg;
16400 
16401 			aux = &env->insn_aux_data[i + delta];
16402 			if (!aux->alu_state ||
16403 			    aux->alu_state == BPF_ALU_NON_POINTER)
16404 				continue;
16405 
16406 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16407 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16408 				BPF_ALU_SANITIZE_SRC;
16409 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16410 
16411 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
16412 			if (isimm) {
16413 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16414 			} else {
16415 				if (isneg)
16416 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16417 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16418 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16419 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16420 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16421 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16422 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16423 			}
16424 			if (!issrc)
16425 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16426 			insn->src_reg = BPF_REG_AX;
16427 			if (isneg)
16428 				insn->code = insn->code == code_add ?
16429 					     code_sub : code_add;
16430 			*patch++ = *insn;
16431 			if (issrc && isneg && !isimm)
16432 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16433 			cnt = patch - insn_buf;
16434 
16435 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16436 			if (!new_prog)
16437 				return -ENOMEM;
16438 
16439 			delta    += cnt - 1;
16440 			env->prog = prog = new_prog;
16441 			insn      = new_prog->insnsi + i + delta;
16442 			continue;
16443 		}
16444 
16445 		if (insn->code != (BPF_JMP | BPF_CALL))
16446 			continue;
16447 		if (insn->src_reg == BPF_PSEUDO_CALL)
16448 			continue;
16449 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16450 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16451 			if (ret)
16452 				return ret;
16453 			if (cnt == 0)
16454 				continue;
16455 
16456 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16457 			if (!new_prog)
16458 				return -ENOMEM;
16459 
16460 			delta	 += cnt - 1;
16461 			env->prog = prog = new_prog;
16462 			insn	  = new_prog->insnsi + i + delta;
16463 			continue;
16464 		}
16465 
16466 		if (insn->imm == BPF_FUNC_get_route_realm)
16467 			prog->dst_needed = 1;
16468 		if (insn->imm == BPF_FUNC_get_prandom_u32)
16469 			bpf_user_rnd_init_once();
16470 		if (insn->imm == BPF_FUNC_override_return)
16471 			prog->kprobe_override = 1;
16472 		if (insn->imm == BPF_FUNC_tail_call) {
16473 			/* If we tail call into other programs, we
16474 			 * cannot make any assumptions since they can
16475 			 * be replaced dynamically during runtime in
16476 			 * the program array.
16477 			 */
16478 			prog->cb_access = 1;
16479 			if (!allow_tail_call_in_subprogs(env))
16480 				prog->aux->stack_depth = MAX_BPF_STACK;
16481 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16482 
16483 			/* mark bpf_tail_call as different opcode to avoid
16484 			 * conditional branch in the interpreter for every normal
16485 			 * call and to prevent accidental JITing by JIT compiler
16486 			 * that doesn't support bpf_tail_call yet
16487 			 */
16488 			insn->imm = 0;
16489 			insn->code = BPF_JMP | BPF_TAIL_CALL;
16490 
16491 			aux = &env->insn_aux_data[i + delta];
16492 			if (env->bpf_capable && !prog->blinding_requested &&
16493 			    prog->jit_requested &&
16494 			    !bpf_map_key_poisoned(aux) &&
16495 			    !bpf_map_ptr_poisoned(aux) &&
16496 			    !bpf_map_ptr_unpriv(aux)) {
16497 				struct bpf_jit_poke_descriptor desc = {
16498 					.reason = BPF_POKE_REASON_TAIL_CALL,
16499 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16500 					.tail_call.key = bpf_map_key_immediate(aux),
16501 					.insn_idx = i + delta,
16502 				};
16503 
16504 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
16505 				if (ret < 0) {
16506 					verbose(env, "adding tail call poke descriptor failed\n");
16507 					return ret;
16508 				}
16509 
16510 				insn->imm = ret + 1;
16511 				continue;
16512 			}
16513 
16514 			if (!bpf_map_ptr_unpriv(aux))
16515 				continue;
16516 
16517 			/* instead of changing every JIT dealing with tail_call
16518 			 * emit two extra insns:
16519 			 * if (index >= max_entries) goto out;
16520 			 * index &= array->index_mask;
16521 			 * to avoid out-of-bounds cpu speculation
16522 			 */
16523 			if (bpf_map_ptr_poisoned(aux)) {
16524 				verbose(env, "tail_call abusing map_ptr\n");
16525 				return -EINVAL;
16526 			}
16527 
16528 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16529 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16530 						  map_ptr->max_entries, 2);
16531 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16532 						    container_of(map_ptr,
16533 								 struct bpf_array,
16534 								 map)->index_mask);
16535 			insn_buf[2] = *insn;
16536 			cnt = 3;
16537 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16538 			if (!new_prog)
16539 				return -ENOMEM;
16540 
16541 			delta    += cnt - 1;
16542 			env->prog = prog = new_prog;
16543 			insn      = new_prog->insnsi + i + delta;
16544 			continue;
16545 		}
16546 
16547 		if (insn->imm == BPF_FUNC_timer_set_callback) {
16548 			/* The verifier will process callback_fn as many times as necessary
16549 			 * with different maps and the register states prepared by
16550 			 * set_timer_callback_state will be accurate.
16551 			 *
16552 			 * The following use case is valid:
16553 			 *   map1 is shared by prog1, prog2, prog3.
16554 			 *   prog1 calls bpf_timer_init for some map1 elements
16555 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
16556 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
16557 			 *   prog3 calls bpf_timer_start for some map1 elements.
16558 			 *     Those that were not both bpf_timer_init-ed and
16559 			 *     bpf_timer_set_callback-ed will return -EINVAL.
16560 			 */
16561 			struct bpf_insn ld_addrs[2] = {
16562 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16563 			};
16564 
16565 			insn_buf[0] = ld_addrs[0];
16566 			insn_buf[1] = ld_addrs[1];
16567 			insn_buf[2] = *insn;
16568 			cnt = 3;
16569 
16570 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16571 			if (!new_prog)
16572 				return -ENOMEM;
16573 
16574 			delta    += cnt - 1;
16575 			env->prog = prog = new_prog;
16576 			insn      = new_prog->insnsi + i + delta;
16577 			goto patch_call_imm;
16578 		}
16579 
16580 		if (is_storage_get_function(insn->imm)) {
16581 			if (!env->prog->aux->sleepable ||
16582 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
16583 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16584 			else
16585 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16586 			insn_buf[1] = *insn;
16587 			cnt = 2;
16588 
16589 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16590 			if (!new_prog)
16591 				return -ENOMEM;
16592 
16593 			delta += cnt - 1;
16594 			env->prog = prog = new_prog;
16595 			insn = new_prog->insnsi + i + delta;
16596 			goto patch_call_imm;
16597 		}
16598 
16599 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16600 		 * and other inlining handlers are currently limited to 64 bit
16601 		 * only.
16602 		 */
16603 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16604 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
16605 		     insn->imm == BPF_FUNC_map_update_elem ||
16606 		     insn->imm == BPF_FUNC_map_delete_elem ||
16607 		     insn->imm == BPF_FUNC_map_push_elem   ||
16608 		     insn->imm == BPF_FUNC_map_pop_elem    ||
16609 		     insn->imm == BPF_FUNC_map_peek_elem   ||
16610 		     insn->imm == BPF_FUNC_redirect_map    ||
16611 		     insn->imm == BPF_FUNC_for_each_map_elem ||
16612 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16613 			aux = &env->insn_aux_data[i + delta];
16614 			if (bpf_map_ptr_poisoned(aux))
16615 				goto patch_call_imm;
16616 
16617 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16618 			ops = map_ptr->ops;
16619 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
16620 			    ops->map_gen_lookup) {
16621 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16622 				if (cnt == -EOPNOTSUPP)
16623 					goto patch_map_ops_generic;
16624 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16625 					verbose(env, "bpf verifier is misconfigured\n");
16626 					return -EINVAL;
16627 				}
16628 
16629 				new_prog = bpf_patch_insn_data(env, i + delta,
16630 							       insn_buf, cnt);
16631 				if (!new_prog)
16632 					return -ENOMEM;
16633 
16634 				delta    += cnt - 1;
16635 				env->prog = prog = new_prog;
16636 				insn      = new_prog->insnsi + i + delta;
16637 				continue;
16638 			}
16639 
16640 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
16641 				     (void *(*)(struct bpf_map *map, void *key))NULL));
16642 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
16643 				     (int (*)(struct bpf_map *map, void *key))NULL));
16644 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
16645 				     (int (*)(struct bpf_map *map, void *key, void *value,
16646 					      u64 flags))NULL));
16647 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
16648 				     (int (*)(struct bpf_map *map, void *value,
16649 					      u64 flags))NULL));
16650 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
16651 				     (int (*)(struct bpf_map *map, void *value))NULL));
16652 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
16653 				     (int (*)(struct bpf_map *map, void *value))NULL));
16654 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
16655 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
16656 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
16657 				     (int (*)(struct bpf_map *map,
16658 					      bpf_callback_t callback_fn,
16659 					      void *callback_ctx,
16660 					      u64 flags))NULL));
16661 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
16662 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
16663 
16664 patch_map_ops_generic:
16665 			switch (insn->imm) {
16666 			case BPF_FUNC_map_lookup_elem:
16667 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
16668 				continue;
16669 			case BPF_FUNC_map_update_elem:
16670 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
16671 				continue;
16672 			case BPF_FUNC_map_delete_elem:
16673 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
16674 				continue;
16675 			case BPF_FUNC_map_push_elem:
16676 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
16677 				continue;
16678 			case BPF_FUNC_map_pop_elem:
16679 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
16680 				continue;
16681 			case BPF_FUNC_map_peek_elem:
16682 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
16683 				continue;
16684 			case BPF_FUNC_redirect_map:
16685 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
16686 				continue;
16687 			case BPF_FUNC_for_each_map_elem:
16688 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
16689 				continue;
16690 			case BPF_FUNC_map_lookup_percpu_elem:
16691 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
16692 				continue;
16693 			}
16694 
16695 			goto patch_call_imm;
16696 		}
16697 
16698 		/* Implement bpf_jiffies64 inline. */
16699 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16700 		    insn->imm == BPF_FUNC_jiffies64) {
16701 			struct bpf_insn ld_jiffies_addr[2] = {
16702 				BPF_LD_IMM64(BPF_REG_0,
16703 					     (unsigned long)&jiffies),
16704 			};
16705 
16706 			insn_buf[0] = ld_jiffies_addr[0];
16707 			insn_buf[1] = ld_jiffies_addr[1];
16708 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
16709 						  BPF_REG_0, 0);
16710 			cnt = 3;
16711 
16712 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
16713 						       cnt);
16714 			if (!new_prog)
16715 				return -ENOMEM;
16716 
16717 			delta    += cnt - 1;
16718 			env->prog = prog = new_prog;
16719 			insn      = new_prog->insnsi + i + delta;
16720 			continue;
16721 		}
16722 
16723 		/* Implement bpf_get_func_arg inline. */
16724 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16725 		    insn->imm == BPF_FUNC_get_func_arg) {
16726 			/* Load nr_args from ctx - 8 */
16727 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16728 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
16729 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
16730 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
16731 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
16732 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16733 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
16734 			insn_buf[7] = BPF_JMP_A(1);
16735 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
16736 			cnt = 9;
16737 
16738 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 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_ret inline. */
16749 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16750 		    insn->imm == BPF_FUNC_get_func_ret) {
16751 			if (eatype == BPF_TRACE_FEXIT ||
16752 			    eatype == BPF_MODIFY_RETURN) {
16753 				/* Load nr_args from ctx - 8 */
16754 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16755 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
16756 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
16757 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16758 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
16759 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
16760 				cnt = 6;
16761 			} else {
16762 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
16763 				cnt = 1;
16764 			}
16765 
16766 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16767 			if (!new_prog)
16768 				return -ENOMEM;
16769 
16770 			delta    += cnt - 1;
16771 			env->prog = prog = new_prog;
16772 			insn      = new_prog->insnsi + i + delta;
16773 			continue;
16774 		}
16775 
16776 		/* Implement get_func_arg_cnt inline. */
16777 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16778 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16779 			/* Load nr_args from ctx - 8 */
16780 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16781 
16782 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16783 			if (!new_prog)
16784 				return -ENOMEM;
16785 
16786 			env->prog = prog = new_prog;
16787 			insn      = new_prog->insnsi + i + delta;
16788 			continue;
16789 		}
16790 
16791 		/* Implement bpf_get_func_ip inline. */
16792 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16793 		    insn->imm == BPF_FUNC_get_func_ip) {
16794 			/* Load IP address from ctx - 16 */
16795 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16796 
16797 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16798 			if (!new_prog)
16799 				return -ENOMEM;
16800 
16801 			env->prog = prog = new_prog;
16802 			insn      = new_prog->insnsi + i + delta;
16803 			continue;
16804 		}
16805 
16806 patch_call_imm:
16807 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16808 		/* all functions that have prototype and verifier allowed
16809 		 * programs to call them, must be real in-kernel functions
16810 		 */
16811 		if (!fn->func) {
16812 			verbose(env,
16813 				"kernel subsystem misconfigured func %s#%d\n",
16814 				func_id_name(insn->imm), insn->imm);
16815 			return -EFAULT;
16816 		}
16817 		insn->imm = fn->func - __bpf_call_base;
16818 	}
16819 
16820 	/* Since poke tab is now finalized, publish aux to tracker. */
16821 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16822 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16823 		if (!map_ptr->ops->map_poke_track ||
16824 		    !map_ptr->ops->map_poke_untrack ||
16825 		    !map_ptr->ops->map_poke_run) {
16826 			verbose(env, "bpf verifier is misconfigured\n");
16827 			return -EINVAL;
16828 		}
16829 
16830 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16831 		if (ret < 0) {
16832 			verbose(env, "tracking tail call prog failed\n");
16833 			return ret;
16834 		}
16835 	}
16836 
16837 	sort_kfunc_descs_by_imm(env->prog);
16838 
16839 	return 0;
16840 }
16841 
16842 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16843 					int position,
16844 					s32 stack_base,
16845 					u32 callback_subprogno,
16846 					u32 *cnt)
16847 {
16848 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16849 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16850 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16851 	int reg_loop_max = BPF_REG_6;
16852 	int reg_loop_cnt = BPF_REG_7;
16853 	int reg_loop_ctx = BPF_REG_8;
16854 
16855 	struct bpf_prog *new_prog;
16856 	u32 callback_start;
16857 	u32 call_insn_offset;
16858 	s32 callback_offset;
16859 
16860 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16861 	 * be careful to modify this code in sync.
16862 	 */
16863 	struct bpf_insn insn_buf[] = {
16864 		/* Return error and jump to the end of the patch if
16865 		 * expected number of iterations is too big.
16866 		 */
16867 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16868 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16869 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16870 		/* spill R6, R7, R8 to use these as loop vars */
16871 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16872 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16873 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16874 		/* initialize loop vars */
16875 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16876 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16877 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16878 		/* loop header,
16879 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16880 		 */
16881 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16882 		/* callback call,
16883 		 * correct callback offset would be set after patching
16884 		 */
16885 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16886 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16887 		BPF_CALL_REL(0),
16888 		/* increment loop counter */
16889 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16890 		/* jump to loop header if callback returned 0 */
16891 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16892 		/* return value of bpf_loop,
16893 		 * set R0 to the number of iterations
16894 		 */
16895 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16896 		/* restore original values of R6, R7, R8 */
16897 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16898 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16899 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16900 	};
16901 
16902 	*cnt = ARRAY_SIZE(insn_buf);
16903 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16904 	if (!new_prog)
16905 		return new_prog;
16906 
16907 	/* callback start is known only after patching */
16908 	callback_start = env->subprog_info[callback_subprogno].start;
16909 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16910 	call_insn_offset = position + 12;
16911 	callback_offset = callback_start - call_insn_offset - 1;
16912 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16913 
16914 	return new_prog;
16915 }
16916 
16917 static bool is_bpf_loop_call(struct bpf_insn *insn)
16918 {
16919 	return insn->code == (BPF_JMP | BPF_CALL) &&
16920 		insn->src_reg == 0 &&
16921 		insn->imm == BPF_FUNC_loop;
16922 }
16923 
16924 /* For all sub-programs in the program (including main) check
16925  * insn_aux_data to see if there are bpf_loop calls that require
16926  * inlining. If such calls are found the calls are replaced with a
16927  * sequence of instructions produced by `inline_bpf_loop` function and
16928  * subprog stack_depth is increased by the size of 3 registers.
16929  * This stack space is used to spill values of the R6, R7, R8.  These
16930  * registers are used to store the loop bound, counter and context
16931  * variables.
16932  */
16933 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16934 {
16935 	struct bpf_subprog_info *subprogs = env->subprog_info;
16936 	int i, cur_subprog = 0, cnt, delta = 0;
16937 	struct bpf_insn *insn = env->prog->insnsi;
16938 	int insn_cnt = env->prog->len;
16939 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16940 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16941 	u16 stack_depth_extra = 0;
16942 
16943 	for (i = 0; i < insn_cnt; i++, insn++) {
16944 		struct bpf_loop_inline_state *inline_state =
16945 			&env->insn_aux_data[i + delta].loop_inline_state;
16946 
16947 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16948 			struct bpf_prog *new_prog;
16949 
16950 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16951 			new_prog = inline_bpf_loop(env,
16952 						   i + delta,
16953 						   -(stack_depth + stack_depth_extra),
16954 						   inline_state->callback_subprogno,
16955 						   &cnt);
16956 			if (!new_prog)
16957 				return -ENOMEM;
16958 
16959 			delta     += cnt - 1;
16960 			env->prog  = new_prog;
16961 			insn       = new_prog->insnsi + i + delta;
16962 		}
16963 
16964 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16965 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16966 			cur_subprog++;
16967 			stack_depth = subprogs[cur_subprog].stack_depth;
16968 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16969 			stack_depth_extra = 0;
16970 		}
16971 	}
16972 
16973 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16974 
16975 	return 0;
16976 }
16977 
16978 static void free_states(struct bpf_verifier_env *env)
16979 {
16980 	struct bpf_verifier_state_list *sl, *sln;
16981 	int i;
16982 
16983 	sl = env->free_list;
16984 	while (sl) {
16985 		sln = sl->next;
16986 		free_verifier_state(&sl->state, false);
16987 		kfree(sl);
16988 		sl = sln;
16989 	}
16990 	env->free_list = NULL;
16991 
16992 	if (!env->explored_states)
16993 		return;
16994 
16995 	for (i = 0; i < state_htab_size(env); i++) {
16996 		sl = env->explored_states[i];
16997 
16998 		while (sl) {
16999 			sln = sl->next;
17000 			free_verifier_state(&sl->state, false);
17001 			kfree(sl);
17002 			sl = sln;
17003 		}
17004 		env->explored_states[i] = NULL;
17005 	}
17006 }
17007 
17008 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17009 {
17010 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17011 	struct bpf_verifier_state *state;
17012 	struct bpf_reg_state *regs;
17013 	int ret, i;
17014 
17015 	env->prev_linfo = NULL;
17016 	env->pass_cnt++;
17017 
17018 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17019 	if (!state)
17020 		return -ENOMEM;
17021 	state->curframe = 0;
17022 	state->speculative = false;
17023 	state->branches = 1;
17024 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17025 	if (!state->frame[0]) {
17026 		kfree(state);
17027 		return -ENOMEM;
17028 	}
17029 	env->cur_state = state;
17030 	init_func_state(env, state->frame[0],
17031 			BPF_MAIN_FUNC /* callsite */,
17032 			0 /* frameno */,
17033 			subprog);
17034 	state->first_insn_idx = env->subprog_info[subprog].start;
17035 	state->last_insn_idx = -1;
17036 
17037 	regs = state->frame[state->curframe]->regs;
17038 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17039 		ret = btf_prepare_func_args(env, subprog, regs);
17040 		if (ret)
17041 			goto out;
17042 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17043 			if (regs[i].type == PTR_TO_CTX)
17044 				mark_reg_known_zero(env, regs, i);
17045 			else if (regs[i].type == SCALAR_VALUE)
17046 				mark_reg_unknown(env, regs, i);
17047 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
17048 				const u32 mem_size = regs[i].mem_size;
17049 
17050 				mark_reg_known_zero(env, regs, i);
17051 				regs[i].mem_size = mem_size;
17052 				regs[i].id = ++env->id_gen;
17053 			}
17054 		}
17055 	} else {
17056 		/* 1st arg to a function */
17057 		regs[BPF_REG_1].type = PTR_TO_CTX;
17058 		mark_reg_known_zero(env, regs, BPF_REG_1);
17059 		ret = btf_check_subprog_arg_match(env, subprog, regs);
17060 		if (ret == -EFAULT)
17061 			/* unlikely verifier bug. abort.
17062 			 * ret == 0 and ret < 0 are sadly acceptable for
17063 			 * main() function due to backward compatibility.
17064 			 * Like socket filter program may be written as:
17065 			 * int bpf_prog(struct pt_regs *ctx)
17066 			 * and never dereference that ctx in the program.
17067 			 * 'struct pt_regs' is a type mismatch for socket
17068 			 * filter that should be using 'struct __sk_buff'.
17069 			 */
17070 			goto out;
17071 	}
17072 
17073 	ret = do_check(env);
17074 out:
17075 	/* check for NULL is necessary, since cur_state can be freed inside
17076 	 * do_check() under memory pressure.
17077 	 */
17078 	if (env->cur_state) {
17079 		free_verifier_state(env->cur_state, true);
17080 		env->cur_state = NULL;
17081 	}
17082 	while (!pop_stack(env, NULL, NULL, false));
17083 	if (!ret && pop_log)
17084 		bpf_vlog_reset(&env->log, 0);
17085 	free_states(env);
17086 	return ret;
17087 }
17088 
17089 /* Verify all global functions in a BPF program one by one based on their BTF.
17090  * All global functions must pass verification. Otherwise the whole program is rejected.
17091  * Consider:
17092  * int bar(int);
17093  * int foo(int f)
17094  * {
17095  *    return bar(f);
17096  * }
17097  * int bar(int b)
17098  * {
17099  *    ...
17100  * }
17101  * foo() will be verified first for R1=any_scalar_value. During verification it
17102  * will be assumed that bar() already verified successfully and call to bar()
17103  * from foo() will be checked for type match only. Later bar() will be verified
17104  * independently to check that it's safe for R1=any_scalar_value.
17105  */
17106 static int do_check_subprogs(struct bpf_verifier_env *env)
17107 {
17108 	struct bpf_prog_aux *aux = env->prog->aux;
17109 	int i, ret;
17110 
17111 	if (!aux->func_info)
17112 		return 0;
17113 
17114 	for (i = 1; i < env->subprog_cnt; i++) {
17115 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17116 			continue;
17117 		env->insn_idx = env->subprog_info[i].start;
17118 		WARN_ON_ONCE(env->insn_idx == 0);
17119 		ret = do_check_common(env, i);
17120 		if (ret) {
17121 			return ret;
17122 		} else if (env->log.level & BPF_LOG_LEVEL) {
17123 			verbose(env,
17124 				"Func#%d is safe for any args that match its prototype\n",
17125 				i);
17126 		}
17127 	}
17128 	return 0;
17129 }
17130 
17131 static int do_check_main(struct bpf_verifier_env *env)
17132 {
17133 	int ret;
17134 
17135 	env->insn_idx = 0;
17136 	ret = do_check_common(env, 0);
17137 	if (!ret)
17138 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17139 	return ret;
17140 }
17141 
17142 
17143 static void print_verification_stats(struct bpf_verifier_env *env)
17144 {
17145 	int i;
17146 
17147 	if (env->log.level & BPF_LOG_STATS) {
17148 		verbose(env, "verification time %lld usec\n",
17149 			div_u64(env->verification_time, 1000));
17150 		verbose(env, "stack depth ");
17151 		for (i = 0; i < env->subprog_cnt; i++) {
17152 			u32 depth = env->subprog_info[i].stack_depth;
17153 
17154 			verbose(env, "%d", depth);
17155 			if (i + 1 < env->subprog_cnt)
17156 				verbose(env, "+");
17157 		}
17158 		verbose(env, "\n");
17159 	}
17160 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17161 		"total_states %d peak_states %d mark_read %d\n",
17162 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17163 		env->max_states_per_insn, env->total_states,
17164 		env->peak_states, env->longest_mark_read_walk);
17165 }
17166 
17167 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17168 {
17169 	const struct btf_type *t, *func_proto;
17170 	const struct bpf_struct_ops *st_ops;
17171 	const struct btf_member *member;
17172 	struct bpf_prog *prog = env->prog;
17173 	u32 btf_id, member_idx;
17174 	const char *mname;
17175 
17176 	if (!prog->gpl_compatible) {
17177 		verbose(env, "struct ops programs must have a GPL compatible license\n");
17178 		return -EINVAL;
17179 	}
17180 
17181 	btf_id = prog->aux->attach_btf_id;
17182 	st_ops = bpf_struct_ops_find(btf_id);
17183 	if (!st_ops) {
17184 		verbose(env, "attach_btf_id %u is not a supported struct\n",
17185 			btf_id);
17186 		return -ENOTSUPP;
17187 	}
17188 
17189 	t = st_ops->type;
17190 	member_idx = prog->expected_attach_type;
17191 	if (member_idx >= btf_type_vlen(t)) {
17192 		verbose(env, "attach to invalid member idx %u of struct %s\n",
17193 			member_idx, st_ops->name);
17194 		return -EINVAL;
17195 	}
17196 
17197 	member = &btf_type_member(t)[member_idx];
17198 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17199 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17200 					       NULL);
17201 	if (!func_proto) {
17202 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17203 			mname, member_idx, st_ops->name);
17204 		return -EINVAL;
17205 	}
17206 
17207 	if (st_ops->check_member) {
17208 		int err = st_ops->check_member(t, member, prog);
17209 
17210 		if (err) {
17211 			verbose(env, "attach to unsupported member %s of struct %s\n",
17212 				mname, st_ops->name);
17213 			return err;
17214 		}
17215 	}
17216 
17217 	prog->aux->attach_func_proto = func_proto;
17218 	prog->aux->attach_func_name = mname;
17219 	env->ops = st_ops->verifier_ops;
17220 
17221 	return 0;
17222 }
17223 #define SECURITY_PREFIX "security_"
17224 
17225 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17226 {
17227 	if (within_error_injection_list(addr) ||
17228 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17229 		return 0;
17230 
17231 	return -EINVAL;
17232 }
17233 
17234 /* list of non-sleepable functions that are otherwise on
17235  * ALLOW_ERROR_INJECTION list
17236  */
17237 BTF_SET_START(btf_non_sleepable_error_inject)
17238 /* Three functions below can be called from sleepable and non-sleepable context.
17239  * Assume non-sleepable from bpf safety point of view.
17240  */
17241 BTF_ID(func, __filemap_add_folio)
17242 BTF_ID(func, should_fail_alloc_page)
17243 BTF_ID(func, should_failslab)
17244 BTF_SET_END(btf_non_sleepable_error_inject)
17245 
17246 static int check_non_sleepable_error_inject(u32 btf_id)
17247 {
17248 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17249 }
17250 
17251 int bpf_check_attach_target(struct bpf_verifier_log *log,
17252 			    const struct bpf_prog *prog,
17253 			    const struct bpf_prog *tgt_prog,
17254 			    u32 btf_id,
17255 			    struct bpf_attach_target_info *tgt_info)
17256 {
17257 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17258 	const char prefix[] = "btf_trace_";
17259 	int ret = 0, subprog = -1, i;
17260 	const struct btf_type *t;
17261 	bool conservative = true;
17262 	const char *tname;
17263 	struct btf *btf;
17264 	long addr = 0;
17265 
17266 	if (!btf_id) {
17267 		bpf_log(log, "Tracing programs must provide btf_id\n");
17268 		return -EINVAL;
17269 	}
17270 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17271 	if (!btf) {
17272 		bpf_log(log,
17273 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17274 		return -EINVAL;
17275 	}
17276 	t = btf_type_by_id(btf, btf_id);
17277 	if (!t) {
17278 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17279 		return -EINVAL;
17280 	}
17281 	tname = btf_name_by_offset(btf, t->name_off);
17282 	if (!tname) {
17283 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17284 		return -EINVAL;
17285 	}
17286 	if (tgt_prog) {
17287 		struct bpf_prog_aux *aux = tgt_prog->aux;
17288 
17289 		if (bpf_prog_is_dev_bound(prog->aux) &&
17290 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17291 			bpf_log(log, "Target program bound device mismatch");
17292 			return -EINVAL;
17293 		}
17294 
17295 		for (i = 0; i < aux->func_info_cnt; i++)
17296 			if (aux->func_info[i].type_id == btf_id) {
17297 				subprog = i;
17298 				break;
17299 			}
17300 		if (subprog == -1) {
17301 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
17302 			return -EINVAL;
17303 		}
17304 		conservative = aux->func_info_aux[subprog].unreliable;
17305 		if (prog_extension) {
17306 			if (conservative) {
17307 				bpf_log(log,
17308 					"Cannot replace static functions\n");
17309 				return -EINVAL;
17310 			}
17311 			if (!prog->jit_requested) {
17312 				bpf_log(log,
17313 					"Extension programs should be JITed\n");
17314 				return -EINVAL;
17315 			}
17316 		}
17317 		if (!tgt_prog->jited) {
17318 			bpf_log(log, "Can attach to only JITed progs\n");
17319 			return -EINVAL;
17320 		}
17321 		if (tgt_prog->type == prog->type) {
17322 			/* Cannot fentry/fexit another fentry/fexit program.
17323 			 * Cannot attach program extension to another extension.
17324 			 * It's ok to attach fentry/fexit to extension program.
17325 			 */
17326 			bpf_log(log, "Cannot recursively attach\n");
17327 			return -EINVAL;
17328 		}
17329 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17330 		    prog_extension &&
17331 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17332 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17333 			/* Program extensions can extend all program types
17334 			 * except fentry/fexit. The reason is the following.
17335 			 * The fentry/fexit programs are used for performance
17336 			 * analysis, stats and can be attached to any program
17337 			 * type except themselves. When extension program is
17338 			 * replacing XDP function it is necessary to allow
17339 			 * performance analysis of all functions. Both original
17340 			 * XDP program and its program extension. Hence
17341 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17342 			 * allowed. If extending of fentry/fexit was allowed it
17343 			 * would be possible to create long call chain
17344 			 * fentry->extension->fentry->extension beyond
17345 			 * reasonable stack size. Hence extending fentry is not
17346 			 * allowed.
17347 			 */
17348 			bpf_log(log, "Cannot extend fentry/fexit\n");
17349 			return -EINVAL;
17350 		}
17351 	} else {
17352 		if (prog_extension) {
17353 			bpf_log(log, "Cannot replace kernel functions\n");
17354 			return -EINVAL;
17355 		}
17356 	}
17357 
17358 	switch (prog->expected_attach_type) {
17359 	case BPF_TRACE_RAW_TP:
17360 		if (tgt_prog) {
17361 			bpf_log(log,
17362 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17363 			return -EINVAL;
17364 		}
17365 		if (!btf_type_is_typedef(t)) {
17366 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
17367 				btf_id);
17368 			return -EINVAL;
17369 		}
17370 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17371 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17372 				btf_id, tname);
17373 			return -EINVAL;
17374 		}
17375 		tname += sizeof(prefix) - 1;
17376 		t = btf_type_by_id(btf, t->type);
17377 		if (!btf_type_is_ptr(t))
17378 			/* should never happen in valid vmlinux build */
17379 			return -EINVAL;
17380 		t = btf_type_by_id(btf, t->type);
17381 		if (!btf_type_is_func_proto(t))
17382 			/* should never happen in valid vmlinux build */
17383 			return -EINVAL;
17384 
17385 		break;
17386 	case BPF_TRACE_ITER:
17387 		if (!btf_type_is_func(t)) {
17388 			bpf_log(log, "attach_btf_id %u is not a function\n",
17389 				btf_id);
17390 			return -EINVAL;
17391 		}
17392 		t = btf_type_by_id(btf, t->type);
17393 		if (!btf_type_is_func_proto(t))
17394 			return -EINVAL;
17395 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17396 		if (ret)
17397 			return ret;
17398 		break;
17399 	default:
17400 		if (!prog_extension)
17401 			return -EINVAL;
17402 		fallthrough;
17403 	case BPF_MODIFY_RETURN:
17404 	case BPF_LSM_MAC:
17405 	case BPF_LSM_CGROUP:
17406 	case BPF_TRACE_FENTRY:
17407 	case BPF_TRACE_FEXIT:
17408 		if (!btf_type_is_func(t)) {
17409 			bpf_log(log, "attach_btf_id %u is not a function\n",
17410 				btf_id);
17411 			return -EINVAL;
17412 		}
17413 		if (prog_extension &&
17414 		    btf_check_type_match(log, prog, btf, t))
17415 			return -EINVAL;
17416 		t = btf_type_by_id(btf, t->type);
17417 		if (!btf_type_is_func_proto(t))
17418 			return -EINVAL;
17419 
17420 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17421 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17422 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17423 			return -EINVAL;
17424 
17425 		if (tgt_prog && conservative)
17426 			t = NULL;
17427 
17428 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17429 		if (ret < 0)
17430 			return ret;
17431 
17432 		if (tgt_prog) {
17433 			if (subprog == 0)
17434 				addr = (long) tgt_prog->bpf_func;
17435 			else
17436 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17437 		} else {
17438 			addr = kallsyms_lookup_name(tname);
17439 			if (!addr) {
17440 				bpf_log(log,
17441 					"The address of function %s cannot be found\n",
17442 					tname);
17443 				return -ENOENT;
17444 			}
17445 		}
17446 
17447 		if (prog->aux->sleepable) {
17448 			ret = -EINVAL;
17449 			switch (prog->type) {
17450 			case BPF_PROG_TYPE_TRACING:
17451 
17452 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
17453 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17454 				 */
17455 				if (!check_non_sleepable_error_inject(btf_id) &&
17456 				    within_error_injection_list(addr))
17457 					ret = 0;
17458 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
17459 				 * in the fmodret id set with the KF_SLEEPABLE flag.
17460 				 */
17461 				else {
17462 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17463 
17464 					if (flags && (*flags & KF_SLEEPABLE))
17465 						ret = 0;
17466 				}
17467 				break;
17468 			case BPF_PROG_TYPE_LSM:
17469 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
17470 				 * Only some of them are sleepable.
17471 				 */
17472 				if (bpf_lsm_is_sleepable_hook(btf_id))
17473 					ret = 0;
17474 				break;
17475 			default:
17476 				break;
17477 			}
17478 			if (ret) {
17479 				bpf_log(log, "%s is not sleepable\n", tname);
17480 				return ret;
17481 			}
17482 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17483 			if (tgt_prog) {
17484 				bpf_log(log, "can't modify return codes of BPF programs\n");
17485 				return -EINVAL;
17486 			}
17487 			ret = -EINVAL;
17488 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
17489 			    !check_attach_modify_return(addr, tname))
17490 				ret = 0;
17491 			if (ret) {
17492 				bpf_log(log, "%s() is not modifiable\n", tname);
17493 				return ret;
17494 			}
17495 		}
17496 
17497 		break;
17498 	}
17499 	tgt_info->tgt_addr = addr;
17500 	tgt_info->tgt_name = tname;
17501 	tgt_info->tgt_type = t;
17502 	return 0;
17503 }
17504 
17505 BTF_SET_START(btf_id_deny)
17506 BTF_ID_UNUSED
17507 #ifdef CONFIG_SMP
17508 BTF_ID(func, migrate_disable)
17509 BTF_ID(func, migrate_enable)
17510 #endif
17511 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17512 BTF_ID(func, rcu_read_unlock_strict)
17513 #endif
17514 BTF_SET_END(btf_id_deny)
17515 
17516 static bool can_be_sleepable(struct bpf_prog *prog)
17517 {
17518 	if (prog->type == BPF_PROG_TYPE_TRACING) {
17519 		switch (prog->expected_attach_type) {
17520 		case BPF_TRACE_FENTRY:
17521 		case BPF_TRACE_FEXIT:
17522 		case BPF_MODIFY_RETURN:
17523 		case BPF_TRACE_ITER:
17524 			return true;
17525 		default:
17526 			return false;
17527 		}
17528 	}
17529 	return prog->type == BPF_PROG_TYPE_LSM ||
17530 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17531 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17532 }
17533 
17534 static int check_attach_btf_id(struct bpf_verifier_env *env)
17535 {
17536 	struct bpf_prog *prog = env->prog;
17537 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17538 	struct bpf_attach_target_info tgt_info = {};
17539 	u32 btf_id = prog->aux->attach_btf_id;
17540 	struct bpf_trampoline *tr;
17541 	int ret;
17542 	u64 key;
17543 
17544 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17545 		if (prog->aux->sleepable)
17546 			/* attach_btf_id checked to be zero already */
17547 			return 0;
17548 		verbose(env, "Syscall programs can only be sleepable\n");
17549 		return -EINVAL;
17550 	}
17551 
17552 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17553 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17554 		return -EINVAL;
17555 	}
17556 
17557 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17558 		return check_struct_ops_btf_id(env);
17559 
17560 	if (prog->type != BPF_PROG_TYPE_TRACING &&
17561 	    prog->type != BPF_PROG_TYPE_LSM &&
17562 	    prog->type != BPF_PROG_TYPE_EXT)
17563 		return 0;
17564 
17565 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17566 	if (ret)
17567 		return ret;
17568 
17569 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17570 		/* to make freplace equivalent to their targets, they need to
17571 		 * inherit env->ops and expected_attach_type for the rest of the
17572 		 * verification
17573 		 */
17574 		env->ops = bpf_verifier_ops[tgt_prog->type];
17575 		prog->expected_attach_type = tgt_prog->expected_attach_type;
17576 	}
17577 
17578 	/* store info about the attachment target that will be used later */
17579 	prog->aux->attach_func_proto = tgt_info.tgt_type;
17580 	prog->aux->attach_func_name = tgt_info.tgt_name;
17581 
17582 	if (tgt_prog) {
17583 		prog->aux->saved_dst_prog_type = tgt_prog->type;
17584 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17585 	}
17586 
17587 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17588 		prog->aux->attach_btf_trace = true;
17589 		return 0;
17590 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17591 		if (!bpf_iter_prog_supported(prog))
17592 			return -EINVAL;
17593 		return 0;
17594 	}
17595 
17596 	if (prog->type == BPF_PROG_TYPE_LSM) {
17597 		ret = bpf_lsm_verify_prog(&env->log, prog);
17598 		if (ret < 0)
17599 			return ret;
17600 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
17601 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
17602 		return -EINVAL;
17603 	}
17604 
17605 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17606 	tr = bpf_trampoline_get(key, &tgt_info);
17607 	if (!tr)
17608 		return -ENOMEM;
17609 
17610 	prog->aux->dst_trampoline = tr;
17611 	return 0;
17612 }
17613 
17614 struct btf *bpf_get_btf_vmlinux(void)
17615 {
17616 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17617 		mutex_lock(&bpf_verifier_lock);
17618 		if (!btf_vmlinux)
17619 			btf_vmlinux = btf_parse_vmlinux();
17620 		mutex_unlock(&bpf_verifier_lock);
17621 	}
17622 	return btf_vmlinux;
17623 }
17624 
17625 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
17626 {
17627 	u64 start_time = ktime_get_ns();
17628 	struct bpf_verifier_env *env;
17629 	struct bpf_verifier_log *log;
17630 	int i, len, ret = -EINVAL;
17631 	bool is_priv;
17632 
17633 	/* no program is valid */
17634 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
17635 		return -EINVAL;
17636 
17637 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
17638 	 * allocate/free it every time bpf_check() is called
17639 	 */
17640 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
17641 	if (!env)
17642 		return -ENOMEM;
17643 	log = &env->log;
17644 
17645 	len = (*prog)->len;
17646 	env->insn_aux_data =
17647 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
17648 	ret = -ENOMEM;
17649 	if (!env->insn_aux_data)
17650 		goto err_free_env;
17651 	for (i = 0; i < len; i++)
17652 		env->insn_aux_data[i].orig_idx = i;
17653 	env->prog = *prog;
17654 	env->ops = bpf_verifier_ops[env->prog->type];
17655 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
17656 	is_priv = bpf_capable();
17657 
17658 	bpf_get_btf_vmlinux();
17659 
17660 	/* grab the mutex to protect few globals used by verifier */
17661 	if (!is_priv)
17662 		mutex_lock(&bpf_verifier_lock);
17663 
17664 	if (attr->log_level || attr->log_buf || attr->log_size) {
17665 		/* user requested verbose verifier output
17666 		 * and supplied buffer to store the verification trace
17667 		 */
17668 		log->level = attr->log_level;
17669 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
17670 		log->len_total = attr->log_size;
17671 
17672 		/* log attributes have to be sane */
17673 		if (!bpf_verifier_log_attr_valid(log)) {
17674 			ret = -EINVAL;
17675 			goto err_unlock;
17676 		}
17677 	}
17678 
17679 	mark_verifier_state_clean(env);
17680 
17681 	if (IS_ERR(btf_vmlinux)) {
17682 		/* Either gcc or pahole or kernel are broken. */
17683 		verbose(env, "in-kernel BTF is malformed\n");
17684 		ret = PTR_ERR(btf_vmlinux);
17685 		goto skip_full_check;
17686 	}
17687 
17688 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
17689 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
17690 		env->strict_alignment = true;
17691 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
17692 		env->strict_alignment = false;
17693 
17694 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
17695 	env->allow_uninit_stack = bpf_allow_uninit_stack();
17696 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
17697 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
17698 	env->bpf_capable = bpf_capable();
17699 	env->rcu_tag_supported = btf_vmlinux &&
17700 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
17701 
17702 	if (is_priv)
17703 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
17704 
17705 	env->explored_states = kvcalloc(state_htab_size(env),
17706 				       sizeof(struct bpf_verifier_state_list *),
17707 				       GFP_USER);
17708 	ret = -ENOMEM;
17709 	if (!env->explored_states)
17710 		goto skip_full_check;
17711 
17712 	ret = add_subprog_and_kfunc(env);
17713 	if (ret < 0)
17714 		goto skip_full_check;
17715 
17716 	ret = check_subprogs(env);
17717 	if (ret < 0)
17718 		goto skip_full_check;
17719 
17720 	ret = check_btf_info(env, attr, uattr);
17721 	if (ret < 0)
17722 		goto skip_full_check;
17723 
17724 	ret = check_attach_btf_id(env);
17725 	if (ret)
17726 		goto skip_full_check;
17727 
17728 	ret = resolve_pseudo_ldimm64(env);
17729 	if (ret < 0)
17730 		goto skip_full_check;
17731 
17732 	if (bpf_prog_is_offloaded(env->prog->aux)) {
17733 		ret = bpf_prog_offload_verifier_prep(env->prog);
17734 		if (ret)
17735 			goto skip_full_check;
17736 	}
17737 
17738 	ret = check_cfg(env);
17739 	if (ret < 0)
17740 		goto skip_full_check;
17741 
17742 	ret = do_check_subprogs(env);
17743 	ret = ret ?: do_check_main(env);
17744 
17745 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
17746 		ret = bpf_prog_offload_finalize(env);
17747 
17748 skip_full_check:
17749 	kvfree(env->explored_states);
17750 
17751 	if (ret == 0)
17752 		ret = check_max_stack_depth(env);
17753 
17754 	/* instruction rewrites happen after this point */
17755 	if (ret == 0)
17756 		ret = optimize_bpf_loop(env);
17757 
17758 	if (is_priv) {
17759 		if (ret == 0)
17760 			opt_hard_wire_dead_code_branches(env);
17761 		if (ret == 0)
17762 			ret = opt_remove_dead_code(env);
17763 		if (ret == 0)
17764 			ret = opt_remove_nops(env);
17765 	} else {
17766 		if (ret == 0)
17767 			sanitize_dead_code(env);
17768 	}
17769 
17770 	if (ret == 0)
17771 		/* program is valid, convert *(u32*)(ctx + off) accesses */
17772 		ret = convert_ctx_accesses(env);
17773 
17774 	if (ret == 0)
17775 		ret = do_misc_fixups(env);
17776 
17777 	/* do 32-bit optimization after insn patching has done so those patched
17778 	 * insns could be handled correctly.
17779 	 */
17780 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
17781 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
17782 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
17783 								     : false;
17784 	}
17785 
17786 	if (ret == 0)
17787 		ret = fixup_call_args(env);
17788 
17789 	env->verification_time = ktime_get_ns() - start_time;
17790 	print_verification_stats(env);
17791 	env->prog->aux->verified_insns = env->insn_processed;
17792 
17793 	if (log->level && bpf_verifier_log_full(log))
17794 		ret = -ENOSPC;
17795 	if (log->level && !log->ubuf) {
17796 		ret = -EFAULT;
17797 		goto err_release_maps;
17798 	}
17799 
17800 	if (ret)
17801 		goto err_release_maps;
17802 
17803 	if (env->used_map_cnt) {
17804 		/* if program passed verifier, update used_maps in bpf_prog_info */
17805 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17806 							  sizeof(env->used_maps[0]),
17807 							  GFP_KERNEL);
17808 
17809 		if (!env->prog->aux->used_maps) {
17810 			ret = -ENOMEM;
17811 			goto err_release_maps;
17812 		}
17813 
17814 		memcpy(env->prog->aux->used_maps, env->used_maps,
17815 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17816 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17817 	}
17818 	if (env->used_btf_cnt) {
17819 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17820 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17821 							  sizeof(env->used_btfs[0]),
17822 							  GFP_KERNEL);
17823 		if (!env->prog->aux->used_btfs) {
17824 			ret = -ENOMEM;
17825 			goto err_release_maps;
17826 		}
17827 
17828 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17829 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17830 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17831 	}
17832 	if (env->used_map_cnt || env->used_btf_cnt) {
17833 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17834 		 * bpf_ld_imm64 instructions
17835 		 */
17836 		convert_pseudo_ld_imm64(env);
17837 	}
17838 
17839 	adjust_btf_func(env);
17840 
17841 err_release_maps:
17842 	if (!env->prog->aux->used_maps)
17843 		/* if we didn't copy map pointers into bpf_prog_info, release
17844 		 * them now. Otherwise free_used_maps() will release them.
17845 		 */
17846 		release_maps(env);
17847 	if (!env->prog->aux->used_btfs)
17848 		release_btfs(env);
17849 
17850 	/* extension progs temporarily inherit the attach_type of their targets
17851 	   for verification purposes, so set it back to zero before returning
17852 	 */
17853 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17854 		env->prog->expected_attach_type = 0;
17855 
17856 	*prog = env->prog;
17857 err_unlock:
17858 	if (!is_priv)
17859 		mutex_unlock(&bpf_verifier_lock);
17860 	vfree(env->insn_aux_data);
17861 err_free_env:
17862 	kfree(env);
17863 	return ret;
17864 }
17865