xref: /linux/kernel/bpf/verifier.c (revision 40e0b09081420853542571c38875b48b60404ebb)
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 
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198 
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203 
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 			      const struct bpf_map *map, bool unpriv)
206 {
207 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 	unpriv |= bpf_map_ptr_unpriv(aux);
209 	aux->map_ptr_state = (unsigned long)map |
210 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212 
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217 
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222 
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227 
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 	bool poisoned = bpf_map_key_poisoned(aux);
231 
232 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235 
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 	return insn->code == (BPF_JMP | BPF_CALL) &&
239 	       insn->src_reg == BPF_PSEUDO_CALL;
240 }
241 
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 	return insn->code == (BPF_JMP | BPF_CALL) &&
245 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247 
248 struct bpf_call_arg_meta {
249 	struct bpf_map *map_ptr;
250 	bool raw_mode;
251 	bool pkt_access;
252 	u8 release_regno;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 	struct btf_field *kptr_field;
266 	u8 uninit_dynptr_regno;
267 };
268 
269 struct btf *btf_vmlinux;
270 
271 static DEFINE_MUTEX(bpf_verifier_lock);
272 
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 	const struct bpf_line_info *linfo;
277 	const struct bpf_prog *prog;
278 	u32 i, nr_linfo;
279 
280 	prog = env->prog;
281 	nr_linfo = prog->aux->nr_linfo;
282 
283 	if (!nr_linfo || insn_off >= prog->len)
284 		return NULL;
285 
286 	linfo = prog->aux->linfo;
287 	for (i = 1; i < nr_linfo; i++)
288 		if (insn_off < linfo[i].insn_off)
289 			break;
290 
291 	return &linfo[i - 1];
292 }
293 
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 		       va_list args)
296 {
297 	unsigned int n;
298 
299 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 
301 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 		  "verifier log line truncated - local buffer too short\n");
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 
307 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 		return;
309 	}
310 
311 	n = min(log->len_total - log->len_used - 1, n);
312 	log->kbuf[n] = '\0';
313 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 		log->len_used += n;
315 	else
316 		log->ubuf = NULL;
317 }
318 
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 	char zero = 0;
322 
323 	if (!bpf_verifier_log_needed(log))
324 		return;
325 
326 	log->len_used = new_pos;
327 	if (put_user(zero, log->ubuf + new_pos))
328 		log->ubuf = NULL;
329 }
330 
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 					   const char *fmt, ...)
337 {
338 	va_list args;
339 
340 	if (!bpf_verifier_log_needed(&env->log))
341 		return;
342 
343 	va_start(args, fmt);
344 	bpf_verifier_vlog(&env->log, fmt, args);
345 	va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 	struct bpf_verifier_env *env = private_data;
352 	va_list args;
353 
354 	if (!bpf_verifier_log_needed(&env->log))
355 		return;
356 
357 	va_start(args, fmt);
358 	bpf_verifier_vlog(&env->log, fmt, args);
359 	va_end(args);
360 }
361 
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 			    const char *fmt, ...)
364 {
365 	va_list args;
366 
367 	if (!bpf_verifier_log_needed(log))
368 		return;
369 
370 	va_start(args, fmt);
371 	bpf_verifier_vlog(log, fmt, args);
372 	va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375 
376 static const char *ltrim(const char *s)
377 {
378 	while (isspace(*s))
379 		s++;
380 
381 	return s;
382 }
383 
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 					 u32 insn_off,
386 					 const char *prefix_fmt, ...)
387 {
388 	const struct bpf_line_info *linfo;
389 
390 	if (!bpf_verifier_log_needed(&env->log))
391 		return;
392 
393 	linfo = find_linfo(env, insn_off);
394 	if (!linfo || linfo == env->prev_linfo)
395 		return;
396 
397 	if (prefix_fmt) {
398 		va_list args;
399 
400 		va_start(args, prefix_fmt);
401 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 		va_end(args);
403 	}
404 
405 	verbose(env, "%s\n",
406 		ltrim(btf_name_by_offset(env->prog->aux->btf,
407 					 linfo->line_off)));
408 
409 	env->prev_linfo = linfo;
410 }
411 
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 				   struct bpf_reg_state *reg,
414 				   struct tnum *range, const char *ctx,
415 				   const char *reg_name)
416 {
417 	char tn_buf[48];
418 
419 	verbose(env, "At %s the register %s ", ctx, reg_name);
420 	if (!tnum_is_unknown(reg->var_off)) {
421 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 		verbose(env, "has value %s", tn_buf);
423 	} else {
424 		verbose(env, "has unknown scalar value");
425 	}
426 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 	verbose(env, " should have been in %s\n", tn_buf);
428 }
429 
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 	type = base_type(type);
433 	return type == PTR_TO_PACKET ||
434 	       type == PTR_TO_PACKET_META;
435 }
436 
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_SOCK_COMMON ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_XDP_SOCK;
443 }
444 
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 	return type == PTR_TO_SOCKET ||
448 		type == PTR_TO_TCP_SOCK ||
449 		type == PTR_TO_MAP_VALUE ||
450 		type == PTR_TO_MAP_KEY ||
451 		type == PTR_TO_SOCK_COMMON;
452 }
453 
454 static bool type_is_ptr_alloc_obj(u32 type)
455 {
456 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
457 }
458 
459 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
460 {
461 	struct btf_record *rec = NULL;
462 	struct btf_struct_meta *meta;
463 
464 	if (reg->type == PTR_TO_MAP_VALUE) {
465 		rec = reg->map_ptr->record;
466 	} else if (type_is_ptr_alloc_obj(reg->type)) {
467 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
468 		if (meta)
469 			rec = meta->record;
470 	}
471 	return rec;
472 }
473 
474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
475 {
476 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
477 }
478 
479 static bool type_is_rdonly_mem(u32 type)
480 {
481 	return type & MEM_RDONLY;
482 }
483 
484 static bool type_may_be_null(u32 type)
485 {
486 	return type & PTR_MAYBE_NULL;
487 }
488 
489 static bool is_acquire_function(enum bpf_func_id func_id,
490 				const struct bpf_map *map)
491 {
492 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
493 
494 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
495 	    func_id == BPF_FUNC_sk_lookup_udp ||
496 	    func_id == BPF_FUNC_skc_lookup_tcp ||
497 	    func_id == BPF_FUNC_ringbuf_reserve ||
498 	    func_id == BPF_FUNC_kptr_xchg)
499 		return true;
500 
501 	if (func_id == BPF_FUNC_map_lookup_elem &&
502 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
503 	     map_type == BPF_MAP_TYPE_SOCKHASH))
504 		return true;
505 
506 	return false;
507 }
508 
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511 	return func_id == BPF_FUNC_tcp_sock ||
512 		func_id == BPF_FUNC_sk_fullsock ||
513 		func_id == BPF_FUNC_skc_to_tcp_sock ||
514 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
515 		func_id == BPF_FUNC_skc_to_udp6_sock ||
516 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
517 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
519 }
520 
521 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
522 {
523 	return func_id == BPF_FUNC_dynptr_data;
524 }
525 
526 static bool is_callback_calling_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_for_each_map_elem ||
529 	       func_id == BPF_FUNC_timer_set_callback ||
530 	       func_id == BPF_FUNC_find_vma ||
531 	       func_id == BPF_FUNC_loop ||
532 	       func_id == BPF_FUNC_user_ringbuf_drain;
533 }
534 
535 static bool is_storage_get_function(enum bpf_func_id func_id)
536 {
537 	return func_id == BPF_FUNC_sk_storage_get ||
538 	       func_id == BPF_FUNC_inode_storage_get ||
539 	       func_id == BPF_FUNC_task_storage_get ||
540 	       func_id == BPF_FUNC_cgrp_storage_get;
541 }
542 
543 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
544 					const struct bpf_map *map)
545 {
546 	int ref_obj_uses = 0;
547 
548 	if (is_ptr_cast_function(func_id))
549 		ref_obj_uses++;
550 	if (is_acquire_function(func_id, map))
551 		ref_obj_uses++;
552 	if (is_dynptr_ref_function(func_id))
553 		ref_obj_uses++;
554 
555 	return ref_obj_uses > 1;
556 }
557 
558 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
559 {
560 	return BPF_CLASS(insn->code) == BPF_STX &&
561 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
562 	       insn->imm == BPF_CMPXCHG;
563 }
564 
565 /* string representation of 'enum bpf_reg_type'
566  *
567  * Note that reg_type_str() can not appear more than once in a single verbose()
568  * statement.
569  */
570 static const char *reg_type_str(struct bpf_verifier_env *env,
571 				enum bpf_reg_type type)
572 {
573 	char postfix[16] = {0}, prefix[64] = {0};
574 	static const char * const str[] = {
575 		[NOT_INIT]		= "?",
576 		[SCALAR_VALUE]		= "scalar",
577 		[PTR_TO_CTX]		= "ctx",
578 		[CONST_PTR_TO_MAP]	= "map_ptr",
579 		[PTR_TO_MAP_VALUE]	= "map_value",
580 		[PTR_TO_STACK]		= "fp",
581 		[PTR_TO_PACKET]		= "pkt",
582 		[PTR_TO_PACKET_META]	= "pkt_meta",
583 		[PTR_TO_PACKET_END]	= "pkt_end",
584 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
585 		[PTR_TO_SOCKET]		= "sock",
586 		[PTR_TO_SOCK_COMMON]	= "sock_common",
587 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
588 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
589 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
590 		[PTR_TO_BTF_ID]		= "ptr_",
591 		[PTR_TO_MEM]		= "mem",
592 		[PTR_TO_BUF]		= "buf",
593 		[PTR_TO_FUNC]		= "func",
594 		[PTR_TO_MAP_KEY]	= "map_key",
595 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
596 	};
597 
598 	if (type & PTR_MAYBE_NULL) {
599 		if (base_type(type) == PTR_TO_BTF_ID)
600 			strncpy(postfix, "or_null_", 16);
601 		else
602 			strncpy(postfix, "_or_null", 16);
603 	}
604 
605 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
606 		 type & MEM_RDONLY ? "rdonly_" : "",
607 		 type & MEM_RINGBUF ? "ringbuf_" : "",
608 		 type & MEM_USER ? "user_" : "",
609 		 type & MEM_PERCPU ? "percpu_" : "",
610 		 type & MEM_RCU ? "rcu_" : "",
611 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
612 		 type & PTR_TRUSTED ? "trusted_" : ""
613 	);
614 
615 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
616 		 prefix, str[base_type(type)], postfix);
617 	return env->type_str_buf;
618 }
619 
620 static char slot_type_char[] = {
621 	[STACK_INVALID]	= '?',
622 	[STACK_SPILL]	= 'r',
623 	[STACK_MISC]	= 'm',
624 	[STACK_ZERO]	= '0',
625 	[STACK_DYNPTR]	= 'd',
626 };
627 
628 static void print_liveness(struct bpf_verifier_env *env,
629 			   enum bpf_reg_liveness live)
630 {
631 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
632 	    verbose(env, "_");
633 	if (live & REG_LIVE_READ)
634 		verbose(env, "r");
635 	if (live & REG_LIVE_WRITTEN)
636 		verbose(env, "w");
637 	if (live & REG_LIVE_DONE)
638 		verbose(env, "D");
639 }
640 
641 static int get_spi(s32 off)
642 {
643 	return (-off - 1) / BPF_REG_SIZE;
644 }
645 
646 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
647 {
648 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
649 
650 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
651 	 * within [0, allocated_stack).
652 	 *
653 	 * Please note that the spi grows downwards. For example, a dynptr
654 	 * takes the size of two stack slots; the first slot will be at
655 	 * spi and the second slot will be at spi - 1.
656 	 */
657 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
658 }
659 
660 static struct bpf_func_state *func(struct bpf_verifier_env *env,
661 				   const struct bpf_reg_state *reg)
662 {
663 	struct bpf_verifier_state *cur = env->cur_state;
664 
665 	return cur->frame[reg->frameno];
666 }
667 
668 static const char *kernel_type_name(const struct btf* btf, u32 id)
669 {
670 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
671 }
672 
673 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
674 {
675 	env->scratched_regs |= 1U << regno;
676 }
677 
678 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
679 {
680 	env->scratched_stack_slots |= 1ULL << spi;
681 }
682 
683 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
684 {
685 	return (env->scratched_regs >> regno) & 1;
686 }
687 
688 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
689 {
690 	return (env->scratched_stack_slots >> regno) & 1;
691 }
692 
693 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
694 {
695 	return env->scratched_regs || env->scratched_stack_slots;
696 }
697 
698 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
699 {
700 	env->scratched_regs = 0U;
701 	env->scratched_stack_slots = 0ULL;
702 }
703 
704 /* Used for printing the entire verifier state. */
705 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
706 {
707 	env->scratched_regs = ~0U;
708 	env->scratched_stack_slots = ~0ULL;
709 }
710 
711 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
712 {
713 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
714 	case DYNPTR_TYPE_LOCAL:
715 		return BPF_DYNPTR_TYPE_LOCAL;
716 	case DYNPTR_TYPE_RINGBUF:
717 		return BPF_DYNPTR_TYPE_RINGBUF;
718 	default:
719 		return BPF_DYNPTR_TYPE_INVALID;
720 	}
721 }
722 
723 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
724 {
725 	return type == BPF_DYNPTR_TYPE_RINGBUF;
726 }
727 
728 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
729 			      enum bpf_dynptr_type type,
730 			      bool first_slot);
731 
732 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
733 				struct bpf_reg_state *reg);
734 
735 static void mark_dynptr_stack_regs(struct bpf_reg_state *sreg1,
736 				   struct bpf_reg_state *sreg2,
737 				   enum bpf_dynptr_type type)
738 {
739 	__mark_dynptr_reg(sreg1, type, true);
740 	__mark_dynptr_reg(sreg2, type, false);
741 }
742 
743 static void mark_dynptr_cb_reg(struct bpf_reg_state *reg,
744 			       enum bpf_dynptr_type type)
745 {
746 	__mark_dynptr_reg(reg, type, true);
747 }
748 
749 
750 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
751 				   enum bpf_arg_type arg_type, int insn_idx)
752 {
753 	struct bpf_func_state *state = func(env, reg);
754 	enum bpf_dynptr_type type;
755 	int spi, i, id;
756 
757 	spi = get_spi(reg->off);
758 
759 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760 		return -EINVAL;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(&state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		id = acquire_reference_state(env, insn_idx);
777 		if (id < 0)
778 			return id;
779 
780 		state->stack[spi].spilled_ptr.ref_obj_id = id;
781 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
782 	}
783 
784 	return 0;
785 }
786 
787 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
788 {
789 	struct bpf_func_state *state = func(env, reg);
790 	int spi, i;
791 
792 	spi = get_spi(reg->off);
793 
794 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
795 		return -EINVAL;
796 
797 	for (i = 0; i < BPF_REG_SIZE; i++) {
798 		state->stack[spi].slot_type[i] = STACK_INVALID;
799 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
800 	}
801 
802 	/* Invalidate any slices associated with this dynptr */
803 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
804 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
805 
806 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
807 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
808 	return 0;
809 }
810 
811 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
812 {
813 	struct bpf_func_state *state = func(env, reg);
814 	int spi, i;
815 
816 	if (reg->type == CONST_PTR_TO_DYNPTR)
817 		return false;
818 
819 	spi = get_spi(reg->off);
820 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
821 		return true;
822 
823 	for (i = 0; i < BPF_REG_SIZE; i++) {
824 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
825 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
826 			return false;
827 	}
828 
829 	return true;
830 }
831 
832 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
833 {
834 	struct bpf_func_state *state = func(env, reg);
835 	int spi;
836 	int i;
837 
838 	/* This already represents first slot of initialized bpf_dynptr */
839 	if (reg->type == CONST_PTR_TO_DYNPTR)
840 		return true;
841 
842 	spi = get_spi(reg->off);
843 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
844 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
845 		return false;
846 
847 	for (i = 0; i < BPF_REG_SIZE; i++) {
848 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
849 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
850 			return false;
851 	}
852 
853 	return true;
854 }
855 
856 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
857 				    enum bpf_arg_type arg_type)
858 {
859 	struct bpf_func_state *state = func(env, reg);
860 	enum bpf_dynptr_type dynptr_type;
861 	int spi;
862 
863 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
864 	if (arg_type == ARG_PTR_TO_DYNPTR)
865 		return true;
866 
867 	dynptr_type = arg_to_dynptr_type(arg_type);
868 	if (reg->type == CONST_PTR_TO_DYNPTR) {
869 		return reg->dynptr.type == dynptr_type;
870 	} else {
871 		spi = get_spi(reg->off);
872 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
873 	}
874 }
875 
876 /* The reg state of a pointer or a bounded scalar was saved when
877  * it was spilled to the stack.
878  */
879 static bool is_spilled_reg(const struct bpf_stack_state *stack)
880 {
881 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
882 }
883 
884 static void scrub_spilled_slot(u8 *stype)
885 {
886 	if (*stype != STACK_INVALID)
887 		*stype = STACK_MISC;
888 }
889 
890 static void print_verifier_state(struct bpf_verifier_env *env,
891 				 const struct bpf_func_state *state,
892 				 bool print_all)
893 {
894 	const struct bpf_reg_state *reg;
895 	enum bpf_reg_type t;
896 	int i;
897 
898 	if (state->frameno)
899 		verbose(env, " frame%d:", state->frameno);
900 	for (i = 0; i < MAX_BPF_REG; i++) {
901 		reg = &state->regs[i];
902 		t = reg->type;
903 		if (t == NOT_INIT)
904 			continue;
905 		if (!print_all && !reg_scratched(env, i))
906 			continue;
907 		verbose(env, " R%d", i);
908 		print_liveness(env, reg->live);
909 		verbose(env, "=");
910 		if (t == SCALAR_VALUE && reg->precise)
911 			verbose(env, "P");
912 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
913 		    tnum_is_const(reg->var_off)) {
914 			/* reg->off should be 0 for SCALAR_VALUE */
915 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
916 			verbose(env, "%lld", reg->var_off.value + reg->off);
917 		} else {
918 			const char *sep = "";
919 
920 			verbose(env, "%s", reg_type_str(env, t));
921 			if (base_type(t) == PTR_TO_BTF_ID)
922 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
923 			verbose(env, "(");
924 /*
925  * _a stands for append, was shortened to avoid multiline statements below.
926  * This macro is used to output a comma separated list of attributes.
927  */
928 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
929 
930 			if (reg->id)
931 				verbose_a("id=%d", reg->id);
932 			if (reg->ref_obj_id)
933 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
934 			if (t != SCALAR_VALUE)
935 				verbose_a("off=%d", reg->off);
936 			if (type_is_pkt_pointer(t))
937 				verbose_a("r=%d", reg->range);
938 			else if (base_type(t) == CONST_PTR_TO_MAP ||
939 				 base_type(t) == PTR_TO_MAP_KEY ||
940 				 base_type(t) == PTR_TO_MAP_VALUE)
941 				verbose_a("ks=%d,vs=%d",
942 					  reg->map_ptr->key_size,
943 					  reg->map_ptr->value_size);
944 			if (tnum_is_const(reg->var_off)) {
945 				/* Typically an immediate SCALAR_VALUE, but
946 				 * could be a pointer whose offset is too big
947 				 * for reg->off
948 				 */
949 				verbose_a("imm=%llx", reg->var_off.value);
950 			} else {
951 				if (reg->smin_value != reg->umin_value &&
952 				    reg->smin_value != S64_MIN)
953 					verbose_a("smin=%lld", (long long)reg->smin_value);
954 				if (reg->smax_value != reg->umax_value &&
955 				    reg->smax_value != S64_MAX)
956 					verbose_a("smax=%lld", (long long)reg->smax_value);
957 				if (reg->umin_value != 0)
958 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
959 				if (reg->umax_value != U64_MAX)
960 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
961 				if (!tnum_is_unknown(reg->var_off)) {
962 					char tn_buf[48];
963 
964 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
965 					verbose_a("var_off=%s", tn_buf);
966 				}
967 				if (reg->s32_min_value != reg->smin_value &&
968 				    reg->s32_min_value != S32_MIN)
969 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
970 				if (reg->s32_max_value != reg->smax_value &&
971 				    reg->s32_max_value != S32_MAX)
972 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
973 				if (reg->u32_min_value != reg->umin_value &&
974 				    reg->u32_min_value != U32_MIN)
975 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
976 				if (reg->u32_max_value != reg->umax_value &&
977 				    reg->u32_max_value != U32_MAX)
978 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
979 			}
980 #undef verbose_a
981 
982 			verbose(env, ")");
983 		}
984 	}
985 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
986 		char types_buf[BPF_REG_SIZE + 1];
987 		bool valid = false;
988 		int j;
989 
990 		for (j = 0; j < BPF_REG_SIZE; j++) {
991 			if (state->stack[i].slot_type[j] != STACK_INVALID)
992 				valid = true;
993 			types_buf[j] = slot_type_char[
994 					state->stack[i].slot_type[j]];
995 		}
996 		types_buf[BPF_REG_SIZE] = 0;
997 		if (!valid)
998 			continue;
999 		if (!print_all && !stack_slot_scratched(env, i))
1000 			continue;
1001 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1002 		print_liveness(env, state->stack[i].spilled_ptr.live);
1003 		if (is_spilled_reg(&state->stack[i])) {
1004 			reg = &state->stack[i].spilled_ptr;
1005 			t = reg->type;
1006 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1007 			if (t == SCALAR_VALUE && reg->precise)
1008 				verbose(env, "P");
1009 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1010 				verbose(env, "%lld", reg->var_off.value + reg->off);
1011 		} else {
1012 			verbose(env, "=%s", types_buf);
1013 		}
1014 	}
1015 	if (state->acquired_refs && state->refs[0].id) {
1016 		verbose(env, " refs=%d", state->refs[0].id);
1017 		for (i = 1; i < state->acquired_refs; i++)
1018 			if (state->refs[i].id)
1019 				verbose(env, ",%d", state->refs[i].id);
1020 	}
1021 	if (state->in_callback_fn)
1022 		verbose(env, " cb");
1023 	if (state->in_async_callback_fn)
1024 		verbose(env, " async_cb");
1025 	verbose(env, "\n");
1026 	mark_verifier_state_clean(env);
1027 }
1028 
1029 static inline u32 vlog_alignment(u32 pos)
1030 {
1031 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1032 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1033 }
1034 
1035 static void print_insn_state(struct bpf_verifier_env *env,
1036 			     const struct bpf_func_state *state)
1037 {
1038 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1039 		/* remove new line character */
1040 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1041 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1042 	} else {
1043 		verbose(env, "%d:", env->insn_idx);
1044 	}
1045 	print_verifier_state(env, state, false);
1046 }
1047 
1048 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1049  * small to hold src. This is different from krealloc since we don't want to preserve
1050  * the contents of dst.
1051  *
1052  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1053  * not be allocated.
1054  */
1055 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1056 {
1057 	size_t alloc_bytes;
1058 	void *orig = dst;
1059 	size_t bytes;
1060 
1061 	if (ZERO_OR_NULL_PTR(src))
1062 		goto out;
1063 
1064 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1065 		return NULL;
1066 
1067 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1068 	dst = krealloc(orig, alloc_bytes, flags);
1069 	if (!dst) {
1070 		kfree(orig);
1071 		return NULL;
1072 	}
1073 
1074 	memcpy(dst, src, bytes);
1075 out:
1076 	return dst ? dst : ZERO_SIZE_PTR;
1077 }
1078 
1079 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1080  * small to hold new_n items. new items are zeroed out if the array grows.
1081  *
1082  * Contrary to krealloc_array, does not free arr if new_n is zero.
1083  */
1084 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1085 {
1086 	size_t alloc_size;
1087 	void *new_arr;
1088 
1089 	if (!new_n || old_n == new_n)
1090 		goto out;
1091 
1092 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1093 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1094 	if (!new_arr) {
1095 		kfree(arr);
1096 		return NULL;
1097 	}
1098 	arr = new_arr;
1099 
1100 	if (new_n > old_n)
1101 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1102 
1103 out:
1104 	return arr ? arr : ZERO_SIZE_PTR;
1105 }
1106 
1107 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1108 {
1109 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1110 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1111 	if (!dst->refs)
1112 		return -ENOMEM;
1113 
1114 	dst->acquired_refs = src->acquired_refs;
1115 	return 0;
1116 }
1117 
1118 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1119 {
1120 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1121 
1122 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1123 				GFP_KERNEL);
1124 	if (!dst->stack)
1125 		return -ENOMEM;
1126 
1127 	dst->allocated_stack = src->allocated_stack;
1128 	return 0;
1129 }
1130 
1131 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1132 {
1133 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1134 				    sizeof(struct bpf_reference_state));
1135 	if (!state->refs)
1136 		return -ENOMEM;
1137 
1138 	state->acquired_refs = n;
1139 	return 0;
1140 }
1141 
1142 static int grow_stack_state(struct bpf_func_state *state, int size)
1143 {
1144 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1145 
1146 	if (old_n >= n)
1147 		return 0;
1148 
1149 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1150 	if (!state->stack)
1151 		return -ENOMEM;
1152 
1153 	state->allocated_stack = size;
1154 	return 0;
1155 }
1156 
1157 /* Acquire a pointer id from the env and update the state->refs to include
1158  * this new pointer reference.
1159  * On success, returns a valid pointer id to associate with the register
1160  * On failure, returns a negative errno.
1161  */
1162 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1163 {
1164 	struct bpf_func_state *state = cur_func(env);
1165 	int new_ofs = state->acquired_refs;
1166 	int id, err;
1167 
1168 	err = resize_reference_state(state, state->acquired_refs + 1);
1169 	if (err)
1170 		return err;
1171 	id = ++env->id_gen;
1172 	state->refs[new_ofs].id = id;
1173 	state->refs[new_ofs].insn_idx = insn_idx;
1174 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1175 
1176 	return id;
1177 }
1178 
1179 /* release function corresponding to acquire_reference_state(). Idempotent. */
1180 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1181 {
1182 	int i, last_idx;
1183 
1184 	last_idx = state->acquired_refs - 1;
1185 	for (i = 0; i < state->acquired_refs; i++) {
1186 		if (state->refs[i].id == ptr_id) {
1187 			/* Cannot release caller references in callbacks */
1188 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1189 				return -EINVAL;
1190 			if (last_idx && i != last_idx)
1191 				memcpy(&state->refs[i], &state->refs[last_idx],
1192 				       sizeof(*state->refs));
1193 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1194 			state->acquired_refs--;
1195 			return 0;
1196 		}
1197 	}
1198 	return -EINVAL;
1199 }
1200 
1201 static void free_func_state(struct bpf_func_state *state)
1202 {
1203 	if (!state)
1204 		return;
1205 	kfree(state->refs);
1206 	kfree(state->stack);
1207 	kfree(state);
1208 }
1209 
1210 static void clear_jmp_history(struct bpf_verifier_state *state)
1211 {
1212 	kfree(state->jmp_history);
1213 	state->jmp_history = NULL;
1214 	state->jmp_history_cnt = 0;
1215 }
1216 
1217 static void free_verifier_state(struct bpf_verifier_state *state,
1218 				bool free_self)
1219 {
1220 	int i;
1221 
1222 	for (i = 0; i <= state->curframe; i++) {
1223 		free_func_state(state->frame[i]);
1224 		state->frame[i] = NULL;
1225 	}
1226 	clear_jmp_history(state);
1227 	if (free_self)
1228 		kfree(state);
1229 }
1230 
1231 /* copy verifier state from src to dst growing dst stack space
1232  * when necessary to accommodate larger src stack
1233  */
1234 static int copy_func_state(struct bpf_func_state *dst,
1235 			   const struct bpf_func_state *src)
1236 {
1237 	int err;
1238 
1239 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1240 	err = copy_reference_state(dst, src);
1241 	if (err)
1242 		return err;
1243 	return copy_stack_state(dst, src);
1244 }
1245 
1246 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1247 			       const struct bpf_verifier_state *src)
1248 {
1249 	struct bpf_func_state *dst;
1250 	int i, err;
1251 
1252 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1253 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1254 					    GFP_USER);
1255 	if (!dst_state->jmp_history)
1256 		return -ENOMEM;
1257 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1258 
1259 	/* if dst has more stack frames then src frame, free them */
1260 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1261 		free_func_state(dst_state->frame[i]);
1262 		dst_state->frame[i] = NULL;
1263 	}
1264 	dst_state->speculative = src->speculative;
1265 	dst_state->active_rcu_lock = src->active_rcu_lock;
1266 	dst_state->curframe = src->curframe;
1267 	dst_state->active_lock.ptr = src->active_lock.ptr;
1268 	dst_state->active_lock.id = src->active_lock.id;
1269 	dst_state->branches = src->branches;
1270 	dst_state->parent = src->parent;
1271 	dst_state->first_insn_idx = src->first_insn_idx;
1272 	dst_state->last_insn_idx = src->last_insn_idx;
1273 	for (i = 0; i <= src->curframe; i++) {
1274 		dst = dst_state->frame[i];
1275 		if (!dst) {
1276 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1277 			if (!dst)
1278 				return -ENOMEM;
1279 			dst_state->frame[i] = dst;
1280 		}
1281 		err = copy_func_state(dst, src->frame[i]);
1282 		if (err)
1283 			return err;
1284 	}
1285 	return 0;
1286 }
1287 
1288 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1289 {
1290 	while (st) {
1291 		u32 br = --st->branches;
1292 
1293 		/* WARN_ON(br > 1) technically makes sense here,
1294 		 * but see comment in push_stack(), hence:
1295 		 */
1296 		WARN_ONCE((int)br < 0,
1297 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1298 			  br);
1299 		if (br)
1300 			break;
1301 		st = st->parent;
1302 	}
1303 }
1304 
1305 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1306 		     int *insn_idx, bool pop_log)
1307 {
1308 	struct bpf_verifier_state *cur = env->cur_state;
1309 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1310 	int err;
1311 
1312 	if (env->head == NULL)
1313 		return -ENOENT;
1314 
1315 	if (cur) {
1316 		err = copy_verifier_state(cur, &head->st);
1317 		if (err)
1318 			return err;
1319 	}
1320 	if (pop_log)
1321 		bpf_vlog_reset(&env->log, head->log_pos);
1322 	if (insn_idx)
1323 		*insn_idx = head->insn_idx;
1324 	if (prev_insn_idx)
1325 		*prev_insn_idx = head->prev_insn_idx;
1326 	elem = head->next;
1327 	free_verifier_state(&head->st, false);
1328 	kfree(head);
1329 	env->head = elem;
1330 	env->stack_size--;
1331 	return 0;
1332 }
1333 
1334 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1335 					     int insn_idx, int prev_insn_idx,
1336 					     bool speculative)
1337 {
1338 	struct bpf_verifier_state *cur = env->cur_state;
1339 	struct bpf_verifier_stack_elem *elem;
1340 	int err;
1341 
1342 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1343 	if (!elem)
1344 		goto err;
1345 
1346 	elem->insn_idx = insn_idx;
1347 	elem->prev_insn_idx = prev_insn_idx;
1348 	elem->next = env->head;
1349 	elem->log_pos = env->log.len_used;
1350 	env->head = elem;
1351 	env->stack_size++;
1352 	err = copy_verifier_state(&elem->st, cur);
1353 	if (err)
1354 		goto err;
1355 	elem->st.speculative |= speculative;
1356 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1357 		verbose(env, "The sequence of %d jumps is too complex.\n",
1358 			env->stack_size);
1359 		goto err;
1360 	}
1361 	if (elem->st.parent) {
1362 		++elem->st.parent->branches;
1363 		/* WARN_ON(branches > 2) technically makes sense here,
1364 		 * but
1365 		 * 1. speculative states will bump 'branches' for non-branch
1366 		 * instructions
1367 		 * 2. is_state_visited() heuristics may decide not to create
1368 		 * a new state for a sequence of branches and all such current
1369 		 * and cloned states will be pointing to a single parent state
1370 		 * which might have large 'branches' count.
1371 		 */
1372 	}
1373 	return &elem->st;
1374 err:
1375 	free_verifier_state(env->cur_state, true);
1376 	env->cur_state = NULL;
1377 	/* pop all elements and return */
1378 	while (!pop_stack(env, NULL, NULL, false));
1379 	return NULL;
1380 }
1381 
1382 #define CALLER_SAVED_REGS 6
1383 static const int caller_saved[CALLER_SAVED_REGS] = {
1384 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1385 };
1386 
1387 /* This helper doesn't clear reg->id */
1388 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1389 {
1390 	reg->var_off = tnum_const(imm);
1391 	reg->smin_value = (s64)imm;
1392 	reg->smax_value = (s64)imm;
1393 	reg->umin_value = imm;
1394 	reg->umax_value = imm;
1395 
1396 	reg->s32_min_value = (s32)imm;
1397 	reg->s32_max_value = (s32)imm;
1398 	reg->u32_min_value = (u32)imm;
1399 	reg->u32_max_value = (u32)imm;
1400 }
1401 
1402 /* Mark the unknown part of a register (variable offset or scalar value) as
1403  * known to have the value @imm.
1404  */
1405 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1406 {
1407 	/* Clear off and union(map_ptr, range) */
1408 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1409 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1410 	reg->id = 0;
1411 	reg->ref_obj_id = 0;
1412 	___mark_reg_known(reg, imm);
1413 }
1414 
1415 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1416 {
1417 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1418 	reg->s32_min_value = (s32)imm;
1419 	reg->s32_max_value = (s32)imm;
1420 	reg->u32_min_value = (u32)imm;
1421 	reg->u32_max_value = (u32)imm;
1422 }
1423 
1424 /* Mark the 'variable offset' part of a register as zero.  This should be
1425  * used only on registers holding a pointer type.
1426  */
1427 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1428 {
1429 	__mark_reg_known(reg, 0);
1430 }
1431 
1432 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1433 {
1434 	__mark_reg_known(reg, 0);
1435 	reg->type = SCALAR_VALUE;
1436 }
1437 
1438 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1439 				struct bpf_reg_state *regs, u32 regno)
1440 {
1441 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1442 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1443 		/* Something bad happened, let's kill all regs */
1444 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1445 			__mark_reg_not_init(env, regs + regno);
1446 		return;
1447 	}
1448 	__mark_reg_known_zero(regs + regno);
1449 }
1450 
1451 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1452 			      bool first_slot)
1453 {
1454 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1455 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1456 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1457 	 */
1458 	__mark_reg_known_zero(reg);
1459 	reg->type = CONST_PTR_TO_DYNPTR;
1460 	reg->dynptr.type = type;
1461 	reg->dynptr.first_slot = first_slot;
1462 }
1463 
1464 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1465 {
1466 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1467 		const struct bpf_map *map = reg->map_ptr;
1468 
1469 		if (map->inner_map_meta) {
1470 			reg->type = CONST_PTR_TO_MAP;
1471 			reg->map_ptr = map->inner_map_meta;
1472 			/* transfer reg's id which is unique for every map_lookup_elem
1473 			 * as UID of the inner map.
1474 			 */
1475 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1476 				reg->map_uid = reg->id;
1477 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1478 			reg->type = PTR_TO_XDP_SOCK;
1479 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1480 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1481 			reg->type = PTR_TO_SOCKET;
1482 		} else {
1483 			reg->type = PTR_TO_MAP_VALUE;
1484 		}
1485 		return;
1486 	}
1487 
1488 	reg->type &= ~PTR_MAYBE_NULL;
1489 }
1490 
1491 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1492 {
1493 	return type_is_pkt_pointer(reg->type);
1494 }
1495 
1496 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1497 {
1498 	return reg_is_pkt_pointer(reg) ||
1499 	       reg->type == PTR_TO_PACKET_END;
1500 }
1501 
1502 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1503 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1504 				    enum bpf_reg_type which)
1505 {
1506 	/* The register can already have a range from prior markings.
1507 	 * This is fine as long as it hasn't been advanced from its
1508 	 * origin.
1509 	 */
1510 	return reg->type == which &&
1511 	       reg->id == 0 &&
1512 	       reg->off == 0 &&
1513 	       tnum_equals_const(reg->var_off, 0);
1514 }
1515 
1516 /* Reset the min/max bounds of a register */
1517 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1518 {
1519 	reg->smin_value = S64_MIN;
1520 	reg->smax_value = S64_MAX;
1521 	reg->umin_value = 0;
1522 	reg->umax_value = U64_MAX;
1523 
1524 	reg->s32_min_value = S32_MIN;
1525 	reg->s32_max_value = S32_MAX;
1526 	reg->u32_min_value = 0;
1527 	reg->u32_max_value = U32_MAX;
1528 }
1529 
1530 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1531 {
1532 	reg->smin_value = S64_MIN;
1533 	reg->smax_value = S64_MAX;
1534 	reg->umin_value = 0;
1535 	reg->umax_value = U64_MAX;
1536 }
1537 
1538 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1539 {
1540 	reg->s32_min_value = S32_MIN;
1541 	reg->s32_max_value = S32_MAX;
1542 	reg->u32_min_value = 0;
1543 	reg->u32_max_value = U32_MAX;
1544 }
1545 
1546 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1547 {
1548 	struct tnum var32_off = tnum_subreg(reg->var_off);
1549 
1550 	/* min signed is max(sign bit) | min(other bits) */
1551 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1552 			var32_off.value | (var32_off.mask & S32_MIN));
1553 	/* max signed is min(sign bit) | max(other bits) */
1554 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1555 			var32_off.value | (var32_off.mask & S32_MAX));
1556 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1557 	reg->u32_max_value = min(reg->u32_max_value,
1558 				 (u32)(var32_off.value | var32_off.mask));
1559 }
1560 
1561 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1562 {
1563 	/* min signed is max(sign bit) | min(other bits) */
1564 	reg->smin_value = max_t(s64, reg->smin_value,
1565 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1566 	/* max signed is min(sign bit) | max(other bits) */
1567 	reg->smax_value = min_t(s64, reg->smax_value,
1568 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1569 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1570 	reg->umax_value = min(reg->umax_value,
1571 			      reg->var_off.value | reg->var_off.mask);
1572 }
1573 
1574 static void __update_reg_bounds(struct bpf_reg_state *reg)
1575 {
1576 	__update_reg32_bounds(reg);
1577 	__update_reg64_bounds(reg);
1578 }
1579 
1580 /* Uses signed min/max values to inform unsigned, and vice-versa */
1581 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583 	/* Learn sign from signed bounds.
1584 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1585 	 * are the same, so combine.  This works even in the negative case, e.g.
1586 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1587 	 */
1588 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1589 		reg->s32_min_value = reg->u32_min_value =
1590 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1591 		reg->s32_max_value = reg->u32_max_value =
1592 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1593 		return;
1594 	}
1595 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1596 	 * boundary, so we must be careful.
1597 	 */
1598 	if ((s32)reg->u32_max_value >= 0) {
1599 		/* Positive.  We can't learn anything from the smin, but smax
1600 		 * is positive, hence safe.
1601 		 */
1602 		reg->s32_min_value = reg->u32_min_value;
1603 		reg->s32_max_value = reg->u32_max_value =
1604 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1605 	} else if ((s32)reg->u32_min_value < 0) {
1606 		/* Negative.  We can't learn anything from the smax, but smin
1607 		 * is negative, hence safe.
1608 		 */
1609 		reg->s32_min_value = reg->u32_min_value =
1610 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1611 		reg->s32_max_value = reg->u32_max_value;
1612 	}
1613 }
1614 
1615 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1616 {
1617 	/* Learn sign from signed bounds.
1618 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1619 	 * are the same, so combine.  This works even in the negative case, e.g.
1620 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1621 	 */
1622 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1623 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1624 							  reg->umin_value);
1625 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1626 							  reg->umax_value);
1627 		return;
1628 	}
1629 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1630 	 * boundary, so we must be careful.
1631 	 */
1632 	if ((s64)reg->umax_value >= 0) {
1633 		/* Positive.  We can't learn anything from the smin, but smax
1634 		 * is positive, hence safe.
1635 		 */
1636 		reg->smin_value = reg->umin_value;
1637 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1638 							  reg->umax_value);
1639 	} else if ((s64)reg->umin_value < 0) {
1640 		/* Negative.  We can't learn anything from the smax, but smin
1641 		 * is negative, hence safe.
1642 		 */
1643 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1644 							  reg->umin_value);
1645 		reg->smax_value = reg->umax_value;
1646 	}
1647 }
1648 
1649 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1650 {
1651 	__reg32_deduce_bounds(reg);
1652 	__reg64_deduce_bounds(reg);
1653 }
1654 
1655 /* Attempts to improve var_off based on unsigned min/max information */
1656 static void __reg_bound_offset(struct bpf_reg_state *reg)
1657 {
1658 	struct tnum var64_off = tnum_intersect(reg->var_off,
1659 					       tnum_range(reg->umin_value,
1660 							  reg->umax_value));
1661 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1662 						tnum_range(reg->u32_min_value,
1663 							   reg->u32_max_value));
1664 
1665 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1666 }
1667 
1668 static void reg_bounds_sync(struct bpf_reg_state *reg)
1669 {
1670 	/* We might have learned new bounds from the var_off. */
1671 	__update_reg_bounds(reg);
1672 	/* We might have learned something about the sign bit. */
1673 	__reg_deduce_bounds(reg);
1674 	/* We might have learned some bits from the bounds. */
1675 	__reg_bound_offset(reg);
1676 	/* Intersecting with the old var_off might have improved our bounds
1677 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1678 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1679 	 */
1680 	__update_reg_bounds(reg);
1681 }
1682 
1683 static bool __reg32_bound_s64(s32 a)
1684 {
1685 	return a >= 0 && a <= S32_MAX;
1686 }
1687 
1688 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1689 {
1690 	reg->umin_value = reg->u32_min_value;
1691 	reg->umax_value = reg->u32_max_value;
1692 
1693 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1694 	 * be positive otherwise set to worse case bounds and refine later
1695 	 * from tnum.
1696 	 */
1697 	if (__reg32_bound_s64(reg->s32_min_value) &&
1698 	    __reg32_bound_s64(reg->s32_max_value)) {
1699 		reg->smin_value = reg->s32_min_value;
1700 		reg->smax_value = reg->s32_max_value;
1701 	} else {
1702 		reg->smin_value = 0;
1703 		reg->smax_value = U32_MAX;
1704 	}
1705 }
1706 
1707 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1708 {
1709 	/* special case when 64-bit register has upper 32-bit register
1710 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1711 	 * allowing us to use 32-bit bounds directly,
1712 	 */
1713 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1714 		__reg_assign_32_into_64(reg);
1715 	} else {
1716 		/* Otherwise the best we can do is push lower 32bit known and
1717 		 * unknown bits into register (var_off set from jmp logic)
1718 		 * then learn as much as possible from the 64-bit tnum
1719 		 * known and unknown bits. The previous smin/smax bounds are
1720 		 * invalid here because of jmp32 compare so mark them unknown
1721 		 * so they do not impact tnum bounds calculation.
1722 		 */
1723 		__mark_reg64_unbounded(reg);
1724 	}
1725 	reg_bounds_sync(reg);
1726 }
1727 
1728 static bool __reg64_bound_s32(s64 a)
1729 {
1730 	return a >= S32_MIN && a <= S32_MAX;
1731 }
1732 
1733 static bool __reg64_bound_u32(u64 a)
1734 {
1735 	return a >= U32_MIN && a <= U32_MAX;
1736 }
1737 
1738 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1739 {
1740 	__mark_reg32_unbounded(reg);
1741 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1742 		reg->s32_min_value = (s32)reg->smin_value;
1743 		reg->s32_max_value = (s32)reg->smax_value;
1744 	}
1745 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1746 		reg->u32_min_value = (u32)reg->umin_value;
1747 		reg->u32_max_value = (u32)reg->umax_value;
1748 	}
1749 	reg_bounds_sync(reg);
1750 }
1751 
1752 /* Mark a register as having a completely unknown (scalar) value. */
1753 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1754 			       struct bpf_reg_state *reg)
1755 {
1756 	/*
1757 	 * Clear type, off, and union(map_ptr, range) and
1758 	 * padding between 'type' and union
1759 	 */
1760 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1761 	reg->type = SCALAR_VALUE;
1762 	reg->id = 0;
1763 	reg->ref_obj_id = 0;
1764 	reg->var_off = tnum_unknown;
1765 	reg->frameno = 0;
1766 	reg->precise = !env->bpf_capable;
1767 	__mark_reg_unbounded(reg);
1768 }
1769 
1770 static void mark_reg_unknown(struct bpf_verifier_env *env,
1771 			     struct bpf_reg_state *regs, u32 regno)
1772 {
1773 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1774 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1775 		/* Something bad happened, let's kill all regs except FP */
1776 		for (regno = 0; regno < BPF_REG_FP; regno++)
1777 			__mark_reg_not_init(env, regs + regno);
1778 		return;
1779 	}
1780 	__mark_reg_unknown(env, regs + regno);
1781 }
1782 
1783 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1784 				struct bpf_reg_state *reg)
1785 {
1786 	__mark_reg_unknown(env, reg);
1787 	reg->type = NOT_INIT;
1788 }
1789 
1790 static void mark_reg_not_init(struct bpf_verifier_env *env,
1791 			      struct bpf_reg_state *regs, u32 regno)
1792 {
1793 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1794 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1795 		/* Something bad happened, let's kill all regs except FP */
1796 		for (regno = 0; regno < BPF_REG_FP; regno++)
1797 			__mark_reg_not_init(env, regs + regno);
1798 		return;
1799 	}
1800 	__mark_reg_not_init(env, regs + regno);
1801 }
1802 
1803 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1804 			    struct bpf_reg_state *regs, u32 regno,
1805 			    enum bpf_reg_type reg_type,
1806 			    struct btf *btf, u32 btf_id,
1807 			    enum bpf_type_flag flag)
1808 {
1809 	if (reg_type == SCALAR_VALUE) {
1810 		mark_reg_unknown(env, regs, regno);
1811 		return;
1812 	}
1813 	mark_reg_known_zero(env, regs, regno);
1814 	regs[regno].type = PTR_TO_BTF_ID | flag;
1815 	regs[regno].btf = btf;
1816 	regs[regno].btf_id = btf_id;
1817 }
1818 
1819 #define DEF_NOT_SUBREG	(0)
1820 static void init_reg_state(struct bpf_verifier_env *env,
1821 			   struct bpf_func_state *state)
1822 {
1823 	struct bpf_reg_state *regs = state->regs;
1824 	int i;
1825 
1826 	for (i = 0; i < MAX_BPF_REG; i++) {
1827 		mark_reg_not_init(env, regs, i);
1828 		regs[i].live = REG_LIVE_NONE;
1829 		regs[i].parent = NULL;
1830 		regs[i].subreg_def = DEF_NOT_SUBREG;
1831 	}
1832 
1833 	/* frame pointer */
1834 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1835 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1836 	regs[BPF_REG_FP].frameno = state->frameno;
1837 }
1838 
1839 #define BPF_MAIN_FUNC (-1)
1840 static void init_func_state(struct bpf_verifier_env *env,
1841 			    struct bpf_func_state *state,
1842 			    int callsite, int frameno, int subprogno)
1843 {
1844 	state->callsite = callsite;
1845 	state->frameno = frameno;
1846 	state->subprogno = subprogno;
1847 	state->callback_ret_range = tnum_range(0, 0);
1848 	init_reg_state(env, state);
1849 	mark_verifier_state_scratched(env);
1850 }
1851 
1852 /* Similar to push_stack(), but for async callbacks */
1853 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1854 						int insn_idx, int prev_insn_idx,
1855 						int subprog)
1856 {
1857 	struct bpf_verifier_stack_elem *elem;
1858 	struct bpf_func_state *frame;
1859 
1860 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1861 	if (!elem)
1862 		goto err;
1863 
1864 	elem->insn_idx = insn_idx;
1865 	elem->prev_insn_idx = prev_insn_idx;
1866 	elem->next = env->head;
1867 	elem->log_pos = env->log.len_used;
1868 	env->head = elem;
1869 	env->stack_size++;
1870 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1871 		verbose(env,
1872 			"The sequence of %d jumps is too complex for async cb.\n",
1873 			env->stack_size);
1874 		goto err;
1875 	}
1876 	/* Unlike push_stack() do not copy_verifier_state().
1877 	 * The caller state doesn't matter.
1878 	 * This is async callback. It starts in a fresh stack.
1879 	 * Initialize it similar to do_check_common().
1880 	 */
1881 	elem->st.branches = 1;
1882 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1883 	if (!frame)
1884 		goto err;
1885 	init_func_state(env, frame,
1886 			BPF_MAIN_FUNC /* callsite */,
1887 			0 /* frameno within this callchain */,
1888 			subprog /* subprog number within this prog */);
1889 	elem->st.frame[0] = frame;
1890 	return &elem->st;
1891 err:
1892 	free_verifier_state(env->cur_state, true);
1893 	env->cur_state = NULL;
1894 	/* pop all elements and return */
1895 	while (!pop_stack(env, NULL, NULL, false));
1896 	return NULL;
1897 }
1898 
1899 
1900 enum reg_arg_type {
1901 	SRC_OP,		/* register is used as source operand */
1902 	DST_OP,		/* register is used as destination operand */
1903 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1904 };
1905 
1906 static int cmp_subprogs(const void *a, const void *b)
1907 {
1908 	return ((struct bpf_subprog_info *)a)->start -
1909 	       ((struct bpf_subprog_info *)b)->start;
1910 }
1911 
1912 static int find_subprog(struct bpf_verifier_env *env, int off)
1913 {
1914 	struct bpf_subprog_info *p;
1915 
1916 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1917 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1918 	if (!p)
1919 		return -ENOENT;
1920 	return p - env->subprog_info;
1921 
1922 }
1923 
1924 static int add_subprog(struct bpf_verifier_env *env, int off)
1925 {
1926 	int insn_cnt = env->prog->len;
1927 	int ret;
1928 
1929 	if (off >= insn_cnt || off < 0) {
1930 		verbose(env, "call to invalid destination\n");
1931 		return -EINVAL;
1932 	}
1933 	ret = find_subprog(env, off);
1934 	if (ret >= 0)
1935 		return ret;
1936 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1937 		verbose(env, "too many subprograms\n");
1938 		return -E2BIG;
1939 	}
1940 	/* determine subprog starts. The end is one before the next starts */
1941 	env->subprog_info[env->subprog_cnt++].start = off;
1942 	sort(env->subprog_info, env->subprog_cnt,
1943 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1944 	return env->subprog_cnt - 1;
1945 }
1946 
1947 #define MAX_KFUNC_DESCS 256
1948 #define MAX_KFUNC_BTFS	256
1949 
1950 struct bpf_kfunc_desc {
1951 	struct btf_func_model func_model;
1952 	u32 func_id;
1953 	s32 imm;
1954 	u16 offset;
1955 };
1956 
1957 struct bpf_kfunc_btf {
1958 	struct btf *btf;
1959 	struct module *module;
1960 	u16 offset;
1961 };
1962 
1963 struct bpf_kfunc_desc_tab {
1964 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1965 	u32 nr_descs;
1966 };
1967 
1968 struct bpf_kfunc_btf_tab {
1969 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1970 	u32 nr_descs;
1971 };
1972 
1973 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1974 {
1975 	const struct bpf_kfunc_desc *d0 = a;
1976 	const struct bpf_kfunc_desc *d1 = b;
1977 
1978 	/* func_id is not greater than BTF_MAX_TYPE */
1979 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1980 }
1981 
1982 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1983 {
1984 	const struct bpf_kfunc_btf *d0 = a;
1985 	const struct bpf_kfunc_btf *d1 = b;
1986 
1987 	return d0->offset - d1->offset;
1988 }
1989 
1990 static const struct bpf_kfunc_desc *
1991 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1992 {
1993 	struct bpf_kfunc_desc desc = {
1994 		.func_id = func_id,
1995 		.offset = offset,
1996 	};
1997 	struct bpf_kfunc_desc_tab *tab;
1998 
1999 	tab = prog->aux->kfunc_tab;
2000 	return bsearch(&desc, tab->descs, tab->nr_descs,
2001 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2002 }
2003 
2004 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2005 					 s16 offset)
2006 {
2007 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2008 	struct bpf_kfunc_btf_tab *tab;
2009 	struct bpf_kfunc_btf *b;
2010 	struct module *mod;
2011 	struct btf *btf;
2012 	int btf_fd;
2013 
2014 	tab = env->prog->aux->kfunc_btf_tab;
2015 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2016 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2017 	if (!b) {
2018 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2019 			verbose(env, "too many different module BTFs\n");
2020 			return ERR_PTR(-E2BIG);
2021 		}
2022 
2023 		if (bpfptr_is_null(env->fd_array)) {
2024 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2025 			return ERR_PTR(-EPROTO);
2026 		}
2027 
2028 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2029 					    offset * sizeof(btf_fd),
2030 					    sizeof(btf_fd)))
2031 			return ERR_PTR(-EFAULT);
2032 
2033 		btf = btf_get_by_fd(btf_fd);
2034 		if (IS_ERR(btf)) {
2035 			verbose(env, "invalid module BTF fd specified\n");
2036 			return btf;
2037 		}
2038 
2039 		if (!btf_is_module(btf)) {
2040 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2041 			btf_put(btf);
2042 			return ERR_PTR(-EINVAL);
2043 		}
2044 
2045 		mod = btf_try_get_module(btf);
2046 		if (!mod) {
2047 			btf_put(btf);
2048 			return ERR_PTR(-ENXIO);
2049 		}
2050 
2051 		b = &tab->descs[tab->nr_descs++];
2052 		b->btf = btf;
2053 		b->module = mod;
2054 		b->offset = offset;
2055 
2056 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2057 		     kfunc_btf_cmp_by_off, NULL);
2058 	}
2059 	return b->btf;
2060 }
2061 
2062 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2063 {
2064 	if (!tab)
2065 		return;
2066 
2067 	while (tab->nr_descs--) {
2068 		module_put(tab->descs[tab->nr_descs].module);
2069 		btf_put(tab->descs[tab->nr_descs].btf);
2070 	}
2071 	kfree(tab);
2072 }
2073 
2074 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2075 {
2076 	if (offset) {
2077 		if (offset < 0) {
2078 			/* In the future, this can be allowed to increase limit
2079 			 * of fd index into fd_array, interpreted as u16.
2080 			 */
2081 			verbose(env, "negative offset disallowed for kernel module function call\n");
2082 			return ERR_PTR(-EINVAL);
2083 		}
2084 
2085 		return __find_kfunc_desc_btf(env, offset);
2086 	}
2087 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2088 }
2089 
2090 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2091 {
2092 	const struct btf_type *func, *func_proto;
2093 	struct bpf_kfunc_btf_tab *btf_tab;
2094 	struct bpf_kfunc_desc_tab *tab;
2095 	struct bpf_prog_aux *prog_aux;
2096 	struct bpf_kfunc_desc *desc;
2097 	const char *func_name;
2098 	struct btf *desc_btf;
2099 	unsigned long call_imm;
2100 	unsigned long addr;
2101 	int err;
2102 
2103 	prog_aux = env->prog->aux;
2104 	tab = prog_aux->kfunc_tab;
2105 	btf_tab = prog_aux->kfunc_btf_tab;
2106 	if (!tab) {
2107 		if (!btf_vmlinux) {
2108 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2109 			return -ENOTSUPP;
2110 		}
2111 
2112 		if (!env->prog->jit_requested) {
2113 			verbose(env, "JIT is required for calling kernel function\n");
2114 			return -ENOTSUPP;
2115 		}
2116 
2117 		if (!bpf_jit_supports_kfunc_call()) {
2118 			verbose(env, "JIT does not support calling kernel function\n");
2119 			return -ENOTSUPP;
2120 		}
2121 
2122 		if (!env->prog->gpl_compatible) {
2123 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2124 			return -EINVAL;
2125 		}
2126 
2127 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2128 		if (!tab)
2129 			return -ENOMEM;
2130 		prog_aux->kfunc_tab = tab;
2131 	}
2132 
2133 	/* func_id == 0 is always invalid, but instead of returning an error, be
2134 	 * conservative and wait until the code elimination pass before returning
2135 	 * error, so that invalid calls that get pruned out can be in BPF programs
2136 	 * loaded from userspace.  It is also required that offset be untouched
2137 	 * for such calls.
2138 	 */
2139 	if (!func_id && !offset)
2140 		return 0;
2141 
2142 	if (!btf_tab && offset) {
2143 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2144 		if (!btf_tab)
2145 			return -ENOMEM;
2146 		prog_aux->kfunc_btf_tab = btf_tab;
2147 	}
2148 
2149 	desc_btf = find_kfunc_desc_btf(env, offset);
2150 	if (IS_ERR(desc_btf)) {
2151 		verbose(env, "failed to find BTF for kernel function\n");
2152 		return PTR_ERR(desc_btf);
2153 	}
2154 
2155 	if (find_kfunc_desc(env->prog, func_id, offset))
2156 		return 0;
2157 
2158 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2159 		verbose(env, "too many different kernel function calls\n");
2160 		return -E2BIG;
2161 	}
2162 
2163 	func = btf_type_by_id(desc_btf, func_id);
2164 	if (!func || !btf_type_is_func(func)) {
2165 		verbose(env, "kernel btf_id %u is not a function\n",
2166 			func_id);
2167 		return -EINVAL;
2168 	}
2169 	func_proto = btf_type_by_id(desc_btf, func->type);
2170 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2171 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2172 			func_id);
2173 		return -EINVAL;
2174 	}
2175 
2176 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2177 	addr = kallsyms_lookup_name(func_name);
2178 	if (!addr) {
2179 		verbose(env, "cannot find address for kernel function %s\n",
2180 			func_name);
2181 		return -EINVAL;
2182 	}
2183 
2184 	call_imm = BPF_CALL_IMM(addr);
2185 	/* Check whether or not the relative offset overflows desc->imm */
2186 	if ((unsigned long)(s32)call_imm != call_imm) {
2187 		verbose(env, "address of kernel function %s is out of range\n",
2188 			func_name);
2189 		return -EINVAL;
2190 	}
2191 
2192 	desc = &tab->descs[tab->nr_descs++];
2193 	desc->func_id = func_id;
2194 	desc->imm = call_imm;
2195 	desc->offset = offset;
2196 	err = btf_distill_func_proto(&env->log, desc_btf,
2197 				     func_proto, func_name,
2198 				     &desc->func_model);
2199 	if (!err)
2200 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2201 		     kfunc_desc_cmp_by_id_off, NULL);
2202 	return err;
2203 }
2204 
2205 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2206 {
2207 	const struct bpf_kfunc_desc *d0 = a;
2208 	const struct bpf_kfunc_desc *d1 = b;
2209 
2210 	if (d0->imm > d1->imm)
2211 		return 1;
2212 	else if (d0->imm < d1->imm)
2213 		return -1;
2214 	return 0;
2215 }
2216 
2217 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2218 {
2219 	struct bpf_kfunc_desc_tab *tab;
2220 
2221 	tab = prog->aux->kfunc_tab;
2222 	if (!tab)
2223 		return;
2224 
2225 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2226 	     kfunc_desc_cmp_by_imm, NULL);
2227 }
2228 
2229 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2230 {
2231 	return !!prog->aux->kfunc_tab;
2232 }
2233 
2234 const struct btf_func_model *
2235 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2236 			 const struct bpf_insn *insn)
2237 {
2238 	const struct bpf_kfunc_desc desc = {
2239 		.imm = insn->imm,
2240 	};
2241 	const struct bpf_kfunc_desc *res;
2242 	struct bpf_kfunc_desc_tab *tab;
2243 
2244 	tab = prog->aux->kfunc_tab;
2245 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2246 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2247 
2248 	return res ? &res->func_model : NULL;
2249 }
2250 
2251 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2252 {
2253 	struct bpf_subprog_info *subprog = env->subprog_info;
2254 	struct bpf_insn *insn = env->prog->insnsi;
2255 	int i, ret, insn_cnt = env->prog->len;
2256 
2257 	/* Add entry function. */
2258 	ret = add_subprog(env, 0);
2259 	if (ret)
2260 		return ret;
2261 
2262 	for (i = 0; i < insn_cnt; i++, insn++) {
2263 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2264 		    !bpf_pseudo_kfunc_call(insn))
2265 			continue;
2266 
2267 		if (!env->bpf_capable) {
2268 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2269 			return -EPERM;
2270 		}
2271 
2272 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2273 			ret = add_subprog(env, i + insn->imm + 1);
2274 		else
2275 			ret = add_kfunc_call(env, insn->imm, insn->off);
2276 
2277 		if (ret < 0)
2278 			return ret;
2279 	}
2280 
2281 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2282 	 * logic. 'subprog_cnt' should not be increased.
2283 	 */
2284 	subprog[env->subprog_cnt].start = insn_cnt;
2285 
2286 	if (env->log.level & BPF_LOG_LEVEL2)
2287 		for (i = 0; i < env->subprog_cnt; i++)
2288 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2289 
2290 	return 0;
2291 }
2292 
2293 static int check_subprogs(struct bpf_verifier_env *env)
2294 {
2295 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2296 	struct bpf_subprog_info *subprog = env->subprog_info;
2297 	struct bpf_insn *insn = env->prog->insnsi;
2298 	int insn_cnt = env->prog->len;
2299 
2300 	/* now check that all jumps are within the same subprog */
2301 	subprog_start = subprog[cur_subprog].start;
2302 	subprog_end = subprog[cur_subprog + 1].start;
2303 	for (i = 0; i < insn_cnt; i++) {
2304 		u8 code = insn[i].code;
2305 
2306 		if (code == (BPF_JMP | BPF_CALL) &&
2307 		    insn[i].imm == BPF_FUNC_tail_call &&
2308 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2309 			subprog[cur_subprog].has_tail_call = true;
2310 		if (BPF_CLASS(code) == BPF_LD &&
2311 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2312 			subprog[cur_subprog].has_ld_abs = true;
2313 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2314 			goto next;
2315 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2316 			goto next;
2317 		off = i + insn[i].off + 1;
2318 		if (off < subprog_start || off >= subprog_end) {
2319 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2320 			return -EINVAL;
2321 		}
2322 next:
2323 		if (i == subprog_end - 1) {
2324 			/* to avoid fall-through from one subprog into another
2325 			 * the last insn of the subprog should be either exit
2326 			 * or unconditional jump back
2327 			 */
2328 			if (code != (BPF_JMP | BPF_EXIT) &&
2329 			    code != (BPF_JMP | BPF_JA)) {
2330 				verbose(env, "last insn is not an exit or jmp\n");
2331 				return -EINVAL;
2332 			}
2333 			subprog_start = subprog_end;
2334 			cur_subprog++;
2335 			if (cur_subprog < env->subprog_cnt)
2336 				subprog_end = subprog[cur_subprog + 1].start;
2337 		}
2338 	}
2339 	return 0;
2340 }
2341 
2342 /* Parentage chain of this register (or stack slot) should take care of all
2343  * issues like callee-saved registers, stack slot allocation time, etc.
2344  */
2345 static int mark_reg_read(struct bpf_verifier_env *env,
2346 			 const struct bpf_reg_state *state,
2347 			 struct bpf_reg_state *parent, u8 flag)
2348 {
2349 	bool writes = parent == state->parent; /* Observe write marks */
2350 	int cnt = 0;
2351 
2352 	while (parent) {
2353 		/* if read wasn't screened by an earlier write ... */
2354 		if (writes && state->live & REG_LIVE_WRITTEN)
2355 			break;
2356 		if (parent->live & REG_LIVE_DONE) {
2357 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2358 				reg_type_str(env, parent->type),
2359 				parent->var_off.value, parent->off);
2360 			return -EFAULT;
2361 		}
2362 		/* The first condition is more likely to be true than the
2363 		 * second, checked it first.
2364 		 */
2365 		if ((parent->live & REG_LIVE_READ) == flag ||
2366 		    parent->live & REG_LIVE_READ64)
2367 			/* The parentage chain never changes and
2368 			 * this parent was already marked as LIVE_READ.
2369 			 * There is no need to keep walking the chain again and
2370 			 * keep re-marking all parents as LIVE_READ.
2371 			 * This case happens when the same register is read
2372 			 * multiple times without writes into it in-between.
2373 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2374 			 * then no need to set the weak REG_LIVE_READ32.
2375 			 */
2376 			break;
2377 		/* ... then we depend on parent's value */
2378 		parent->live |= flag;
2379 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2380 		if (flag == REG_LIVE_READ64)
2381 			parent->live &= ~REG_LIVE_READ32;
2382 		state = parent;
2383 		parent = state->parent;
2384 		writes = true;
2385 		cnt++;
2386 	}
2387 
2388 	if (env->longest_mark_read_walk < cnt)
2389 		env->longest_mark_read_walk = cnt;
2390 	return 0;
2391 }
2392 
2393 /* This function is supposed to be used by the following 32-bit optimization
2394  * code only. It returns TRUE if the source or destination register operates
2395  * on 64-bit, otherwise return FALSE.
2396  */
2397 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2398 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2399 {
2400 	u8 code, class, op;
2401 
2402 	code = insn->code;
2403 	class = BPF_CLASS(code);
2404 	op = BPF_OP(code);
2405 	if (class == BPF_JMP) {
2406 		/* BPF_EXIT for "main" will reach here. Return TRUE
2407 		 * conservatively.
2408 		 */
2409 		if (op == BPF_EXIT)
2410 			return true;
2411 		if (op == BPF_CALL) {
2412 			/* BPF to BPF call will reach here because of marking
2413 			 * caller saved clobber with DST_OP_NO_MARK for which we
2414 			 * don't care the register def because they are anyway
2415 			 * marked as NOT_INIT already.
2416 			 */
2417 			if (insn->src_reg == BPF_PSEUDO_CALL)
2418 				return false;
2419 			/* Helper call will reach here because of arg type
2420 			 * check, conservatively return TRUE.
2421 			 */
2422 			if (t == SRC_OP)
2423 				return true;
2424 
2425 			return false;
2426 		}
2427 	}
2428 
2429 	if (class == BPF_ALU64 || class == BPF_JMP ||
2430 	    /* BPF_END always use BPF_ALU class. */
2431 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2432 		return true;
2433 
2434 	if (class == BPF_ALU || class == BPF_JMP32)
2435 		return false;
2436 
2437 	if (class == BPF_LDX) {
2438 		if (t != SRC_OP)
2439 			return BPF_SIZE(code) == BPF_DW;
2440 		/* LDX source must be ptr. */
2441 		return true;
2442 	}
2443 
2444 	if (class == BPF_STX) {
2445 		/* BPF_STX (including atomic variants) has multiple source
2446 		 * operands, one of which is a ptr. Check whether the caller is
2447 		 * asking about it.
2448 		 */
2449 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2450 			return true;
2451 		return BPF_SIZE(code) == BPF_DW;
2452 	}
2453 
2454 	if (class == BPF_LD) {
2455 		u8 mode = BPF_MODE(code);
2456 
2457 		/* LD_IMM64 */
2458 		if (mode == BPF_IMM)
2459 			return true;
2460 
2461 		/* Both LD_IND and LD_ABS return 32-bit data. */
2462 		if (t != SRC_OP)
2463 			return  false;
2464 
2465 		/* Implicit ctx ptr. */
2466 		if (regno == BPF_REG_6)
2467 			return true;
2468 
2469 		/* Explicit source could be any width. */
2470 		return true;
2471 	}
2472 
2473 	if (class == BPF_ST)
2474 		/* The only source register for BPF_ST is a ptr. */
2475 		return true;
2476 
2477 	/* Conservatively return true at default. */
2478 	return true;
2479 }
2480 
2481 /* Return the regno defined by the insn, or -1. */
2482 static int insn_def_regno(const struct bpf_insn *insn)
2483 {
2484 	switch (BPF_CLASS(insn->code)) {
2485 	case BPF_JMP:
2486 	case BPF_JMP32:
2487 	case BPF_ST:
2488 		return -1;
2489 	case BPF_STX:
2490 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2491 		    (insn->imm & BPF_FETCH)) {
2492 			if (insn->imm == BPF_CMPXCHG)
2493 				return BPF_REG_0;
2494 			else
2495 				return insn->src_reg;
2496 		} else {
2497 			return -1;
2498 		}
2499 	default:
2500 		return insn->dst_reg;
2501 	}
2502 }
2503 
2504 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2505 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2506 {
2507 	int dst_reg = insn_def_regno(insn);
2508 
2509 	if (dst_reg == -1)
2510 		return false;
2511 
2512 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2513 }
2514 
2515 static void mark_insn_zext(struct bpf_verifier_env *env,
2516 			   struct bpf_reg_state *reg)
2517 {
2518 	s32 def_idx = reg->subreg_def;
2519 
2520 	if (def_idx == DEF_NOT_SUBREG)
2521 		return;
2522 
2523 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2524 	/* The dst will be zero extended, so won't be sub-register anymore. */
2525 	reg->subreg_def = DEF_NOT_SUBREG;
2526 }
2527 
2528 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2529 			 enum reg_arg_type t)
2530 {
2531 	struct bpf_verifier_state *vstate = env->cur_state;
2532 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2533 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2534 	struct bpf_reg_state *reg, *regs = state->regs;
2535 	bool rw64;
2536 
2537 	if (regno >= MAX_BPF_REG) {
2538 		verbose(env, "R%d is invalid\n", regno);
2539 		return -EINVAL;
2540 	}
2541 
2542 	mark_reg_scratched(env, regno);
2543 
2544 	reg = &regs[regno];
2545 	rw64 = is_reg64(env, insn, regno, reg, t);
2546 	if (t == SRC_OP) {
2547 		/* check whether register used as source operand can be read */
2548 		if (reg->type == NOT_INIT) {
2549 			verbose(env, "R%d !read_ok\n", regno);
2550 			return -EACCES;
2551 		}
2552 		/* We don't need to worry about FP liveness because it's read-only */
2553 		if (regno == BPF_REG_FP)
2554 			return 0;
2555 
2556 		if (rw64)
2557 			mark_insn_zext(env, reg);
2558 
2559 		return mark_reg_read(env, reg, reg->parent,
2560 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2561 	} else {
2562 		/* check whether register used as dest operand can be written to */
2563 		if (regno == BPF_REG_FP) {
2564 			verbose(env, "frame pointer is read only\n");
2565 			return -EACCES;
2566 		}
2567 		reg->live |= REG_LIVE_WRITTEN;
2568 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2569 		if (t == DST_OP)
2570 			mark_reg_unknown(env, regs, regno);
2571 	}
2572 	return 0;
2573 }
2574 
2575 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2576 {
2577 	env->insn_aux_data[idx].jmp_point = true;
2578 }
2579 
2580 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2581 {
2582 	return env->insn_aux_data[insn_idx].jmp_point;
2583 }
2584 
2585 /* for any branch, call, exit record the history of jmps in the given state */
2586 static int push_jmp_history(struct bpf_verifier_env *env,
2587 			    struct bpf_verifier_state *cur)
2588 {
2589 	u32 cnt = cur->jmp_history_cnt;
2590 	struct bpf_idx_pair *p;
2591 	size_t alloc_size;
2592 
2593 	if (!is_jmp_point(env, env->insn_idx))
2594 		return 0;
2595 
2596 	cnt++;
2597 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2598 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2599 	if (!p)
2600 		return -ENOMEM;
2601 	p[cnt - 1].idx = env->insn_idx;
2602 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2603 	cur->jmp_history = p;
2604 	cur->jmp_history_cnt = cnt;
2605 	return 0;
2606 }
2607 
2608 /* Backtrack one insn at a time. If idx is not at the top of recorded
2609  * history then previous instruction came from straight line execution.
2610  */
2611 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2612 			     u32 *history)
2613 {
2614 	u32 cnt = *history;
2615 
2616 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2617 		i = st->jmp_history[cnt - 1].prev_idx;
2618 		(*history)--;
2619 	} else {
2620 		i--;
2621 	}
2622 	return i;
2623 }
2624 
2625 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2626 {
2627 	const struct btf_type *func;
2628 	struct btf *desc_btf;
2629 
2630 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2631 		return NULL;
2632 
2633 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2634 	if (IS_ERR(desc_btf))
2635 		return "<error>";
2636 
2637 	func = btf_type_by_id(desc_btf, insn->imm);
2638 	return btf_name_by_offset(desc_btf, func->name_off);
2639 }
2640 
2641 /* For given verifier state backtrack_insn() is called from the last insn to
2642  * the first insn. Its purpose is to compute a bitmask of registers and
2643  * stack slots that needs precision in the parent verifier state.
2644  */
2645 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2646 			  u32 *reg_mask, u64 *stack_mask)
2647 {
2648 	const struct bpf_insn_cbs cbs = {
2649 		.cb_call	= disasm_kfunc_name,
2650 		.cb_print	= verbose,
2651 		.private_data	= env,
2652 	};
2653 	struct bpf_insn *insn = env->prog->insnsi + idx;
2654 	u8 class = BPF_CLASS(insn->code);
2655 	u8 opcode = BPF_OP(insn->code);
2656 	u8 mode = BPF_MODE(insn->code);
2657 	u32 dreg = 1u << insn->dst_reg;
2658 	u32 sreg = 1u << insn->src_reg;
2659 	u32 spi;
2660 
2661 	if (insn->code == 0)
2662 		return 0;
2663 	if (env->log.level & BPF_LOG_LEVEL2) {
2664 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2665 		verbose(env, "%d: ", idx);
2666 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2667 	}
2668 
2669 	if (class == BPF_ALU || class == BPF_ALU64) {
2670 		if (!(*reg_mask & dreg))
2671 			return 0;
2672 		if (opcode == BPF_MOV) {
2673 			if (BPF_SRC(insn->code) == BPF_X) {
2674 				/* dreg = sreg
2675 				 * dreg needs precision after this insn
2676 				 * sreg needs precision before this insn
2677 				 */
2678 				*reg_mask &= ~dreg;
2679 				*reg_mask |= sreg;
2680 			} else {
2681 				/* dreg = K
2682 				 * dreg needs precision after this insn.
2683 				 * Corresponding register is already marked
2684 				 * as precise=true in this verifier state.
2685 				 * No further markings in parent are necessary
2686 				 */
2687 				*reg_mask &= ~dreg;
2688 			}
2689 		} else {
2690 			if (BPF_SRC(insn->code) == BPF_X) {
2691 				/* dreg += sreg
2692 				 * both dreg and sreg need precision
2693 				 * before this insn
2694 				 */
2695 				*reg_mask |= sreg;
2696 			} /* else dreg += K
2697 			   * dreg still needs precision before this insn
2698 			   */
2699 		}
2700 	} else if (class == BPF_LDX) {
2701 		if (!(*reg_mask & dreg))
2702 			return 0;
2703 		*reg_mask &= ~dreg;
2704 
2705 		/* scalars can only be spilled into stack w/o losing precision.
2706 		 * Load from any other memory can be zero extended.
2707 		 * The desire to keep that precision is already indicated
2708 		 * by 'precise' mark in corresponding register of this state.
2709 		 * No further tracking necessary.
2710 		 */
2711 		if (insn->src_reg != BPF_REG_FP)
2712 			return 0;
2713 
2714 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2715 		 * that [fp - off] slot contains scalar that needs to be
2716 		 * tracked with precision
2717 		 */
2718 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2719 		if (spi >= 64) {
2720 			verbose(env, "BUG spi %d\n", spi);
2721 			WARN_ONCE(1, "verifier backtracking bug");
2722 			return -EFAULT;
2723 		}
2724 		*stack_mask |= 1ull << spi;
2725 	} else if (class == BPF_STX || class == BPF_ST) {
2726 		if (*reg_mask & dreg)
2727 			/* stx & st shouldn't be using _scalar_ dst_reg
2728 			 * to access memory. It means backtracking
2729 			 * encountered a case of pointer subtraction.
2730 			 */
2731 			return -ENOTSUPP;
2732 		/* scalars can only be spilled into stack */
2733 		if (insn->dst_reg != BPF_REG_FP)
2734 			return 0;
2735 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2736 		if (spi >= 64) {
2737 			verbose(env, "BUG spi %d\n", spi);
2738 			WARN_ONCE(1, "verifier backtracking bug");
2739 			return -EFAULT;
2740 		}
2741 		if (!(*stack_mask & (1ull << spi)))
2742 			return 0;
2743 		*stack_mask &= ~(1ull << spi);
2744 		if (class == BPF_STX)
2745 			*reg_mask |= sreg;
2746 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2747 		if (opcode == BPF_CALL) {
2748 			if (insn->src_reg == BPF_PSEUDO_CALL)
2749 				return -ENOTSUPP;
2750 			/* BPF helpers that invoke callback subprogs are
2751 			 * equivalent to BPF_PSEUDO_CALL above
2752 			 */
2753 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2754 				return -ENOTSUPP;
2755 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2756 			 * catch this error later. Make backtracking conservative
2757 			 * with ENOTSUPP.
2758 			 */
2759 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2760 				return -ENOTSUPP;
2761 			/* regular helper call sets R0 */
2762 			*reg_mask &= ~1;
2763 			if (*reg_mask & 0x3f) {
2764 				/* if backtracing was looking for registers R1-R5
2765 				 * they should have been found already.
2766 				 */
2767 				verbose(env, "BUG regs %x\n", *reg_mask);
2768 				WARN_ONCE(1, "verifier backtracking bug");
2769 				return -EFAULT;
2770 			}
2771 		} else if (opcode == BPF_EXIT) {
2772 			return -ENOTSUPP;
2773 		}
2774 	} else if (class == BPF_LD) {
2775 		if (!(*reg_mask & dreg))
2776 			return 0;
2777 		*reg_mask &= ~dreg;
2778 		/* It's ld_imm64 or ld_abs or ld_ind.
2779 		 * For ld_imm64 no further tracking of precision
2780 		 * into parent is necessary
2781 		 */
2782 		if (mode == BPF_IND || mode == BPF_ABS)
2783 			/* to be analyzed */
2784 			return -ENOTSUPP;
2785 	}
2786 	return 0;
2787 }
2788 
2789 /* the scalar precision tracking algorithm:
2790  * . at the start all registers have precise=false.
2791  * . scalar ranges are tracked as normal through alu and jmp insns.
2792  * . once precise value of the scalar register is used in:
2793  *   .  ptr + scalar alu
2794  *   . if (scalar cond K|scalar)
2795  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2796  *   backtrack through the verifier states and mark all registers and
2797  *   stack slots with spilled constants that these scalar regisers
2798  *   should be precise.
2799  * . during state pruning two registers (or spilled stack slots)
2800  *   are equivalent if both are not precise.
2801  *
2802  * Note the verifier cannot simply walk register parentage chain,
2803  * since many different registers and stack slots could have been
2804  * used to compute single precise scalar.
2805  *
2806  * The approach of starting with precise=true for all registers and then
2807  * backtrack to mark a register as not precise when the verifier detects
2808  * that program doesn't care about specific value (e.g., when helper
2809  * takes register as ARG_ANYTHING parameter) is not safe.
2810  *
2811  * It's ok to walk single parentage chain of the verifier states.
2812  * It's possible that this backtracking will go all the way till 1st insn.
2813  * All other branches will be explored for needing precision later.
2814  *
2815  * The backtracking needs to deal with cases like:
2816  *   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)
2817  * r9 -= r8
2818  * r5 = r9
2819  * if r5 > 0x79f goto pc+7
2820  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2821  * r5 += 1
2822  * ...
2823  * call bpf_perf_event_output#25
2824  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2825  *
2826  * and this case:
2827  * r6 = 1
2828  * call foo // uses callee's r6 inside to compute r0
2829  * r0 += r6
2830  * if r0 == 0 goto
2831  *
2832  * to track above reg_mask/stack_mask needs to be independent for each frame.
2833  *
2834  * Also if parent's curframe > frame where backtracking started,
2835  * the verifier need to mark registers in both frames, otherwise callees
2836  * may incorrectly prune callers. This is similar to
2837  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2838  *
2839  * For now backtracking falls back into conservative marking.
2840  */
2841 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2842 				     struct bpf_verifier_state *st)
2843 {
2844 	struct bpf_func_state *func;
2845 	struct bpf_reg_state *reg;
2846 	int i, j;
2847 
2848 	/* big hammer: mark all scalars precise in this path.
2849 	 * pop_stack may still get !precise scalars.
2850 	 * We also skip current state and go straight to first parent state,
2851 	 * because precision markings in current non-checkpointed state are
2852 	 * not needed. See why in the comment in __mark_chain_precision below.
2853 	 */
2854 	for (st = st->parent; st; st = st->parent) {
2855 		for (i = 0; i <= st->curframe; i++) {
2856 			func = st->frame[i];
2857 			for (j = 0; j < BPF_REG_FP; j++) {
2858 				reg = &func->regs[j];
2859 				if (reg->type != SCALAR_VALUE)
2860 					continue;
2861 				reg->precise = true;
2862 			}
2863 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2864 				if (!is_spilled_reg(&func->stack[j]))
2865 					continue;
2866 				reg = &func->stack[j].spilled_ptr;
2867 				if (reg->type != SCALAR_VALUE)
2868 					continue;
2869 				reg->precise = true;
2870 			}
2871 		}
2872 	}
2873 }
2874 
2875 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2876 {
2877 	struct bpf_func_state *func;
2878 	struct bpf_reg_state *reg;
2879 	int i, j;
2880 
2881 	for (i = 0; i <= st->curframe; i++) {
2882 		func = st->frame[i];
2883 		for (j = 0; j < BPF_REG_FP; j++) {
2884 			reg = &func->regs[j];
2885 			if (reg->type != SCALAR_VALUE)
2886 				continue;
2887 			reg->precise = false;
2888 		}
2889 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2890 			if (!is_spilled_reg(&func->stack[j]))
2891 				continue;
2892 			reg = &func->stack[j].spilled_ptr;
2893 			if (reg->type != SCALAR_VALUE)
2894 				continue;
2895 			reg->precise = false;
2896 		}
2897 	}
2898 }
2899 
2900 /*
2901  * __mark_chain_precision() backtracks BPF program instruction sequence and
2902  * chain of verifier states making sure that register *regno* (if regno >= 0)
2903  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2904  * SCALARS, as well as any other registers and slots that contribute to
2905  * a tracked state of given registers/stack slots, depending on specific BPF
2906  * assembly instructions (see backtrack_insns() for exact instruction handling
2907  * logic). This backtracking relies on recorded jmp_history and is able to
2908  * traverse entire chain of parent states. This process ends only when all the
2909  * necessary registers/slots and their transitive dependencies are marked as
2910  * precise.
2911  *
2912  * One important and subtle aspect is that precise marks *do not matter* in
2913  * the currently verified state (current state). It is important to understand
2914  * why this is the case.
2915  *
2916  * First, note that current state is the state that is not yet "checkpointed",
2917  * i.e., it is not yet put into env->explored_states, and it has no children
2918  * states as well. It's ephemeral, and can end up either a) being discarded if
2919  * compatible explored state is found at some point or BPF_EXIT instruction is
2920  * reached or b) checkpointed and put into env->explored_states, branching out
2921  * into one or more children states.
2922  *
2923  * In the former case, precise markings in current state are completely
2924  * ignored by state comparison code (see regsafe() for details). Only
2925  * checkpointed ("old") state precise markings are important, and if old
2926  * state's register/slot is precise, regsafe() assumes current state's
2927  * register/slot as precise and checks value ranges exactly and precisely. If
2928  * states turn out to be compatible, current state's necessary precise
2929  * markings and any required parent states' precise markings are enforced
2930  * after the fact with propagate_precision() logic, after the fact. But it's
2931  * important to realize that in this case, even after marking current state
2932  * registers/slots as precise, we immediately discard current state. So what
2933  * actually matters is any of the precise markings propagated into current
2934  * state's parent states, which are always checkpointed (due to b) case above).
2935  * As such, for scenario a) it doesn't matter if current state has precise
2936  * markings set or not.
2937  *
2938  * Now, for the scenario b), checkpointing and forking into child(ren)
2939  * state(s). Note that before current state gets to checkpointing step, any
2940  * processed instruction always assumes precise SCALAR register/slot
2941  * knowledge: if precise value or range is useful to prune jump branch, BPF
2942  * verifier takes this opportunity enthusiastically. Similarly, when
2943  * register's value is used to calculate offset or memory address, exact
2944  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2945  * what we mentioned above about state comparison ignoring precise markings
2946  * during state comparison, BPF verifier ignores and also assumes precise
2947  * markings *at will* during instruction verification process. But as verifier
2948  * assumes precision, it also propagates any precision dependencies across
2949  * parent states, which are not yet finalized, so can be further restricted
2950  * based on new knowledge gained from restrictions enforced by their children
2951  * states. This is so that once those parent states are finalized, i.e., when
2952  * they have no more active children state, state comparison logic in
2953  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2954  * required for correctness.
2955  *
2956  * To build a bit more intuition, note also that once a state is checkpointed,
2957  * the path we took to get to that state is not important. This is crucial
2958  * property for state pruning. When state is checkpointed and finalized at
2959  * some instruction index, it can be correctly and safely used to "short
2960  * circuit" any *compatible* state that reaches exactly the same instruction
2961  * index. I.e., if we jumped to that instruction from a completely different
2962  * code path than original finalized state was derived from, it doesn't
2963  * matter, current state can be discarded because from that instruction
2964  * forward having a compatible state will ensure we will safely reach the
2965  * exit. States describe preconditions for further exploration, but completely
2966  * forget the history of how we got here.
2967  *
2968  * This also means that even if we needed precise SCALAR range to get to
2969  * finalized state, but from that point forward *that same* SCALAR register is
2970  * never used in a precise context (i.e., it's precise value is not needed for
2971  * correctness), it's correct and safe to mark such register as "imprecise"
2972  * (i.e., precise marking set to false). This is what we rely on when we do
2973  * not set precise marking in current state. If no child state requires
2974  * precision for any given SCALAR register, it's safe to dictate that it can
2975  * be imprecise. If any child state does require this register to be precise,
2976  * we'll mark it precise later retroactively during precise markings
2977  * propagation from child state to parent states.
2978  *
2979  * Skipping precise marking setting in current state is a mild version of
2980  * relying on the above observation. But we can utilize this property even
2981  * more aggressively by proactively forgetting any precise marking in the
2982  * current state (which we inherited from the parent state), right before we
2983  * checkpoint it and branch off into new child state. This is done by
2984  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2985  * finalized states which help in short circuiting more future states.
2986  */
2987 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2988 				  int spi)
2989 {
2990 	struct bpf_verifier_state *st = env->cur_state;
2991 	int first_idx = st->first_insn_idx;
2992 	int last_idx = env->insn_idx;
2993 	struct bpf_func_state *func;
2994 	struct bpf_reg_state *reg;
2995 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2996 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2997 	bool skip_first = true;
2998 	bool new_marks = false;
2999 	int i, err;
3000 
3001 	if (!env->bpf_capable)
3002 		return 0;
3003 
3004 	/* Do sanity checks against current state of register and/or stack
3005 	 * slot, but don't set precise flag in current state, as precision
3006 	 * tracking in the current state is unnecessary.
3007 	 */
3008 	func = st->frame[frame];
3009 	if (regno >= 0) {
3010 		reg = &func->regs[regno];
3011 		if (reg->type != SCALAR_VALUE) {
3012 			WARN_ONCE(1, "backtracing misuse");
3013 			return -EFAULT;
3014 		}
3015 		new_marks = true;
3016 	}
3017 
3018 	while (spi >= 0) {
3019 		if (!is_spilled_reg(&func->stack[spi])) {
3020 			stack_mask = 0;
3021 			break;
3022 		}
3023 		reg = &func->stack[spi].spilled_ptr;
3024 		if (reg->type != SCALAR_VALUE) {
3025 			stack_mask = 0;
3026 			break;
3027 		}
3028 		new_marks = true;
3029 		break;
3030 	}
3031 
3032 	if (!new_marks)
3033 		return 0;
3034 	if (!reg_mask && !stack_mask)
3035 		return 0;
3036 
3037 	for (;;) {
3038 		DECLARE_BITMAP(mask, 64);
3039 		u32 history = st->jmp_history_cnt;
3040 
3041 		if (env->log.level & BPF_LOG_LEVEL2)
3042 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3043 
3044 		if (last_idx < 0) {
3045 			/* we are at the entry into subprog, which
3046 			 * is expected for global funcs, but only if
3047 			 * requested precise registers are R1-R5
3048 			 * (which are global func's input arguments)
3049 			 */
3050 			if (st->curframe == 0 &&
3051 			    st->frame[0]->subprogno > 0 &&
3052 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3053 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3054 				bitmap_from_u64(mask, reg_mask);
3055 				for_each_set_bit(i, mask, 32) {
3056 					reg = &st->frame[0]->regs[i];
3057 					if (reg->type != SCALAR_VALUE) {
3058 						reg_mask &= ~(1u << i);
3059 						continue;
3060 					}
3061 					reg->precise = true;
3062 				}
3063 				return 0;
3064 			}
3065 
3066 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3067 				st->frame[0]->subprogno, reg_mask, stack_mask);
3068 			WARN_ONCE(1, "verifier backtracking bug");
3069 			return -EFAULT;
3070 		}
3071 
3072 		for (i = last_idx;;) {
3073 			if (skip_first) {
3074 				err = 0;
3075 				skip_first = false;
3076 			} else {
3077 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3078 			}
3079 			if (err == -ENOTSUPP) {
3080 				mark_all_scalars_precise(env, st);
3081 				return 0;
3082 			} else if (err) {
3083 				return err;
3084 			}
3085 			if (!reg_mask && !stack_mask)
3086 				/* Found assignment(s) into tracked register in this state.
3087 				 * Since this state is already marked, just return.
3088 				 * Nothing to be tracked further in the parent state.
3089 				 */
3090 				return 0;
3091 			if (i == first_idx)
3092 				break;
3093 			i = get_prev_insn_idx(st, i, &history);
3094 			if (i >= env->prog->len) {
3095 				/* This can happen if backtracking reached insn 0
3096 				 * and there are still reg_mask or stack_mask
3097 				 * to backtrack.
3098 				 * It means the backtracking missed the spot where
3099 				 * particular register was initialized with a constant.
3100 				 */
3101 				verbose(env, "BUG backtracking idx %d\n", i);
3102 				WARN_ONCE(1, "verifier backtracking bug");
3103 				return -EFAULT;
3104 			}
3105 		}
3106 		st = st->parent;
3107 		if (!st)
3108 			break;
3109 
3110 		new_marks = false;
3111 		func = st->frame[frame];
3112 		bitmap_from_u64(mask, reg_mask);
3113 		for_each_set_bit(i, mask, 32) {
3114 			reg = &func->regs[i];
3115 			if (reg->type != SCALAR_VALUE) {
3116 				reg_mask &= ~(1u << i);
3117 				continue;
3118 			}
3119 			if (!reg->precise)
3120 				new_marks = true;
3121 			reg->precise = true;
3122 		}
3123 
3124 		bitmap_from_u64(mask, stack_mask);
3125 		for_each_set_bit(i, mask, 64) {
3126 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3127 				/* the sequence of instructions:
3128 				 * 2: (bf) r3 = r10
3129 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3130 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3131 				 * doesn't contain jmps. It's backtracked
3132 				 * as a single block.
3133 				 * During backtracking insn 3 is not recognized as
3134 				 * stack access, so at the end of backtracking
3135 				 * stack slot fp-8 is still marked in stack_mask.
3136 				 * However the parent state may not have accessed
3137 				 * fp-8 and it's "unallocated" stack space.
3138 				 * In such case fallback to conservative.
3139 				 */
3140 				mark_all_scalars_precise(env, st);
3141 				return 0;
3142 			}
3143 
3144 			if (!is_spilled_reg(&func->stack[i])) {
3145 				stack_mask &= ~(1ull << i);
3146 				continue;
3147 			}
3148 			reg = &func->stack[i].spilled_ptr;
3149 			if (reg->type != SCALAR_VALUE) {
3150 				stack_mask &= ~(1ull << i);
3151 				continue;
3152 			}
3153 			if (!reg->precise)
3154 				new_marks = true;
3155 			reg->precise = true;
3156 		}
3157 		if (env->log.level & BPF_LOG_LEVEL2) {
3158 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3159 				new_marks ? "didn't have" : "already had",
3160 				reg_mask, stack_mask);
3161 			print_verifier_state(env, func, true);
3162 		}
3163 
3164 		if (!reg_mask && !stack_mask)
3165 			break;
3166 		if (!new_marks)
3167 			break;
3168 
3169 		last_idx = st->last_insn_idx;
3170 		first_idx = st->first_insn_idx;
3171 	}
3172 	return 0;
3173 }
3174 
3175 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3176 {
3177 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3178 }
3179 
3180 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3181 {
3182 	return __mark_chain_precision(env, frame, regno, -1);
3183 }
3184 
3185 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3186 {
3187 	return __mark_chain_precision(env, frame, -1, spi);
3188 }
3189 
3190 static bool is_spillable_regtype(enum bpf_reg_type type)
3191 {
3192 	switch (base_type(type)) {
3193 	case PTR_TO_MAP_VALUE:
3194 	case PTR_TO_STACK:
3195 	case PTR_TO_CTX:
3196 	case PTR_TO_PACKET:
3197 	case PTR_TO_PACKET_META:
3198 	case PTR_TO_PACKET_END:
3199 	case PTR_TO_FLOW_KEYS:
3200 	case CONST_PTR_TO_MAP:
3201 	case PTR_TO_SOCKET:
3202 	case PTR_TO_SOCK_COMMON:
3203 	case PTR_TO_TCP_SOCK:
3204 	case PTR_TO_XDP_SOCK:
3205 	case PTR_TO_BTF_ID:
3206 	case PTR_TO_BUF:
3207 	case PTR_TO_MEM:
3208 	case PTR_TO_FUNC:
3209 	case PTR_TO_MAP_KEY:
3210 		return true;
3211 	default:
3212 		return false;
3213 	}
3214 }
3215 
3216 /* Does this register contain a constant zero? */
3217 static bool register_is_null(struct bpf_reg_state *reg)
3218 {
3219 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3220 }
3221 
3222 static bool register_is_const(struct bpf_reg_state *reg)
3223 {
3224 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3225 }
3226 
3227 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3228 {
3229 	return tnum_is_unknown(reg->var_off) &&
3230 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3231 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3232 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3233 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3234 }
3235 
3236 static bool register_is_bounded(struct bpf_reg_state *reg)
3237 {
3238 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3239 }
3240 
3241 static bool __is_pointer_value(bool allow_ptr_leaks,
3242 			       const struct bpf_reg_state *reg)
3243 {
3244 	if (allow_ptr_leaks)
3245 		return false;
3246 
3247 	return reg->type != SCALAR_VALUE;
3248 }
3249 
3250 static void save_register_state(struct bpf_func_state *state,
3251 				int spi, struct bpf_reg_state *reg,
3252 				int size)
3253 {
3254 	int i;
3255 
3256 	state->stack[spi].spilled_ptr = *reg;
3257 	if (size == BPF_REG_SIZE)
3258 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3259 
3260 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3261 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3262 
3263 	/* size < 8 bytes spill */
3264 	for (; i; i--)
3265 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3266 }
3267 
3268 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3269  * stack boundary and alignment are checked in check_mem_access()
3270  */
3271 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3272 				       /* stack frame we're writing to */
3273 				       struct bpf_func_state *state,
3274 				       int off, int size, int value_regno,
3275 				       int insn_idx)
3276 {
3277 	struct bpf_func_state *cur; /* state of the current function */
3278 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3279 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3280 	struct bpf_reg_state *reg = NULL;
3281 
3282 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3283 	if (err)
3284 		return err;
3285 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3286 	 * so it's aligned access and [off, off + size) are within stack limits
3287 	 */
3288 	if (!env->allow_ptr_leaks &&
3289 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3290 	    size != BPF_REG_SIZE) {
3291 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3292 		return -EACCES;
3293 	}
3294 
3295 	cur = env->cur_state->frame[env->cur_state->curframe];
3296 	if (value_regno >= 0)
3297 		reg = &cur->regs[value_regno];
3298 	if (!env->bypass_spec_v4) {
3299 		bool sanitize = reg && is_spillable_regtype(reg->type);
3300 
3301 		for (i = 0; i < size; i++) {
3302 			u8 type = state->stack[spi].slot_type[i];
3303 
3304 			if (type != STACK_MISC && type != STACK_ZERO) {
3305 				sanitize = true;
3306 				break;
3307 			}
3308 		}
3309 
3310 		if (sanitize)
3311 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3312 	}
3313 
3314 	mark_stack_slot_scratched(env, spi);
3315 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3316 	    !register_is_null(reg) && env->bpf_capable) {
3317 		if (dst_reg != BPF_REG_FP) {
3318 			/* The backtracking logic can only recognize explicit
3319 			 * stack slot address like [fp - 8]. Other spill of
3320 			 * scalar via different register has to be conservative.
3321 			 * Backtrack from here and mark all registers as precise
3322 			 * that contributed into 'reg' being a constant.
3323 			 */
3324 			err = mark_chain_precision(env, value_regno);
3325 			if (err)
3326 				return err;
3327 		}
3328 		save_register_state(state, spi, reg, size);
3329 	} else if (reg && is_spillable_regtype(reg->type)) {
3330 		/* register containing pointer is being spilled into stack */
3331 		if (size != BPF_REG_SIZE) {
3332 			verbose_linfo(env, insn_idx, "; ");
3333 			verbose(env, "invalid size of register spill\n");
3334 			return -EACCES;
3335 		}
3336 		if (state != cur && reg->type == PTR_TO_STACK) {
3337 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3338 			return -EINVAL;
3339 		}
3340 		save_register_state(state, spi, reg, size);
3341 	} else {
3342 		u8 type = STACK_MISC;
3343 
3344 		/* regular write of data into stack destroys any spilled ptr */
3345 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3346 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3347 		if (is_spilled_reg(&state->stack[spi]))
3348 			for (i = 0; i < BPF_REG_SIZE; i++)
3349 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3350 
3351 		/* only mark the slot as written if all 8 bytes were written
3352 		 * otherwise read propagation may incorrectly stop too soon
3353 		 * when stack slots are partially written.
3354 		 * This heuristic means that read propagation will be
3355 		 * conservative, since it will add reg_live_read marks
3356 		 * to stack slots all the way to first state when programs
3357 		 * writes+reads less than 8 bytes
3358 		 */
3359 		if (size == BPF_REG_SIZE)
3360 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3361 
3362 		/* when we zero initialize stack slots mark them as such */
3363 		if (reg && register_is_null(reg)) {
3364 			/* backtracking doesn't work for STACK_ZERO yet. */
3365 			err = mark_chain_precision(env, value_regno);
3366 			if (err)
3367 				return err;
3368 			type = STACK_ZERO;
3369 		}
3370 
3371 		/* Mark slots affected by this stack write. */
3372 		for (i = 0; i < size; i++)
3373 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3374 				type;
3375 	}
3376 	return 0;
3377 }
3378 
3379 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3380  * known to contain a variable offset.
3381  * This function checks whether the write is permitted and conservatively
3382  * tracks the effects of the write, considering that each stack slot in the
3383  * dynamic range is potentially written to.
3384  *
3385  * 'off' includes 'regno->off'.
3386  * 'value_regno' can be -1, meaning that an unknown value is being written to
3387  * the stack.
3388  *
3389  * Spilled pointers in range are not marked as written because we don't know
3390  * what's going to be actually written. This means that read propagation for
3391  * future reads cannot be terminated by this write.
3392  *
3393  * For privileged programs, uninitialized stack slots are considered
3394  * initialized by this write (even though we don't know exactly what offsets
3395  * are going to be written to). The idea is that we don't want the verifier to
3396  * reject future reads that access slots written to through variable offsets.
3397  */
3398 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3399 				     /* func where register points to */
3400 				     struct bpf_func_state *state,
3401 				     int ptr_regno, int off, int size,
3402 				     int value_regno, int insn_idx)
3403 {
3404 	struct bpf_func_state *cur; /* state of the current function */
3405 	int min_off, max_off;
3406 	int i, err;
3407 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3408 	bool writing_zero = false;
3409 	/* set if the fact that we're writing a zero is used to let any
3410 	 * stack slots remain STACK_ZERO
3411 	 */
3412 	bool zero_used = false;
3413 
3414 	cur = env->cur_state->frame[env->cur_state->curframe];
3415 	ptr_reg = &cur->regs[ptr_regno];
3416 	min_off = ptr_reg->smin_value + off;
3417 	max_off = ptr_reg->smax_value + off + size;
3418 	if (value_regno >= 0)
3419 		value_reg = &cur->regs[value_regno];
3420 	if (value_reg && register_is_null(value_reg))
3421 		writing_zero = true;
3422 
3423 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3424 	if (err)
3425 		return err;
3426 
3427 
3428 	/* Variable offset writes destroy any spilled pointers in range. */
3429 	for (i = min_off; i < max_off; i++) {
3430 		u8 new_type, *stype;
3431 		int slot, spi;
3432 
3433 		slot = -i - 1;
3434 		spi = slot / BPF_REG_SIZE;
3435 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3436 		mark_stack_slot_scratched(env, spi);
3437 
3438 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3439 			/* Reject the write if range we may write to has not
3440 			 * been initialized beforehand. If we didn't reject
3441 			 * here, the ptr status would be erased below (even
3442 			 * though not all slots are actually overwritten),
3443 			 * possibly opening the door to leaks.
3444 			 *
3445 			 * We do however catch STACK_INVALID case below, and
3446 			 * only allow reading possibly uninitialized memory
3447 			 * later for CAP_PERFMON, as the write may not happen to
3448 			 * that slot.
3449 			 */
3450 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3451 				insn_idx, i);
3452 			return -EINVAL;
3453 		}
3454 
3455 		/* Erase all spilled pointers. */
3456 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3457 
3458 		/* Update the slot type. */
3459 		new_type = STACK_MISC;
3460 		if (writing_zero && *stype == STACK_ZERO) {
3461 			new_type = STACK_ZERO;
3462 			zero_used = true;
3463 		}
3464 		/* If the slot is STACK_INVALID, we check whether it's OK to
3465 		 * pretend that it will be initialized by this write. The slot
3466 		 * might not actually be written to, and so if we mark it as
3467 		 * initialized future reads might leak uninitialized memory.
3468 		 * For privileged programs, we will accept such reads to slots
3469 		 * that may or may not be written because, if we're reject
3470 		 * them, the error would be too confusing.
3471 		 */
3472 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3473 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3474 					insn_idx, i);
3475 			return -EINVAL;
3476 		}
3477 		*stype = new_type;
3478 	}
3479 	if (zero_used) {
3480 		/* backtracking doesn't work for STACK_ZERO yet. */
3481 		err = mark_chain_precision(env, value_regno);
3482 		if (err)
3483 			return err;
3484 	}
3485 	return 0;
3486 }
3487 
3488 /* When register 'dst_regno' is assigned some values from stack[min_off,
3489  * max_off), we set the register's type according to the types of the
3490  * respective stack slots. If all the stack values are known to be zeros, then
3491  * so is the destination reg. Otherwise, the register is considered to be
3492  * SCALAR. This function does not deal with register filling; the caller must
3493  * ensure that all spilled registers in the stack range have been marked as
3494  * read.
3495  */
3496 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3497 				/* func where src register points to */
3498 				struct bpf_func_state *ptr_state,
3499 				int min_off, int max_off, int dst_regno)
3500 {
3501 	struct bpf_verifier_state *vstate = env->cur_state;
3502 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3503 	int i, slot, spi;
3504 	u8 *stype;
3505 	int zeros = 0;
3506 
3507 	for (i = min_off; i < max_off; i++) {
3508 		slot = -i - 1;
3509 		spi = slot / BPF_REG_SIZE;
3510 		stype = ptr_state->stack[spi].slot_type;
3511 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3512 			break;
3513 		zeros++;
3514 	}
3515 	if (zeros == max_off - min_off) {
3516 		/* any access_size read into register is zero extended,
3517 		 * so the whole register == const_zero
3518 		 */
3519 		__mark_reg_const_zero(&state->regs[dst_regno]);
3520 		/* backtracking doesn't support STACK_ZERO yet,
3521 		 * so mark it precise here, so that later
3522 		 * backtracking can stop here.
3523 		 * Backtracking may not need this if this register
3524 		 * doesn't participate in pointer adjustment.
3525 		 * Forward propagation of precise flag is not
3526 		 * necessary either. This mark is only to stop
3527 		 * backtracking. Any register that contributed
3528 		 * to const 0 was marked precise before spill.
3529 		 */
3530 		state->regs[dst_regno].precise = true;
3531 	} else {
3532 		/* have read misc data from the stack */
3533 		mark_reg_unknown(env, state->regs, dst_regno);
3534 	}
3535 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3536 }
3537 
3538 /* Read the stack at 'off' and put the results into the register indicated by
3539  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3540  * spilled reg.
3541  *
3542  * 'dst_regno' can be -1, meaning that the read value is not going to a
3543  * register.
3544  *
3545  * The access is assumed to be within the current stack bounds.
3546  */
3547 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3548 				      /* func where src register points to */
3549 				      struct bpf_func_state *reg_state,
3550 				      int off, int size, int dst_regno)
3551 {
3552 	struct bpf_verifier_state *vstate = env->cur_state;
3553 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3554 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3555 	struct bpf_reg_state *reg;
3556 	u8 *stype, type;
3557 
3558 	stype = reg_state->stack[spi].slot_type;
3559 	reg = &reg_state->stack[spi].spilled_ptr;
3560 
3561 	if (is_spilled_reg(&reg_state->stack[spi])) {
3562 		u8 spill_size = 1;
3563 
3564 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3565 			spill_size++;
3566 
3567 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3568 			if (reg->type != SCALAR_VALUE) {
3569 				verbose_linfo(env, env->insn_idx, "; ");
3570 				verbose(env, "invalid size of register fill\n");
3571 				return -EACCES;
3572 			}
3573 
3574 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3575 			if (dst_regno < 0)
3576 				return 0;
3577 
3578 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3579 				/* The earlier check_reg_arg() has decided the
3580 				 * subreg_def for this insn.  Save it first.
3581 				 */
3582 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3583 
3584 				state->regs[dst_regno] = *reg;
3585 				state->regs[dst_regno].subreg_def = subreg_def;
3586 			} else {
3587 				for (i = 0; i < size; i++) {
3588 					type = stype[(slot - i) % BPF_REG_SIZE];
3589 					if (type == STACK_SPILL)
3590 						continue;
3591 					if (type == STACK_MISC)
3592 						continue;
3593 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3594 						off, i, size);
3595 					return -EACCES;
3596 				}
3597 				mark_reg_unknown(env, state->regs, dst_regno);
3598 			}
3599 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3600 			return 0;
3601 		}
3602 
3603 		if (dst_regno >= 0) {
3604 			/* restore register state from stack */
3605 			state->regs[dst_regno] = *reg;
3606 			/* mark reg as written since spilled pointer state likely
3607 			 * has its liveness marks cleared by is_state_visited()
3608 			 * which resets stack/reg liveness for state transitions
3609 			 */
3610 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3611 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3612 			/* If dst_regno==-1, the caller is asking us whether
3613 			 * it is acceptable to use this value as a SCALAR_VALUE
3614 			 * (e.g. for XADD).
3615 			 * We must not allow unprivileged callers to do that
3616 			 * with spilled pointers.
3617 			 */
3618 			verbose(env, "leaking pointer from stack off %d\n",
3619 				off);
3620 			return -EACCES;
3621 		}
3622 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3623 	} else {
3624 		for (i = 0; i < size; i++) {
3625 			type = stype[(slot - i) % BPF_REG_SIZE];
3626 			if (type == STACK_MISC)
3627 				continue;
3628 			if (type == STACK_ZERO)
3629 				continue;
3630 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3631 				off, i, size);
3632 			return -EACCES;
3633 		}
3634 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3635 		if (dst_regno >= 0)
3636 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3637 	}
3638 	return 0;
3639 }
3640 
3641 enum bpf_access_src {
3642 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3643 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3644 };
3645 
3646 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3647 					 int regno, int off, int access_size,
3648 					 bool zero_size_allowed,
3649 					 enum bpf_access_src type,
3650 					 struct bpf_call_arg_meta *meta);
3651 
3652 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3653 {
3654 	return cur_regs(env) + regno;
3655 }
3656 
3657 /* Read the stack at 'ptr_regno + off' and put the result into the register
3658  * 'dst_regno'.
3659  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3660  * but not its variable offset.
3661  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3662  *
3663  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3664  * filling registers (i.e. reads of spilled register cannot be detected when
3665  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3666  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3667  * offset; for a fixed offset check_stack_read_fixed_off should be used
3668  * instead.
3669  */
3670 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3671 				    int ptr_regno, int off, int size, int dst_regno)
3672 {
3673 	/* The state of the source register. */
3674 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3675 	struct bpf_func_state *ptr_state = func(env, reg);
3676 	int err;
3677 	int min_off, max_off;
3678 
3679 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3680 	 */
3681 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3682 					    false, ACCESS_DIRECT, NULL);
3683 	if (err)
3684 		return err;
3685 
3686 	min_off = reg->smin_value + off;
3687 	max_off = reg->smax_value + off;
3688 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3689 	return 0;
3690 }
3691 
3692 /* check_stack_read dispatches to check_stack_read_fixed_off or
3693  * check_stack_read_var_off.
3694  *
3695  * The caller must ensure that the offset falls within the allocated stack
3696  * bounds.
3697  *
3698  * 'dst_regno' is a register which will receive the value from the stack. It
3699  * can be -1, meaning that the read value is not going to a register.
3700  */
3701 static int check_stack_read(struct bpf_verifier_env *env,
3702 			    int ptr_regno, int off, int size,
3703 			    int dst_regno)
3704 {
3705 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3706 	struct bpf_func_state *state = func(env, reg);
3707 	int err;
3708 	/* Some accesses are only permitted with a static offset. */
3709 	bool var_off = !tnum_is_const(reg->var_off);
3710 
3711 	/* The offset is required to be static when reads don't go to a
3712 	 * register, in order to not leak pointers (see
3713 	 * check_stack_read_fixed_off).
3714 	 */
3715 	if (dst_regno < 0 && var_off) {
3716 		char tn_buf[48];
3717 
3718 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3719 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3720 			tn_buf, off, size);
3721 		return -EACCES;
3722 	}
3723 	/* Variable offset is prohibited for unprivileged mode for simplicity
3724 	 * since it requires corresponding support in Spectre masking for stack
3725 	 * ALU. See also retrieve_ptr_limit().
3726 	 */
3727 	if (!env->bypass_spec_v1 && var_off) {
3728 		char tn_buf[48];
3729 
3730 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3731 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3732 				ptr_regno, tn_buf);
3733 		return -EACCES;
3734 	}
3735 
3736 	if (!var_off) {
3737 		off += reg->var_off.value;
3738 		err = check_stack_read_fixed_off(env, state, off, size,
3739 						 dst_regno);
3740 	} else {
3741 		/* Variable offset stack reads need more conservative handling
3742 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3743 		 * branch.
3744 		 */
3745 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3746 					       dst_regno);
3747 	}
3748 	return err;
3749 }
3750 
3751 
3752 /* check_stack_write dispatches to check_stack_write_fixed_off or
3753  * check_stack_write_var_off.
3754  *
3755  * 'ptr_regno' is the register used as a pointer into the stack.
3756  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3757  * 'value_regno' is the register whose value we're writing to the stack. It can
3758  * be -1, meaning that we're not writing from a register.
3759  *
3760  * The caller must ensure that the offset falls within the maximum stack size.
3761  */
3762 static int check_stack_write(struct bpf_verifier_env *env,
3763 			     int ptr_regno, int off, int size,
3764 			     int value_regno, int insn_idx)
3765 {
3766 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3767 	struct bpf_func_state *state = func(env, reg);
3768 	int err;
3769 
3770 	if (tnum_is_const(reg->var_off)) {
3771 		off += reg->var_off.value;
3772 		err = check_stack_write_fixed_off(env, state, off, size,
3773 						  value_regno, insn_idx);
3774 	} else {
3775 		/* Variable offset stack reads need more conservative handling
3776 		 * than fixed offset ones.
3777 		 */
3778 		err = check_stack_write_var_off(env, state,
3779 						ptr_regno, off, size,
3780 						value_regno, insn_idx);
3781 	}
3782 	return err;
3783 }
3784 
3785 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3786 				 int off, int size, enum bpf_access_type type)
3787 {
3788 	struct bpf_reg_state *regs = cur_regs(env);
3789 	struct bpf_map *map = regs[regno].map_ptr;
3790 	u32 cap = bpf_map_flags_to_cap(map);
3791 
3792 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3793 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3794 			map->value_size, off, size);
3795 		return -EACCES;
3796 	}
3797 
3798 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3799 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3800 			map->value_size, off, size);
3801 		return -EACCES;
3802 	}
3803 
3804 	return 0;
3805 }
3806 
3807 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3808 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3809 			      int off, int size, u32 mem_size,
3810 			      bool zero_size_allowed)
3811 {
3812 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3813 	struct bpf_reg_state *reg;
3814 
3815 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3816 		return 0;
3817 
3818 	reg = &cur_regs(env)[regno];
3819 	switch (reg->type) {
3820 	case PTR_TO_MAP_KEY:
3821 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3822 			mem_size, off, size);
3823 		break;
3824 	case PTR_TO_MAP_VALUE:
3825 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3826 			mem_size, off, size);
3827 		break;
3828 	case PTR_TO_PACKET:
3829 	case PTR_TO_PACKET_META:
3830 	case PTR_TO_PACKET_END:
3831 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3832 			off, size, regno, reg->id, off, mem_size);
3833 		break;
3834 	case PTR_TO_MEM:
3835 	default:
3836 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3837 			mem_size, off, size);
3838 	}
3839 
3840 	return -EACCES;
3841 }
3842 
3843 /* check read/write into a memory region with possible variable offset */
3844 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3845 				   int off, int size, u32 mem_size,
3846 				   bool zero_size_allowed)
3847 {
3848 	struct bpf_verifier_state *vstate = env->cur_state;
3849 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3850 	struct bpf_reg_state *reg = &state->regs[regno];
3851 	int err;
3852 
3853 	/* We may have adjusted the register pointing to memory region, so we
3854 	 * need to try adding each of min_value and max_value to off
3855 	 * to make sure our theoretical access will be safe.
3856 	 *
3857 	 * The minimum value is only important with signed
3858 	 * comparisons where we can't assume the floor of a
3859 	 * value is 0.  If we are using signed variables for our
3860 	 * index'es we need to make sure that whatever we use
3861 	 * will have a set floor within our range.
3862 	 */
3863 	if (reg->smin_value < 0 &&
3864 	    (reg->smin_value == S64_MIN ||
3865 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3866 	      reg->smin_value + off < 0)) {
3867 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3868 			regno);
3869 		return -EACCES;
3870 	}
3871 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3872 				 mem_size, zero_size_allowed);
3873 	if (err) {
3874 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3875 			regno);
3876 		return err;
3877 	}
3878 
3879 	/* If we haven't set a max value then we need to bail since we can't be
3880 	 * sure we won't do bad things.
3881 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3882 	 */
3883 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3884 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3885 			regno);
3886 		return -EACCES;
3887 	}
3888 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3889 				 mem_size, zero_size_allowed);
3890 	if (err) {
3891 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3892 			regno);
3893 		return err;
3894 	}
3895 
3896 	return 0;
3897 }
3898 
3899 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3900 			       const struct bpf_reg_state *reg, int regno,
3901 			       bool fixed_off_ok)
3902 {
3903 	/* Access to this pointer-typed register or passing it to a helper
3904 	 * is only allowed in its original, unmodified form.
3905 	 */
3906 
3907 	if (reg->off < 0) {
3908 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3909 			reg_type_str(env, reg->type), regno, reg->off);
3910 		return -EACCES;
3911 	}
3912 
3913 	if (!fixed_off_ok && reg->off) {
3914 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3915 			reg_type_str(env, reg->type), regno, reg->off);
3916 		return -EACCES;
3917 	}
3918 
3919 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3920 		char tn_buf[48];
3921 
3922 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3923 		verbose(env, "variable %s access var_off=%s disallowed\n",
3924 			reg_type_str(env, reg->type), tn_buf);
3925 		return -EACCES;
3926 	}
3927 
3928 	return 0;
3929 }
3930 
3931 int check_ptr_off_reg(struct bpf_verifier_env *env,
3932 		      const struct bpf_reg_state *reg, int regno)
3933 {
3934 	return __check_ptr_off_reg(env, reg, regno, false);
3935 }
3936 
3937 static int map_kptr_match_type(struct bpf_verifier_env *env,
3938 			       struct btf_field *kptr_field,
3939 			       struct bpf_reg_state *reg, u32 regno)
3940 {
3941 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3942 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3943 	const char *reg_name = "";
3944 
3945 	/* Only unreferenced case accepts untrusted pointers */
3946 	if (kptr_field->type == BPF_KPTR_UNREF)
3947 		perm_flags |= PTR_UNTRUSTED;
3948 
3949 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3950 		goto bad_type;
3951 
3952 	if (!btf_is_kernel(reg->btf)) {
3953 		verbose(env, "R%d must point to kernel BTF\n", regno);
3954 		return -EINVAL;
3955 	}
3956 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3957 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3958 
3959 	/* For ref_ptr case, release function check should ensure we get one
3960 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3961 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3962 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3963 	 * reg->off and reg->ref_obj_id are not needed here.
3964 	 */
3965 	if (__check_ptr_off_reg(env, reg, regno, true))
3966 		return -EACCES;
3967 
3968 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3969 	 * we also need to take into account the reg->off.
3970 	 *
3971 	 * We want to support cases like:
3972 	 *
3973 	 * struct foo {
3974 	 *         struct bar br;
3975 	 *         struct baz bz;
3976 	 * };
3977 	 *
3978 	 * struct foo *v;
3979 	 * v = func();	      // PTR_TO_BTF_ID
3980 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3981 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3982 	 *                    // first member type of struct after comparison fails
3983 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3984 	 *                    // to match type
3985 	 *
3986 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3987 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3988 	 * the struct to match type against first member of struct, i.e. reject
3989 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3990 	 * strict mode to true for type match.
3991 	 */
3992 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3993 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3994 				  kptr_field->type == BPF_KPTR_REF))
3995 		goto bad_type;
3996 	return 0;
3997 bad_type:
3998 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3999 		reg_type_str(env, reg->type), reg_name);
4000 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4001 	if (kptr_field->type == BPF_KPTR_UNREF)
4002 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4003 			targ_name);
4004 	else
4005 		verbose(env, "\n");
4006 	return -EINVAL;
4007 }
4008 
4009 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4010 				 int value_regno, int insn_idx,
4011 				 struct btf_field *kptr_field)
4012 {
4013 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4014 	int class = BPF_CLASS(insn->code);
4015 	struct bpf_reg_state *val_reg;
4016 
4017 	/* Things we already checked for in check_map_access and caller:
4018 	 *  - Reject cases where variable offset may touch kptr
4019 	 *  - size of access (must be BPF_DW)
4020 	 *  - tnum_is_const(reg->var_off)
4021 	 *  - kptr_field->offset == off + reg->var_off.value
4022 	 */
4023 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4024 	if (BPF_MODE(insn->code) != BPF_MEM) {
4025 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4026 		return -EACCES;
4027 	}
4028 
4029 	/* We only allow loading referenced kptr, since it will be marked as
4030 	 * untrusted, similar to unreferenced kptr.
4031 	 */
4032 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4033 		verbose(env, "store to referenced kptr disallowed\n");
4034 		return -EACCES;
4035 	}
4036 
4037 	if (class == BPF_LDX) {
4038 		val_reg = reg_state(env, value_regno);
4039 		/* We can simply mark the value_regno receiving the pointer
4040 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4041 		 */
4042 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4043 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4044 		/* For mark_ptr_or_null_reg */
4045 		val_reg->id = ++env->id_gen;
4046 	} else if (class == BPF_STX) {
4047 		val_reg = reg_state(env, value_regno);
4048 		if (!register_is_null(val_reg) &&
4049 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4050 			return -EACCES;
4051 	} else if (class == BPF_ST) {
4052 		if (insn->imm) {
4053 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4054 				kptr_field->offset);
4055 			return -EACCES;
4056 		}
4057 	} else {
4058 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4059 		return -EACCES;
4060 	}
4061 	return 0;
4062 }
4063 
4064 /* check read/write into a map element with possible variable offset */
4065 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4066 			    int off, int size, bool zero_size_allowed,
4067 			    enum bpf_access_src src)
4068 {
4069 	struct bpf_verifier_state *vstate = env->cur_state;
4070 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4071 	struct bpf_reg_state *reg = &state->regs[regno];
4072 	struct bpf_map *map = reg->map_ptr;
4073 	struct btf_record *rec;
4074 	int err, i;
4075 
4076 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4077 				      zero_size_allowed);
4078 	if (err)
4079 		return err;
4080 
4081 	if (IS_ERR_OR_NULL(map->record))
4082 		return 0;
4083 	rec = map->record;
4084 	for (i = 0; i < rec->cnt; i++) {
4085 		struct btf_field *field = &rec->fields[i];
4086 		u32 p = field->offset;
4087 
4088 		/* If any part of a field  can be touched by load/store, reject
4089 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4090 		 * it is sufficient to check x1 < y2 && y1 < x2.
4091 		 */
4092 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4093 		    p < reg->umax_value + off + size) {
4094 			switch (field->type) {
4095 			case BPF_KPTR_UNREF:
4096 			case BPF_KPTR_REF:
4097 				if (src != ACCESS_DIRECT) {
4098 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4099 					return -EACCES;
4100 				}
4101 				if (!tnum_is_const(reg->var_off)) {
4102 					verbose(env, "kptr access cannot have variable offset\n");
4103 					return -EACCES;
4104 				}
4105 				if (p != off + reg->var_off.value) {
4106 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4107 						p, off + reg->var_off.value);
4108 					return -EACCES;
4109 				}
4110 				if (size != bpf_size_to_bytes(BPF_DW)) {
4111 					verbose(env, "kptr access size must be BPF_DW\n");
4112 					return -EACCES;
4113 				}
4114 				break;
4115 			default:
4116 				verbose(env, "%s cannot be accessed directly by load/store\n",
4117 					btf_field_type_name(field->type));
4118 				return -EACCES;
4119 			}
4120 		}
4121 	}
4122 	return 0;
4123 }
4124 
4125 #define MAX_PACKET_OFF 0xffff
4126 
4127 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4128 				       const struct bpf_call_arg_meta *meta,
4129 				       enum bpf_access_type t)
4130 {
4131 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4132 
4133 	switch (prog_type) {
4134 	/* Program types only with direct read access go here! */
4135 	case BPF_PROG_TYPE_LWT_IN:
4136 	case BPF_PROG_TYPE_LWT_OUT:
4137 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4138 	case BPF_PROG_TYPE_SK_REUSEPORT:
4139 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4140 	case BPF_PROG_TYPE_CGROUP_SKB:
4141 		if (t == BPF_WRITE)
4142 			return false;
4143 		fallthrough;
4144 
4145 	/* Program types with direct read + write access go here! */
4146 	case BPF_PROG_TYPE_SCHED_CLS:
4147 	case BPF_PROG_TYPE_SCHED_ACT:
4148 	case BPF_PROG_TYPE_XDP:
4149 	case BPF_PROG_TYPE_LWT_XMIT:
4150 	case BPF_PROG_TYPE_SK_SKB:
4151 	case BPF_PROG_TYPE_SK_MSG:
4152 		if (meta)
4153 			return meta->pkt_access;
4154 
4155 		env->seen_direct_write = true;
4156 		return true;
4157 
4158 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4159 		if (t == BPF_WRITE)
4160 			env->seen_direct_write = true;
4161 
4162 		return true;
4163 
4164 	default:
4165 		return false;
4166 	}
4167 }
4168 
4169 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4170 			       int size, bool zero_size_allowed)
4171 {
4172 	struct bpf_reg_state *regs = cur_regs(env);
4173 	struct bpf_reg_state *reg = &regs[regno];
4174 	int err;
4175 
4176 	/* We may have added a variable offset to the packet pointer; but any
4177 	 * reg->range we have comes after that.  We are only checking the fixed
4178 	 * offset.
4179 	 */
4180 
4181 	/* We don't allow negative numbers, because we aren't tracking enough
4182 	 * detail to prove they're safe.
4183 	 */
4184 	if (reg->smin_value < 0) {
4185 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4186 			regno);
4187 		return -EACCES;
4188 	}
4189 
4190 	err = reg->range < 0 ? -EINVAL :
4191 	      __check_mem_access(env, regno, off, size, reg->range,
4192 				 zero_size_allowed);
4193 	if (err) {
4194 		verbose(env, "R%d offset is outside of the packet\n", regno);
4195 		return err;
4196 	}
4197 
4198 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4199 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4200 	 * otherwise find_good_pkt_pointers would have refused to set range info
4201 	 * that __check_mem_access would have rejected this pkt access.
4202 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4203 	 */
4204 	env->prog->aux->max_pkt_offset =
4205 		max_t(u32, env->prog->aux->max_pkt_offset,
4206 		      off + reg->umax_value + size - 1);
4207 
4208 	return err;
4209 }
4210 
4211 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4212 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4213 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4214 			    struct btf **btf, u32 *btf_id)
4215 {
4216 	struct bpf_insn_access_aux info = {
4217 		.reg_type = *reg_type,
4218 		.log = &env->log,
4219 	};
4220 
4221 	if (env->ops->is_valid_access &&
4222 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4223 		/* A non zero info.ctx_field_size indicates that this field is a
4224 		 * candidate for later verifier transformation to load the whole
4225 		 * field and then apply a mask when accessed with a narrower
4226 		 * access than actual ctx access size. A zero info.ctx_field_size
4227 		 * will only allow for whole field access and rejects any other
4228 		 * type of narrower access.
4229 		 */
4230 		*reg_type = info.reg_type;
4231 
4232 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4233 			*btf = info.btf;
4234 			*btf_id = info.btf_id;
4235 		} else {
4236 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4237 		}
4238 		/* remember the offset of last byte accessed in ctx */
4239 		if (env->prog->aux->max_ctx_offset < off + size)
4240 			env->prog->aux->max_ctx_offset = off + size;
4241 		return 0;
4242 	}
4243 
4244 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4245 	return -EACCES;
4246 }
4247 
4248 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4249 				  int size)
4250 {
4251 	if (size < 0 || off < 0 ||
4252 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4253 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4254 			off, size);
4255 		return -EACCES;
4256 	}
4257 	return 0;
4258 }
4259 
4260 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4261 			     u32 regno, int off, int size,
4262 			     enum bpf_access_type t)
4263 {
4264 	struct bpf_reg_state *regs = cur_regs(env);
4265 	struct bpf_reg_state *reg = &regs[regno];
4266 	struct bpf_insn_access_aux info = {};
4267 	bool valid;
4268 
4269 	if (reg->smin_value < 0) {
4270 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4271 			regno);
4272 		return -EACCES;
4273 	}
4274 
4275 	switch (reg->type) {
4276 	case PTR_TO_SOCK_COMMON:
4277 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4278 		break;
4279 	case PTR_TO_SOCKET:
4280 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4281 		break;
4282 	case PTR_TO_TCP_SOCK:
4283 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4284 		break;
4285 	case PTR_TO_XDP_SOCK:
4286 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4287 		break;
4288 	default:
4289 		valid = false;
4290 	}
4291 
4292 
4293 	if (valid) {
4294 		env->insn_aux_data[insn_idx].ctx_field_size =
4295 			info.ctx_field_size;
4296 		return 0;
4297 	}
4298 
4299 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4300 		regno, reg_type_str(env, reg->type), off, size);
4301 
4302 	return -EACCES;
4303 }
4304 
4305 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4306 {
4307 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4308 }
4309 
4310 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4311 {
4312 	const struct bpf_reg_state *reg = reg_state(env, regno);
4313 
4314 	return reg->type == PTR_TO_CTX;
4315 }
4316 
4317 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4318 {
4319 	const struct bpf_reg_state *reg = reg_state(env, regno);
4320 
4321 	return type_is_sk_pointer(reg->type);
4322 }
4323 
4324 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4325 {
4326 	const struct bpf_reg_state *reg = reg_state(env, regno);
4327 
4328 	return type_is_pkt_pointer(reg->type);
4329 }
4330 
4331 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4332 {
4333 	const struct bpf_reg_state *reg = reg_state(env, regno);
4334 
4335 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4336 	return reg->type == PTR_TO_FLOW_KEYS;
4337 }
4338 
4339 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4340 {
4341 	/* A referenced register is always trusted. */
4342 	if (reg->ref_obj_id)
4343 		return true;
4344 
4345 	/* If a register is not referenced, it is trusted if it has the
4346 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4347 	 * other type modifiers may be safe, but we elect to take an opt-in
4348 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4349 	 * not.
4350 	 *
4351 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4352 	 * for whether a register is trusted.
4353 	 */
4354 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4355 	       !bpf_type_has_unsafe_modifiers(reg->type);
4356 }
4357 
4358 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4359 {
4360 	return reg->type & MEM_RCU;
4361 }
4362 
4363 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4364 				   const struct bpf_reg_state *reg,
4365 				   int off, int size, bool strict)
4366 {
4367 	struct tnum reg_off;
4368 	int ip_align;
4369 
4370 	/* Byte size accesses are always allowed. */
4371 	if (!strict || size == 1)
4372 		return 0;
4373 
4374 	/* For platforms that do not have a Kconfig enabling
4375 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4376 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4377 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4378 	 * to this code only in strict mode where we want to emulate
4379 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4380 	 * unconditional IP align value of '2'.
4381 	 */
4382 	ip_align = 2;
4383 
4384 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4385 	if (!tnum_is_aligned(reg_off, size)) {
4386 		char tn_buf[48];
4387 
4388 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4389 		verbose(env,
4390 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4391 			ip_align, tn_buf, reg->off, off, size);
4392 		return -EACCES;
4393 	}
4394 
4395 	return 0;
4396 }
4397 
4398 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4399 				       const struct bpf_reg_state *reg,
4400 				       const char *pointer_desc,
4401 				       int off, int size, bool strict)
4402 {
4403 	struct tnum reg_off;
4404 
4405 	/* Byte size accesses are always allowed. */
4406 	if (!strict || size == 1)
4407 		return 0;
4408 
4409 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4410 	if (!tnum_is_aligned(reg_off, size)) {
4411 		char tn_buf[48];
4412 
4413 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4414 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4415 			pointer_desc, tn_buf, reg->off, off, size);
4416 		return -EACCES;
4417 	}
4418 
4419 	return 0;
4420 }
4421 
4422 static int check_ptr_alignment(struct bpf_verifier_env *env,
4423 			       const struct bpf_reg_state *reg, int off,
4424 			       int size, bool strict_alignment_once)
4425 {
4426 	bool strict = env->strict_alignment || strict_alignment_once;
4427 	const char *pointer_desc = "";
4428 
4429 	switch (reg->type) {
4430 	case PTR_TO_PACKET:
4431 	case PTR_TO_PACKET_META:
4432 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4433 		 * right in front, treat it the very same way.
4434 		 */
4435 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4436 	case PTR_TO_FLOW_KEYS:
4437 		pointer_desc = "flow keys ";
4438 		break;
4439 	case PTR_TO_MAP_KEY:
4440 		pointer_desc = "key ";
4441 		break;
4442 	case PTR_TO_MAP_VALUE:
4443 		pointer_desc = "value ";
4444 		break;
4445 	case PTR_TO_CTX:
4446 		pointer_desc = "context ";
4447 		break;
4448 	case PTR_TO_STACK:
4449 		pointer_desc = "stack ";
4450 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4451 		 * and check_stack_read_fixed_off() relies on stack accesses being
4452 		 * aligned.
4453 		 */
4454 		strict = true;
4455 		break;
4456 	case PTR_TO_SOCKET:
4457 		pointer_desc = "sock ";
4458 		break;
4459 	case PTR_TO_SOCK_COMMON:
4460 		pointer_desc = "sock_common ";
4461 		break;
4462 	case PTR_TO_TCP_SOCK:
4463 		pointer_desc = "tcp_sock ";
4464 		break;
4465 	case PTR_TO_XDP_SOCK:
4466 		pointer_desc = "xdp_sock ";
4467 		break;
4468 	default:
4469 		break;
4470 	}
4471 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4472 					   strict);
4473 }
4474 
4475 static int update_stack_depth(struct bpf_verifier_env *env,
4476 			      const struct bpf_func_state *func,
4477 			      int off)
4478 {
4479 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4480 
4481 	if (stack >= -off)
4482 		return 0;
4483 
4484 	/* update known max for given subprogram */
4485 	env->subprog_info[func->subprogno].stack_depth = -off;
4486 	return 0;
4487 }
4488 
4489 /* starting from main bpf function walk all instructions of the function
4490  * and recursively walk all callees that given function can call.
4491  * Ignore jump and exit insns.
4492  * Since recursion is prevented by check_cfg() this algorithm
4493  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4494  */
4495 static int check_max_stack_depth(struct bpf_verifier_env *env)
4496 {
4497 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4498 	struct bpf_subprog_info *subprog = env->subprog_info;
4499 	struct bpf_insn *insn = env->prog->insnsi;
4500 	bool tail_call_reachable = false;
4501 	int ret_insn[MAX_CALL_FRAMES];
4502 	int ret_prog[MAX_CALL_FRAMES];
4503 	int j;
4504 
4505 process_func:
4506 	/* protect against potential stack overflow that might happen when
4507 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4508 	 * depth for such case down to 256 so that the worst case scenario
4509 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4510 	 * 8k).
4511 	 *
4512 	 * To get the idea what might happen, see an example:
4513 	 * func1 -> sub rsp, 128
4514 	 *  subfunc1 -> sub rsp, 256
4515 	 *  tailcall1 -> add rsp, 256
4516 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4517 	 *   subfunc2 -> sub rsp, 64
4518 	 *   subfunc22 -> sub rsp, 128
4519 	 *   tailcall2 -> add rsp, 128
4520 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4521 	 *
4522 	 * tailcall will unwind the current stack frame but it will not get rid
4523 	 * of caller's stack as shown on the example above.
4524 	 */
4525 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4526 		verbose(env,
4527 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4528 			depth);
4529 		return -EACCES;
4530 	}
4531 	/* round up to 32-bytes, since this is granularity
4532 	 * of interpreter stack size
4533 	 */
4534 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4535 	if (depth > MAX_BPF_STACK) {
4536 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4537 			frame + 1, depth);
4538 		return -EACCES;
4539 	}
4540 continue_func:
4541 	subprog_end = subprog[idx + 1].start;
4542 	for (; i < subprog_end; i++) {
4543 		int next_insn;
4544 
4545 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4546 			continue;
4547 		/* remember insn and function to return to */
4548 		ret_insn[frame] = i + 1;
4549 		ret_prog[frame] = idx;
4550 
4551 		/* find the callee */
4552 		next_insn = i + insn[i].imm + 1;
4553 		idx = find_subprog(env, next_insn);
4554 		if (idx < 0) {
4555 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4556 				  next_insn);
4557 			return -EFAULT;
4558 		}
4559 		if (subprog[idx].is_async_cb) {
4560 			if (subprog[idx].has_tail_call) {
4561 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4562 				return -EFAULT;
4563 			}
4564 			 /* async callbacks don't increase bpf prog stack size */
4565 			continue;
4566 		}
4567 		i = next_insn;
4568 
4569 		if (subprog[idx].has_tail_call)
4570 			tail_call_reachable = true;
4571 
4572 		frame++;
4573 		if (frame >= MAX_CALL_FRAMES) {
4574 			verbose(env, "the call stack of %d frames is too deep !\n",
4575 				frame);
4576 			return -E2BIG;
4577 		}
4578 		goto process_func;
4579 	}
4580 	/* if tail call got detected across bpf2bpf calls then mark each of the
4581 	 * currently present subprog frames as tail call reachable subprogs;
4582 	 * this info will be utilized by JIT so that we will be preserving the
4583 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4584 	 */
4585 	if (tail_call_reachable)
4586 		for (j = 0; j < frame; j++)
4587 			subprog[ret_prog[j]].tail_call_reachable = true;
4588 	if (subprog[0].tail_call_reachable)
4589 		env->prog->aux->tail_call_reachable = true;
4590 
4591 	/* end of for() loop means the last insn of the 'subprog'
4592 	 * was reached. Doesn't matter whether it was JA or EXIT
4593 	 */
4594 	if (frame == 0)
4595 		return 0;
4596 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4597 	frame--;
4598 	i = ret_insn[frame];
4599 	idx = ret_prog[frame];
4600 	goto continue_func;
4601 }
4602 
4603 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4604 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4605 				  const struct bpf_insn *insn, int idx)
4606 {
4607 	int start = idx + insn->imm + 1, subprog;
4608 
4609 	subprog = find_subprog(env, start);
4610 	if (subprog < 0) {
4611 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4612 			  start);
4613 		return -EFAULT;
4614 	}
4615 	return env->subprog_info[subprog].stack_depth;
4616 }
4617 #endif
4618 
4619 static int __check_buffer_access(struct bpf_verifier_env *env,
4620 				 const char *buf_info,
4621 				 const struct bpf_reg_state *reg,
4622 				 int regno, int off, int size)
4623 {
4624 	if (off < 0) {
4625 		verbose(env,
4626 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4627 			regno, buf_info, off, size);
4628 		return -EACCES;
4629 	}
4630 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4631 		char tn_buf[48];
4632 
4633 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4634 		verbose(env,
4635 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4636 			regno, off, tn_buf);
4637 		return -EACCES;
4638 	}
4639 
4640 	return 0;
4641 }
4642 
4643 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4644 				  const struct bpf_reg_state *reg,
4645 				  int regno, int off, int size)
4646 {
4647 	int err;
4648 
4649 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4650 	if (err)
4651 		return err;
4652 
4653 	if (off + size > env->prog->aux->max_tp_access)
4654 		env->prog->aux->max_tp_access = off + size;
4655 
4656 	return 0;
4657 }
4658 
4659 static int check_buffer_access(struct bpf_verifier_env *env,
4660 			       const struct bpf_reg_state *reg,
4661 			       int regno, int off, int size,
4662 			       bool zero_size_allowed,
4663 			       u32 *max_access)
4664 {
4665 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4666 	int err;
4667 
4668 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4669 	if (err)
4670 		return err;
4671 
4672 	if (off + size > *max_access)
4673 		*max_access = off + size;
4674 
4675 	return 0;
4676 }
4677 
4678 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4679 static void zext_32_to_64(struct bpf_reg_state *reg)
4680 {
4681 	reg->var_off = tnum_subreg(reg->var_off);
4682 	__reg_assign_32_into_64(reg);
4683 }
4684 
4685 /* truncate register to smaller size (in bytes)
4686  * must be called with size < BPF_REG_SIZE
4687  */
4688 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4689 {
4690 	u64 mask;
4691 
4692 	/* clear high bits in bit representation */
4693 	reg->var_off = tnum_cast(reg->var_off, size);
4694 
4695 	/* fix arithmetic bounds */
4696 	mask = ((u64)1 << (size * 8)) - 1;
4697 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4698 		reg->umin_value &= mask;
4699 		reg->umax_value &= mask;
4700 	} else {
4701 		reg->umin_value = 0;
4702 		reg->umax_value = mask;
4703 	}
4704 	reg->smin_value = reg->umin_value;
4705 	reg->smax_value = reg->umax_value;
4706 
4707 	/* If size is smaller than 32bit register the 32bit register
4708 	 * values are also truncated so we push 64-bit bounds into
4709 	 * 32-bit bounds. Above were truncated < 32-bits already.
4710 	 */
4711 	if (size >= 4)
4712 		return;
4713 	__reg_combine_64_into_32(reg);
4714 }
4715 
4716 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4717 {
4718 	/* A map is considered read-only if the following condition are true:
4719 	 *
4720 	 * 1) BPF program side cannot change any of the map content. The
4721 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4722 	 *    and was set at map creation time.
4723 	 * 2) The map value(s) have been initialized from user space by a
4724 	 *    loader and then "frozen", such that no new map update/delete
4725 	 *    operations from syscall side are possible for the rest of
4726 	 *    the map's lifetime from that point onwards.
4727 	 * 3) Any parallel/pending map update/delete operations from syscall
4728 	 *    side have been completed. Only after that point, it's safe to
4729 	 *    assume that map value(s) are immutable.
4730 	 */
4731 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4732 	       READ_ONCE(map->frozen) &&
4733 	       !bpf_map_write_active(map);
4734 }
4735 
4736 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4737 {
4738 	void *ptr;
4739 	u64 addr;
4740 	int err;
4741 
4742 	err = map->ops->map_direct_value_addr(map, &addr, off);
4743 	if (err)
4744 		return err;
4745 	ptr = (void *)(long)addr + off;
4746 
4747 	switch (size) {
4748 	case sizeof(u8):
4749 		*val = (u64)*(u8 *)ptr;
4750 		break;
4751 	case sizeof(u16):
4752 		*val = (u64)*(u16 *)ptr;
4753 		break;
4754 	case sizeof(u32):
4755 		*val = (u64)*(u32 *)ptr;
4756 		break;
4757 	case sizeof(u64):
4758 		*val = *(u64 *)ptr;
4759 		break;
4760 	default:
4761 		return -EINVAL;
4762 	}
4763 	return 0;
4764 }
4765 
4766 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4767 				   struct bpf_reg_state *regs,
4768 				   int regno, int off, int size,
4769 				   enum bpf_access_type atype,
4770 				   int value_regno)
4771 {
4772 	struct bpf_reg_state *reg = regs + regno;
4773 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4774 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4775 	enum bpf_type_flag flag = 0;
4776 	u32 btf_id;
4777 	int ret;
4778 
4779 	if (!env->allow_ptr_leaks) {
4780 		verbose(env,
4781 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4782 			tname);
4783 		return -EPERM;
4784 	}
4785 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4786 		verbose(env,
4787 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4788 			tname);
4789 		return -EINVAL;
4790 	}
4791 	if (off < 0) {
4792 		verbose(env,
4793 			"R%d is ptr_%s invalid negative access: off=%d\n",
4794 			regno, tname, off);
4795 		return -EACCES;
4796 	}
4797 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4798 		char tn_buf[48];
4799 
4800 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4801 		verbose(env,
4802 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4803 			regno, tname, off, tn_buf);
4804 		return -EACCES;
4805 	}
4806 
4807 	if (reg->type & MEM_USER) {
4808 		verbose(env,
4809 			"R%d is ptr_%s access user memory: off=%d\n",
4810 			regno, tname, off);
4811 		return -EACCES;
4812 	}
4813 
4814 	if (reg->type & MEM_PERCPU) {
4815 		verbose(env,
4816 			"R%d is ptr_%s access percpu memory: off=%d\n",
4817 			regno, tname, off);
4818 		return -EACCES;
4819 	}
4820 
4821 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4822 		if (!btf_is_kernel(reg->btf)) {
4823 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4824 			return -EFAULT;
4825 		}
4826 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4827 	} else {
4828 		/* Writes are permitted with default btf_struct_access for
4829 		 * program allocated objects (which always have ref_obj_id > 0),
4830 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4831 		 */
4832 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4833 			verbose(env, "only read is supported\n");
4834 			return -EACCES;
4835 		}
4836 
4837 		if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4838 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4839 			return -EFAULT;
4840 		}
4841 
4842 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4843 	}
4844 
4845 	if (ret < 0)
4846 		return ret;
4847 
4848 	/* If this is an untrusted pointer, all pointers formed by walking it
4849 	 * also inherit the untrusted flag.
4850 	 */
4851 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4852 		flag |= PTR_UNTRUSTED;
4853 
4854 	/* By default any pointer obtained from walking a trusted pointer is
4855 	 * no longer trusted except the rcu case below.
4856 	 */
4857 	flag &= ~PTR_TRUSTED;
4858 
4859 	if (flag & MEM_RCU) {
4860 		/* Mark value register as MEM_RCU only if it is protected by
4861 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
4862 		 * itself can already indicate trustedness inside the rcu
4863 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
4864 		 * it could be null in some cases.
4865 		 */
4866 		if (!env->cur_state->active_rcu_lock ||
4867 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
4868 			flag &= ~MEM_RCU;
4869 		else
4870 			flag |= PTR_MAYBE_NULL;
4871 	} else if (reg->type & MEM_RCU) {
4872 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
4873 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
4874 		 */
4875 		flag |= PTR_UNTRUSTED;
4876 	}
4877 
4878 	if (atype == BPF_READ && value_regno >= 0)
4879 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4880 
4881 	return 0;
4882 }
4883 
4884 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4885 				   struct bpf_reg_state *regs,
4886 				   int regno, int off, int size,
4887 				   enum bpf_access_type atype,
4888 				   int value_regno)
4889 {
4890 	struct bpf_reg_state *reg = regs + regno;
4891 	struct bpf_map *map = reg->map_ptr;
4892 	struct bpf_reg_state map_reg;
4893 	enum bpf_type_flag flag = 0;
4894 	const struct btf_type *t;
4895 	const char *tname;
4896 	u32 btf_id;
4897 	int ret;
4898 
4899 	if (!btf_vmlinux) {
4900 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4901 		return -ENOTSUPP;
4902 	}
4903 
4904 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4905 		verbose(env, "map_ptr access not supported for map type %d\n",
4906 			map->map_type);
4907 		return -ENOTSUPP;
4908 	}
4909 
4910 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4911 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4912 
4913 	if (!env->allow_ptr_leaks) {
4914 		verbose(env,
4915 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4916 			tname);
4917 		return -EPERM;
4918 	}
4919 
4920 	if (off < 0) {
4921 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4922 			regno, tname, off);
4923 		return -EACCES;
4924 	}
4925 
4926 	if (atype != BPF_READ) {
4927 		verbose(env, "only read from %s is supported\n", tname);
4928 		return -EACCES;
4929 	}
4930 
4931 	/* Simulate access to a PTR_TO_BTF_ID */
4932 	memset(&map_reg, 0, sizeof(map_reg));
4933 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4934 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4935 	if (ret < 0)
4936 		return ret;
4937 
4938 	if (value_regno >= 0)
4939 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4940 
4941 	return 0;
4942 }
4943 
4944 /* Check that the stack access at the given offset is within bounds. The
4945  * maximum valid offset is -1.
4946  *
4947  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4948  * -state->allocated_stack for reads.
4949  */
4950 static int check_stack_slot_within_bounds(int off,
4951 					  struct bpf_func_state *state,
4952 					  enum bpf_access_type t)
4953 {
4954 	int min_valid_off;
4955 
4956 	if (t == BPF_WRITE)
4957 		min_valid_off = -MAX_BPF_STACK;
4958 	else
4959 		min_valid_off = -state->allocated_stack;
4960 
4961 	if (off < min_valid_off || off > -1)
4962 		return -EACCES;
4963 	return 0;
4964 }
4965 
4966 /* Check that the stack access at 'regno + off' falls within the maximum stack
4967  * bounds.
4968  *
4969  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4970  */
4971 static int check_stack_access_within_bounds(
4972 		struct bpf_verifier_env *env,
4973 		int regno, int off, int access_size,
4974 		enum bpf_access_src src, enum bpf_access_type type)
4975 {
4976 	struct bpf_reg_state *regs = cur_regs(env);
4977 	struct bpf_reg_state *reg = regs + regno;
4978 	struct bpf_func_state *state = func(env, reg);
4979 	int min_off, max_off;
4980 	int err;
4981 	char *err_extra;
4982 
4983 	if (src == ACCESS_HELPER)
4984 		/* We don't know if helpers are reading or writing (or both). */
4985 		err_extra = " indirect access to";
4986 	else if (type == BPF_READ)
4987 		err_extra = " read from";
4988 	else
4989 		err_extra = " write to";
4990 
4991 	if (tnum_is_const(reg->var_off)) {
4992 		min_off = reg->var_off.value + off;
4993 		if (access_size > 0)
4994 			max_off = min_off + access_size - 1;
4995 		else
4996 			max_off = min_off;
4997 	} else {
4998 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4999 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5000 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5001 				err_extra, regno);
5002 			return -EACCES;
5003 		}
5004 		min_off = reg->smin_value + off;
5005 		if (access_size > 0)
5006 			max_off = reg->smax_value + off + access_size - 1;
5007 		else
5008 			max_off = min_off;
5009 	}
5010 
5011 	err = check_stack_slot_within_bounds(min_off, state, type);
5012 	if (!err)
5013 		err = check_stack_slot_within_bounds(max_off, state, type);
5014 
5015 	if (err) {
5016 		if (tnum_is_const(reg->var_off)) {
5017 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5018 				err_extra, regno, off, access_size);
5019 		} else {
5020 			char tn_buf[48];
5021 
5022 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5023 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5024 				err_extra, regno, tn_buf, access_size);
5025 		}
5026 	}
5027 	return err;
5028 }
5029 
5030 /* check whether memory at (regno + off) is accessible for t = (read | write)
5031  * if t==write, value_regno is a register which value is stored into memory
5032  * if t==read, value_regno is a register which will receive the value from memory
5033  * if t==write && value_regno==-1, some unknown value is stored into memory
5034  * if t==read && value_regno==-1, don't care what we read from memory
5035  */
5036 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5037 			    int off, int bpf_size, enum bpf_access_type t,
5038 			    int value_regno, bool strict_alignment_once)
5039 {
5040 	struct bpf_reg_state *regs = cur_regs(env);
5041 	struct bpf_reg_state *reg = regs + regno;
5042 	struct bpf_func_state *state;
5043 	int size, err = 0;
5044 
5045 	size = bpf_size_to_bytes(bpf_size);
5046 	if (size < 0)
5047 		return size;
5048 
5049 	/* alignment checks will add in reg->off themselves */
5050 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5051 	if (err)
5052 		return err;
5053 
5054 	/* for access checks, reg->off is just part of off */
5055 	off += reg->off;
5056 
5057 	if (reg->type == PTR_TO_MAP_KEY) {
5058 		if (t == BPF_WRITE) {
5059 			verbose(env, "write to change key R%d not allowed\n", regno);
5060 			return -EACCES;
5061 		}
5062 
5063 		err = check_mem_region_access(env, regno, off, size,
5064 					      reg->map_ptr->key_size, false);
5065 		if (err)
5066 			return err;
5067 		if (value_regno >= 0)
5068 			mark_reg_unknown(env, regs, value_regno);
5069 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5070 		struct btf_field *kptr_field = NULL;
5071 
5072 		if (t == BPF_WRITE && value_regno >= 0 &&
5073 		    is_pointer_value(env, value_regno)) {
5074 			verbose(env, "R%d leaks addr into map\n", value_regno);
5075 			return -EACCES;
5076 		}
5077 		err = check_map_access_type(env, regno, off, size, t);
5078 		if (err)
5079 			return err;
5080 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5081 		if (err)
5082 			return err;
5083 		if (tnum_is_const(reg->var_off))
5084 			kptr_field = btf_record_find(reg->map_ptr->record,
5085 						     off + reg->var_off.value, BPF_KPTR);
5086 		if (kptr_field) {
5087 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5088 		} else if (t == BPF_READ && value_regno >= 0) {
5089 			struct bpf_map *map = reg->map_ptr;
5090 
5091 			/* if map is read-only, track its contents as scalars */
5092 			if (tnum_is_const(reg->var_off) &&
5093 			    bpf_map_is_rdonly(map) &&
5094 			    map->ops->map_direct_value_addr) {
5095 				int map_off = off + reg->var_off.value;
5096 				u64 val = 0;
5097 
5098 				err = bpf_map_direct_read(map, map_off, size,
5099 							  &val);
5100 				if (err)
5101 					return err;
5102 
5103 				regs[value_regno].type = SCALAR_VALUE;
5104 				__mark_reg_known(&regs[value_regno], val);
5105 			} else {
5106 				mark_reg_unknown(env, regs, value_regno);
5107 			}
5108 		}
5109 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5110 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5111 
5112 		if (type_may_be_null(reg->type)) {
5113 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5114 				reg_type_str(env, reg->type));
5115 			return -EACCES;
5116 		}
5117 
5118 		if (t == BPF_WRITE && rdonly_mem) {
5119 			verbose(env, "R%d cannot write into %s\n",
5120 				regno, reg_type_str(env, reg->type));
5121 			return -EACCES;
5122 		}
5123 
5124 		if (t == BPF_WRITE && value_regno >= 0 &&
5125 		    is_pointer_value(env, value_regno)) {
5126 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5127 			return -EACCES;
5128 		}
5129 
5130 		err = check_mem_region_access(env, regno, off, size,
5131 					      reg->mem_size, false);
5132 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5133 			mark_reg_unknown(env, regs, value_regno);
5134 	} else if (reg->type == PTR_TO_CTX) {
5135 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5136 		struct btf *btf = NULL;
5137 		u32 btf_id = 0;
5138 
5139 		if (t == BPF_WRITE && value_regno >= 0 &&
5140 		    is_pointer_value(env, value_regno)) {
5141 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5142 			return -EACCES;
5143 		}
5144 
5145 		err = check_ptr_off_reg(env, reg, regno);
5146 		if (err < 0)
5147 			return err;
5148 
5149 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5150 				       &btf_id);
5151 		if (err)
5152 			verbose_linfo(env, insn_idx, "; ");
5153 		if (!err && t == BPF_READ && value_regno >= 0) {
5154 			/* ctx access returns either a scalar, or a
5155 			 * PTR_TO_PACKET[_META,_END]. In the latter
5156 			 * case, we know the offset is zero.
5157 			 */
5158 			if (reg_type == SCALAR_VALUE) {
5159 				mark_reg_unknown(env, regs, value_regno);
5160 			} else {
5161 				mark_reg_known_zero(env, regs,
5162 						    value_regno);
5163 				if (type_may_be_null(reg_type))
5164 					regs[value_regno].id = ++env->id_gen;
5165 				/* A load of ctx field could have different
5166 				 * actual load size with the one encoded in the
5167 				 * insn. When the dst is PTR, it is for sure not
5168 				 * a sub-register.
5169 				 */
5170 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5171 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5172 					regs[value_regno].btf = btf;
5173 					regs[value_regno].btf_id = btf_id;
5174 				}
5175 			}
5176 			regs[value_regno].type = reg_type;
5177 		}
5178 
5179 	} else if (reg->type == PTR_TO_STACK) {
5180 		/* Basic bounds checks. */
5181 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5182 		if (err)
5183 			return err;
5184 
5185 		state = func(env, reg);
5186 		err = update_stack_depth(env, state, off);
5187 		if (err)
5188 			return err;
5189 
5190 		if (t == BPF_READ)
5191 			err = check_stack_read(env, regno, off, size,
5192 					       value_regno);
5193 		else
5194 			err = check_stack_write(env, regno, off, size,
5195 						value_regno, insn_idx);
5196 	} else if (reg_is_pkt_pointer(reg)) {
5197 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5198 			verbose(env, "cannot write into packet\n");
5199 			return -EACCES;
5200 		}
5201 		if (t == BPF_WRITE && value_regno >= 0 &&
5202 		    is_pointer_value(env, value_regno)) {
5203 			verbose(env, "R%d leaks addr into packet\n",
5204 				value_regno);
5205 			return -EACCES;
5206 		}
5207 		err = check_packet_access(env, regno, off, size, false);
5208 		if (!err && t == BPF_READ && value_regno >= 0)
5209 			mark_reg_unknown(env, regs, value_regno);
5210 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5211 		if (t == BPF_WRITE && value_regno >= 0 &&
5212 		    is_pointer_value(env, value_regno)) {
5213 			verbose(env, "R%d leaks addr into flow keys\n",
5214 				value_regno);
5215 			return -EACCES;
5216 		}
5217 
5218 		err = check_flow_keys_access(env, off, size);
5219 		if (!err && t == BPF_READ && value_regno >= 0)
5220 			mark_reg_unknown(env, regs, value_regno);
5221 	} else if (type_is_sk_pointer(reg->type)) {
5222 		if (t == BPF_WRITE) {
5223 			verbose(env, "R%d cannot write into %s\n",
5224 				regno, reg_type_str(env, reg->type));
5225 			return -EACCES;
5226 		}
5227 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5228 		if (!err && value_regno >= 0)
5229 			mark_reg_unknown(env, regs, value_regno);
5230 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5231 		err = check_tp_buffer_access(env, reg, regno, off, size);
5232 		if (!err && t == BPF_READ && value_regno >= 0)
5233 			mark_reg_unknown(env, regs, value_regno);
5234 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5235 		   !type_may_be_null(reg->type)) {
5236 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5237 					      value_regno);
5238 	} else if (reg->type == CONST_PTR_TO_MAP) {
5239 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5240 					      value_regno);
5241 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5242 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5243 		u32 *max_access;
5244 
5245 		if (rdonly_mem) {
5246 			if (t == BPF_WRITE) {
5247 				verbose(env, "R%d cannot write into %s\n",
5248 					regno, reg_type_str(env, reg->type));
5249 				return -EACCES;
5250 			}
5251 			max_access = &env->prog->aux->max_rdonly_access;
5252 		} else {
5253 			max_access = &env->prog->aux->max_rdwr_access;
5254 		}
5255 
5256 		err = check_buffer_access(env, reg, regno, off, size, false,
5257 					  max_access);
5258 
5259 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5260 			mark_reg_unknown(env, regs, value_regno);
5261 	} else {
5262 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5263 			reg_type_str(env, reg->type));
5264 		return -EACCES;
5265 	}
5266 
5267 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5268 	    regs[value_regno].type == SCALAR_VALUE) {
5269 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5270 		coerce_reg_to_size(&regs[value_regno], size);
5271 	}
5272 	return err;
5273 }
5274 
5275 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5276 {
5277 	int load_reg;
5278 	int err;
5279 
5280 	switch (insn->imm) {
5281 	case BPF_ADD:
5282 	case BPF_ADD | BPF_FETCH:
5283 	case BPF_AND:
5284 	case BPF_AND | BPF_FETCH:
5285 	case BPF_OR:
5286 	case BPF_OR | BPF_FETCH:
5287 	case BPF_XOR:
5288 	case BPF_XOR | BPF_FETCH:
5289 	case BPF_XCHG:
5290 	case BPF_CMPXCHG:
5291 		break;
5292 	default:
5293 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5294 		return -EINVAL;
5295 	}
5296 
5297 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5298 		verbose(env, "invalid atomic operand size\n");
5299 		return -EINVAL;
5300 	}
5301 
5302 	/* check src1 operand */
5303 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5304 	if (err)
5305 		return err;
5306 
5307 	/* check src2 operand */
5308 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5309 	if (err)
5310 		return err;
5311 
5312 	if (insn->imm == BPF_CMPXCHG) {
5313 		/* Check comparison of R0 with memory location */
5314 		const u32 aux_reg = BPF_REG_0;
5315 
5316 		err = check_reg_arg(env, aux_reg, SRC_OP);
5317 		if (err)
5318 			return err;
5319 
5320 		if (is_pointer_value(env, aux_reg)) {
5321 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5322 			return -EACCES;
5323 		}
5324 	}
5325 
5326 	if (is_pointer_value(env, insn->src_reg)) {
5327 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5328 		return -EACCES;
5329 	}
5330 
5331 	if (is_ctx_reg(env, insn->dst_reg) ||
5332 	    is_pkt_reg(env, insn->dst_reg) ||
5333 	    is_flow_key_reg(env, insn->dst_reg) ||
5334 	    is_sk_reg(env, insn->dst_reg)) {
5335 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5336 			insn->dst_reg,
5337 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5338 		return -EACCES;
5339 	}
5340 
5341 	if (insn->imm & BPF_FETCH) {
5342 		if (insn->imm == BPF_CMPXCHG)
5343 			load_reg = BPF_REG_0;
5344 		else
5345 			load_reg = insn->src_reg;
5346 
5347 		/* check and record load of old value */
5348 		err = check_reg_arg(env, load_reg, DST_OP);
5349 		if (err)
5350 			return err;
5351 	} else {
5352 		/* This instruction accesses a memory location but doesn't
5353 		 * actually load it into a register.
5354 		 */
5355 		load_reg = -1;
5356 	}
5357 
5358 	/* Check whether we can read the memory, with second call for fetch
5359 	 * case to simulate the register fill.
5360 	 */
5361 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5362 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5363 	if (!err && load_reg >= 0)
5364 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5365 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5366 				       true);
5367 	if (err)
5368 		return err;
5369 
5370 	/* Check whether we can write into the same memory. */
5371 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5372 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5373 	if (err)
5374 		return err;
5375 
5376 	return 0;
5377 }
5378 
5379 /* When register 'regno' is used to read the stack (either directly or through
5380  * a helper function) make sure that it's within stack boundary and, depending
5381  * on the access type, that all elements of the stack are initialized.
5382  *
5383  * 'off' includes 'regno->off', but not its dynamic part (if any).
5384  *
5385  * All registers that have been spilled on the stack in the slots within the
5386  * read offsets are marked as read.
5387  */
5388 static int check_stack_range_initialized(
5389 		struct bpf_verifier_env *env, int regno, int off,
5390 		int access_size, bool zero_size_allowed,
5391 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5392 {
5393 	struct bpf_reg_state *reg = reg_state(env, regno);
5394 	struct bpf_func_state *state = func(env, reg);
5395 	int err, min_off, max_off, i, j, slot, spi;
5396 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5397 	enum bpf_access_type bounds_check_type;
5398 	/* Some accesses can write anything into the stack, others are
5399 	 * read-only.
5400 	 */
5401 	bool clobber = false;
5402 
5403 	if (access_size == 0 && !zero_size_allowed) {
5404 		verbose(env, "invalid zero-sized read\n");
5405 		return -EACCES;
5406 	}
5407 
5408 	if (type == ACCESS_HELPER) {
5409 		/* The bounds checks for writes are more permissive than for
5410 		 * reads. However, if raw_mode is not set, we'll do extra
5411 		 * checks below.
5412 		 */
5413 		bounds_check_type = BPF_WRITE;
5414 		clobber = true;
5415 	} else {
5416 		bounds_check_type = BPF_READ;
5417 	}
5418 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5419 					       type, bounds_check_type);
5420 	if (err)
5421 		return err;
5422 
5423 
5424 	if (tnum_is_const(reg->var_off)) {
5425 		min_off = max_off = reg->var_off.value + off;
5426 	} else {
5427 		/* Variable offset is prohibited for unprivileged mode for
5428 		 * simplicity since it requires corresponding support in
5429 		 * Spectre masking for stack ALU.
5430 		 * See also retrieve_ptr_limit().
5431 		 */
5432 		if (!env->bypass_spec_v1) {
5433 			char tn_buf[48];
5434 
5435 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5436 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5437 				regno, err_extra, tn_buf);
5438 			return -EACCES;
5439 		}
5440 		/* Only initialized buffer on stack is allowed to be accessed
5441 		 * with variable offset. With uninitialized buffer it's hard to
5442 		 * guarantee that whole memory is marked as initialized on
5443 		 * helper return since specific bounds are unknown what may
5444 		 * cause uninitialized stack leaking.
5445 		 */
5446 		if (meta && meta->raw_mode)
5447 			meta = NULL;
5448 
5449 		min_off = reg->smin_value + off;
5450 		max_off = reg->smax_value + off;
5451 	}
5452 
5453 	if (meta && meta->raw_mode) {
5454 		meta->access_size = access_size;
5455 		meta->regno = regno;
5456 		return 0;
5457 	}
5458 
5459 	for (i = min_off; i < max_off + access_size; i++) {
5460 		u8 *stype;
5461 
5462 		slot = -i - 1;
5463 		spi = slot / BPF_REG_SIZE;
5464 		if (state->allocated_stack <= slot)
5465 			goto err;
5466 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5467 		if (*stype == STACK_MISC)
5468 			goto mark;
5469 		if (*stype == STACK_ZERO) {
5470 			if (clobber) {
5471 				/* helper can write anything into the stack */
5472 				*stype = STACK_MISC;
5473 			}
5474 			goto mark;
5475 		}
5476 
5477 		if (is_spilled_reg(&state->stack[spi]) &&
5478 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5479 		     env->allow_ptr_leaks)) {
5480 			if (clobber) {
5481 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5482 				for (j = 0; j < BPF_REG_SIZE; j++)
5483 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5484 			}
5485 			goto mark;
5486 		}
5487 
5488 err:
5489 		if (tnum_is_const(reg->var_off)) {
5490 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5491 				err_extra, regno, min_off, i - min_off, access_size);
5492 		} else {
5493 			char tn_buf[48];
5494 
5495 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5496 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5497 				err_extra, regno, tn_buf, i - min_off, access_size);
5498 		}
5499 		return -EACCES;
5500 mark:
5501 		/* reading any byte out of 8-byte 'spill_slot' will cause
5502 		 * the whole slot to be marked as 'read'
5503 		 */
5504 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5505 			      state->stack[spi].spilled_ptr.parent,
5506 			      REG_LIVE_READ64);
5507 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5508 		 * be sure that whether stack slot is written to or not. Hence,
5509 		 * we must still conservatively propagate reads upwards even if
5510 		 * helper may write to the entire memory range.
5511 		 */
5512 	}
5513 	return update_stack_depth(env, state, min_off);
5514 }
5515 
5516 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5517 				   int access_size, bool zero_size_allowed,
5518 				   struct bpf_call_arg_meta *meta)
5519 {
5520 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5521 	u32 *max_access;
5522 
5523 	switch (base_type(reg->type)) {
5524 	case PTR_TO_PACKET:
5525 	case PTR_TO_PACKET_META:
5526 		return check_packet_access(env, regno, reg->off, access_size,
5527 					   zero_size_allowed);
5528 	case PTR_TO_MAP_KEY:
5529 		if (meta && meta->raw_mode) {
5530 			verbose(env, "R%d cannot write into %s\n", regno,
5531 				reg_type_str(env, reg->type));
5532 			return -EACCES;
5533 		}
5534 		return check_mem_region_access(env, regno, reg->off, access_size,
5535 					       reg->map_ptr->key_size, false);
5536 	case PTR_TO_MAP_VALUE:
5537 		if (check_map_access_type(env, regno, reg->off, access_size,
5538 					  meta && meta->raw_mode ? BPF_WRITE :
5539 					  BPF_READ))
5540 			return -EACCES;
5541 		return check_map_access(env, regno, reg->off, access_size,
5542 					zero_size_allowed, ACCESS_HELPER);
5543 	case PTR_TO_MEM:
5544 		if (type_is_rdonly_mem(reg->type)) {
5545 			if (meta && meta->raw_mode) {
5546 				verbose(env, "R%d cannot write into %s\n", regno,
5547 					reg_type_str(env, reg->type));
5548 				return -EACCES;
5549 			}
5550 		}
5551 		return check_mem_region_access(env, regno, reg->off,
5552 					       access_size, reg->mem_size,
5553 					       zero_size_allowed);
5554 	case PTR_TO_BUF:
5555 		if (type_is_rdonly_mem(reg->type)) {
5556 			if (meta && meta->raw_mode) {
5557 				verbose(env, "R%d cannot write into %s\n", regno,
5558 					reg_type_str(env, reg->type));
5559 				return -EACCES;
5560 			}
5561 
5562 			max_access = &env->prog->aux->max_rdonly_access;
5563 		} else {
5564 			max_access = &env->prog->aux->max_rdwr_access;
5565 		}
5566 		return check_buffer_access(env, reg, regno, reg->off,
5567 					   access_size, zero_size_allowed,
5568 					   max_access);
5569 	case PTR_TO_STACK:
5570 		return check_stack_range_initialized(
5571 				env,
5572 				regno, reg->off, access_size,
5573 				zero_size_allowed, ACCESS_HELPER, meta);
5574 	case PTR_TO_CTX:
5575 		/* in case the function doesn't know how to access the context,
5576 		 * (because we are in a program of type SYSCALL for example), we
5577 		 * can not statically check its size.
5578 		 * Dynamically check it now.
5579 		 */
5580 		if (!env->ops->convert_ctx_access) {
5581 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5582 			int offset = access_size - 1;
5583 
5584 			/* Allow zero-byte read from PTR_TO_CTX */
5585 			if (access_size == 0)
5586 				return zero_size_allowed ? 0 : -EACCES;
5587 
5588 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5589 						atype, -1, false);
5590 		}
5591 
5592 		fallthrough;
5593 	default: /* scalar_value or invalid ptr */
5594 		/* Allow zero-byte read from NULL, regardless of pointer type */
5595 		if (zero_size_allowed && access_size == 0 &&
5596 		    register_is_null(reg))
5597 			return 0;
5598 
5599 		verbose(env, "R%d type=%s ", regno,
5600 			reg_type_str(env, reg->type));
5601 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5602 		return -EACCES;
5603 	}
5604 }
5605 
5606 static int check_mem_size_reg(struct bpf_verifier_env *env,
5607 			      struct bpf_reg_state *reg, u32 regno,
5608 			      bool zero_size_allowed,
5609 			      struct bpf_call_arg_meta *meta)
5610 {
5611 	int err;
5612 
5613 	/* This is used to refine r0 return value bounds for helpers
5614 	 * that enforce this value as an upper bound on return values.
5615 	 * See do_refine_retval_range() for helpers that can refine
5616 	 * the return value. C type of helper is u32 so we pull register
5617 	 * bound from umax_value however, if negative verifier errors
5618 	 * out. Only upper bounds can be learned because retval is an
5619 	 * int type and negative retvals are allowed.
5620 	 */
5621 	meta->msize_max_value = reg->umax_value;
5622 
5623 	/* The register is SCALAR_VALUE; the access check
5624 	 * happens using its boundaries.
5625 	 */
5626 	if (!tnum_is_const(reg->var_off))
5627 		/* For unprivileged variable accesses, disable raw
5628 		 * mode so that the program is required to
5629 		 * initialize all the memory that the helper could
5630 		 * just partially fill up.
5631 		 */
5632 		meta = NULL;
5633 
5634 	if (reg->smin_value < 0) {
5635 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5636 			regno);
5637 		return -EACCES;
5638 	}
5639 
5640 	if (reg->umin_value == 0) {
5641 		err = check_helper_mem_access(env, regno - 1, 0,
5642 					      zero_size_allowed,
5643 					      meta);
5644 		if (err)
5645 			return err;
5646 	}
5647 
5648 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5649 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5650 			regno);
5651 		return -EACCES;
5652 	}
5653 	err = check_helper_mem_access(env, regno - 1,
5654 				      reg->umax_value,
5655 				      zero_size_allowed, meta);
5656 	if (!err)
5657 		err = mark_chain_precision(env, regno);
5658 	return err;
5659 }
5660 
5661 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5662 		   u32 regno, u32 mem_size)
5663 {
5664 	bool may_be_null = type_may_be_null(reg->type);
5665 	struct bpf_reg_state saved_reg;
5666 	struct bpf_call_arg_meta meta;
5667 	int err;
5668 
5669 	if (register_is_null(reg))
5670 		return 0;
5671 
5672 	memset(&meta, 0, sizeof(meta));
5673 	/* Assuming that the register contains a value check if the memory
5674 	 * access is safe. Temporarily save and restore the register's state as
5675 	 * the conversion shouldn't be visible to a caller.
5676 	 */
5677 	if (may_be_null) {
5678 		saved_reg = *reg;
5679 		mark_ptr_not_null_reg(reg);
5680 	}
5681 
5682 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5683 	/* Check access for BPF_WRITE */
5684 	meta.raw_mode = true;
5685 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5686 
5687 	if (may_be_null)
5688 		*reg = saved_reg;
5689 
5690 	return err;
5691 }
5692 
5693 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5694 				    u32 regno)
5695 {
5696 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5697 	bool may_be_null = type_may_be_null(mem_reg->type);
5698 	struct bpf_reg_state saved_reg;
5699 	struct bpf_call_arg_meta meta;
5700 	int err;
5701 
5702 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5703 
5704 	memset(&meta, 0, sizeof(meta));
5705 
5706 	if (may_be_null) {
5707 		saved_reg = *mem_reg;
5708 		mark_ptr_not_null_reg(mem_reg);
5709 	}
5710 
5711 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5712 	/* Check access for BPF_WRITE */
5713 	meta.raw_mode = true;
5714 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5715 
5716 	if (may_be_null)
5717 		*mem_reg = saved_reg;
5718 	return err;
5719 }
5720 
5721 /* Implementation details:
5722  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5723  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5724  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5725  * Two separate bpf_obj_new will also have different reg->id.
5726  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5727  * clears reg->id after value_or_null->value transition, since the verifier only
5728  * cares about the range of access to valid map value pointer and doesn't care
5729  * about actual address of the map element.
5730  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5731  * reg->id > 0 after value_or_null->value transition. By doing so
5732  * two bpf_map_lookups will be considered two different pointers that
5733  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5734  * returned from bpf_obj_new.
5735  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5736  * dead-locks.
5737  * Since only one bpf_spin_lock is allowed the checks are simpler than
5738  * reg_is_refcounted() logic. The verifier needs to remember only
5739  * one spin_lock instead of array of acquired_refs.
5740  * cur_state->active_lock remembers which map value element or allocated
5741  * object got locked and clears it after bpf_spin_unlock.
5742  */
5743 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5744 			     bool is_lock)
5745 {
5746 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5747 	struct bpf_verifier_state *cur = env->cur_state;
5748 	bool is_const = tnum_is_const(reg->var_off);
5749 	u64 val = reg->var_off.value;
5750 	struct bpf_map *map = NULL;
5751 	struct btf *btf = NULL;
5752 	struct btf_record *rec;
5753 
5754 	if (!is_const) {
5755 		verbose(env,
5756 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5757 			regno);
5758 		return -EINVAL;
5759 	}
5760 	if (reg->type == PTR_TO_MAP_VALUE) {
5761 		map = reg->map_ptr;
5762 		if (!map->btf) {
5763 			verbose(env,
5764 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5765 				map->name);
5766 			return -EINVAL;
5767 		}
5768 	} else {
5769 		btf = reg->btf;
5770 	}
5771 
5772 	rec = reg_btf_record(reg);
5773 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5774 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5775 			map ? map->name : "kptr");
5776 		return -EINVAL;
5777 	}
5778 	if (rec->spin_lock_off != val + reg->off) {
5779 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5780 			val + reg->off, rec->spin_lock_off);
5781 		return -EINVAL;
5782 	}
5783 	if (is_lock) {
5784 		if (cur->active_lock.ptr) {
5785 			verbose(env,
5786 				"Locking two bpf_spin_locks are not allowed\n");
5787 			return -EINVAL;
5788 		}
5789 		if (map)
5790 			cur->active_lock.ptr = map;
5791 		else
5792 			cur->active_lock.ptr = btf;
5793 		cur->active_lock.id = reg->id;
5794 	} else {
5795 		struct bpf_func_state *fstate = cur_func(env);
5796 		void *ptr;
5797 		int i;
5798 
5799 		if (map)
5800 			ptr = map;
5801 		else
5802 			ptr = btf;
5803 
5804 		if (!cur->active_lock.ptr) {
5805 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5806 			return -EINVAL;
5807 		}
5808 		if (cur->active_lock.ptr != ptr ||
5809 		    cur->active_lock.id != reg->id) {
5810 			verbose(env, "bpf_spin_unlock of different lock\n");
5811 			return -EINVAL;
5812 		}
5813 		cur->active_lock.ptr = NULL;
5814 		cur->active_lock.id = 0;
5815 
5816 		for (i = fstate->acquired_refs - 1; i >= 0; i--) {
5817 			int err;
5818 
5819 			/* Complain on error because this reference state cannot
5820 			 * be freed before this point, as bpf_spin_lock critical
5821 			 * section does not allow functions that release the
5822 			 * allocated object immediately.
5823 			 */
5824 			if (!fstate->refs[i].release_on_unlock)
5825 				continue;
5826 			err = release_reference(env, fstate->refs[i].id);
5827 			if (err) {
5828 				verbose(env, "failed to release release_on_unlock reference");
5829 				return err;
5830 			}
5831 		}
5832 	}
5833 	return 0;
5834 }
5835 
5836 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5837 			      struct bpf_call_arg_meta *meta)
5838 {
5839 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5840 	bool is_const = tnum_is_const(reg->var_off);
5841 	struct bpf_map *map = reg->map_ptr;
5842 	u64 val = reg->var_off.value;
5843 
5844 	if (!is_const) {
5845 		verbose(env,
5846 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5847 			regno);
5848 		return -EINVAL;
5849 	}
5850 	if (!map->btf) {
5851 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5852 			map->name);
5853 		return -EINVAL;
5854 	}
5855 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
5856 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5857 		return -EINVAL;
5858 	}
5859 	if (map->record->timer_off != val + reg->off) {
5860 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5861 			val + reg->off, map->record->timer_off);
5862 		return -EINVAL;
5863 	}
5864 	if (meta->map_ptr) {
5865 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5866 		return -EFAULT;
5867 	}
5868 	meta->map_uid = reg->map_uid;
5869 	meta->map_ptr = map;
5870 	return 0;
5871 }
5872 
5873 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5874 			     struct bpf_call_arg_meta *meta)
5875 {
5876 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5877 	struct bpf_map *map_ptr = reg->map_ptr;
5878 	struct btf_field *kptr_field;
5879 	u32 kptr_off;
5880 
5881 	if (!tnum_is_const(reg->var_off)) {
5882 		verbose(env,
5883 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5884 			regno);
5885 		return -EINVAL;
5886 	}
5887 	if (!map_ptr->btf) {
5888 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5889 			map_ptr->name);
5890 		return -EINVAL;
5891 	}
5892 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5893 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5894 		return -EINVAL;
5895 	}
5896 
5897 	meta->map_ptr = map_ptr;
5898 	kptr_off = reg->off + reg->var_off.value;
5899 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5900 	if (!kptr_field) {
5901 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5902 		return -EACCES;
5903 	}
5904 	if (kptr_field->type != BPF_KPTR_REF) {
5905 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5906 		return -EACCES;
5907 	}
5908 	meta->kptr_field = kptr_field;
5909 	return 0;
5910 }
5911 
5912 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
5913  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
5914  *
5915  * In both cases we deal with the first 8 bytes, but need to mark the next 8
5916  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
5917  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
5918  *
5919  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
5920  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
5921  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
5922  * mutate the view of the dynptr and also possibly destroy it. In the latter
5923  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
5924  * memory that dynptr points to.
5925  *
5926  * The verifier will keep track both levels of mutation (bpf_dynptr's in
5927  * reg->type and the memory's in reg->dynptr.type), but there is no support for
5928  * readonly dynptr view yet, hence only the first case is tracked and checked.
5929  *
5930  * This is consistent with how C applies the const modifier to a struct object,
5931  * where the pointer itself inside bpf_dynptr becomes const but not what it
5932  * points to.
5933  *
5934  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
5935  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
5936  */
5937 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
5938 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
5939 {
5940 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5941 
5942 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
5943 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
5944 	 */
5945 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
5946 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
5947 		return -EFAULT;
5948 	}
5949 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
5950 	 * check_func_arg_reg_off's logic. We only need to check offset
5951 	 * alignment for PTR_TO_STACK.
5952 	 */
5953 	if (reg->type == PTR_TO_STACK && (reg->off % BPF_REG_SIZE)) {
5954 		verbose(env, "cannot pass in dynptr at an offset=%d\n", reg->off);
5955 		return -EINVAL;
5956 	}
5957 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
5958 	 *		 constructing a mutable bpf_dynptr object.
5959 	 *
5960 	 *		 Currently, this is only possible with PTR_TO_STACK
5961 	 *		 pointing to a region of at least 16 bytes which doesn't
5962 	 *		 contain an existing bpf_dynptr.
5963 	 *
5964 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
5965 	 *		 mutated or destroyed. However, the memory it points to
5966 	 *		 may be mutated.
5967 	 *
5968 	 *  None       - Points to a initialized dynptr that can be mutated and
5969 	 *		 destroyed, including mutation of the memory it points
5970 	 *		 to.
5971 	 */
5972 	if (arg_type & MEM_UNINIT) {
5973 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
5974 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
5975 			return -EINVAL;
5976 		}
5977 
5978 		/* We only support one dynptr being uninitialized at the moment,
5979 		 * which is sufficient for the helper functions we have right now.
5980 		 */
5981 		if (meta->uninit_dynptr_regno) {
5982 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
5983 			return -EFAULT;
5984 		}
5985 
5986 		meta->uninit_dynptr_regno = regno;
5987 	} else /* MEM_RDONLY and None case from above */ {
5988 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
5989 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
5990 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
5991 			return -EINVAL;
5992 		}
5993 
5994 		if (!is_dynptr_reg_valid_init(env, reg)) {
5995 			verbose(env,
5996 				"Expected an initialized dynptr as arg #%d\n",
5997 				regno);
5998 			return -EINVAL;
5999 		}
6000 
6001 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6002 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6003 			const char *err_extra = "";
6004 
6005 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6006 			case DYNPTR_TYPE_LOCAL:
6007 				err_extra = "local";
6008 				break;
6009 			case DYNPTR_TYPE_RINGBUF:
6010 				err_extra = "ringbuf";
6011 				break;
6012 			default:
6013 				err_extra = "<unknown>";
6014 				break;
6015 			}
6016 			verbose(env,
6017 				"Expected a dynptr of type %s as arg #%d\n",
6018 				err_extra, regno);
6019 			return -EINVAL;
6020 		}
6021 	}
6022 	return 0;
6023 }
6024 
6025 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6026 {
6027 	return type == ARG_CONST_SIZE ||
6028 	       type == ARG_CONST_SIZE_OR_ZERO;
6029 }
6030 
6031 static bool arg_type_is_release(enum bpf_arg_type type)
6032 {
6033 	return type & OBJ_RELEASE;
6034 }
6035 
6036 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6037 {
6038 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6039 }
6040 
6041 static int int_ptr_type_to_size(enum bpf_arg_type type)
6042 {
6043 	if (type == ARG_PTR_TO_INT)
6044 		return sizeof(u32);
6045 	else if (type == ARG_PTR_TO_LONG)
6046 		return sizeof(u64);
6047 
6048 	return -EINVAL;
6049 }
6050 
6051 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6052 				 const struct bpf_call_arg_meta *meta,
6053 				 enum bpf_arg_type *arg_type)
6054 {
6055 	if (!meta->map_ptr) {
6056 		/* kernel subsystem misconfigured verifier */
6057 		verbose(env, "invalid map_ptr to access map->type\n");
6058 		return -EACCES;
6059 	}
6060 
6061 	switch (meta->map_ptr->map_type) {
6062 	case BPF_MAP_TYPE_SOCKMAP:
6063 	case BPF_MAP_TYPE_SOCKHASH:
6064 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6065 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6066 		} else {
6067 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6068 			return -EINVAL;
6069 		}
6070 		break;
6071 	case BPF_MAP_TYPE_BLOOM_FILTER:
6072 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6073 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6074 		break;
6075 	default:
6076 		break;
6077 	}
6078 	return 0;
6079 }
6080 
6081 struct bpf_reg_types {
6082 	const enum bpf_reg_type types[10];
6083 	u32 *btf_id;
6084 };
6085 
6086 static const struct bpf_reg_types sock_types = {
6087 	.types = {
6088 		PTR_TO_SOCK_COMMON,
6089 		PTR_TO_SOCKET,
6090 		PTR_TO_TCP_SOCK,
6091 		PTR_TO_XDP_SOCK,
6092 	},
6093 };
6094 
6095 #ifdef CONFIG_NET
6096 static const struct bpf_reg_types btf_id_sock_common_types = {
6097 	.types = {
6098 		PTR_TO_SOCK_COMMON,
6099 		PTR_TO_SOCKET,
6100 		PTR_TO_TCP_SOCK,
6101 		PTR_TO_XDP_SOCK,
6102 		PTR_TO_BTF_ID,
6103 		PTR_TO_BTF_ID | PTR_TRUSTED,
6104 	},
6105 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6106 };
6107 #endif
6108 
6109 static const struct bpf_reg_types mem_types = {
6110 	.types = {
6111 		PTR_TO_STACK,
6112 		PTR_TO_PACKET,
6113 		PTR_TO_PACKET_META,
6114 		PTR_TO_MAP_KEY,
6115 		PTR_TO_MAP_VALUE,
6116 		PTR_TO_MEM,
6117 		PTR_TO_MEM | MEM_RINGBUF,
6118 		PTR_TO_BUF,
6119 	},
6120 };
6121 
6122 static const struct bpf_reg_types int_ptr_types = {
6123 	.types = {
6124 		PTR_TO_STACK,
6125 		PTR_TO_PACKET,
6126 		PTR_TO_PACKET_META,
6127 		PTR_TO_MAP_KEY,
6128 		PTR_TO_MAP_VALUE,
6129 	},
6130 };
6131 
6132 static const struct bpf_reg_types spin_lock_types = {
6133 	.types = {
6134 		PTR_TO_MAP_VALUE,
6135 		PTR_TO_BTF_ID | MEM_ALLOC,
6136 	}
6137 };
6138 
6139 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6140 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6141 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6142 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6143 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6144 static const struct bpf_reg_types btf_ptr_types = {
6145 	.types = {
6146 		PTR_TO_BTF_ID,
6147 		PTR_TO_BTF_ID | PTR_TRUSTED,
6148 		PTR_TO_BTF_ID | MEM_RCU,
6149 	},
6150 };
6151 static const struct bpf_reg_types percpu_btf_ptr_types = {
6152 	.types = {
6153 		PTR_TO_BTF_ID | MEM_PERCPU,
6154 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6155 	}
6156 };
6157 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6158 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6159 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6160 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6161 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6162 static const struct bpf_reg_types dynptr_types = {
6163 	.types = {
6164 		PTR_TO_STACK,
6165 		CONST_PTR_TO_DYNPTR,
6166 	}
6167 };
6168 
6169 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6170 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6171 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6172 	[ARG_CONST_SIZE]		= &scalar_types,
6173 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6174 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6175 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6176 	[ARG_PTR_TO_CTX]		= &context_types,
6177 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6178 #ifdef CONFIG_NET
6179 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6180 #endif
6181 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6182 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6183 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6184 	[ARG_PTR_TO_MEM]		= &mem_types,
6185 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6186 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6187 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6188 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6189 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6190 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6191 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6192 	[ARG_PTR_TO_TIMER]		= &timer_types,
6193 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6194 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6195 };
6196 
6197 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6198 			  enum bpf_arg_type arg_type,
6199 			  const u32 *arg_btf_id,
6200 			  struct bpf_call_arg_meta *meta)
6201 {
6202 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6203 	enum bpf_reg_type expected, type = reg->type;
6204 	const struct bpf_reg_types *compatible;
6205 	int i, j;
6206 
6207 	compatible = compatible_reg_types[base_type(arg_type)];
6208 	if (!compatible) {
6209 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6210 		return -EFAULT;
6211 	}
6212 
6213 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6214 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6215 	 *
6216 	 * Same for MAYBE_NULL:
6217 	 *
6218 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6219 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6220 	 *
6221 	 * Therefore we fold these flags depending on the arg_type before comparison.
6222 	 */
6223 	if (arg_type & MEM_RDONLY)
6224 		type &= ~MEM_RDONLY;
6225 	if (arg_type & PTR_MAYBE_NULL)
6226 		type &= ~PTR_MAYBE_NULL;
6227 
6228 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6229 		expected = compatible->types[i];
6230 		if (expected == NOT_INIT)
6231 			break;
6232 
6233 		if (type == expected)
6234 			goto found;
6235 	}
6236 
6237 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6238 	for (j = 0; j + 1 < i; j++)
6239 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6240 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6241 	return -EACCES;
6242 
6243 found:
6244 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6245 		/* For bpf_sk_release, it needs to match against first member
6246 		 * 'struct sock_common', hence make an exception for it. This
6247 		 * allows bpf_sk_release to work for multiple socket types.
6248 		 */
6249 		bool strict_type_match = arg_type_is_release(arg_type) &&
6250 					 meta->func_id != BPF_FUNC_sk_release;
6251 
6252 		if (!arg_btf_id) {
6253 			if (!compatible->btf_id) {
6254 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6255 				return -EFAULT;
6256 			}
6257 			arg_btf_id = compatible->btf_id;
6258 		}
6259 
6260 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6261 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6262 				return -EACCES;
6263 		} else {
6264 			if (arg_btf_id == BPF_PTR_POISON) {
6265 				verbose(env, "verifier internal error:");
6266 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6267 					regno);
6268 				return -EACCES;
6269 			}
6270 
6271 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6272 						  btf_vmlinux, *arg_btf_id,
6273 						  strict_type_match)) {
6274 				verbose(env, "R%d is of type %s but %s is expected\n",
6275 					regno, kernel_type_name(reg->btf, reg->btf_id),
6276 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6277 				return -EACCES;
6278 			}
6279 		}
6280 	} else if (type_is_alloc(reg->type)) {
6281 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6282 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6283 			return -EFAULT;
6284 		}
6285 	}
6286 
6287 	return 0;
6288 }
6289 
6290 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6291 			   const struct bpf_reg_state *reg, int regno,
6292 			   enum bpf_arg_type arg_type)
6293 {
6294 	u32 type = reg->type;
6295 
6296 	/* When referenced register is passed to release function, its fixed
6297 	 * offset must be 0.
6298 	 *
6299 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6300 	 * meta->release_regno.
6301 	 */
6302 	if (arg_type_is_release(arg_type)) {
6303 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6304 		 * may not directly point to the object being released, but to
6305 		 * dynptr pointing to such object, which might be at some offset
6306 		 * on the stack. In that case, we simply to fallback to the
6307 		 * default handling.
6308 		 */
6309 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6310 			return 0;
6311 		/* Doing check_ptr_off_reg check for the offset will catch this
6312 		 * because fixed_off_ok is false, but checking here allows us
6313 		 * to give the user a better error message.
6314 		 */
6315 		if (reg->off) {
6316 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6317 				regno);
6318 			return -EINVAL;
6319 		}
6320 		return __check_ptr_off_reg(env, reg, regno, false);
6321 	}
6322 
6323 	switch (type) {
6324 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6325 	case PTR_TO_STACK:
6326 	case PTR_TO_PACKET:
6327 	case PTR_TO_PACKET_META:
6328 	case PTR_TO_MAP_KEY:
6329 	case PTR_TO_MAP_VALUE:
6330 	case PTR_TO_MEM:
6331 	case PTR_TO_MEM | MEM_RDONLY:
6332 	case PTR_TO_MEM | MEM_RINGBUF:
6333 	case PTR_TO_BUF:
6334 	case PTR_TO_BUF | MEM_RDONLY:
6335 	case SCALAR_VALUE:
6336 		return 0;
6337 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6338 	 * fixed offset.
6339 	 */
6340 	case PTR_TO_BTF_ID:
6341 	case PTR_TO_BTF_ID | MEM_ALLOC:
6342 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6343 	case PTR_TO_BTF_ID | MEM_RCU:
6344 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6345 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6346 		 * its fixed offset must be 0. In the other cases, fixed offset
6347 		 * can be non-zero. This was already checked above. So pass
6348 		 * fixed_off_ok as true to allow fixed offset for all other
6349 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6350 		 * still need to do checks instead of returning.
6351 		 */
6352 		return __check_ptr_off_reg(env, reg, regno, true);
6353 	default:
6354 		return __check_ptr_off_reg(env, reg, regno, false);
6355 	}
6356 }
6357 
6358 static u32 dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6359 {
6360 	struct bpf_func_state *state = func(env, reg);
6361 	int spi;
6362 
6363 	if (reg->type == CONST_PTR_TO_DYNPTR)
6364 		return reg->ref_obj_id;
6365 
6366 	spi = get_spi(reg->off);
6367 	return state->stack[spi].spilled_ptr.ref_obj_id;
6368 }
6369 
6370 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6371 			  struct bpf_call_arg_meta *meta,
6372 			  const struct bpf_func_proto *fn)
6373 {
6374 	u32 regno = BPF_REG_1 + arg;
6375 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6376 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6377 	enum bpf_reg_type type = reg->type;
6378 	u32 *arg_btf_id = NULL;
6379 	int err = 0;
6380 
6381 	if (arg_type == ARG_DONTCARE)
6382 		return 0;
6383 
6384 	err = check_reg_arg(env, regno, SRC_OP);
6385 	if (err)
6386 		return err;
6387 
6388 	if (arg_type == ARG_ANYTHING) {
6389 		if (is_pointer_value(env, regno)) {
6390 			verbose(env, "R%d leaks addr into helper function\n",
6391 				regno);
6392 			return -EACCES;
6393 		}
6394 		return 0;
6395 	}
6396 
6397 	if (type_is_pkt_pointer(type) &&
6398 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6399 		verbose(env, "helper access to the packet is not allowed\n");
6400 		return -EACCES;
6401 	}
6402 
6403 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6404 		err = resolve_map_arg_type(env, meta, &arg_type);
6405 		if (err)
6406 			return err;
6407 	}
6408 
6409 	if (register_is_null(reg) && type_may_be_null(arg_type))
6410 		/* A NULL register has a SCALAR_VALUE type, so skip
6411 		 * type checking.
6412 		 */
6413 		goto skip_type_check;
6414 
6415 	/* arg_btf_id and arg_size are in a union. */
6416 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6417 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6418 		arg_btf_id = fn->arg_btf_id[arg];
6419 
6420 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6421 	if (err)
6422 		return err;
6423 
6424 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6425 	if (err)
6426 		return err;
6427 
6428 skip_type_check:
6429 	if (arg_type_is_release(arg_type)) {
6430 		if (arg_type_is_dynptr(arg_type)) {
6431 			struct bpf_func_state *state = func(env, reg);
6432 			int spi;
6433 
6434 			/* Only dynptr created on stack can be released, thus
6435 			 * the get_spi and stack state checks for spilled_ptr
6436 			 * should only be done before process_dynptr_func for
6437 			 * PTR_TO_STACK.
6438 			 */
6439 			if (reg->type == PTR_TO_STACK) {
6440 				spi = get_spi(reg->off);
6441 				if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6442 				    !state->stack[spi].spilled_ptr.ref_obj_id) {
6443 					verbose(env, "arg %d is an unacquired reference\n", regno);
6444 					return -EINVAL;
6445 				}
6446 			} else {
6447 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6448 				return -EINVAL;
6449 			}
6450 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6451 			verbose(env, "R%d must be referenced when passed to release function\n",
6452 				regno);
6453 			return -EINVAL;
6454 		}
6455 		if (meta->release_regno) {
6456 			verbose(env, "verifier internal error: more than one release argument\n");
6457 			return -EFAULT;
6458 		}
6459 		meta->release_regno = regno;
6460 	}
6461 
6462 	if (reg->ref_obj_id) {
6463 		if (meta->ref_obj_id) {
6464 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6465 				regno, reg->ref_obj_id,
6466 				meta->ref_obj_id);
6467 			return -EFAULT;
6468 		}
6469 		meta->ref_obj_id = reg->ref_obj_id;
6470 	}
6471 
6472 	switch (base_type(arg_type)) {
6473 	case ARG_CONST_MAP_PTR:
6474 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6475 		if (meta->map_ptr) {
6476 			/* Use map_uid (which is unique id of inner map) to reject:
6477 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6478 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6479 			 * if (inner_map1 && inner_map2) {
6480 			 *     timer = bpf_map_lookup_elem(inner_map1);
6481 			 *     if (timer)
6482 			 *         // mismatch would have been allowed
6483 			 *         bpf_timer_init(timer, inner_map2);
6484 			 * }
6485 			 *
6486 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6487 			 */
6488 			if (meta->map_ptr != reg->map_ptr ||
6489 			    meta->map_uid != reg->map_uid) {
6490 				verbose(env,
6491 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6492 					meta->map_uid, reg->map_uid);
6493 				return -EINVAL;
6494 			}
6495 		}
6496 		meta->map_ptr = reg->map_ptr;
6497 		meta->map_uid = reg->map_uid;
6498 		break;
6499 	case ARG_PTR_TO_MAP_KEY:
6500 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6501 		 * check that [key, key + map->key_size) are within
6502 		 * stack limits and initialized
6503 		 */
6504 		if (!meta->map_ptr) {
6505 			/* in function declaration map_ptr must come before
6506 			 * map_key, so that it's verified and known before
6507 			 * we have to check map_key here. Otherwise it means
6508 			 * that kernel subsystem misconfigured verifier
6509 			 */
6510 			verbose(env, "invalid map_ptr to access map->key\n");
6511 			return -EACCES;
6512 		}
6513 		err = check_helper_mem_access(env, regno,
6514 					      meta->map_ptr->key_size, false,
6515 					      NULL);
6516 		break;
6517 	case ARG_PTR_TO_MAP_VALUE:
6518 		if (type_may_be_null(arg_type) && register_is_null(reg))
6519 			return 0;
6520 
6521 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6522 		 * check [value, value + map->value_size) validity
6523 		 */
6524 		if (!meta->map_ptr) {
6525 			/* kernel subsystem misconfigured verifier */
6526 			verbose(env, "invalid map_ptr to access map->value\n");
6527 			return -EACCES;
6528 		}
6529 		meta->raw_mode = arg_type & MEM_UNINIT;
6530 		err = check_helper_mem_access(env, regno,
6531 					      meta->map_ptr->value_size, false,
6532 					      meta);
6533 		break;
6534 	case ARG_PTR_TO_PERCPU_BTF_ID:
6535 		if (!reg->btf_id) {
6536 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6537 			return -EACCES;
6538 		}
6539 		meta->ret_btf = reg->btf;
6540 		meta->ret_btf_id = reg->btf_id;
6541 		break;
6542 	case ARG_PTR_TO_SPIN_LOCK:
6543 		if (meta->func_id == BPF_FUNC_spin_lock) {
6544 			err = process_spin_lock(env, regno, true);
6545 			if (err)
6546 				return err;
6547 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6548 			err = process_spin_lock(env, regno, false);
6549 			if (err)
6550 				return err;
6551 		} else {
6552 			verbose(env, "verifier internal error\n");
6553 			return -EFAULT;
6554 		}
6555 		break;
6556 	case ARG_PTR_TO_TIMER:
6557 		err = process_timer_func(env, regno, meta);
6558 		if (err)
6559 			return err;
6560 		break;
6561 	case ARG_PTR_TO_FUNC:
6562 		meta->subprogno = reg->subprogno;
6563 		break;
6564 	case ARG_PTR_TO_MEM:
6565 		/* The access to this pointer is only checked when we hit the
6566 		 * next is_mem_size argument below.
6567 		 */
6568 		meta->raw_mode = arg_type & MEM_UNINIT;
6569 		if (arg_type & MEM_FIXED_SIZE) {
6570 			err = check_helper_mem_access(env, regno,
6571 						      fn->arg_size[arg], false,
6572 						      meta);
6573 		}
6574 		break;
6575 	case ARG_CONST_SIZE:
6576 		err = check_mem_size_reg(env, reg, regno, false, meta);
6577 		break;
6578 	case ARG_CONST_SIZE_OR_ZERO:
6579 		err = check_mem_size_reg(env, reg, regno, true, meta);
6580 		break;
6581 	case ARG_PTR_TO_DYNPTR:
6582 		err = process_dynptr_func(env, regno, arg_type, meta);
6583 		if (err)
6584 			return err;
6585 		break;
6586 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6587 		if (!tnum_is_const(reg->var_off)) {
6588 			verbose(env, "R%d is not a known constant'\n",
6589 				regno);
6590 			return -EACCES;
6591 		}
6592 		meta->mem_size = reg->var_off.value;
6593 		err = mark_chain_precision(env, regno);
6594 		if (err)
6595 			return err;
6596 		break;
6597 	case ARG_PTR_TO_INT:
6598 	case ARG_PTR_TO_LONG:
6599 	{
6600 		int size = int_ptr_type_to_size(arg_type);
6601 
6602 		err = check_helper_mem_access(env, regno, size, false, meta);
6603 		if (err)
6604 			return err;
6605 		err = check_ptr_alignment(env, reg, 0, size, true);
6606 		break;
6607 	}
6608 	case ARG_PTR_TO_CONST_STR:
6609 	{
6610 		struct bpf_map *map = reg->map_ptr;
6611 		int map_off;
6612 		u64 map_addr;
6613 		char *str_ptr;
6614 
6615 		if (!bpf_map_is_rdonly(map)) {
6616 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6617 			return -EACCES;
6618 		}
6619 
6620 		if (!tnum_is_const(reg->var_off)) {
6621 			verbose(env, "R%d is not a constant address'\n", regno);
6622 			return -EACCES;
6623 		}
6624 
6625 		if (!map->ops->map_direct_value_addr) {
6626 			verbose(env, "no direct value access support for this map type\n");
6627 			return -EACCES;
6628 		}
6629 
6630 		err = check_map_access(env, regno, reg->off,
6631 				       map->value_size - reg->off, false,
6632 				       ACCESS_HELPER);
6633 		if (err)
6634 			return err;
6635 
6636 		map_off = reg->off + reg->var_off.value;
6637 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6638 		if (err) {
6639 			verbose(env, "direct value access on string failed\n");
6640 			return err;
6641 		}
6642 
6643 		str_ptr = (char *)(long)(map_addr);
6644 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6645 			verbose(env, "string is not zero-terminated\n");
6646 			return -EINVAL;
6647 		}
6648 		break;
6649 	}
6650 	case ARG_PTR_TO_KPTR:
6651 		err = process_kptr_func(env, regno, meta);
6652 		if (err)
6653 			return err;
6654 		break;
6655 	}
6656 
6657 	return err;
6658 }
6659 
6660 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6661 {
6662 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6663 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6664 
6665 	if (func_id != BPF_FUNC_map_update_elem)
6666 		return false;
6667 
6668 	/* It's not possible to get access to a locked struct sock in these
6669 	 * contexts, so updating is safe.
6670 	 */
6671 	switch (type) {
6672 	case BPF_PROG_TYPE_TRACING:
6673 		if (eatype == BPF_TRACE_ITER)
6674 			return true;
6675 		break;
6676 	case BPF_PROG_TYPE_SOCKET_FILTER:
6677 	case BPF_PROG_TYPE_SCHED_CLS:
6678 	case BPF_PROG_TYPE_SCHED_ACT:
6679 	case BPF_PROG_TYPE_XDP:
6680 	case BPF_PROG_TYPE_SK_REUSEPORT:
6681 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6682 	case BPF_PROG_TYPE_SK_LOOKUP:
6683 		return true;
6684 	default:
6685 		break;
6686 	}
6687 
6688 	verbose(env, "cannot update sockmap in this context\n");
6689 	return false;
6690 }
6691 
6692 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6693 {
6694 	return env->prog->jit_requested &&
6695 	       bpf_jit_supports_subprog_tailcalls();
6696 }
6697 
6698 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6699 					struct bpf_map *map, int func_id)
6700 {
6701 	if (!map)
6702 		return 0;
6703 
6704 	/* We need a two way check, first is from map perspective ... */
6705 	switch (map->map_type) {
6706 	case BPF_MAP_TYPE_PROG_ARRAY:
6707 		if (func_id != BPF_FUNC_tail_call)
6708 			goto error;
6709 		break;
6710 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6711 		if (func_id != BPF_FUNC_perf_event_read &&
6712 		    func_id != BPF_FUNC_perf_event_output &&
6713 		    func_id != BPF_FUNC_skb_output &&
6714 		    func_id != BPF_FUNC_perf_event_read_value &&
6715 		    func_id != BPF_FUNC_xdp_output)
6716 			goto error;
6717 		break;
6718 	case BPF_MAP_TYPE_RINGBUF:
6719 		if (func_id != BPF_FUNC_ringbuf_output &&
6720 		    func_id != BPF_FUNC_ringbuf_reserve &&
6721 		    func_id != BPF_FUNC_ringbuf_query &&
6722 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6723 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6724 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6725 			goto error;
6726 		break;
6727 	case BPF_MAP_TYPE_USER_RINGBUF:
6728 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6729 			goto error;
6730 		break;
6731 	case BPF_MAP_TYPE_STACK_TRACE:
6732 		if (func_id != BPF_FUNC_get_stackid)
6733 			goto error;
6734 		break;
6735 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6736 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6737 		    func_id != BPF_FUNC_current_task_under_cgroup)
6738 			goto error;
6739 		break;
6740 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6741 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6742 		if (func_id != BPF_FUNC_get_local_storage)
6743 			goto error;
6744 		break;
6745 	case BPF_MAP_TYPE_DEVMAP:
6746 	case BPF_MAP_TYPE_DEVMAP_HASH:
6747 		if (func_id != BPF_FUNC_redirect_map &&
6748 		    func_id != BPF_FUNC_map_lookup_elem)
6749 			goto error;
6750 		break;
6751 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6752 	 * appear.
6753 	 */
6754 	case BPF_MAP_TYPE_CPUMAP:
6755 		if (func_id != BPF_FUNC_redirect_map)
6756 			goto error;
6757 		break;
6758 	case BPF_MAP_TYPE_XSKMAP:
6759 		if (func_id != BPF_FUNC_redirect_map &&
6760 		    func_id != BPF_FUNC_map_lookup_elem)
6761 			goto error;
6762 		break;
6763 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6764 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6765 		if (func_id != BPF_FUNC_map_lookup_elem)
6766 			goto error;
6767 		break;
6768 	case BPF_MAP_TYPE_SOCKMAP:
6769 		if (func_id != BPF_FUNC_sk_redirect_map &&
6770 		    func_id != BPF_FUNC_sock_map_update &&
6771 		    func_id != BPF_FUNC_map_delete_elem &&
6772 		    func_id != BPF_FUNC_msg_redirect_map &&
6773 		    func_id != BPF_FUNC_sk_select_reuseport &&
6774 		    func_id != BPF_FUNC_map_lookup_elem &&
6775 		    !may_update_sockmap(env, func_id))
6776 			goto error;
6777 		break;
6778 	case BPF_MAP_TYPE_SOCKHASH:
6779 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6780 		    func_id != BPF_FUNC_sock_hash_update &&
6781 		    func_id != BPF_FUNC_map_delete_elem &&
6782 		    func_id != BPF_FUNC_msg_redirect_hash &&
6783 		    func_id != BPF_FUNC_sk_select_reuseport &&
6784 		    func_id != BPF_FUNC_map_lookup_elem &&
6785 		    !may_update_sockmap(env, func_id))
6786 			goto error;
6787 		break;
6788 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6789 		if (func_id != BPF_FUNC_sk_select_reuseport)
6790 			goto error;
6791 		break;
6792 	case BPF_MAP_TYPE_QUEUE:
6793 	case BPF_MAP_TYPE_STACK:
6794 		if (func_id != BPF_FUNC_map_peek_elem &&
6795 		    func_id != BPF_FUNC_map_pop_elem &&
6796 		    func_id != BPF_FUNC_map_push_elem)
6797 			goto error;
6798 		break;
6799 	case BPF_MAP_TYPE_SK_STORAGE:
6800 		if (func_id != BPF_FUNC_sk_storage_get &&
6801 		    func_id != BPF_FUNC_sk_storage_delete)
6802 			goto error;
6803 		break;
6804 	case BPF_MAP_TYPE_INODE_STORAGE:
6805 		if (func_id != BPF_FUNC_inode_storage_get &&
6806 		    func_id != BPF_FUNC_inode_storage_delete)
6807 			goto error;
6808 		break;
6809 	case BPF_MAP_TYPE_TASK_STORAGE:
6810 		if (func_id != BPF_FUNC_task_storage_get &&
6811 		    func_id != BPF_FUNC_task_storage_delete)
6812 			goto error;
6813 		break;
6814 	case BPF_MAP_TYPE_CGRP_STORAGE:
6815 		if (func_id != BPF_FUNC_cgrp_storage_get &&
6816 		    func_id != BPF_FUNC_cgrp_storage_delete)
6817 			goto error;
6818 		break;
6819 	case BPF_MAP_TYPE_BLOOM_FILTER:
6820 		if (func_id != BPF_FUNC_map_peek_elem &&
6821 		    func_id != BPF_FUNC_map_push_elem)
6822 			goto error;
6823 		break;
6824 	default:
6825 		break;
6826 	}
6827 
6828 	/* ... and second from the function itself. */
6829 	switch (func_id) {
6830 	case BPF_FUNC_tail_call:
6831 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6832 			goto error;
6833 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6834 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6835 			return -EINVAL;
6836 		}
6837 		break;
6838 	case BPF_FUNC_perf_event_read:
6839 	case BPF_FUNC_perf_event_output:
6840 	case BPF_FUNC_perf_event_read_value:
6841 	case BPF_FUNC_skb_output:
6842 	case BPF_FUNC_xdp_output:
6843 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6844 			goto error;
6845 		break;
6846 	case BPF_FUNC_ringbuf_output:
6847 	case BPF_FUNC_ringbuf_reserve:
6848 	case BPF_FUNC_ringbuf_query:
6849 	case BPF_FUNC_ringbuf_reserve_dynptr:
6850 	case BPF_FUNC_ringbuf_submit_dynptr:
6851 	case BPF_FUNC_ringbuf_discard_dynptr:
6852 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6853 			goto error;
6854 		break;
6855 	case BPF_FUNC_user_ringbuf_drain:
6856 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6857 			goto error;
6858 		break;
6859 	case BPF_FUNC_get_stackid:
6860 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6861 			goto error;
6862 		break;
6863 	case BPF_FUNC_current_task_under_cgroup:
6864 	case BPF_FUNC_skb_under_cgroup:
6865 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6866 			goto error;
6867 		break;
6868 	case BPF_FUNC_redirect_map:
6869 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6870 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6871 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6872 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6873 			goto error;
6874 		break;
6875 	case BPF_FUNC_sk_redirect_map:
6876 	case BPF_FUNC_msg_redirect_map:
6877 	case BPF_FUNC_sock_map_update:
6878 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6879 			goto error;
6880 		break;
6881 	case BPF_FUNC_sk_redirect_hash:
6882 	case BPF_FUNC_msg_redirect_hash:
6883 	case BPF_FUNC_sock_hash_update:
6884 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6885 			goto error;
6886 		break;
6887 	case BPF_FUNC_get_local_storage:
6888 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6889 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6890 			goto error;
6891 		break;
6892 	case BPF_FUNC_sk_select_reuseport:
6893 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6894 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6895 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6896 			goto error;
6897 		break;
6898 	case BPF_FUNC_map_pop_elem:
6899 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6900 		    map->map_type != BPF_MAP_TYPE_STACK)
6901 			goto error;
6902 		break;
6903 	case BPF_FUNC_map_peek_elem:
6904 	case BPF_FUNC_map_push_elem:
6905 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6906 		    map->map_type != BPF_MAP_TYPE_STACK &&
6907 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6908 			goto error;
6909 		break;
6910 	case BPF_FUNC_map_lookup_percpu_elem:
6911 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6912 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6913 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6914 			goto error;
6915 		break;
6916 	case BPF_FUNC_sk_storage_get:
6917 	case BPF_FUNC_sk_storage_delete:
6918 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6919 			goto error;
6920 		break;
6921 	case BPF_FUNC_inode_storage_get:
6922 	case BPF_FUNC_inode_storage_delete:
6923 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6924 			goto error;
6925 		break;
6926 	case BPF_FUNC_task_storage_get:
6927 	case BPF_FUNC_task_storage_delete:
6928 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6929 			goto error;
6930 		break;
6931 	case BPF_FUNC_cgrp_storage_get:
6932 	case BPF_FUNC_cgrp_storage_delete:
6933 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6934 			goto error;
6935 		break;
6936 	default:
6937 		break;
6938 	}
6939 
6940 	return 0;
6941 error:
6942 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6943 		map->map_type, func_id_name(func_id), func_id);
6944 	return -EINVAL;
6945 }
6946 
6947 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6948 {
6949 	int count = 0;
6950 
6951 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6952 		count++;
6953 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6954 		count++;
6955 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6956 		count++;
6957 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6958 		count++;
6959 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6960 		count++;
6961 
6962 	/* We only support one arg being in raw mode at the moment,
6963 	 * which is sufficient for the helper functions we have
6964 	 * right now.
6965 	 */
6966 	return count <= 1;
6967 }
6968 
6969 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6970 {
6971 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6972 	bool has_size = fn->arg_size[arg] != 0;
6973 	bool is_next_size = false;
6974 
6975 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6976 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6977 
6978 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6979 		return is_next_size;
6980 
6981 	return has_size == is_next_size || is_next_size == is_fixed;
6982 }
6983 
6984 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6985 {
6986 	/* bpf_xxx(..., buf, len) call will access 'len'
6987 	 * bytes from memory 'buf'. Both arg types need
6988 	 * to be paired, so make sure there's no buggy
6989 	 * helper function specification.
6990 	 */
6991 	if (arg_type_is_mem_size(fn->arg1_type) ||
6992 	    check_args_pair_invalid(fn, 0) ||
6993 	    check_args_pair_invalid(fn, 1) ||
6994 	    check_args_pair_invalid(fn, 2) ||
6995 	    check_args_pair_invalid(fn, 3) ||
6996 	    check_args_pair_invalid(fn, 4))
6997 		return false;
6998 
6999 	return true;
7000 }
7001 
7002 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7003 {
7004 	int i;
7005 
7006 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7007 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7008 			return !!fn->arg_btf_id[i];
7009 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7010 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7011 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7012 		    /* arg_btf_id and arg_size are in a union. */
7013 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7014 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7015 			return false;
7016 	}
7017 
7018 	return true;
7019 }
7020 
7021 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7022 {
7023 	return check_raw_mode_ok(fn) &&
7024 	       check_arg_pair_ok(fn) &&
7025 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7026 }
7027 
7028 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7029  * are now invalid, so turn them into unknown SCALAR_VALUE.
7030  */
7031 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7032 {
7033 	struct bpf_func_state *state;
7034 	struct bpf_reg_state *reg;
7035 
7036 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7037 		if (reg_is_pkt_pointer_any(reg))
7038 			__mark_reg_unknown(env, reg);
7039 	}));
7040 }
7041 
7042 enum {
7043 	AT_PKT_END = -1,
7044 	BEYOND_PKT_END = -2,
7045 };
7046 
7047 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7048 {
7049 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7050 	struct bpf_reg_state *reg = &state->regs[regn];
7051 
7052 	if (reg->type != PTR_TO_PACKET)
7053 		/* PTR_TO_PACKET_META is not supported yet */
7054 		return;
7055 
7056 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7057 	 * How far beyond pkt_end it goes is unknown.
7058 	 * if (!range_open) it's the case of pkt >= pkt_end
7059 	 * if (range_open) it's the case of pkt > pkt_end
7060 	 * hence this pointer is at least 1 byte bigger than pkt_end
7061 	 */
7062 	if (range_open)
7063 		reg->range = BEYOND_PKT_END;
7064 	else
7065 		reg->range = AT_PKT_END;
7066 }
7067 
7068 /* The pointer with the specified id has released its reference to kernel
7069  * resources. Identify all copies of the same pointer and clear the reference.
7070  */
7071 static int release_reference(struct bpf_verifier_env *env,
7072 			     int ref_obj_id)
7073 {
7074 	struct bpf_func_state *state;
7075 	struct bpf_reg_state *reg;
7076 	int err;
7077 
7078 	err = release_reference_state(cur_func(env), ref_obj_id);
7079 	if (err)
7080 		return err;
7081 
7082 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7083 		if (reg->ref_obj_id == ref_obj_id) {
7084 			if (!env->allow_ptr_leaks)
7085 				__mark_reg_not_init(env, reg);
7086 			else
7087 				__mark_reg_unknown(env, reg);
7088 		}
7089 	}));
7090 
7091 	return 0;
7092 }
7093 
7094 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7095 				    struct bpf_reg_state *regs)
7096 {
7097 	int i;
7098 
7099 	/* after the call registers r0 - r5 were scratched */
7100 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7101 		mark_reg_not_init(env, regs, caller_saved[i]);
7102 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7103 	}
7104 }
7105 
7106 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7107 				   struct bpf_func_state *caller,
7108 				   struct bpf_func_state *callee,
7109 				   int insn_idx);
7110 
7111 static int set_callee_state(struct bpf_verifier_env *env,
7112 			    struct bpf_func_state *caller,
7113 			    struct bpf_func_state *callee, int insn_idx);
7114 
7115 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7116 			     int *insn_idx, int subprog,
7117 			     set_callee_state_fn set_callee_state_cb)
7118 {
7119 	struct bpf_verifier_state *state = env->cur_state;
7120 	struct bpf_func_info_aux *func_info_aux;
7121 	struct bpf_func_state *caller, *callee;
7122 	int err;
7123 	bool is_global = false;
7124 
7125 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7126 		verbose(env, "the call stack of %d frames is too deep\n",
7127 			state->curframe + 2);
7128 		return -E2BIG;
7129 	}
7130 
7131 	caller = state->frame[state->curframe];
7132 	if (state->frame[state->curframe + 1]) {
7133 		verbose(env, "verifier bug. Frame %d already allocated\n",
7134 			state->curframe + 1);
7135 		return -EFAULT;
7136 	}
7137 
7138 	func_info_aux = env->prog->aux->func_info_aux;
7139 	if (func_info_aux)
7140 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7141 	err = btf_check_subprog_call(env, subprog, caller->regs);
7142 	if (err == -EFAULT)
7143 		return err;
7144 	if (is_global) {
7145 		if (err) {
7146 			verbose(env, "Caller passes invalid args into func#%d\n",
7147 				subprog);
7148 			return err;
7149 		} else {
7150 			if (env->log.level & BPF_LOG_LEVEL)
7151 				verbose(env,
7152 					"Func#%d is global and valid. Skipping.\n",
7153 					subprog);
7154 			clear_caller_saved_regs(env, caller->regs);
7155 
7156 			/* All global functions return a 64-bit SCALAR_VALUE */
7157 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7158 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7159 
7160 			/* continue with next insn after call */
7161 			return 0;
7162 		}
7163 	}
7164 
7165 	/* set_callee_state is used for direct subprog calls, but we are
7166 	 * interested in validating only BPF helpers that can call subprogs as
7167 	 * callbacks
7168 	 */
7169 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7170 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7171 			func_id_name(insn->imm), insn->imm);
7172 		return -EFAULT;
7173 	}
7174 
7175 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7176 	    insn->src_reg == 0 &&
7177 	    insn->imm == BPF_FUNC_timer_set_callback) {
7178 		struct bpf_verifier_state *async_cb;
7179 
7180 		/* there is no real recursion here. timer callbacks are async */
7181 		env->subprog_info[subprog].is_async_cb = true;
7182 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7183 					 *insn_idx, subprog);
7184 		if (!async_cb)
7185 			return -EFAULT;
7186 		callee = async_cb->frame[0];
7187 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7188 
7189 		/* Convert bpf_timer_set_callback() args into timer callback args */
7190 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7191 		if (err)
7192 			return err;
7193 
7194 		clear_caller_saved_regs(env, caller->regs);
7195 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7196 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7197 		/* continue with next insn after call */
7198 		return 0;
7199 	}
7200 
7201 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7202 	if (!callee)
7203 		return -ENOMEM;
7204 	state->frame[state->curframe + 1] = callee;
7205 
7206 	/* callee cannot access r0, r6 - r9 for reading and has to write
7207 	 * into its own stack before reading from it.
7208 	 * callee can read/write into caller's stack
7209 	 */
7210 	init_func_state(env, callee,
7211 			/* remember the callsite, it will be used by bpf_exit */
7212 			*insn_idx /* callsite */,
7213 			state->curframe + 1 /* frameno within this callchain */,
7214 			subprog /* subprog number within this prog */);
7215 
7216 	/* Transfer references to the callee */
7217 	err = copy_reference_state(callee, caller);
7218 	if (err)
7219 		goto err_out;
7220 
7221 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7222 	if (err)
7223 		goto err_out;
7224 
7225 	clear_caller_saved_regs(env, caller->regs);
7226 
7227 	/* only increment it after check_reg_arg() finished */
7228 	state->curframe++;
7229 
7230 	/* and go analyze first insn of the callee */
7231 	*insn_idx = env->subprog_info[subprog].start - 1;
7232 
7233 	if (env->log.level & BPF_LOG_LEVEL) {
7234 		verbose(env, "caller:\n");
7235 		print_verifier_state(env, caller, true);
7236 		verbose(env, "callee:\n");
7237 		print_verifier_state(env, callee, true);
7238 	}
7239 	return 0;
7240 
7241 err_out:
7242 	free_func_state(callee);
7243 	state->frame[state->curframe + 1] = NULL;
7244 	return err;
7245 }
7246 
7247 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7248 				   struct bpf_func_state *caller,
7249 				   struct bpf_func_state *callee)
7250 {
7251 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7252 	 *      void *callback_ctx, u64 flags);
7253 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7254 	 *      void *callback_ctx);
7255 	 */
7256 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7257 
7258 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7259 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7260 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7261 
7262 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7263 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7264 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7265 
7266 	/* pointer to stack or null */
7267 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7268 
7269 	/* unused */
7270 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7271 	return 0;
7272 }
7273 
7274 static int set_callee_state(struct bpf_verifier_env *env,
7275 			    struct bpf_func_state *caller,
7276 			    struct bpf_func_state *callee, int insn_idx)
7277 {
7278 	int i;
7279 
7280 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7281 	 * pointers, which connects us up to the liveness chain
7282 	 */
7283 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7284 		callee->regs[i] = caller->regs[i];
7285 	return 0;
7286 }
7287 
7288 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7289 			   int *insn_idx)
7290 {
7291 	int subprog, target_insn;
7292 
7293 	target_insn = *insn_idx + insn->imm + 1;
7294 	subprog = find_subprog(env, target_insn);
7295 	if (subprog < 0) {
7296 		verbose(env, "verifier bug. No program starts at insn %d\n",
7297 			target_insn);
7298 		return -EFAULT;
7299 	}
7300 
7301 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7302 }
7303 
7304 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7305 				       struct bpf_func_state *caller,
7306 				       struct bpf_func_state *callee,
7307 				       int insn_idx)
7308 {
7309 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7310 	struct bpf_map *map;
7311 	int err;
7312 
7313 	if (bpf_map_ptr_poisoned(insn_aux)) {
7314 		verbose(env, "tail_call abusing map_ptr\n");
7315 		return -EINVAL;
7316 	}
7317 
7318 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7319 	if (!map->ops->map_set_for_each_callback_args ||
7320 	    !map->ops->map_for_each_callback) {
7321 		verbose(env, "callback function not allowed for map\n");
7322 		return -ENOTSUPP;
7323 	}
7324 
7325 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7326 	if (err)
7327 		return err;
7328 
7329 	callee->in_callback_fn = true;
7330 	callee->callback_ret_range = tnum_range(0, 1);
7331 	return 0;
7332 }
7333 
7334 static int set_loop_callback_state(struct bpf_verifier_env *env,
7335 				   struct bpf_func_state *caller,
7336 				   struct bpf_func_state *callee,
7337 				   int insn_idx)
7338 {
7339 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7340 	 *	    u64 flags);
7341 	 * callback_fn(u32 index, void *callback_ctx);
7342 	 */
7343 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7344 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7345 
7346 	/* unused */
7347 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7348 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7349 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7350 
7351 	callee->in_callback_fn = true;
7352 	callee->callback_ret_range = tnum_range(0, 1);
7353 	return 0;
7354 }
7355 
7356 static int set_timer_callback_state(struct bpf_verifier_env *env,
7357 				    struct bpf_func_state *caller,
7358 				    struct bpf_func_state *callee,
7359 				    int insn_idx)
7360 {
7361 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7362 
7363 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7364 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7365 	 */
7366 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7367 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7368 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7369 
7370 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7371 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7372 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7373 
7374 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7375 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7376 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7377 
7378 	/* unused */
7379 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7380 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7381 	callee->in_async_callback_fn = true;
7382 	callee->callback_ret_range = tnum_range(0, 1);
7383 	return 0;
7384 }
7385 
7386 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7387 				       struct bpf_func_state *caller,
7388 				       struct bpf_func_state *callee,
7389 				       int insn_idx)
7390 {
7391 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7392 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7393 	 * (callback_fn)(struct task_struct *task,
7394 	 *               struct vm_area_struct *vma, void *callback_ctx);
7395 	 */
7396 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7397 
7398 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7399 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7400 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7401 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7402 
7403 	/* pointer to stack or null */
7404 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7405 
7406 	/* unused */
7407 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7408 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7409 	callee->in_callback_fn = true;
7410 	callee->callback_ret_range = tnum_range(0, 1);
7411 	return 0;
7412 }
7413 
7414 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7415 					   struct bpf_func_state *caller,
7416 					   struct bpf_func_state *callee,
7417 					   int insn_idx)
7418 {
7419 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7420 	 *			  callback_ctx, u64 flags);
7421 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7422 	 */
7423 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7424 	mark_dynptr_cb_reg(&callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7425 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7426 
7427 	/* unused */
7428 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7429 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7430 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7431 
7432 	callee->in_callback_fn = true;
7433 	callee->callback_ret_range = tnum_range(0, 1);
7434 	return 0;
7435 }
7436 
7437 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7438 {
7439 	struct bpf_verifier_state *state = env->cur_state;
7440 	struct bpf_func_state *caller, *callee;
7441 	struct bpf_reg_state *r0;
7442 	int err;
7443 
7444 	callee = state->frame[state->curframe];
7445 	r0 = &callee->regs[BPF_REG_0];
7446 	if (r0->type == PTR_TO_STACK) {
7447 		/* technically it's ok to return caller's stack pointer
7448 		 * (or caller's caller's pointer) back to the caller,
7449 		 * since these pointers are valid. Only current stack
7450 		 * pointer will be invalid as soon as function exits,
7451 		 * but let's be conservative
7452 		 */
7453 		verbose(env, "cannot return stack pointer to the caller\n");
7454 		return -EINVAL;
7455 	}
7456 
7457 	caller = state->frame[state->curframe - 1];
7458 	if (callee->in_callback_fn) {
7459 		/* enforce R0 return value range [0, 1]. */
7460 		struct tnum range = callee->callback_ret_range;
7461 
7462 		if (r0->type != SCALAR_VALUE) {
7463 			verbose(env, "R0 not a scalar value\n");
7464 			return -EACCES;
7465 		}
7466 		if (!tnum_in(range, r0->var_off)) {
7467 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7468 			return -EINVAL;
7469 		}
7470 	} else {
7471 		/* return to the caller whatever r0 had in the callee */
7472 		caller->regs[BPF_REG_0] = *r0;
7473 	}
7474 
7475 	/* callback_fn frame should have released its own additions to parent's
7476 	 * reference state at this point, or check_reference_leak would
7477 	 * complain, hence it must be the same as the caller. There is no need
7478 	 * to copy it back.
7479 	 */
7480 	if (!callee->in_callback_fn) {
7481 		/* Transfer references to the caller */
7482 		err = copy_reference_state(caller, callee);
7483 		if (err)
7484 			return err;
7485 	}
7486 
7487 	*insn_idx = callee->callsite + 1;
7488 	if (env->log.level & BPF_LOG_LEVEL) {
7489 		verbose(env, "returning from callee:\n");
7490 		print_verifier_state(env, callee, true);
7491 		verbose(env, "to caller at %d:\n", *insn_idx);
7492 		print_verifier_state(env, caller, true);
7493 	}
7494 	/* clear everything in the callee */
7495 	free_func_state(callee);
7496 	state->frame[state->curframe--] = NULL;
7497 	return 0;
7498 }
7499 
7500 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7501 				   int func_id,
7502 				   struct bpf_call_arg_meta *meta)
7503 {
7504 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7505 
7506 	if (ret_type != RET_INTEGER ||
7507 	    (func_id != BPF_FUNC_get_stack &&
7508 	     func_id != BPF_FUNC_get_task_stack &&
7509 	     func_id != BPF_FUNC_probe_read_str &&
7510 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7511 	     func_id != BPF_FUNC_probe_read_user_str))
7512 		return;
7513 
7514 	ret_reg->smax_value = meta->msize_max_value;
7515 	ret_reg->s32_max_value = meta->msize_max_value;
7516 	ret_reg->smin_value = -MAX_ERRNO;
7517 	ret_reg->s32_min_value = -MAX_ERRNO;
7518 	reg_bounds_sync(ret_reg);
7519 }
7520 
7521 static int
7522 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7523 		int func_id, int insn_idx)
7524 {
7525 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7526 	struct bpf_map *map = meta->map_ptr;
7527 
7528 	if (func_id != BPF_FUNC_tail_call &&
7529 	    func_id != BPF_FUNC_map_lookup_elem &&
7530 	    func_id != BPF_FUNC_map_update_elem &&
7531 	    func_id != BPF_FUNC_map_delete_elem &&
7532 	    func_id != BPF_FUNC_map_push_elem &&
7533 	    func_id != BPF_FUNC_map_pop_elem &&
7534 	    func_id != BPF_FUNC_map_peek_elem &&
7535 	    func_id != BPF_FUNC_for_each_map_elem &&
7536 	    func_id != BPF_FUNC_redirect_map &&
7537 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7538 		return 0;
7539 
7540 	if (map == NULL) {
7541 		verbose(env, "kernel subsystem misconfigured verifier\n");
7542 		return -EINVAL;
7543 	}
7544 
7545 	/* In case of read-only, some additional restrictions
7546 	 * need to be applied in order to prevent altering the
7547 	 * state of the map from program side.
7548 	 */
7549 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7550 	    (func_id == BPF_FUNC_map_delete_elem ||
7551 	     func_id == BPF_FUNC_map_update_elem ||
7552 	     func_id == BPF_FUNC_map_push_elem ||
7553 	     func_id == BPF_FUNC_map_pop_elem)) {
7554 		verbose(env, "write into map forbidden\n");
7555 		return -EACCES;
7556 	}
7557 
7558 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7559 		bpf_map_ptr_store(aux, meta->map_ptr,
7560 				  !meta->map_ptr->bypass_spec_v1);
7561 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7562 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7563 				  !meta->map_ptr->bypass_spec_v1);
7564 	return 0;
7565 }
7566 
7567 static int
7568 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7569 		int func_id, int insn_idx)
7570 {
7571 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7572 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7573 	struct bpf_map *map = meta->map_ptr;
7574 	u64 val, max;
7575 	int err;
7576 
7577 	if (func_id != BPF_FUNC_tail_call)
7578 		return 0;
7579 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7580 		verbose(env, "kernel subsystem misconfigured verifier\n");
7581 		return -EINVAL;
7582 	}
7583 
7584 	reg = &regs[BPF_REG_3];
7585 	val = reg->var_off.value;
7586 	max = map->max_entries;
7587 
7588 	if (!(register_is_const(reg) && val < max)) {
7589 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7590 		return 0;
7591 	}
7592 
7593 	err = mark_chain_precision(env, BPF_REG_3);
7594 	if (err)
7595 		return err;
7596 	if (bpf_map_key_unseen(aux))
7597 		bpf_map_key_store(aux, val);
7598 	else if (!bpf_map_key_poisoned(aux) &&
7599 		  bpf_map_key_immediate(aux) != val)
7600 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7601 	return 0;
7602 }
7603 
7604 static int check_reference_leak(struct bpf_verifier_env *env)
7605 {
7606 	struct bpf_func_state *state = cur_func(env);
7607 	bool refs_lingering = false;
7608 	int i;
7609 
7610 	if (state->frameno && !state->in_callback_fn)
7611 		return 0;
7612 
7613 	for (i = 0; i < state->acquired_refs; i++) {
7614 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7615 			continue;
7616 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7617 			state->refs[i].id, state->refs[i].insn_idx);
7618 		refs_lingering = true;
7619 	}
7620 	return refs_lingering ? -EINVAL : 0;
7621 }
7622 
7623 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7624 				   struct bpf_reg_state *regs)
7625 {
7626 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7627 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7628 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7629 	struct bpf_bprintf_data data = {};
7630 	int err, fmt_map_off, num_args;
7631 	u64 fmt_addr;
7632 	char *fmt;
7633 
7634 	/* data must be an array of u64 */
7635 	if (data_len_reg->var_off.value % 8)
7636 		return -EINVAL;
7637 	num_args = data_len_reg->var_off.value / 8;
7638 
7639 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7640 	 * and map_direct_value_addr is set.
7641 	 */
7642 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7643 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7644 						  fmt_map_off);
7645 	if (err) {
7646 		verbose(env, "verifier bug\n");
7647 		return -EFAULT;
7648 	}
7649 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7650 
7651 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7652 	 * can focus on validating the format specifiers.
7653 	 */
7654 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7655 	if (err < 0)
7656 		verbose(env, "Invalid format string\n");
7657 
7658 	return err;
7659 }
7660 
7661 static int check_get_func_ip(struct bpf_verifier_env *env)
7662 {
7663 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7664 	int func_id = BPF_FUNC_get_func_ip;
7665 
7666 	if (type == BPF_PROG_TYPE_TRACING) {
7667 		if (!bpf_prog_has_trampoline(env->prog)) {
7668 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7669 				func_id_name(func_id), func_id);
7670 			return -ENOTSUPP;
7671 		}
7672 		return 0;
7673 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7674 		return 0;
7675 	}
7676 
7677 	verbose(env, "func %s#%d not supported for program type %d\n",
7678 		func_id_name(func_id), func_id, type);
7679 	return -ENOTSUPP;
7680 }
7681 
7682 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7683 {
7684 	return &env->insn_aux_data[env->insn_idx];
7685 }
7686 
7687 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7688 {
7689 	struct bpf_reg_state *regs = cur_regs(env);
7690 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7691 	bool reg_is_null = register_is_null(reg);
7692 
7693 	if (reg_is_null)
7694 		mark_chain_precision(env, BPF_REG_4);
7695 
7696 	return reg_is_null;
7697 }
7698 
7699 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7700 {
7701 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7702 
7703 	if (!state->initialized) {
7704 		state->initialized = 1;
7705 		state->fit_for_inline = loop_flag_is_zero(env);
7706 		state->callback_subprogno = subprogno;
7707 		return;
7708 	}
7709 
7710 	if (!state->fit_for_inline)
7711 		return;
7712 
7713 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7714 				 state->callback_subprogno == subprogno);
7715 }
7716 
7717 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7718 			     int *insn_idx_p)
7719 {
7720 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7721 	const struct bpf_func_proto *fn = NULL;
7722 	enum bpf_return_type ret_type;
7723 	enum bpf_type_flag ret_flag;
7724 	struct bpf_reg_state *regs;
7725 	struct bpf_call_arg_meta meta;
7726 	int insn_idx = *insn_idx_p;
7727 	bool changes_data;
7728 	int i, err, func_id;
7729 
7730 	/* find function prototype */
7731 	func_id = insn->imm;
7732 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7733 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7734 			func_id);
7735 		return -EINVAL;
7736 	}
7737 
7738 	if (env->ops->get_func_proto)
7739 		fn = env->ops->get_func_proto(func_id, env->prog);
7740 	if (!fn) {
7741 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7742 			func_id);
7743 		return -EINVAL;
7744 	}
7745 
7746 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7747 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7748 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7749 		return -EINVAL;
7750 	}
7751 
7752 	if (fn->allowed && !fn->allowed(env->prog)) {
7753 		verbose(env, "helper call is not allowed in probe\n");
7754 		return -EINVAL;
7755 	}
7756 
7757 	if (!env->prog->aux->sleepable && fn->might_sleep) {
7758 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
7759 		return -EINVAL;
7760 	}
7761 
7762 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7763 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7764 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7765 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7766 			func_id_name(func_id), func_id);
7767 		return -EINVAL;
7768 	}
7769 
7770 	memset(&meta, 0, sizeof(meta));
7771 	meta.pkt_access = fn->pkt_access;
7772 
7773 	err = check_func_proto(fn, func_id);
7774 	if (err) {
7775 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7776 			func_id_name(func_id), func_id);
7777 		return err;
7778 	}
7779 
7780 	if (env->cur_state->active_rcu_lock) {
7781 		if (fn->might_sleep) {
7782 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
7783 				func_id_name(func_id), func_id);
7784 			return -EINVAL;
7785 		}
7786 
7787 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
7788 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
7789 	}
7790 
7791 	meta.func_id = func_id;
7792 	/* check args */
7793 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7794 		err = check_func_arg(env, i, &meta, fn);
7795 		if (err)
7796 			return err;
7797 	}
7798 
7799 	err = record_func_map(env, &meta, func_id, insn_idx);
7800 	if (err)
7801 		return err;
7802 
7803 	err = record_func_key(env, &meta, func_id, insn_idx);
7804 	if (err)
7805 		return err;
7806 
7807 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7808 	 * is inferred from register state.
7809 	 */
7810 	for (i = 0; i < meta.access_size; i++) {
7811 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7812 				       BPF_WRITE, -1, false);
7813 		if (err)
7814 			return err;
7815 	}
7816 
7817 	regs = cur_regs(env);
7818 
7819 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7820 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
7821 	 * is safe to do directly.
7822 	 */
7823 	if (meta.uninit_dynptr_regno) {
7824 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
7825 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
7826 			return -EFAULT;
7827 		}
7828 		/* we write BPF_DW bits (8 bytes) at a time */
7829 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7830 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7831 					       i, BPF_DW, BPF_WRITE, -1, false);
7832 			if (err)
7833 				return err;
7834 		}
7835 
7836 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7837 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7838 					      insn_idx);
7839 		if (err)
7840 			return err;
7841 	}
7842 
7843 	if (meta.release_regno) {
7844 		err = -EINVAL;
7845 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7846 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
7847 		 * is safe to do directly.
7848 		 */
7849 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
7850 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
7851 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
7852 				return -EFAULT;
7853 			}
7854 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7855 		} else if (meta.ref_obj_id) {
7856 			err = release_reference(env, meta.ref_obj_id);
7857 		} else if (register_is_null(&regs[meta.release_regno])) {
7858 			/* meta.ref_obj_id can only be 0 if register that is meant to be
7859 			 * released is NULL, which must be > R0.
7860 			 */
7861 			err = 0;
7862 		}
7863 		if (err) {
7864 			verbose(env, "func %s#%d reference has not been acquired before\n",
7865 				func_id_name(func_id), func_id);
7866 			return err;
7867 		}
7868 	}
7869 
7870 	switch (func_id) {
7871 	case BPF_FUNC_tail_call:
7872 		err = check_reference_leak(env);
7873 		if (err) {
7874 			verbose(env, "tail_call would lead to reference leak\n");
7875 			return err;
7876 		}
7877 		break;
7878 	case BPF_FUNC_get_local_storage:
7879 		/* check that flags argument in get_local_storage(map, flags) is 0,
7880 		 * this is required because get_local_storage() can't return an error.
7881 		 */
7882 		if (!register_is_null(&regs[BPF_REG_2])) {
7883 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7884 			return -EINVAL;
7885 		}
7886 		break;
7887 	case BPF_FUNC_for_each_map_elem:
7888 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7889 					set_map_elem_callback_state);
7890 		break;
7891 	case BPF_FUNC_timer_set_callback:
7892 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7893 					set_timer_callback_state);
7894 		break;
7895 	case BPF_FUNC_find_vma:
7896 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7897 					set_find_vma_callback_state);
7898 		break;
7899 	case BPF_FUNC_snprintf:
7900 		err = check_bpf_snprintf_call(env, regs);
7901 		break;
7902 	case BPF_FUNC_loop:
7903 		update_loop_inline_state(env, meta.subprogno);
7904 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7905 					set_loop_callback_state);
7906 		break;
7907 	case BPF_FUNC_dynptr_from_mem:
7908 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7909 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7910 				reg_type_str(env, regs[BPF_REG_1].type));
7911 			return -EACCES;
7912 		}
7913 		break;
7914 	case BPF_FUNC_set_retval:
7915 		if (prog_type == BPF_PROG_TYPE_LSM &&
7916 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7917 			if (!env->prog->aux->attach_func_proto->type) {
7918 				/* Make sure programs that attach to void
7919 				 * hooks don't try to modify return value.
7920 				 */
7921 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7922 				return -EINVAL;
7923 			}
7924 		}
7925 		break;
7926 	case BPF_FUNC_dynptr_data:
7927 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7928 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7929 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7930 
7931 				if (meta.ref_obj_id) {
7932 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7933 					return -EFAULT;
7934 				}
7935 
7936 				meta.ref_obj_id = dynptr_ref_obj_id(env, reg);
7937 				break;
7938 			}
7939 		}
7940 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7941 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7942 			return -EFAULT;
7943 		}
7944 		break;
7945 	case BPF_FUNC_user_ringbuf_drain:
7946 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7947 					set_user_ringbuf_callback_state);
7948 		break;
7949 	}
7950 
7951 	if (err)
7952 		return err;
7953 
7954 	/* reset caller saved regs */
7955 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7956 		mark_reg_not_init(env, regs, caller_saved[i]);
7957 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7958 	}
7959 
7960 	/* helper call returns 64-bit value. */
7961 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7962 
7963 	/* update return register (already marked as written above) */
7964 	ret_type = fn->ret_type;
7965 	ret_flag = type_flag(ret_type);
7966 
7967 	switch (base_type(ret_type)) {
7968 	case RET_INTEGER:
7969 		/* sets type to SCALAR_VALUE */
7970 		mark_reg_unknown(env, regs, BPF_REG_0);
7971 		break;
7972 	case RET_VOID:
7973 		regs[BPF_REG_0].type = NOT_INIT;
7974 		break;
7975 	case RET_PTR_TO_MAP_VALUE:
7976 		/* There is no offset yet applied, variable or fixed */
7977 		mark_reg_known_zero(env, regs, BPF_REG_0);
7978 		/* remember map_ptr, so that check_map_access()
7979 		 * can check 'value_size' boundary of memory access
7980 		 * to map element returned from bpf_map_lookup_elem()
7981 		 */
7982 		if (meta.map_ptr == NULL) {
7983 			verbose(env,
7984 				"kernel subsystem misconfigured verifier\n");
7985 			return -EINVAL;
7986 		}
7987 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7988 		regs[BPF_REG_0].map_uid = meta.map_uid;
7989 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7990 		if (!type_may_be_null(ret_type) &&
7991 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7992 			regs[BPF_REG_0].id = ++env->id_gen;
7993 		}
7994 		break;
7995 	case RET_PTR_TO_SOCKET:
7996 		mark_reg_known_zero(env, regs, BPF_REG_0);
7997 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7998 		break;
7999 	case RET_PTR_TO_SOCK_COMMON:
8000 		mark_reg_known_zero(env, regs, BPF_REG_0);
8001 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8002 		break;
8003 	case RET_PTR_TO_TCP_SOCK:
8004 		mark_reg_known_zero(env, regs, BPF_REG_0);
8005 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8006 		break;
8007 	case RET_PTR_TO_MEM:
8008 		mark_reg_known_zero(env, regs, BPF_REG_0);
8009 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8010 		regs[BPF_REG_0].mem_size = meta.mem_size;
8011 		break;
8012 	case RET_PTR_TO_MEM_OR_BTF_ID:
8013 	{
8014 		const struct btf_type *t;
8015 
8016 		mark_reg_known_zero(env, regs, BPF_REG_0);
8017 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8018 		if (!btf_type_is_struct(t)) {
8019 			u32 tsize;
8020 			const struct btf_type *ret;
8021 			const char *tname;
8022 
8023 			/* resolve the type size of ksym. */
8024 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8025 			if (IS_ERR(ret)) {
8026 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8027 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8028 					tname, PTR_ERR(ret));
8029 				return -EINVAL;
8030 			}
8031 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8032 			regs[BPF_REG_0].mem_size = tsize;
8033 		} else {
8034 			/* MEM_RDONLY may be carried from ret_flag, but it
8035 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8036 			 * it will confuse the check of PTR_TO_BTF_ID in
8037 			 * check_mem_access().
8038 			 */
8039 			ret_flag &= ~MEM_RDONLY;
8040 
8041 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8042 			regs[BPF_REG_0].btf = meta.ret_btf;
8043 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8044 		}
8045 		break;
8046 	}
8047 	case RET_PTR_TO_BTF_ID:
8048 	{
8049 		struct btf *ret_btf;
8050 		int ret_btf_id;
8051 
8052 		mark_reg_known_zero(env, regs, BPF_REG_0);
8053 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8054 		if (func_id == BPF_FUNC_kptr_xchg) {
8055 			ret_btf = meta.kptr_field->kptr.btf;
8056 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8057 		} else {
8058 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8059 				verbose(env, "verifier internal error:");
8060 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8061 					func_id_name(func_id));
8062 				return -EINVAL;
8063 			}
8064 			ret_btf = btf_vmlinux;
8065 			ret_btf_id = *fn->ret_btf_id;
8066 		}
8067 		if (ret_btf_id == 0) {
8068 			verbose(env, "invalid return type %u of func %s#%d\n",
8069 				base_type(ret_type), func_id_name(func_id),
8070 				func_id);
8071 			return -EINVAL;
8072 		}
8073 		regs[BPF_REG_0].btf = ret_btf;
8074 		regs[BPF_REG_0].btf_id = ret_btf_id;
8075 		break;
8076 	}
8077 	default:
8078 		verbose(env, "unknown return type %u of func %s#%d\n",
8079 			base_type(ret_type), func_id_name(func_id), func_id);
8080 		return -EINVAL;
8081 	}
8082 
8083 	if (type_may_be_null(regs[BPF_REG_0].type))
8084 		regs[BPF_REG_0].id = ++env->id_gen;
8085 
8086 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8087 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8088 			func_id_name(func_id), func_id);
8089 		return -EFAULT;
8090 	}
8091 
8092 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8093 		/* For release_reference() */
8094 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8095 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8096 		int id = acquire_reference_state(env, insn_idx);
8097 
8098 		if (id < 0)
8099 			return id;
8100 		/* For mark_ptr_or_null_reg() */
8101 		regs[BPF_REG_0].id = id;
8102 		/* For release_reference() */
8103 		regs[BPF_REG_0].ref_obj_id = id;
8104 	}
8105 
8106 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8107 
8108 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8109 	if (err)
8110 		return err;
8111 
8112 	if ((func_id == BPF_FUNC_get_stack ||
8113 	     func_id == BPF_FUNC_get_task_stack) &&
8114 	    !env->prog->has_callchain_buf) {
8115 		const char *err_str;
8116 
8117 #ifdef CONFIG_PERF_EVENTS
8118 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8119 		err_str = "cannot get callchain buffer for func %s#%d\n";
8120 #else
8121 		err = -ENOTSUPP;
8122 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8123 #endif
8124 		if (err) {
8125 			verbose(env, err_str, func_id_name(func_id), func_id);
8126 			return err;
8127 		}
8128 
8129 		env->prog->has_callchain_buf = true;
8130 	}
8131 
8132 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8133 		env->prog->call_get_stack = true;
8134 
8135 	if (func_id == BPF_FUNC_get_func_ip) {
8136 		if (check_get_func_ip(env))
8137 			return -ENOTSUPP;
8138 		env->prog->call_get_func_ip = true;
8139 	}
8140 
8141 	if (changes_data)
8142 		clear_all_pkt_pointers(env);
8143 	return 0;
8144 }
8145 
8146 /* mark_btf_func_reg_size() is used when the reg size is determined by
8147  * the BTF func_proto's return value size and argument.
8148  */
8149 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8150 				   size_t reg_size)
8151 {
8152 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8153 
8154 	if (regno == BPF_REG_0) {
8155 		/* Function return value */
8156 		reg->live |= REG_LIVE_WRITTEN;
8157 		reg->subreg_def = reg_size == sizeof(u64) ?
8158 			DEF_NOT_SUBREG : env->insn_idx + 1;
8159 	} else {
8160 		/* Function argument */
8161 		if (reg_size == sizeof(u64)) {
8162 			mark_insn_zext(env, reg);
8163 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8164 		} else {
8165 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8166 		}
8167 	}
8168 }
8169 
8170 struct bpf_kfunc_call_arg_meta {
8171 	/* In parameters */
8172 	struct btf *btf;
8173 	u32 func_id;
8174 	u32 kfunc_flags;
8175 	const struct btf_type *func_proto;
8176 	const char *func_name;
8177 	/* Out parameters */
8178 	u32 ref_obj_id;
8179 	u8 release_regno;
8180 	bool r0_rdonly;
8181 	u32 ret_btf_id;
8182 	u64 r0_size;
8183 	struct {
8184 		u64 value;
8185 		bool found;
8186 	} arg_constant;
8187 	struct {
8188 		struct btf *btf;
8189 		u32 btf_id;
8190 	} arg_obj_drop;
8191 	struct {
8192 		struct btf_field *field;
8193 	} arg_list_head;
8194 };
8195 
8196 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8197 {
8198 	return meta->kfunc_flags & KF_ACQUIRE;
8199 }
8200 
8201 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8202 {
8203 	return meta->kfunc_flags & KF_RET_NULL;
8204 }
8205 
8206 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8207 {
8208 	return meta->kfunc_flags & KF_RELEASE;
8209 }
8210 
8211 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8212 {
8213 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8214 }
8215 
8216 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8217 {
8218 	return meta->kfunc_flags & KF_SLEEPABLE;
8219 }
8220 
8221 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8222 {
8223 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8224 }
8225 
8226 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8227 {
8228 	return meta->kfunc_flags & KF_RCU;
8229 }
8230 
8231 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8232 {
8233 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8234 }
8235 
8236 static bool __kfunc_param_match_suffix(const struct btf *btf,
8237 				       const struct btf_param *arg,
8238 				       const char *suffix)
8239 {
8240 	int suffix_len = strlen(suffix), len;
8241 	const char *param_name;
8242 
8243 	/* In the future, this can be ported to use BTF tagging */
8244 	param_name = btf_name_by_offset(btf, arg->name_off);
8245 	if (str_is_empty(param_name))
8246 		return false;
8247 	len = strlen(param_name);
8248 	if (len < suffix_len)
8249 		return false;
8250 	param_name += len - suffix_len;
8251 	return !strncmp(param_name, suffix, suffix_len);
8252 }
8253 
8254 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8255 				  const struct btf_param *arg,
8256 				  const struct bpf_reg_state *reg)
8257 {
8258 	const struct btf_type *t;
8259 
8260 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8261 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8262 		return false;
8263 
8264 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8265 }
8266 
8267 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8268 {
8269 	return __kfunc_param_match_suffix(btf, arg, "__k");
8270 }
8271 
8272 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8273 {
8274 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8275 }
8276 
8277 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8278 {
8279 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8280 }
8281 
8282 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8283 					  const struct btf_param *arg,
8284 					  const char *name)
8285 {
8286 	int len, target_len = strlen(name);
8287 	const char *param_name;
8288 
8289 	param_name = btf_name_by_offset(btf, arg->name_off);
8290 	if (str_is_empty(param_name))
8291 		return false;
8292 	len = strlen(param_name);
8293 	if (len != target_len)
8294 		return false;
8295 	if (strcmp(param_name, name))
8296 		return false;
8297 
8298 	return true;
8299 }
8300 
8301 enum {
8302 	KF_ARG_DYNPTR_ID,
8303 	KF_ARG_LIST_HEAD_ID,
8304 	KF_ARG_LIST_NODE_ID,
8305 };
8306 
8307 BTF_ID_LIST(kf_arg_btf_ids)
8308 BTF_ID(struct, bpf_dynptr_kern)
8309 BTF_ID(struct, bpf_list_head)
8310 BTF_ID(struct, bpf_list_node)
8311 
8312 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8313 				    const struct btf_param *arg, int type)
8314 {
8315 	const struct btf_type *t;
8316 	u32 res_id;
8317 
8318 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8319 	if (!t)
8320 		return false;
8321 	if (!btf_type_is_ptr(t))
8322 		return false;
8323 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8324 	if (!t)
8325 		return false;
8326 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8327 }
8328 
8329 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8330 {
8331 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8332 }
8333 
8334 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8335 {
8336 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8337 }
8338 
8339 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8340 {
8341 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8342 }
8343 
8344 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8345 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8346 					const struct btf *btf,
8347 					const struct btf_type *t, int rec)
8348 {
8349 	const struct btf_type *member_type;
8350 	const struct btf_member *member;
8351 	u32 i;
8352 
8353 	if (!btf_type_is_struct(t))
8354 		return false;
8355 
8356 	for_each_member(i, t, member) {
8357 		const struct btf_array *array;
8358 
8359 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8360 		if (btf_type_is_struct(member_type)) {
8361 			if (rec >= 3) {
8362 				verbose(env, "max struct nesting depth exceeded\n");
8363 				return false;
8364 			}
8365 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8366 				return false;
8367 			continue;
8368 		}
8369 		if (btf_type_is_array(member_type)) {
8370 			array = btf_array(member_type);
8371 			if (!array->nelems)
8372 				return false;
8373 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8374 			if (!btf_type_is_scalar(member_type))
8375 				return false;
8376 			continue;
8377 		}
8378 		if (!btf_type_is_scalar(member_type))
8379 			return false;
8380 	}
8381 	return true;
8382 }
8383 
8384 
8385 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8386 #ifdef CONFIG_NET
8387 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8388 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8389 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8390 #endif
8391 };
8392 
8393 enum kfunc_ptr_arg_type {
8394 	KF_ARG_PTR_TO_CTX,
8395 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8396 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8397 	KF_ARG_PTR_TO_DYNPTR,
8398 	KF_ARG_PTR_TO_LIST_HEAD,
8399 	KF_ARG_PTR_TO_LIST_NODE,
8400 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8401 	KF_ARG_PTR_TO_MEM,
8402 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8403 };
8404 
8405 enum special_kfunc_type {
8406 	KF_bpf_obj_new_impl,
8407 	KF_bpf_obj_drop_impl,
8408 	KF_bpf_list_push_front,
8409 	KF_bpf_list_push_back,
8410 	KF_bpf_list_pop_front,
8411 	KF_bpf_list_pop_back,
8412 	KF_bpf_cast_to_kern_ctx,
8413 	KF_bpf_rdonly_cast,
8414 	KF_bpf_rcu_read_lock,
8415 	KF_bpf_rcu_read_unlock,
8416 };
8417 
8418 BTF_SET_START(special_kfunc_set)
8419 BTF_ID(func, bpf_obj_new_impl)
8420 BTF_ID(func, bpf_obj_drop_impl)
8421 BTF_ID(func, bpf_list_push_front)
8422 BTF_ID(func, bpf_list_push_back)
8423 BTF_ID(func, bpf_list_pop_front)
8424 BTF_ID(func, bpf_list_pop_back)
8425 BTF_ID(func, bpf_cast_to_kern_ctx)
8426 BTF_ID(func, bpf_rdonly_cast)
8427 BTF_SET_END(special_kfunc_set)
8428 
8429 BTF_ID_LIST(special_kfunc_list)
8430 BTF_ID(func, bpf_obj_new_impl)
8431 BTF_ID(func, bpf_obj_drop_impl)
8432 BTF_ID(func, bpf_list_push_front)
8433 BTF_ID(func, bpf_list_push_back)
8434 BTF_ID(func, bpf_list_pop_front)
8435 BTF_ID(func, bpf_list_pop_back)
8436 BTF_ID(func, bpf_cast_to_kern_ctx)
8437 BTF_ID(func, bpf_rdonly_cast)
8438 BTF_ID(func, bpf_rcu_read_lock)
8439 BTF_ID(func, bpf_rcu_read_unlock)
8440 
8441 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8442 {
8443 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8444 }
8445 
8446 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8447 {
8448 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8449 }
8450 
8451 static enum kfunc_ptr_arg_type
8452 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8453 		       struct bpf_kfunc_call_arg_meta *meta,
8454 		       const struct btf_type *t, const struct btf_type *ref_t,
8455 		       const char *ref_tname, const struct btf_param *args,
8456 		       int argno, int nargs)
8457 {
8458 	u32 regno = argno + 1;
8459 	struct bpf_reg_state *regs = cur_regs(env);
8460 	struct bpf_reg_state *reg = &regs[regno];
8461 	bool arg_mem_size = false;
8462 
8463 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8464 		return KF_ARG_PTR_TO_CTX;
8465 
8466 	/* In this function, we verify the kfunc's BTF as per the argument type,
8467 	 * leaving the rest of the verification with respect to the register
8468 	 * type to our caller. When a set of conditions hold in the BTF type of
8469 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8470 	 */
8471 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8472 		return KF_ARG_PTR_TO_CTX;
8473 
8474 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8475 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8476 
8477 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8478 		if (!btf_type_is_ptr(ref_t)) {
8479 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8480 			return -EINVAL;
8481 		}
8482 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8483 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8484 		if (!btf_type_is_struct(ref_t)) {
8485 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8486 				meta->func_name, btf_type_str(ref_t), ref_tname);
8487 			return -EINVAL;
8488 		}
8489 		return KF_ARG_PTR_TO_KPTR;
8490 	}
8491 
8492 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8493 		return KF_ARG_PTR_TO_DYNPTR;
8494 
8495 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8496 		return KF_ARG_PTR_TO_LIST_HEAD;
8497 
8498 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8499 		return KF_ARG_PTR_TO_LIST_NODE;
8500 
8501 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8502 		if (!btf_type_is_struct(ref_t)) {
8503 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8504 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8505 			return -EINVAL;
8506 		}
8507 		return KF_ARG_PTR_TO_BTF_ID;
8508 	}
8509 
8510 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8511 		arg_mem_size = true;
8512 
8513 	/* This is the catch all argument type of register types supported by
8514 	 * check_helper_mem_access. However, we only allow when argument type is
8515 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8516 	 * arg_mem_size is true, the pointer can be void *.
8517 	 */
8518 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8519 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8520 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8521 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8522 		return -EINVAL;
8523 	}
8524 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8525 }
8526 
8527 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8528 					struct bpf_reg_state *reg,
8529 					const struct btf_type *ref_t,
8530 					const char *ref_tname, u32 ref_id,
8531 					struct bpf_kfunc_call_arg_meta *meta,
8532 					int argno)
8533 {
8534 	const struct btf_type *reg_ref_t;
8535 	bool strict_type_match = false;
8536 	const struct btf *reg_btf;
8537 	const char *reg_ref_tname;
8538 	u32 reg_ref_id;
8539 
8540 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
8541 		reg_btf = reg->btf;
8542 		reg_ref_id = reg->btf_id;
8543 	} else {
8544 		reg_btf = btf_vmlinux;
8545 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8546 	}
8547 
8548 	if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8549 		strict_type_match = true;
8550 
8551 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8552 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8553 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8554 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8555 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8556 			btf_type_str(reg_ref_t), reg_ref_tname);
8557 		return -EINVAL;
8558 	}
8559 	return 0;
8560 }
8561 
8562 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8563 				      struct bpf_reg_state *reg,
8564 				      const struct btf_type *ref_t,
8565 				      const char *ref_tname,
8566 				      struct bpf_kfunc_call_arg_meta *meta,
8567 				      int argno)
8568 {
8569 	struct btf_field *kptr_field;
8570 
8571 	/* check_func_arg_reg_off allows var_off for
8572 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8573 	 * off_desc.
8574 	 */
8575 	if (!tnum_is_const(reg->var_off)) {
8576 		verbose(env, "arg#0 must have constant offset\n");
8577 		return -EINVAL;
8578 	}
8579 
8580 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8581 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8582 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8583 			reg->off + reg->var_off.value);
8584 		return -EINVAL;
8585 	}
8586 
8587 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8588 				  kptr_field->kptr.btf_id, true)) {
8589 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8590 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8591 		return -EINVAL;
8592 	}
8593 	return 0;
8594 }
8595 
8596 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8597 {
8598 	struct bpf_func_state *state = cur_func(env);
8599 	struct bpf_reg_state *reg;
8600 	int i;
8601 
8602 	/* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8603 	 * subprogs, no global functions. This means that the references would
8604 	 * not be released inside the critical section but they may be added to
8605 	 * the reference state, and the acquired_refs are never copied out for a
8606 	 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8607 	 * critical sections.
8608 	 */
8609 	if (!ref_obj_id) {
8610 		verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8611 		return -EFAULT;
8612 	}
8613 	for (i = 0; i < state->acquired_refs; i++) {
8614 		if (state->refs[i].id == ref_obj_id) {
8615 			if (state->refs[i].release_on_unlock) {
8616 				verbose(env, "verifier internal error: expected false release_on_unlock");
8617 				return -EFAULT;
8618 			}
8619 			state->refs[i].release_on_unlock = true;
8620 			/* Now mark everyone sharing same ref_obj_id as untrusted */
8621 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8622 				if (reg->ref_obj_id == ref_obj_id)
8623 					reg->type |= PTR_UNTRUSTED;
8624 			}));
8625 			return 0;
8626 		}
8627 	}
8628 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8629 	return -EFAULT;
8630 }
8631 
8632 /* Implementation details:
8633  *
8634  * Each register points to some region of memory, which we define as an
8635  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8636  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8637  * allocation. The lock and the data it protects are colocated in the same
8638  * memory region.
8639  *
8640  * Hence, everytime a register holds a pointer value pointing to such
8641  * allocation, the verifier preserves a unique reg->id for it.
8642  *
8643  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8644  * bpf_spin_lock is called.
8645  *
8646  * To enable this, lock state in the verifier captures two values:
8647  *	active_lock.ptr = Register's type specific pointer
8648  *	active_lock.id  = A unique ID for each register pointer value
8649  *
8650  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8651  * supported register types.
8652  *
8653  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8654  * allocated objects is the reg->btf pointer.
8655  *
8656  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8657  * can establish the provenance of the map value statically for each distinct
8658  * lookup into such maps. They always contain a single map value hence unique
8659  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8660  *
8661  * So, in case of global variables, they use array maps with max_entries = 1,
8662  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8663  * into the same map value as max_entries is 1, as described above).
8664  *
8665  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8666  * outer map pointer (in verifier context), but each lookup into an inner map
8667  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8668  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8669  * will get different reg->id assigned to each lookup, hence different
8670  * active_lock.id.
8671  *
8672  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8673  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8674  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8675  */
8676 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8677 {
8678 	void *ptr;
8679 	u32 id;
8680 
8681 	switch ((int)reg->type) {
8682 	case PTR_TO_MAP_VALUE:
8683 		ptr = reg->map_ptr;
8684 		break;
8685 	case PTR_TO_BTF_ID | MEM_ALLOC:
8686 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8687 		ptr = reg->btf;
8688 		break;
8689 	default:
8690 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
8691 		return -EFAULT;
8692 	}
8693 	id = reg->id;
8694 
8695 	if (!env->cur_state->active_lock.ptr)
8696 		return -EINVAL;
8697 	if (env->cur_state->active_lock.ptr != ptr ||
8698 	    env->cur_state->active_lock.id != id) {
8699 		verbose(env, "held lock and object are not in the same allocation\n");
8700 		return -EINVAL;
8701 	}
8702 	return 0;
8703 }
8704 
8705 static bool is_bpf_list_api_kfunc(u32 btf_id)
8706 {
8707 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8708 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8709 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8710 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8711 }
8712 
8713 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8714 					   struct bpf_reg_state *reg, u32 regno,
8715 					   struct bpf_kfunc_call_arg_meta *meta)
8716 {
8717 	struct btf_field *field;
8718 	struct btf_record *rec;
8719 	u32 list_head_off;
8720 
8721 	if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8722 		verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8723 		return -EFAULT;
8724 	}
8725 
8726 	if (!tnum_is_const(reg->var_off)) {
8727 		verbose(env,
8728 			"R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8729 			regno);
8730 		return -EINVAL;
8731 	}
8732 
8733 	rec = reg_btf_record(reg);
8734 	list_head_off = reg->off + reg->var_off.value;
8735 	field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8736 	if (!field) {
8737 		verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8738 		return -EINVAL;
8739 	}
8740 
8741 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8742 	if (check_reg_allocation_locked(env, reg)) {
8743 		verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8744 			rec->spin_lock_off);
8745 		return -EINVAL;
8746 	}
8747 
8748 	if (meta->arg_list_head.field) {
8749 		verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8750 		return -EFAULT;
8751 	}
8752 	meta->arg_list_head.field = field;
8753 	return 0;
8754 }
8755 
8756 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8757 					   struct bpf_reg_state *reg, u32 regno,
8758 					   struct bpf_kfunc_call_arg_meta *meta)
8759 {
8760 	const struct btf_type *et, *t;
8761 	struct btf_field *field;
8762 	struct btf_record *rec;
8763 	u32 list_node_off;
8764 
8765 	if (meta->btf != btf_vmlinux ||
8766 	    (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8767 	     meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8768 		verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8769 		return -EFAULT;
8770 	}
8771 
8772 	if (!tnum_is_const(reg->var_off)) {
8773 		verbose(env,
8774 			"R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8775 			regno);
8776 		return -EINVAL;
8777 	}
8778 
8779 	rec = reg_btf_record(reg);
8780 	list_node_off = reg->off + reg->var_off.value;
8781 	field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8782 	if (!field || field->offset != list_node_off) {
8783 		verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8784 		return -EINVAL;
8785 	}
8786 
8787 	field = meta->arg_list_head.field;
8788 
8789 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
8790 	t = btf_type_by_id(reg->btf, reg->btf_id);
8791 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
8792 				  field->graph_root.value_btf_id, true)) {
8793 		verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8794 			"in struct %s, but arg is at offset=%d in struct %s\n",
8795 			field->graph_root.node_offset,
8796 			btf_name_by_offset(field->graph_root.btf, et->name_off),
8797 			list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8798 		return -EINVAL;
8799 	}
8800 
8801 	if (list_node_off != field->graph_root.node_offset) {
8802 		verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8803 			list_node_off, field->graph_root.node_offset,
8804 			btf_name_by_offset(field->graph_root.btf, et->name_off));
8805 		return -EINVAL;
8806 	}
8807 	/* Set arg#1 for expiration after unlock */
8808 	return ref_set_release_on_unlock(env, reg->ref_obj_id);
8809 }
8810 
8811 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8812 {
8813 	const char *func_name = meta->func_name, *ref_tname;
8814 	const struct btf *btf = meta->btf;
8815 	const struct btf_param *args;
8816 	u32 i, nargs;
8817 	int ret;
8818 
8819 	args = (const struct btf_param *)(meta->func_proto + 1);
8820 	nargs = btf_type_vlen(meta->func_proto);
8821 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8822 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8823 			MAX_BPF_FUNC_REG_ARGS);
8824 		return -EINVAL;
8825 	}
8826 
8827 	/* Check that BTF function arguments match actual types that the
8828 	 * verifier sees.
8829 	 */
8830 	for (i = 0; i < nargs; i++) {
8831 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8832 		const struct btf_type *t, *ref_t, *resolve_ret;
8833 		enum bpf_arg_type arg_type = ARG_DONTCARE;
8834 		u32 regno = i + 1, ref_id, type_size;
8835 		bool is_ret_buf_sz = false;
8836 		int kf_arg_type;
8837 
8838 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8839 
8840 		if (is_kfunc_arg_ignore(btf, &args[i]))
8841 			continue;
8842 
8843 		if (btf_type_is_scalar(t)) {
8844 			if (reg->type != SCALAR_VALUE) {
8845 				verbose(env, "R%d is not a scalar\n", regno);
8846 				return -EINVAL;
8847 			}
8848 
8849 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8850 				if (meta->arg_constant.found) {
8851 					verbose(env, "verifier internal error: only one constant argument permitted\n");
8852 					return -EFAULT;
8853 				}
8854 				if (!tnum_is_const(reg->var_off)) {
8855 					verbose(env, "R%d must be a known constant\n", regno);
8856 					return -EINVAL;
8857 				}
8858 				ret = mark_chain_precision(env, regno);
8859 				if (ret < 0)
8860 					return ret;
8861 				meta->arg_constant.found = true;
8862 				meta->arg_constant.value = reg->var_off.value;
8863 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8864 				meta->r0_rdonly = true;
8865 				is_ret_buf_sz = true;
8866 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8867 				is_ret_buf_sz = true;
8868 			}
8869 
8870 			if (is_ret_buf_sz) {
8871 				if (meta->r0_size) {
8872 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8873 					return -EINVAL;
8874 				}
8875 
8876 				if (!tnum_is_const(reg->var_off)) {
8877 					verbose(env, "R%d is not a const\n", regno);
8878 					return -EINVAL;
8879 				}
8880 
8881 				meta->r0_size = reg->var_off.value;
8882 				ret = mark_chain_precision(env, regno);
8883 				if (ret)
8884 					return ret;
8885 			}
8886 			continue;
8887 		}
8888 
8889 		if (!btf_type_is_ptr(t)) {
8890 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8891 			return -EINVAL;
8892 		}
8893 
8894 		if (reg->ref_obj_id) {
8895 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
8896 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8897 					regno, reg->ref_obj_id,
8898 					meta->ref_obj_id);
8899 				return -EFAULT;
8900 			}
8901 			meta->ref_obj_id = reg->ref_obj_id;
8902 			if (is_kfunc_release(meta))
8903 				meta->release_regno = regno;
8904 		}
8905 
8906 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8907 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8908 
8909 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8910 		if (kf_arg_type < 0)
8911 			return kf_arg_type;
8912 
8913 		switch (kf_arg_type) {
8914 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8915 		case KF_ARG_PTR_TO_BTF_ID:
8916 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
8917 				break;
8918 
8919 			if (!is_trusted_reg(reg)) {
8920 				if (!is_kfunc_rcu(meta)) {
8921 					verbose(env, "R%d must be referenced or trusted\n", regno);
8922 					return -EINVAL;
8923 				}
8924 				if (!is_rcu_reg(reg)) {
8925 					verbose(env, "R%d must be a rcu pointer\n", regno);
8926 					return -EINVAL;
8927 				}
8928 			}
8929 
8930 			fallthrough;
8931 		case KF_ARG_PTR_TO_CTX:
8932 			/* Trusted arguments have the same offset checks as release arguments */
8933 			arg_type |= OBJ_RELEASE;
8934 			break;
8935 		case KF_ARG_PTR_TO_KPTR:
8936 		case KF_ARG_PTR_TO_DYNPTR:
8937 		case KF_ARG_PTR_TO_LIST_HEAD:
8938 		case KF_ARG_PTR_TO_LIST_NODE:
8939 		case KF_ARG_PTR_TO_MEM:
8940 		case KF_ARG_PTR_TO_MEM_SIZE:
8941 			/* Trusted by default */
8942 			break;
8943 		default:
8944 			WARN_ON_ONCE(1);
8945 			return -EFAULT;
8946 		}
8947 
8948 		if (is_kfunc_release(meta) && reg->ref_obj_id)
8949 			arg_type |= OBJ_RELEASE;
8950 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8951 		if (ret < 0)
8952 			return ret;
8953 
8954 		switch (kf_arg_type) {
8955 		case KF_ARG_PTR_TO_CTX:
8956 			if (reg->type != PTR_TO_CTX) {
8957 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8958 				return -EINVAL;
8959 			}
8960 
8961 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8962 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8963 				if (ret < 0)
8964 					return -EINVAL;
8965 				meta->ret_btf_id  = ret;
8966 			}
8967 			break;
8968 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8969 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8970 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
8971 				return -EINVAL;
8972 			}
8973 			if (!reg->ref_obj_id) {
8974 				verbose(env, "allocated object must be referenced\n");
8975 				return -EINVAL;
8976 			}
8977 			if (meta->btf == btf_vmlinux &&
8978 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8979 				meta->arg_obj_drop.btf = reg->btf;
8980 				meta->arg_obj_drop.btf_id = reg->btf_id;
8981 			}
8982 			break;
8983 		case KF_ARG_PTR_TO_KPTR:
8984 			if (reg->type != PTR_TO_MAP_VALUE) {
8985 				verbose(env, "arg#0 expected pointer to map value\n");
8986 				return -EINVAL;
8987 			}
8988 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8989 			if (ret < 0)
8990 				return ret;
8991 			break;
8992 		case KF_ARG_PTR_TO_DYNPTR:
8993 			if (reg->type != PTR_TO_STACK &&
8994 			    reg->type != CONST_PTR_TO_DYNPTR) {
8995 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
8996 				return -EINVAL;
8997 			}
8998 
8999 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
9000 			if (ret < 0)
9001 				return ret;
9002 			break;
9003 		case KF_ARG_PTR_TO_LIST_HEAD:
9004 			if (reg->type != PTR_TO_MAP_VALUE &&
9005 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9006 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9007 				return -EINVAL;
9008 			}
9009 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9010 				verbose(env, "allocated object must be referenced\n");
9011 				return -EINVAL;
9012 			}
9013 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9014 			if (ret < 0)
9015 				return ret;
9016 			break;
9017 		case KF_ARG_PTR_TO_LIST_NODE:
9018 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9019 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9020 				return -EINVAL;
9021 			}
9022 			if (!reg->ref_obj_id) {
9023 				verbose(env, "allocated object must be referenced\n");
9024 				return -EINVAL;
9025 			}
9026 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9027 			if (ret < 0)
9028 				return ret;
9029 			break;
9030 		case KF_ARG_PTR_TO_BTF_ID:
9031 			/* Only base_type is checked, further checks are done here */
9032 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9033 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9034 			    !reg2btf_ids[base_type(reg->type)]) {
9035 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9036 				verbose(env, "expected %s or socket\n",
9037 					reg_type_str(env, base_type(reg->type) |
9038 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9039 				return -EINVAL;
9040 			}
9041 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9042 			if (ret < 0)
9043 				return ret;
9044 			break;
9045 		case KF_ARG_PTR_TO_MEM:
9046 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9047 			if (IS_ERR(resolve_ret)) {
9048 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9049 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9050 				return -EINVAL;
9051 			}
9052 			ret = check_mem_reg(env, reg, regno, type_size);
9053 			if (ret < 0)
9054 				return ret;
9055 			break;
9056 		case KF_ARG_PTR_TO_MEM_SIZE:
9057 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9058 			if (ret < 0) {
9059 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9060 				return ret;
9061 			}
9062 			/* Skip next '__sz' argument */
9063 			i++;
9064 			break;
9065 		}
9066 	}
9067 
9068 	if (is_kfunc_release(meta) && !meta->release_regno) {
9069 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9070 			func_name);
9071 		return -EINVAL;
9072 	}
9073 
9074 	return 0;
9075 }
9076 
9077 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9078 			    int *insn_idx_p)
9079 {
9080 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9081 	struct bpf_reg_state *regs = cur_regs(env);
9082 	const char *func_name, *ptr_type_name;
9083 	bool sleepable, rcu_lock, rcu_unlock;
9084 	struct bpf_kfunc_call_arg_meta meta;
9085 	u32 i, nargs, func_id, ptr_type_id;
9086 	int err, insn_idx = *insn_idx_p;
9087 	const struct btf_param *args;
9088 	const struct btf_type *ret_t;
9089 	struct btf *desc_btf;
9090 	u32 *kfunc_flags;
9091 
9092 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9093 	if (!insn->imm)
9094 		return 0;
9095 
9096 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9097 	if (IS_ERR(desc_btf))
9098 		return PTR_ERR(desc_btf);
9099 
9100 	func_id = insn->imm;
9101 	func = btf_type_by_id(desc_btf, func_id);
9102 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9103 	func_proto = btf_type_by_id(desc_btf, func->type);
9104 
9105 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9106 	if (!kfunc_flags) {
9107 		verbose(env, "calling kernel function %s is not allowed\n",
9108 			func_name);
9109 		return -EACCES;
9110 	}
9111 
9112 	/* Prepare kfunc call metadata */
9113 	memset(&meta, 0, sizeof(meta));
9114 	meta.btf = desc_btf;
9115 	meta.func_id = func_id;
9116 	meta.kfunc_flags = *kfunc_flags;
9117 	meta.func_proto = func_proto;
9118 	meta.func_name = func_name;
9119 
9120 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9121 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9122 		return -EACCES;
9123 	}
9124 
9125 	sleepable = is_kfunc_sleepable(&meta);
9126 	if (sleepable && !env->prog->aux->sleepable) {
9127 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9128 		return -EACCES;
9129 	}
9130 
9131 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9132 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9133 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9134 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9135 		return -EACCES;
9136 	}
9137 
9138 	if (env->cur_state->active_rcu_lock) {
9139 		struct bpf_func_state *state;
9140 		struct bpf_reg_state *reg;
9141 
9142 		if (rcu_lock) {
9143 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9144 			return -EINVAL;
9145 		} else if (rcu_unlock) {
9146 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9147 				if (reg->type & MEM_RCU) {
9148 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9149 					reg->type |= PTR_UNTRUSTED;
9150 				}
9151 			}));
9152 			env->cur_state->active_rcu_lock = false;
9153 		} else if (sleepable) {
9154 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9155 			return -EACCES;
9156 		}
9157 	} else if (rcu_lock) {
9158 		env->cur_state->active_rcu_lock = true;
9159 	} else if (rcu_unlock) {
9160 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9161 		return -EINVAL;
9162 	}
9163 
9164 	/* Check the arguments */
9165 	err = check_kfunc_args(env, &meta);
9166 	if (err < 0)
9167 		return err;
9168 	/* In case of release function, we get register number of refcounted
9169 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9170 	 */
9171 	if (meta.release_regno) {
9172 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9173 		if (err) {
9174 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9175 				func_name, func_id);
9176 			return err;
9177 		}
9178 	}
9179 
9180 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9181 		mark_reg_not_init(env, regs, caller_saved[i]);
9182 
9183 	/* Check return type */
9184 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9185 
9186 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9187 		/* Only exception is bpf_obj_new_impl */
9188 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9189 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9190 			return -EINVAL;
9191 		}
9192 	}
9193 
9194 	if (btf_type_is_scalar(t)) {
9195 		mark_reg_unknown(env, regs, BPF_REG_0);
9196 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9197 	} else if (btf_type_is_ptr(t)) {
9198 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9199 
9200 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9201 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9202 				struct btf *ret_btf;
9203 				u32 ret_btf_id;
9204 
9205 				if (unlikely(!bpf_global_ma_set))
9206 					return -ENOMEM;
9207 
9208 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9209 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9210 					return -EINVAL;
9211 				}
9212 
9213 				ret_btf = env->prog->aux->btf;
9214 				ret_btf_id = meta.arg_constant.value;
9215 
9216 				/* This may be NULL due to user not supplying a BTF */
9217 				if (!ret_btf) {
9218 					verbose(env, "bpf_obj_new requires prog BTF\n");
9219 					return -EINVAL;
9220 				}
9221 
9222 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9223 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9224 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9225 					return -EINVAL;
9226 				}
9227 
9228 				mark_reg_known_zero(env, regs, BPF_REG_0);
9229 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9230 				regs[BPF_REG_0].btf = ret_btf;
9231 				regs[BPF_REG_0].btf_id = ret_btf_id;
9232 
9233 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9234 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9235 					btf_find_struct_meta(ret_btf, ret_btf_id);
9236 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9237 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9238 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9239 							     meta.arg_obj_drop.btf_id);
9240 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9241 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9242 				struct btf_field *field = meta.arg_list_head.field;
9243 
9244 				mark_reg_known_zero(env, regs, BPF_REG_0);
9245 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9246 				regs[BPF_REG_0].btf = field->graph_root.btf;
9247 				regs[BPF_REG_0].btf_id = field->graph_root.value_btf_id;
9248 				regs[BPF_REG_0].off = field->graph_root.node_offset;
9249 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9250 				mark_reg_known_zero(env, regs, BPF_REG_0);
9251 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9252 				regs[BPF_REG_0].btf = desc_btf;
9253 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9254 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9255 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9256 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9257 					verbose(env,
9258 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9259 					return -EINVAL;
9260 				}
9261 
9262 				mark_reg_known_zero(env, regs, BPF_REG_0);
9263 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9264 				regs[BPF_REG_0].btf = desc_btf;
9265 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9266 			} else {
9267 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9268 					meta.func_name);
9269 				return -EFAULT;
9270 			}
9271 		} else if (!__btf_type_is_struct(ptr_type)) {
9272 			if (!meta.r0_size) {
9273 				ptr_type_name = btf_name_by_offset(desc_btf,
9274 								   ptr_type->name_off);
9275 				verbose(env,
9276 					"kernel function %s returns pointer type %s %s is not supported\n",
9277 					func_name,
9278 					btf_type_str(ptr_type),
9279 					ptr_type_name);
9280 				return -EINVAL;
9281 			}
9282 
9283 			mark_reg_known_zero(env, regs, BPF_REG_0);
9284 			regs[BPF_REG_0].type = PTR_TO_MEM;
9285 			regs[BPF_REG_0].mem_size = meta.r0_size;
9286 
9287 			if (meta.r0_rdonly)
9288 				regs[BPF_REG_0].type |= MEM_RDONLY;
9289 
9290 			/* Ensures we don't access the memory after a release_reference() */
9291 			if (meta.ref_obj_id)
9292 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9293 		} else {
9294 			mark_reg_known_zero(env, regs, BPF_REG_0);
9295 			regs[BPF_REG_0].btf = desc_btf;
9296 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9297 			regs[BPF_REG_0].btf_id = ptr_type_id;
9298 		}
9299 
9300 		if (is_kfunc_ret_null(&meta)) {
9301 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9302 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9303 			regs[BPF_REG_0].id = ++env->id_gen;
9304 		}
9305 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9306 		if (is_kfunc_acquire(&meta)) {
9307 			int id = acquire_reference_state(env, insn_idx);
9308 
9309 			if (id < 0)
9310 				return id;
9311 			if (is_kfunc_ret_null(&meta))
9312 				regs[BPF_REG_0].id = id;
9313 			regs[BPF_REG_0].ref_obj_id = id;
9314 		}
9315 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9316 			regs[BPF_REG_0].id = ++env->id_gen;
9317 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9318 
9319 	nargs = btf_type_vlen(func_proto);
9320 	args = (const struct btf_param *)(func_proto + 1);
9321 	for (i = 0; i < nargs; i++) {
9322 		u32 regno = i + 1;
9323 
9324 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9325 		if (btf_type_is_ptr(t))
9326 			mark_btf_func_reg_size(env, regno, sizeof(void *));
9327 		else
9328 			/* scalar. ensured by btf_check_kfunc_arg_match() */
9329 			mark_btf_func_reg_size(env, regno, t->size);
9330 	}
9331 
9332 	return 0;
9333 }
9334 
9335 static bool signed_add_overflows(s64 a, s64 b)
9336 {
9337 	/* Do the add in u64, where overflow is well-defined */
9338 	s64 res = (s64)((u64)a + (u64)b);
9339 
9340 	if (b < 0)
9341 		return res > a;
9342 	return res < a;
9343 }
9344 
9345 static bool signed_add32_overflows(s32 a, s32 b)
9346 {
9347 	/* Do the add in u32, where overflow is well-defined */
9348 	s32 res = (s32)((u32)a + (u32)b);
9349 
9350 	if (b < 0)
9351 		return res > a;
9352 	return res < a;
9353 }
9354 
9355 static bool signed_sub_overflows(s64 a, s64 b)
9356 {
9357 	/* Do the sub in u64, where overflow is well-defined */
9358 	s64 res = (s64)((u64)a - (u64)b);
9359 
9360 	if (b < 0)
9361 		return res < a;
9362 	return res > a;
9363 }
9364 
9365 static bool signed_sub32_overflows(s32 a, s32 b)
9366 {
9367 	/* Do the sub in u32, where overflow is well-defined */
9368 	s32 res = (s32)((u32)a - (u32)b);
9369 
9370 	if (b < 0)
9371 		return res < a;
9372 	return res > a;
9373 }
9374 
9375 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9376 				  const struct bpf_reg_state *reg,
9377 				  enum bpf_reg_type type)
9378 {
9379 	bool known = tnum_is_const(reg->var_off);
9380 	s64 val = reg->var_off.value;
9381 	s64 smin = reg->smin_value;
9382 
9383 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9384 		verbose(env, "math between %s pointer and %lld is not allowed\n",
9385 			reg_type_str(env, type), val);
9386 		return false;
9387 	}
9388 
9389 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9390 		verbose(env, "%s pointer offset %d is not allowed\n",
9391 			reg_type_str(env, type), reg->off);
9392 		return false;
9393 	}
9394 
9395 	if (smin == S64_MIN) {
9396 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9397 			reg_type_str(env, type));
9398 		return false;
9399 	}
9400 
9401 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9402 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
9403 			smin, reg_type_str(env, type));
9404 		return false;
9405 	}
9406 
9407 	return true;
9408 }
9409 
9410 enum {
9411 	REASON_BOUNDS	= -1,
9412 	REASON_TYPE	= -2,
9413 	REASON_PATHS	= -3,
9414 	REASON_LIMIT	= -4,
9415 	REASON_STACK	= -5,
9416 };
9417 
9418 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9419 			      u32 *alu_limit, bool mask_to_left)
9420 {
9421 	u32 max = 0, ptr_limit = 0;
9422 
9423 	switch (ptr_reg->type) {
9424 	case PTR_TO_STACK:
9425 		/* Offset 0 is out-of-bounds, but acceptable start for the
9426 		 * left direction, see BPF_REG_FP. Also, unknown scalar
9427 		 * offset where we would need to deal with min/max bounds is
9428 		 * currently prohibited for unprivileged.
9429 		 */
9430 		max = MAX_BPF_STACK + mask_to_left;
9431 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9432 		break;
9433 	case PTR_TO_MAP_VALUE:
9434 		max = ptr_reg->map_ptr->value_size;
9435 		ptr_limit = (mask_to_left ?
9436 			     ptr_reg->smin_value :
9437 			     ptr_reg->umax_value) + ptr_reg->off;
9438 		break;
9439 	default:
9440 		return REASON_TYPE;
9441 	}
9442 
9443 	if (ptr_limit >= max)
9444 		return REASON_LIMIT;
9445 	*alu_limit = ptr_limit;
9446 	return 0;
9447 }
9448 
9449 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9450 				    const struct bpf_insn *insn)
9451 {
9452 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9453 }
9454 
9455 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9456 				       u32 alu_state, u32 alu_limit)
9457 {
9458 	/* If we arrived here from different branches with different
9459 	 * state or limits to sanitize, then this won't work.
9460 	 */
9461 	if (aux->alu_state &&
9462 	    (aux->alu_state != alu_state ||
9463 	     aux->alu_limit != alu_limit))
9464 		return REASON_PATHS;
9465 
9466 	/* Corresponding fixup done in do_misc_fixups(). */
9467 	aux->alu_state = alu_state;
9468 	aux->alu_limit = alu_limit;
9469 	return 0;
9470 }
9471 
9472 static int sanitize_val_alu(struct bpf_verifier_env *env,
9473 			    struct bpf_insn *insn)
9474 {
9475 	struct bpf_insn_aux_data *aux = cur_aux(env);
9476 
9477 	if (can_skip_alu_sanitation(env, insn))
9478 		return 0;
9479 
9480 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9481 }
9482 
9483 static bool sanitize_needed(u8 opcode)
9484 {
9485 	return opcode == BPF_ADD || opcode == BPF_SUB;
9486 }
9487 
9488 struct bpf_sanitize_info {
9489 	struct bpf_insn_aux_data aux;
9490 	bool mask_to_left;
9491 };
9492 
9493 static struct bpf_verifier_state *
9494 sanitize_speculative_path(struct bpf_verifier_env *env,
9495 			  const struct bpf_insn *insn,
9496 			  u32 next_idx, u32 curr_idx)
9497 {
9498 	struct bpf_verifier_state *branch;
9499 	struct bpf_reg_state *regs;
9500 
9501 	branch = push_stack(env, next_idx, curr_idx, true);
9502 	if (branch && insn) {
9503 		regs = branch->frame[branch->curframe]->regs;
9504 		if (BPF_SRC(insn->code) == BPF_K) {
9505 			mark_reg_unknown(env, regs, insn->dst_reg);
9506 		} else if (BPF_SRC(insn->code) == BPF_X) {
9507 			mark_reg_unknown(env, regs, insn->dst_reg);
9508 			mark_reg_unknown(env, regs, insn->src_reg);
9509 		}
9510 	}
9511 	return branch;
9512 }
9513 
9514 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9515 			    struct bpf_insn *insn,
9516 			    const struct bpf_reg_state *ptr_reg,
9517 			    const struct bpf_reg_state *off_reg,
9518 			    struct bpf_reg_state *dst_reg,
9519 			    struct bpf_sanitize_info *info,
9520 			    const bool commit_window)
9521 {
9522 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9523 	struct bpf_verifier_state *vstate = env->cur_state;
9524 	bool off_is_imm = tnum_is_const(off_reg->var_off);
9525 	bool off_is_neg = off_reg->smin_value < 0;
9526 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
9527 	u8 opcode = BPF_OP(insn->code);
9528 	u32 alu_state, alu_limit;
9529 	struct bpf_reg_state tmp;
9530 	bool ret;
9531 	int err;
9532 
9533 	if (can_skip_alu_sanitation(env, insn))
9534 		return 0;
9535 
9536 	/* We already marked aux for masking from non-speculative
9537 	 * paths, thus we got here in the first place. We only care
9538 	 * to explore bad access from here.
9539 	 */
9540 	if (vstate->speculative)
9541 		goto do_sim;
9542 
9543 	if (!commit_window) {
9544 		if (!tnum_is_const(off_reg->var_off) &&
9545 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9546 			return REASON_BOUNDS;
9547 
9548 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9549 				     (opcode == BPF_SUB && !off_is_neg);
9550 	}
9551 
9552 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9553 	if (err < 0)
9554 		return err;
9555 
9556 	if (commit_window) {
9557 		/* In commit phase we narrow the masking window based on
9558 		 * the observed pointer move after the simulated operation.
9559 		 */
9560 		alu_state = info->aux.alu_state;
9561 		alu_limit = abs(info->aux.alu_limit - alu_limit);
9562 	} else {
9563 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9564 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9565 		alu_state |= ptr_is_dst_reg ?
9566 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9567 
9568 		/* Limit pruning on unknown scalars to enable deep search for
9569 		 * potential masking differences from other program paths.
9570 		 */
9571 		if (!off_is_imm)
9572 			env->explore_alu_limits = true;
9573 	}
9574 
9575 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9576 	if (err < 0)
9577 		return err;
9578 do_sim:
9579 	/* If we're in commit phase, we're done here given we already
9580 	 * pushed the truncated dst_reg into the speculative verification
9581 	 * stack.
9582 	 *
9583 	 * Also, when register is a known constant, we rewrite register-based
9584 	 * operation to immediate-based, and thus do not need masking (and as
9585 	 * a consequence, do not need to simulate the zero-truncation either).
9586 	 */
9587 	if (commit_window || off_is_imm)
9588 		return 0;
9589 
9590 	/* Simulate and find potential out-of-bounds access under
9591 	 * speculative execution from truncation as a result of
9592 	 * masking when off was not within expected range. If off
9593 	 * sits in dst, then we temporarily need to move ptr there
9594 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9595 	 * for cases where we use K-based arithmetic in one direction
9596 	 * and truncated reg-based in the other in order to explore
9597 	 * bad access.
9598 	 */
9599 	if (!ptr_is_dst_reg) {
9600 		tmp = *dst_reg;
9601 		*dst_reg = *ptr_reg;
9602 	}
9603 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9604 					env->insn_idx);
9605 	if (!ptr_is_dst_reg && ret)
9606 		*dst_reg = tmp;
9607 	return !ret ? REASON_STACK : 0;
9608 }
9609 
9610 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9611 {
9612 	struct bpf_verifier_state *vstate = env->cur_state;
9613 
9614 	/* If we simulate paths under speculation, we don't update the
9615 	 * insn as 'seen' such that when we verify unreachable paths in
9616 	 * the non-speculative domain, sanitize_dead_code() can still
9617 	 * rewrite/sanitize them.
9618 	 */
9619 	if (!vstate->speculative)
9620 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9621 }
9622 
9623 static int sanitize_err(struct bpf_verifier_env *env,
9624 			const struct bpf_insn *insn, int reason,
9625 			const struct bpf_reg_state *off_reg,
9626 			const struct bpf_reg_state *dst_reg)
9627 {
9628 	static const char *err = "pointer arithmetic with it prohibited for !root";
9629 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9630 	u32 dst = insn->dst_reg, src = insn->src_reg;
9631 
9632 	switch (reason) {
9633 	case REASON_BOUNDS:
9634 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9635 			off_reg == dst_reg ? dst : src, err);
9636 		break;
9637 	case REASON_TYPE:
9638 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9639 			off_reg == dst_reg ? src : dst, err);
9640 		break;
9641 	case REASON_PATHS:
9642 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9643 			dst, op, err);
9644 		break;
9645 	case REASON_LIMIT:
9646 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9647 			dst, op, err);
9648 		break;
9649 	case REASON_STACK:
9650 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9651 			dst, err);
9652 		break;
9653 	default:
9654 		verbose(env, "verifier internal error: unknown reason (%d)\n",
9655 			reason);
9656 		break;
9657 	}
9658 
9659 	return -EACCES;
9660 }
9661 
9662 /* check that stack access falls within stack limits and that 'reg' doesn't
9663  * have a variable offset.
9664  *
9665  * Variable offset is prohibited for unprivileged mode for simplicity since it
9666  * requires corresponding support in Spectre masking for stack ALU.  See also
9667  * retrieve_ptr_limit().
9668  *
9669  *
9670  * 'off' includes 'reg->off'.
9671  */
9672 static int check_stack_access_for_ptr_arithmetic(
9673 				struct bpf_verifier_env *env,
9674 				int regno,
9675 				const struct bpf_reg_state *reg,
9676 				int off)
9677 {
9678 	if (!tnum_is_const(reg->var_off)) {
9679 		char tn_buf[48];
9680 
9681 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9682 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9683 			regno, tn_buf, off);
9684 		return -EACCES;
9685 	}
9686 
9687 	if (off >= 0 || off < -MAX_BPF_STACK) {
9688 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
9689 			"prohibited for !root; off=%d\n", regno, off);
9690 		return -EACCES;
9691 	}
9692 
9693 	return 0;
9694 }
9695 
9696 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9697 				 const struct bpf_insn *insn,
9698 				 const struct bpf_reg_state *dst_reg)
9699 {
9700 	u32 dst = insn->dst_reg;
9701 
9702 	/* For unprivileged we require that resulting offset must be in bounds
9703 	 * in order to be able to sanitize access later on.
9704 	 */
9705 	if (env->bypass_spec_v1)
9706 		return 0;
9707 
9708 	switch (dst_reg->type) {
9709 	case PTR_TO_STACK:
9710 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9711 					dst_reg->off + dst_reg->var_off.value))
9712 			return -EACCES;
9713 		break;
9714 	case PTR_TO_MAP_VALUE:
9715 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9716 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9717 				"prohibited for !root\n", dst);
9718 			return -EACCES;
9719 		}
9720 		break;
9721 	default:
9722 		break;
9723 	}
9724 
9725 	return 0;
9726 }
9727 
9728 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9729  * Caller should also handle BPF_MOV case separately.
9730  * If we return -EACCES, caller may want to try again treating pointer as a
9731  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9732  */
9733 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9734 				   struct bpf_insn *insn,
9735 				   const struct bpf_reg_state *ptr_reg,
9736 				   const struct bpf_reg_state *off_reg)
9737 {
9738 	struct bpf_verifier_state *vstate = env->cur_state;
9739 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9740 	struct bpf_reg_state *regs = state->regs, *dst_reg;
9741 	bool known = tnum_is_const(off_reg->var_off);
9742 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9743 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9744 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9745 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9746 	struct bpf_sanitize_info info = {};
9747 	u8 opcode = BPF_OP(insn->code);
9748 	u32 dst = insn->dst_reg;
9749 	int ret;
9750 
9751 	dst_reg = &regs[dst];
9752 
9753 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9754 	    smin_val > smax_val || umin_val > umax_val) {
9755 		/* Taint dst register if offset had invalid bounds derived from
9756 		 * e.g. dead branches.
9757 		 */
9758 		__mark_reg_unknown(env, dst_reg);
9759 		return 0;
9760 	}
9761 
9762 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
9763 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
9764 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9765 			__mark_reg_unknown(env, dst_reg);
9766 			return 0;
9767 		}
9768 
9769 		verbose(env,
9770 			"R%d 32-bit pointer arithmetic prohibited\n",
9771 			dst);
9772 		return -EACCES;
9773 	}
9774 
9775 	if (ptr_reg->type & PTR_MAYBE_NULL) {
9776 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9777 			dst, reg_type_str(env, ptr_reg->type));
9778 		return -EACCES;
9779 	}
9780 
9781 	switch (base_type(ptr_reg->type)) {
9782 	case CONST_PTR_TO_MAP:
9783 		/* smin_val represents the known value */
9784 		if (known && smin_val == 0 && opcode == BPF_ADD)
9785 			break;
9786 		fallthrough;
9787 	case PTR_TO_PACKET_END:
9788 	case PTR_TO_SOCKET:
9789 	case PTR_TO_SOCK_COMMON:
9790 	case PTR_TO_TCP_SOCK:
9791 	case PTR_TO_XDP_SOCK:
9792 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9793 			dst, reg_type_str(env, ptr_reg->type));
9794 		return -EACCES;
9795 	default:
9796 		break;
9797 	}
9798 
9799 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9800 	 * The id may be overwritten later if we create a new variable offset.
9801 	 */
9802 	dst_reg->type = ptr_reg->type;
9803 	dst_reg->id = ptr_reg->id;
9804 
9805 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9806 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9807 		return -EINVAL;
9808 
9809 	/* pointer types do not carry 32-bit bounds at the moment. */
9810 	__mark_reg32_unbounded(dst_reg);
9811 
9812 	if (sanitize_needed(opcode)) {
9813 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9814 				       &info, false);
9815 		if (ret < 0)
9816 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9817 	}
9818 
9819 	switch (opcode) {
9820 	case BPF_ADD:
9821 		/* We can take a fixed offset as long as it doesn't overflow
9822 		 * the s32 'off' field
9823 		 */
9824 		if (known && (ptr_reg->off + smin_val ==
9825 			      (s64)(s32)(ptr_reg->off + smin_val))) {
9826 			/* pointer += K.  Accumulate it into fixed offset */
9827 			dst_reg->smin_value = smin_ptr;
9828 			dst_reg->smax_value = smax_ptr;
9829 			dst_reg->umin_value = umin_ptr;
9830 			dst_reg->umax_value = umax_ptr;
9831 			dst_reg->var_off = ptr_reg->var_off;
9832 			dst_reg->off = ptr_reg->off + smin_val;
9833 			dst_reg->raw = ptr_reg->raw;
9834 			break;
9835 		}
9836 		/* A new variable offset is created.  Note that off_reg->off
9837 		 * == 0, since it's a scalar.
9838 		 * dst_reg gets the pointer type and since some positive
9839 		 * integer value was added to the pointer, give it a new 'id'
9840 		 * if it's a PTR_TO_PACKET.
9841 		 * this creates a new 'base' pointer, off_reg (variable) gets
9842 		 * added into the variable offset, and we copy the fixed offset
9843 		 * from ptr_reg.
9844 		 */
9845 		if (signed_add_overflows(smin_ptr, smin_val) ||
9846 		    signed_add_overflows(smax_ptr, smax_val)) {
9847 			dst_reg->smin_value = S64_MIN;
9848 			dst_reg->smax_value = S64_MAX;
9849 		} else {
9850 			dst_reg->smin_value = smin_ptr + smin_val;
9851 			dst_reg->smax_value = smax_ptr + smax_val;
9852 		}
9853 		if (umin_ptr + umin_val < umin_ptr ||
9854 		    umax_ptr + umax_val < umax_ptr) {
9855 			dst_reg->umin_value = 0;
9856 			dst_reg->umax_value = U64_MAX;
9857 		} else {
9858 			dst_reg->umin_value = umin_ptr + umin_val;
9859 			dst_reg->umax_value = umax_ptr + umax_val;
9860 		}
9861 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9862 		dst_reg->off = ptr_reg->off;
9863 		dst_reg->raw = ptr_reg->raw;
9864 		if (reg_is_pkt_pointer(ptr_reg)) {
9865 			dst_reg->id = ++env->id_gen;
9866 			/* something was added to pkt_ptr, set range to zero */
9867 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9868 		}
9869 		break;
9870 	case BPF_SUB:
9871 		if (dst_reg == off_reg) {
9872 			/* scalar -= pointer.  Creates an unknown scalar */
9873 			verbose(env, "R%d tried to subtract pointer from scalar\n",
9874 				dst);
9875 			return -EACCES;
9876 		}
9877 		/* We don't allow subtraction from FP, because (according to
9878 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
9879 		 * be able to deal with it.
9880 		 */
9881 		if (ptr_reg->type == PTR_TO_STACK) {
9882 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
9883 				dst);
9884 			return -EACCES;
9885 		}
9886 		if (known && (ptr_reg->off - smin_val ==
9887 			      (s64)(s32)(ptr_reg->off - smin_val))) {
9888 			/* pointer -= K.  Subtract it from fixed offset */
9889 			dst_reg->smin_value = smin_ptr;
9890 			dst_reg->smax_value = smax_ptr;
9891 			dst_reg->umin_value = umin_ptr;
9892 			dst_reg->umax_value = umax_ptr;
9893 			dst_reg->var_off = ptr_reg->var_off;
9894 			dst_reg->id = ptr_reg->id;
9895 			dst_reg->off = ptr_reg->off - smin_val;
9896 			dst_reg->raw = ptr_reg->raw;
9897 			break;
9898 		}
9899 		/* A new variable offset is created.  If the subtrahend is known
9900 		 * nonnegative, then any reg->range we had before is still good.
9901 		 */
9902 		if (signed_sub_overflows(smin_ptr, smax_val) ||
9903 		    signed_sub_overflows(smax_ptr, smin_val)) {
9904 			/* Overflow possible, we know nothing */
9905 			dst_reg->smin_value = S64_MIN;
9906 			dst_reg->smax_value = S64_MAX;
9907 		} else {
9908 			dst_reg->smin_value = smin_ptr - smax_val;
9909 			dst_reg->smax_value = smax_ptr - smin_val;
9910 		}
9911 		if (umin_ptr < umax_val) {
9912 			/* Overflow possible, we know nothing */
9913 			dst_reg->umin_value = 0;
9914 			dst_reg->umax_value = U64_MAX;
9915 		} else {
9916 			/* Cannot overflow (as long as bounds are consistent) */
9917 			dst_reg->umin_value = umin_ptr - umax_val;
9918 			dst_reg->umax_value = umax_ptr - umin_val;
9919 		}
9920 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9921 		dst_reg->off = ptr_reg->off;
9922 		dst_reg->raw = ptr_reg->raw;
9923 		if (reg_is_pkt_pointer(ptr_reg)) {
9924 			dst_reg->id = ++env->id_gen;
9925 			/* something was added to pkt_ptr, set range to zero */
9926 			if (smin_val < 0)
9927 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9928 		}
9929 		break;
9930 	case BPF_AND:
9931 	case BPF_OR:
9932 	case BPF_XOR:
9933 		/* bitwise ops on pointers are troublesome, prohibit. */
9934 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9935 			dst, bpf_alu_string[opcode >> 4]);
9936 		return -EACCES;
9937 	default:
9938 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
9939 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9940 			dst, bpf_alu_string[opcode >> 4]);
9941 		return -EACCES;
9942 	}
9943 
9944 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9945 		return -EINVAL;
9946 	reg_bounds_sync(dst_reg);
9947 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9948 		return -EACCES;
9949 	if (sanitize_needed(opcode)) {
9950 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9951 				       &info, true);
9952 		if (ret < 0)
9953 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9954 	}
9955 
9956 	return 0;
9957 }
9958 
9959 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9960 				 struct bpf_reg_state *src_reg)
9961 {
9962 	s32 smin_val = src_reg->s32_min_value;
9963 	s32 smax_val = src_reg->s32_max_value;
9964 	u32 umin_val = src_reg->u32_min_value;
9965 	u32 umax_val = src_reg->u32_max_value;
9966 
9967 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9968 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9969 		dst_reg->s32_min_value = S32_MIN;
9970 		dst_reg->s32_max_value = S32_MAX;
9971 	} else {
9972 		dst_reg->s32_min_value += smin_val;
9973 		dst_reg->s32_max_value += smax_val;
9974 	}
9975 	if (dst_reg->u32_min_value + umin_val < umin_val ||
9976 	    dst_reg->u32_max_value + umax_val < umax_val) {
9977 		dst_reg->u32_min_value = 0;
9978 		dst_reg->u32_max_value = U32_MAX;
9979 	} else {
9980 		dst_reg->u32_min_value += umin_val;
9981 		dst_reg->u32_max_value += umax_val;
9982 	}
9983 }
9984 
9985 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9986 			       struct bpf_reg_state *src_reg)
9987 {
9988 	s64 smin_val = src_reg->smin_value;
9989 	s64 smax_val = src_reg->smax_value;
9990 	u64 umin_val = src_reg->umin_value;
9991 	u64 umax_val = src_reg->umax_value;
9992 
9993 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9994 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
9995 		dst_reg->smin_value = S64_MIN;
9996 		dst_reg->smax_value = S64_MAX;
9997 	} else {
9998 		dst_reg->smin_value += smin_val;
9999 		dst_reg->smax_value += smax_val;
10000 	}
10001 	if (dst_reg->umin_value + umin_val < umin_val ||
10002 	    dst_reg->umax_value + umax_val < umax_val) {
10003 		dst_reg->umin_value = 0;
10004 		dst_reg->umax_value = U64_MAX;
10005 	} else {
10006 		dst_reg->umin_value += umin_val;
10007 		dst_reg->umax_value += umax_val;
10008 	}
10009 }
10010 
10011 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10012 				 struct bpf_reg_state *src_reg)
10013 {
10014 	s32 smin_val = src_reg->s32_min_value;
10015 	s32 smax_val = src_reg->s32_max_value;
10016 	u32 umin_val = src_reg->u32_min_value;
10017 	u32 umax_val = src_reg->u32_max_value;
10018 
10019 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10020 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10021 		/* Overflow possible, we know nothing */
10022 		dst_reg->s32_min_value = S32_MIN;
10023 		dst_reg->s32_max_value = S32_MAX;
10024 	} else {
10025 		dst_reg->s32_min_value -= smax_val;
10026 		dst_reg->s32_max_value -= smin_val;
10027 	}
10028 	if (dst_reg->u32_min_value < umax_val) {
10029 		/* Overflow possible, we know nothing */
10030 		dst_reg->u32_min_value = 0;
10031 		dst_reg->u32_max_value = U32_MAX;
10032 	} else {
10033 		/* Cannot overflow (as long as bounds are consistent) */
10034 		dst_reg->u32_min_value -= umax_val;
10035 		dst_reg->u32_max_value -= umin_val;
10036 	}
10037 }
10038 
10039 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10040 			       struct bpf_reg_state *src_reg)
10041 {
10042 	s64 smin_val = src_reg->smin_value;
10043 	s64 smax_val = src_reg->smax_value;
10044 	u64 umin_val = src_reg->umin_value;
10045 	u64 umax_val = src_reg->umax_value;
10046 
10047 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10048 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10049 		/* Overflow possible, we know nothing */
10050 		dst_reg->smin_value = S64_MIN;
10051 		dst_reg->smax_value = S64_MAX;
10052 	} else {
10053 		dst_reg->smin_value -= smax_val;
10054 		dst_reg->smax_value -= smin_val;
10055 	}
10056 	if (dst_reg->umin_value < umax_val) {
10057 		/* Overflow possible, we know nothing */
10058 		dst_reg->umin_value = 0;
10059 		dst_reg->umax_value = U64_MAX;
10060 	} else {
10061 		/* Cannot overflow (as long as bounds are consistent) */
10062 		dst_reg->umin_value -= umax_val;
10063 		dst_reg->umax_value -= umin_val;
10064 	}
10065 }
10066 
10067 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10068 				 struct bpf_reg_state *src_reg)
10069 {
10070 	s32 smin_val = src_reg->s32_min_value;
10071 	u32 umin_val = src_reg->u32_min_value;
10072 	u32 umax_val = src_reg->u32_max_value;
10073 
10074 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10075 		/* Ain't nobody got time to multiply that sign */
10076 		__mark_reg32_unbounded(dst_reg);
10077 		return;
10078 	}
10079 	/* Both values are positive, so we can work with unsigned and
10080 	 * copy the result to signed (unless it exceeds S32_MAX).
10081 	 */
10082 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10083 		/* Potential overflow, we know nothing */
10084 		__mark_reg32_unbounded(dst_reg);
10085 		return;
10086 	}
10087 	dst_reg->u32_min_value *= umin_val;
10088 	dst_reg->u32_max_value *= umax_val;
10089 	if (dst_reg->u32_max_value > S32_MAX) {
10090 		/* Overflow possible, we know nothing */
10091 		dst_reg->s32_min_value = S32_MIN;
10092 		dst_reg->s32_max_value = S32_MAX;
10093 	} else {
10094 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10095 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10096 	}
10097 }
10098 
10099 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10100 			       struct bpf_reg_state *src_reg)
10101 {
10102 	s64 smin_val = src_reg->smin_value;
10103 	u64 umin_val = src_reg->umin_value;
10104 	u64 umax_val = src_reg->umax_value;
10105 
10106 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10107 		/* Ain't nobody got time to multiply that sign */
10108 		__mark_reg64_unbounded(dst_reg);
10109 		return;
10110 	}
10111 	/* Both values are positive, so we can work with unsigned and
10112 	 * copy the result to signed (unless it exceeds S64_MAX).
10113 	 */
10114 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10115 		/* Potential overflow, we know nothing */
10116 		__mark_reg64_unbounded(dst_reg);
10117 		return;
10118 	}
10119 	dst_reg->umin_value *= umin_val;
10120 	dst_reg->umax_value *= umax_val;
10121 	if (dst_reg->umax_value > S64_MAX) {
10122 		/* Overflow possible, we know nothing */
10123 		dst_reg->smin_value = S64_MIN;
10124 		dst_reg->smax_value = S64_MAX;
10125 	} else {
10126 		dst_reg->smin_value = dst_reg->umin_value;
10127 		dst_reg->smax_value = dst_reg->umax_value;
10128 	}
10129 }
10130 
10131 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10132 				 struct bpf_reg_state *src_reg)
10133 {
10134 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10135 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10136 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10137 	s32 smin_val = src_reg->s32_min_value;
10138 	u32 umax_val = src_reg->u32_max_value;
10139 
10140 	if (src_known && dst_known) {
10141 		__mark_reg32_known(dst_reg, var32_off.value);
10142 		return;
10143 	}
10144 
10145 	/* We get our minimum from the var_off, since that's inherently
10146 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10147 	 */
10148 	dst_reg->u32_min_value = var32_off.value;
10149 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10150 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10151 		/* Lose signed bounds when ANDing negative numbers,
10152 		 * ain't nobody got time for that.
10153 		 */
10154 		dst_reg->s32_min_value = S32_MIN;
10155 		dst_reg->s32_max_value = S32_MAX;
10156 	} else {
10157 		/* ANDing two positives gives a positive, so safe to
10158 		 * cast result into s64.
10159 		 */
10160 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10161 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10162 	}
10163 }
10164 
10165 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10166 			       struct bpf_reg_state *src_reg)
10167 {
10168 	bool src_known = tnum_is_const(src_reg->var_off);
10169 	bool dst_known = tnum_is_const(dst_reg->var_off);
10170 	s64 smin_val = src_reg->smin_value;
10171 	u64 umax_val = src_reg->umax_value;
10172 
10173 	if (src_known && dst_known) {
10174 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10175 		return;
10176 	}
10177 
10178 	/* We get our minimum from the var_off, since that's inherently
10179 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10180 	 */
10181 	dst_reg->umin_value = dst_reg->var_off.value;
10182 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10183 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10184 		/* Lose signed bounds when ANDing negative numbers,
10185 		 * ain't nobody got time for that.
10186 		 */
10187 		dst_reg->smin_value = S64_MIN;
10188 		dst_reg->smax_value = S64_MAX;
10189 	} else {
10190 		/* ANDing two positives gives a positive, so safe to
10191 		 * cast result into s64.
10192 		 */
10193 		dst_reg->smin_value = dst_reg->umin_value;
10194 		dst_reg->smax_value = dst_reg->umax_value;
10195 	}
10196 	/* We may learn something more from the var_off */
10197 	__update_reg_bounds(dst_reg);
10198 }
10199 
10200 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10201 				struct bpf_reg_state *src_reg)
10202 {
10203 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10204 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10205 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10206 	s32 smin_val = src_reg->s32_min_value;
10207 	u32 umin_val = src_reg->u32_min_value;
10208 
10209 	if (src_known && dst_known) {
10210 		__mark_reg32_known(dst_reg, var32_off.value);
10211 		return;
10212 	}
10213 
10214 	/* We get our maximum from the var_off, and our minimum is the
10215 	 * maximum of the operands' minima
10216 	 */
10217 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10218 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10219 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10220 		/* Lose signed bounds when ORing negative numbers,
10221 		 * ain't nobody got time for that.
10222 		 */
10223 		dst_reg->s32_min_value = S32_MIN;
10224 		dst_reg->s32_max_value = S32_MAX;
10225 	} else {
10226 		/* ORing two positives gives a positive, so safe to
10227 		 * cast result into s64.
10228 		 */
10229 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10230 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10231 	}
10232 }
10233 
10234 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10235 			      struct bpf_reg_state *src_reg)
10236 {
10237 	bool src_known = tnum_is_const(src_reg->var_off);
10238 	bool dst_known = tnum_is_const(dst_reg->var_off);
10239 	s64 smin_val = src_reg->smin_value;
10240 	u64 umin_val = src_reg->umin_value;
10241 
10242 	if (src_known && dst_known) {
10243 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10244 		return;
10245 	}
10246 
10247 	/* We get our maximum from the var_off, and our minimum is the
10248 	 * maximum of the operands' minima
10249 	 */
10250 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10251 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10252 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10253 		/* Lose signed bounds when ORing negative numbers,
10254 		 * ain't nobody got time for that.
10255 		 */
10256 		dst_reg->smin_value = S64_MIN;
10257 		dst_reg->smax_value = S64_MAX;
10258 	} else {
10259 		/* ORing two positives gives a positive, so safe to
10260 		 * cast result into s64.
10261 		 */
10262 		dst_reg->smin_value = dst_reg->umin_value;
10263 		dst_reg->smax_value = dst_reg->umax_value;
10264 	}
10265 	/* We may learn something more from the var_off */
10266 	__update_reg_bounds(dst_reg);
10267 }
10268 
10269 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10270 				 struct bpf_reg_state *src_reg)
10271 {
10272 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10273 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10274 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10275 	s32 smin_val = src_reg->s32_min_value;
10276 
10277 	if (src_known && dst_known) {
10278 		__mark_reg32_known(dst_reg, var32_off.value);
10279 		return;
10280 	}
10281 
10282 	/* We get both minimum and maximum from the var32_off. */
10283 	dst_reg->u32_min_value = var32_off.value;
10284 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10285 
10286 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10287 		/* XORing two positive sign numbers gives a positive,
10288 		 * so safe to cast u32 result into s32.
10289 		 */
10290 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10291 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10292 	} else {
10293 		dst_reg->s32_min_value = S32_MIN;
10294 		dst_reg->s32_max_value = S32_MAX;
10295 	}
10296 }
10297 
10298 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10299 			       struct bpf_reg_state *src_reg)
10300 {
10301 	bool src_known = tnum_is_const(src_reg->var_off);
10302 	bool dst_known = tnum_is_const(dst_reg->var_off);
10303 	s64 smin_val = src_reg->smin_value;
10304 
10305 	if (src_known && dst_known) {
10306 		/* dst_reg->var_off.value has been updated earlier */
10307 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10308 		return;
10309 	}
10310 
10311 	/* We get both minimum and maximum from the var_off. */
10312 	dst_reg->umin_value = dst_reg->var_off.value;
10313 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10314 
10315 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10316 		/* XORing two positive sign numbers gives a positive,
10317 		 * so safe to cast u64 result into s64.
10318 		 */
10319 		dst_reg->smin_value = dst_reg->umin_value;
10320 		dst_reg->smax_value = dst_reg->umax_value;
10321 	} else {
10322 		dst_reg->smin_value = S64_MIN;
10323 		dst_reg->smax_value = S64_MAX;
10324 	}
10325 
10326 	__update_reg_bounds(dst_reg);
10327 }
10328 
10329 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10330 				   u64 umin_val, u64 umax_val)
10331 {
10332 	/* We lose all sign bit information (except what we can pick
10333 	 * up from var_off)
10334 	 */
10335 	dst_reg->s32_min_value = S32_MIN;
10336 	dst_reg->s32_max_value = S32_MAX;
10337 	/* If we might shift our top bit out, then we know nothing */
10338 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10339 		dst_reg->u32_min_value = 0;
10340 		dst_reg->u32_max_value = U32_MAX;
10341 	} else {
10342 		dst_reg->u32_min_value <<= umin_val;
10343 		dst_reg->u32_max_value <<= umax_val;
10344 	}
10345 }
10346 
10347 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10348 				 struct bpf_reg_state *src_reg)
10349 {
10350 	u32 umax_val = src_reg->u32_max_value;
10351 	u32 umin_val = src_reg->u32_min_value;
10352 	/* u32 alu operation will zext upper bits */
10353 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10354 
10355 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10356 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10357 	/* Not required but being careful mark reg64 bounds as unknown so
10358 	 * that we are forced to pick them up from tnum and zext later and
10359 	 * if some path skips this step we are still safe.
10360 	 */
10361 	__mark_reg64_unbounded(dst_reg);
10362 	__update_reg32_bounds(dst_reg);
10363 }
10364 
10365 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10366 				   u64 umin_val, u64 umax_val)
10367 {
10368 	/* Special case <<32 because it is a common compiler pattern to sign
10369 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10370 	 * positive we know this shift will also be positive so we can track
10371 	 * bounds correctly. Otherwise we lose all sign bit information except
10372 	 * what we can pick up from var_off. Perhaps we can generalize this
10373 	 * later to shifts of any length.
10374 	 */
10375 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10376 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10377 	else
10378 		dst_reg->smax_value = S64_MAX;
10379 
10380 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10381 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10382 	else
10383 		dst_reg->smin_value = S64_MIN;
10384 
10385 	/* If we might shift our top bit out, then we know nothing */
10386 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10387 		dst_reg->umin_value = 0;
10388 		dst_reg->umax_value = U64_MAX;
10389 	} else {
10390 		dst_reg->umin_value <<= umin_val;
10391 		dst_reg->umax_value <<= umax_val;
10392 	}
10393 }
10394 
10395 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10396 			       struct bpf_reg_state *src_reg)
10397 {
10398 	u64 umax_val = src_reg->umax_value;
10399 	u64 umin_val = src_reg->umin_value;
10400 
10401 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
10402 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10403 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10404 
10405 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10406 	/* We may learn something more from the var_off */
10407 	__update_reg_bounds(dst_reg);
10408 }
10409 
10410 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10411 				 struct bpf_reg_state *src_reg)
10412 {
10413 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10414 	u32 umax_val = src_reg->u32_max_value;
10415 	u32 umin_val = src_reg->u32_min_value;
10416 
10417 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10418 	 * be negative, then either:
10419 	 * 1) src_reg might be zero, so the sign bit of the result is
10420 	 *    unknown, so we lose our signed bounds
10421 	 * 2) it's known negative, thus the unsigned bounds capture the
10422 	 *    signed bounds
10423 	 * 3) the signed bounds cross zero, so they tell us nothing
10424 	 *    about the result
10425 	 * If the value in dst_reg is known nonnegative, then again the
10426 	 * unsigned bounds capture the signed bounds.
10427 	 * Thus, in all cases it suffices to blow away our signed bounds
10428 	 * and rely on inferring new ones from the unsigned bounds and
10429 	 * var_off of the result.
10430 	 */
10431 	dst_reg->s32_min_value = S32_MIN;
10432 	dst_reg->s32_max_value = S32_MAX;
10433 
10434 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
10435 	dst_reg->u32_min_value >>= umax_val;
10436 	dst_reg->u32_max_value >>= umin_val;
10437 
10438 	__mark_reg64_unbounded(dst_reg);
10439 	__update_reg32_bounds(dst_reg);
10440 }
10441 
10442 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10443 			       struct bpf_reg_state *src_reg)
10444 {
10445 	u64 umax_val = src_reg->umax_value;
10446 	u64 umin_val = src_reg->umin_value;
10447 
10448 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10449 	 * be negative, then either:
10450 	 * 1) src_reg might be zero, so the sign bit of the result is
10451 	 *    unknown, so we lose our signed bounds
10452 	 * 2) it's known negative, thus the unsigned bounds capture the
10453 	 *    signed bounds
10454 	 * 3) the signed bounds cross zero, so they tell us nothing
10455 	 *    about the result
10456 	 * If the value in dst_reg is known nonnegative, then again the
10457 	 * unsigned bounds capture the signed bounds.
10458 	 * Thus, in all cases it suffices to blow away our signed bounds
10459 	 * and rely on inferring new ones from the unsigned bounds and
10460 	 * var_off of the result.
10461 	 */
10462 	dst_reg->smin_value = S64_MIN;
10463 	dst_reg->smax_value = S64_MAX;
10464 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10465 	dst_reg->umin_value >>= umax_val;
10466 	dst_reg->umax_value >>= umin_val;
10467 
10468 	/* Its not easy to operate on alu32 bounds here because it depends
10469 	 * on bits being shifted in. Take easy way out and mark unbounded
10470 	 * so we can recalculate later from tnum.
10471 	 */
10472 	__mark_reg32_unbounded(dst_reg);
10473 	__update_reg_bounds(dst_reg);
10474 }
10475 
10476 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10477 				  struct bpf_reg_state *src_reg)
10478 {
10479 	u64 umin_val = src_reg->u32_min_value;
10480 
10481 	/* Upon reaching here, src_known is true and
10482 	 * umax_val is equal to umin_val.
10483 	 */
10484 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10485 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10486 
10487 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10488 
10489 	/* blow away the dst_reg umin_value/umax_value and rely on
10490 	 * dst_reg var_off to refine the result.
10491 	 */
10492 	dst_reg->u32_min_value = 0;
10493 	dst_reg->u32_max_value = U32_MAX;
10494 
10495 	__mark_reg64_unbounded(dst_reg);
10496 	__update_reg32_bounds(dst_reg);
10497 }
10498 
10499 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10500 				struct bpf_reg_state *src_reg)
10501 {
10502 	u64 umin_val = src_reg->umin_value;
10503 
10504 	/* Upon reaching here, src_known is true and umax_val is equal
10505 	 * to umin_val.
10506 	 */
10507 	dst_reg->smin_value >>= umin_val;
10508 	dst_reg->smax_value >>= umin_val;
10509 
10510 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10511 
10512 	/* blow away the dst_reg umin_value/umax_value and rely on
10513 	 * dst_reg var_off to refine the result.
10514 	 */
10515 	dst_reg->umin_value = 0;
10516 	dst_reg->umax_value = U64_MAX;
10517 
10518 	/* Its not easy to operate on alu32 bounds here because it depends
10519 	 * on bits being shifted in from upper 32-bits. Take easy way out
10520 	 * and mark unbounded so we can recalculate later from tnum.
10521 	 */
10522 	__mark_reg32_unbounded(dst_reg);
10523 	__update_reg_bounds(dst_reg);
10524 }
10525 
10526 /* WARNING: This function does calculations on 64-bit values, but the actual
10527  * execution may occur on 32-bit values. Therefore, things like bitshifts
10528  * need extra checks in the 32-bit case.
10529  */
10530 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10531 				      struct bpf_insn *insn,
10532 				      struct bpf_reg_state *dst_reg,
10533 				      struct bpf_reg_state src_reg)
10534 {
10535 	struct bpf_reg_state *regs = cur_regs(env);
10536 	u8 opcode = BPF_OP(insn->code);
10537 	bool src_known;
10538 	s64 smin_val, smax_val;
10539 	u64 umin_val, umax_val;
10540 	s32 s32_min_val, s32_max_val;
10541 	u32 u32_min_val, u32_max_val;
10542 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10543 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10544 	int ret;
10545 
10546 	smin_val = src_reg.smin_value;
10547 	smax_val = src_reg.smax_value;
10548 	umin_val = src_reg.umin_value;
10549 	umax_val = src_reg.umax_value;
10550 
10551 	s32_min_val = src_reg.s32_min_value;
10552 	s32_max_val = src_reg.s32_max_value;
10553 	u32_min_val = src_reg.u32_min_value;
10554 	u32_max_val = src_reg.u32_max_value;
10555 
10556 	if (alu32) {
10557 		src_known = tnum_subreg_is_const(src_reg.var_off);
10558 		if ((src_known &&
10559 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10560 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10561 			/* Taint dst register if offset had invalid bounds
10562 			 * derived from e.g. dead branches.
10563 			 */
10564 			__mark_reg_unknown(env, dst_reg);
10565 			return 0;
10566 		}
10567 	} else {
10568 		src_known = tnum_is_const(src_reg.var_off);
10569 		if ((src_known &&
10570 		     (smin_val != smax_val || umin_val != umax_val)) ||
10571 		    smin_val > smax_val || umin_val > umax_val) {
10572 			/* Taint dst register if offset had invalid bounds
10573 			 * derived from e.g. dead branches.
10574 			 */
10575 			__mark_reg_unknown(env, dst_reg);
10576 			return 0;
10577 		}
10578 	}
10579 
10580 	if (!src_known &&
10581 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10582 		__mark_reg_unknown(env, dst_reg);
10583 		return 0;
10584 	}
10585 
10586 	if (sanitize_needed(opcode)) {
10587 		ret = sanitize_val_alu(env, insn);
10588 		if (ret < 0)
10589 			return sanitize_err(env, insn, ret, NULL, NULL);
10590 	}
10591 
10592 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10593 	 * There are two classes of instructions: The first class we track both
10594 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
10595 	 * greatest amount of precision when alu operations are mixed with jmp32
10596 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10597 	 * and BPF_OR. This is possible because these ops have fairly easy to
10598 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10599 	 * See alu32 verifier tests for examples. The second class of
10600 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10601 	 * with regards to tracking sign/unsigned bounds because the bits may
10602 	 * cross subreg boundaries in the alu64 case. When this happens we mark
10603 	 * the reg unbounded in the subreg bound space and use the resulting
10604 	 * tnum to calculate an approximation of the sign/unsigned bounds.
10605 	 */
10606 	switch (opcode) {
10607 	case BPF_ADD:
10608 		scalar32_min_max_add(dst_reg, &src_reg);
10609 		scalar_min_max_add(dst_reg, &src_reg);
10610 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10611 		break;
10612 	case BPF_SUB:
10613 		scalar32_min_max_sub(dst_reg, &src_reg);
10614 		scalar_min_max_sub(dst_reg, &src_reg);
10615 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10616 		break;
10617 	case BPF_MUL:
10618 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10619 		scalar32_min_max_mul(dst_reg, &src_reg);
10620 		scalar_min_max_mul(dst_reg, &src_reg);
10621 		break;
10622 	case BPF_AND:
10623 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10624 		scalar32_min_max_and(dst_reg, &src_reg);
10625 		scalar_min_max_and(dst_reg, &src_reg);
10626 		break;
10627 	case BPF_OR:
10628 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10629 		scalar32_min_max_or(dst_reg, &src_reg);
10630 		scalar_min_max_or(dst_reg, &src_reg);
10631 		break;
10632 	case BPF_XOR:
10633 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10634 		scalar32_min_max_xor(dst_reg, &src_reg);
10635 		scalar_min_max_xor(dst_reg, &src_reg);
10636 		break;
10637 	case BPF_LSH:
10638 		if (umax_val >= insn_bitness) {
10639 			/* Shifts greater than 31 or 63 are undefined.
10640 			 * This includes shifts by a negative number.
10641 			 */
10642 			mark_reg_unknown(env, regs, insn->dst_reg);
10643 			break;
10644 		}
10645 		if (alu32)
10646 			scalar32_min_max_lsh(dst_reg, &src_reg);
10647 		else
10648 			scalar_min_max_lsh(dst_reg, &src_reg);
10649 		break;
10650 	case BPF_RSH:
10651 		if (umax_val >= insn_bitness) {
10652 			/* Shifts greater than 31 or 63 are undefined.
10653 			 * This includes shifts by a negative number.
10654 			 */
10655 			mark_reg_unknown(env, regs, insn->dst_reg);
10656 			break;
10657 		}
10658 		if (alu32)
10659 			scalar32_min_max_rsh(dst_reg, &src_reg);
10660 		else
10661 			scalar_min_max_rsh(dst_reg, &src_reg);
10662 		break;
10663 	case BPF_ARSH:
10664 		if (umax_val >= insn_bitness) {
10665 			/* Shifts greater than 31 or 63 are undefined.
10666 			 * This includes shifts by a negative number.
10667 			 */
10668 			mark_reg_unknown(env, regs, insn->dst_reg);
10669 			break;
10670 		}
10671 		if (alu32)
10672 			scalar32_min_max_arsh(dst_reg, &src_reg);
10673 		else
10674 			scalar_min_max_arsh(dst_reg, &src_reg);
10675 		break;
10676 	default:
10677 		mark_reg_unknown(env, regs, insn->dst_reg);
10678 		break;
10679 	}
10680 
10681 	/* ALU32 ops are zero extended into 64bit register */
10682 	if (alu32)
10683 		zext_32_to_64(dst_reg);
10684 	reg_bounds_sync(dst_reg);
10685 	return 0;
10686 }
10687 
10688 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10689  * and var_off.
10690  */
10691 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10692 				   struct bpf_insn *insn)
10693 {
10694 	struct bpf_verifier_state *vstate = env->cur_state;
10695 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10696 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10697 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10698 	u8 opcode = BPF_OP(insn->code);
10699 	int err;
10700 
10701 	dst_reg = &regs[insn->dst_reg];
10702 	src_reg = NULL;
10703 	if (dst_reg->type != SCALAR_VALUE)
10704 		ptr_reg = dst_reg;
10705 	else
10706 		/* Make sure ID is cleared otherwise dst_reg min/max could be
10707 		 * incorrectly propagated into other registers by find_equal_scalars()
10708 		 */
10709 		dst_reg->id = 0;
10710 	if (BPF_SRC(insn->code) == BPF_X) {
10711 		src_reg = &regs[insn->src_reg];
10712 		if (src_reg->type != SCALAR_VALUE) {
10713 			if (dst_reg->type != SCALAR_VALUE) {
10714 				/* Combining two pointers by any ALU op yields
10715 				 * an arbitrary scalar. Disallow all math except
10716 				 * pointer subtraction
10717 				 */
10718 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10719 					mark_reg_unknown(env, regs, insn->dst_reg);
10720 					return 0;
10721 				}
10722 				verbose(env, "R%d pointer %s pointer prohibited\n",
10723 					insn->dst_reg,
10724 					bpf_alu_string[opcode >> 4]);
10725 				return -EACCES;
10726 			} else {
10727 				/* scalar += pointer
10728 				 * This is legal, but we have to reverse our
10729 				 * src/dest handling in computing the range
10730 				 */
10731 				err = mark_chain_precision(env, insn->dst_reg);
10732 				if (err)
10733 					return err;
10734 				return adjust_ptr_min_max_vals(env, insn,
10735 							       src_reg, dst_reg);
10736 			}
10737 		} else if (ptr_reg) {
10738 			/* pointer += scalar */
10739 			err = mark_chain_precision(env, insn->src_reg);
10740 			if (err)
10741 				return err;
10742 			return adjust_ptr_min_max_vals(env, insn,
10743 						       dst_reg, src_reg);
10744 		} else if (dst_reg->precise) {
10745 			/* if dst_reg is precise, src_reg should be precise as well */
10746 			err = mark_chain_precision(env, insn->src_reg);
10747 			if (err)
10748 				return err;
10749 		}
10750 	} else {
10751 		/* Pretend the src is a reg with a known value, since we only
10752 		 * need to be able to read from this state.
10753 		 */
10754 		off_reg.type = SCALAR_VALUE;
10755 		__mark_reg_known(&off_reg, insn->imm);
10756 		src_reg = &off_reg;
10757 		if (ptr_reg) /* pointer += K */
10758 			return adjust_ptr_min_max_vals(env, insn,
10759 						       ptr_reg, src_reg);
10760 	}
10761 
10762 	/* Got here implies adding two SCALAR_VALUEs */
10763 	if (WARN_ON_ONCE(ptr_reg)) {
10764 		print_verifier_state(env, state, true);
10765 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
10766 		return -EINVAL;
10767 	}
10768 	if (WARN_ON(!src_reg)) {
10769 		print_verifier_state(env, state, true);
10770 		verbose(env, "verifier internal error: no src_reg\n");
10771 		return -EINVAL;
10772 	}
10773 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10774 }
10775 
10776 /* check validity of 32-bit and 64-bit arithmetic operations */
10777 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10778 {
10779 	struct bpf_reg_state *regs = cur_regs(env);
10780 	u8 opcode = BPF_OP(insn->code);
10781 	int err;
10782 
10783 	if (opcode == BPF_END || opcode == BPF_NEG) {
10784 		if (opcode == BPF_NEG) {
10785 			if (BPF_SRC(insn->code) != BPF_K ||
10786 			    insn->src_reg != BPF_REG_0 ||
10787 			    insn->off != 0 || insn->imm != 0) {
10788 				verbose(env, "BPF_NEG uses reserved fields\n");
10789 				return -EINVAL;
10790 			}
10791 		} else {
10792 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10793 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10794 			    BPF_CLASS(insn->code) == BPF_ALU64) {
10795 				verbose(env, "BPF_END uses reserved fields\n");
10796 				return -EINVAL;
10797 			}
10798 		}
10799 
10800 		/* check src operand */
10801 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10802 		if (err)
10803 			return err;
10804 
10805 		if (is_pointer_value(env, insn->dst_reg)) {
10806 			verbose(env, "R%d pointer arithmetic prohibited\n",
10807 				insn->dst_reg);
10808 			return -EACCES;
10809 		}
10810 
10811 		/* check dest operand */
10812 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
10813 		if (err)
10814 			return err;
10815 
10816 	} else if (opcode == BPF_MOV) {
10817 
10818 		if (BPF_SRC(insn->code) == BPF_X) {
10819 			if (insn->imm != 0 || insn->off != 0) {
10820 				verbose(env, "BPF_MOV uses reserved fields\n");
10821 				return -EINVAL;
10822 			}
10823 
10824 			/* check src operand */
10825 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10826 			if (err)
10827 				return err;
10828 		} else {
10829 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10830 				verbose(env, "BPF_MOV uses reserved fields\n");
10831 				return -EINVAL;
10832 			}
10833 		}
10834 
10835 		/* check dest operand, mark as required later */
10836 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10837 		if (err)
10838 			return err;
10839 
10840 		if (BPF_SRC(insn->code) == BPF_X) {
10841 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
10842 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10843 
10844 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10845 				/* case: R1 = R2
10846 				 * copy register state to dest reg
10847 				 */
10848 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10849 					/* Assign src and dst registers the same ID
10850 					 * that will be used by find_equal_scalars()
10851 					 * to propagate min/max range.
10852 					 */
10853 					src_reg->id = ++env->id_gen;
10854 				*dst_reg = *src_reg;
10855 				dst_reg->live |= REG_LIVE_WRITTEN;
10856 				dst_reg->subreg_def = DEF_NOT_SUBREG;
10857 			} else {
10858 				/* R1 = (u32) R2 */
10859 				if (is_pointer_value(env, insn->src_reg)) {
10860 					verbose(env,
10861 						"R%d partial copy of pointer\n",
10862 						insn->src_reg);
10863 					return -EACCES;
10864 				} else if (src_reg->type == SCALAR_VALUE) {
10865 					*dst_reg = *src_reg;
10866 					/* Make sure ID is cleared otherwise
10867 					 * dst_reg min/max could be incorrectly
10868 					 * propagated into src_reg by find_equal_scalars()
10869 					 */
10870 					dst_reg->id = 0;
10871 					dst_reg->live |= REG_LIVE_WRITTEN;
10872 					dst_reg->subreg_def = env->insn_idx + 1;
10873 				} else {
10874 					mark_reg_unknown(env, regs,
10875 							 insn->dst_reg);
10876 				}
10877 				zext_32_to_64(dst_reg);
10878 				reg_bounds_sync(dst_reg);
10879 			}
10880 		} else {
10881 			/* case: R = imm
10882 			 * remember the value we stored into this reg
10883 			 */
10884 			/* clear any state __mark_reg_known doesn't set */
10885 			mark_reg_unknown(env, regs, insn->dst_reg);
10886 			regs[insn->dst_reg].type = SCALAR_VALUE;
10887 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10888 				__mark_reg_known(regs + insn->dst_reg,
10889 						 insn->imm);
10890 			} else {
10891 				__mark_reg_known(regs + insn->dst_reg,
10892 						 (u32)insn->imm);
10893 			}
10894 		}
10895 
10896 	} else if (opcode > BPF_END) {
10897 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10898 		return -EINVAL;
10899 
10900 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
10901 
10902 		if (BPF_SRC(insn->code) == BPF_X) {
10903 			if (insn->imm != 0 || insn->off != 0) {
10904 				verbose(env, "BPF_ALU uses reserved fields\n");
10905 				return -EINVAL;
10906 			}
10907 			/* check src1 operand */
10908 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10909 			if (err)
10910 				return err;
10911 		} else {
10912 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10913 				verbose(env, "BPF_ALU uses reserved fields\n");
10914 				return -EINVAL;
10915 			}
10916 		}
10917 
10918 		/* check src2 operand */
10919 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10920 		if (err)
10921 			return err;
10922 
10923 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10924 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10925 			verbose(env, "div by zero\n");
10926 			return -EINVAL;
10927 		}
10928 
10929 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10930 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10931 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10932 
10933 			if (insn->imm < 0 || insn->imm >= size) {
10934 				verbose(env, "invalid shift %d\n", insn->imm);
10935 				return -EINVAL;
10936 			}
10937 		}
10938 
10939 		/* check dest operand */
10940 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10941 		if (err)
10942 			return err;
10943 
10944 		return adjust_reg_min_max_vals(env, insn);
10945 	}
10946 
10947 	return 0;
10948 }
10949 
10950 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10951 				   struct bpf_reg_state *dst_reg,
10952 				   enum bpf_reg_type type,
10953 				   bool range_right_open)
10954 {
10955 	struct bpf_func_state *state;
10956 	struct bpf_reg_state *reg;
10957 	int new_range;
10958 
10959 	if (dst_reg->off < 0 ||
10960 	    (dst_reg->off == 0 && range_right_open))
10961 		/* This doesn't give us any range */
10962 		return;
10963 
10964 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
10965 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10966 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
10967 		 * than pkt_end, but that's because it's also less than pkt.
10968 		 */
10969 		return;
10970 
10971 	new_range = dst_reg->off;
10972 	if (range_right_open)
10973 		new_range++;
10974 
10975 	/* Examples for register markings:
10976 	 *
10977 	 * pkt_data in dst register:
10978 	 *
10979 	 *   r2 = r3;
10980 	 *   r2 += 8;
10981 	 *   if (r2 > pkt_end) goto <handle exception>
10982 	 *   <access okay>
10983 	 *
10984 	 *   r2 = r3;
10985 	 *   r2 += 8;
10986 	 *   if (r2 < pkt_end) goto <access okay>
10987 	 *   <handle exception>
10988 	 *
10989 	 *   Where:
10990 	 *     r2 == dst_reg, pkt_end == src_reg
10991 	 *     r2=pkt(id=n,off=8,r=0)
10992 	 *     r3=pkt(id=n,off=0,r=0)
10993 	 *
10994 	 * pkt_data in src register:
10995 	 *
10996 	 *   r2 = r3;
10997 	 *   r2 += 8;
10998 	 *   if (pkt_end >= r2) goto <access okay>
10999 	 *   <handle exception>
11000 	 *
11001 	 *   r2 = r3;
11002 	 *   r2 += 8;
11003 	 *   if (pkt_end <= r2) goto <handle exception>
11004 	 *   <access okay>
11005 	 *
11006 	 *   Where:
11007 	 *     pkt_end == dst_reg, r2 == src_reg
11008 	 *     r2=pkt(id=n,off=8,r=0)
11009 	 *     r3=pkt(id=n,off=0,r=0)
11010 	 *
11011 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11012 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11013 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11014 	 * the check.
11015 	 */
11016 
11017 	/* If our ids match, then we must have the same max_value.  And we
11018 	 * don't care about the other reg's fixed offset, since if it's too big
11019 	 * the range won't allow anything.
11020 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11021 	 */
11022 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11023 		if (reg->type == type && reg->id == dst_reg->id)
11024 			/* keep the maximum range already checked */
11025 			reg->range = max(reg->range, new_range);
11026 	}));
11027 }
11028 
11029 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11030 {
11031 	struct tnum subreg = tnum_subreg(reg->var_off);
11032 	s32 sval = (s32)val;
11033 
11034 	switch (opcode) {
11035 	case BPF_JEQ:
11036 		if (tnum_is_const(subreg))
11037 			return !!tnum_equals_const(subreg, val);
11038 		break;
11039 	case BPF_JNE:
11040 		if (tnum_is_const(subreg))
11041 			return !tnum_equals_const(subreg, val);
11042 		break;
11043 	case BPF_JSET:
11044 		if ((~subreg.mask & subreg.value) & val)
11045 			return 1;
11046 		if (!((subreg.mask | subreg.value) & val))
11047 			return 0;
11048 		break;
11049 	case BPF_JGT:
11050 		if (reg->u32_min_value > val)
11051 			return 1;
11052 		else if (reg->u32_max_value <= val)
11053 			return 0;
11054 		break;
11055 	case BPF_JSGT:
11056 		if (reg->s32_min_value > sval)
11057 			return 1;
11058 		else if (reg->s32_max_value <= sval)
11059 			return 0;
11060 		break;
11061 	case BPF_JLT:
11062 		if (reg->u32_max_value < val)
11063 			return 1;
11064 		else if (reg->u32_min_value >= val)
11065 			return 0;
11066 		break;
11067 	case BPF_JSLT:
11068 		if (reg->s32_max_value < sval)
11069 			return 1;
11070 		else if (reg->s32_min_value >= sval)
11071 			return 0;
11072 		break;
11073 	case BPF_JGE:
11074 		if (reg->u32_min_value >= val)
11075 			return 1;
11076 		else if (reg->u32_max_value < val)
11077 			return 0;
11078 		break;
11079 	case BPF_JSGE:
11080 		if (reg->s32_min_value >= sval)
11081 			return 1;
11082 		else if (reg->s32_max_value < sval)
11083 			return 0;
11084 		break;
11085 	case BPF_JLE:
11086 		if (reg->u32_max_value <= val)
11087 			return 1;
11088 		else if (reg->u32_min_value > val)
11089 			return 0;
11090 		break;
11091 	case BPF_JSLE:
11092 		if (reg->s32_max_value <= sval)
11093 			return 1;
11094 		else if (reg->s32_min_value > sval)
11095 			return 0;
11096 		break;
11097 	}
11098 
11099 	return -1;
11100 }
11101 
11102 
11103 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11104 {
11105 	s64 sval = (s64)val;
11106 
11107 	switch (opcode) {
11108 	case BPF_JEQ:
11109 		if (tnum_is_const(reg->var_off))
11110 			return !!tnum_equals_const(reg->var_off, val);
11111 		break;
11112 	case BPF_JNE:
11113 		if (tnum_is_const(reg->var_off))
11114 			return !tnum_equals_const(reg->var_off, val);
11115 		break;
11116 	case BPF_JSET:
11117 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11118 			return 1;
11119 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11120 			return 0;
11121 		break;
11122 	case BPF_JGT:
11123 		if (reg->umin_value > val)
11124 			return 1;
11125 		else if (reg->umax_value <= val)
11126 			return 0;
11127 		break;
11128 	case BPF_JSGT:
11129 		if (reg->smin_value > sval)
11130 			return 1;
11131 		else if (reg->smax_value <= sval)
11132 			return 0;
11133 		break;
11134 	case BPF_JLT:
11135 		if (reg->umax_value < val)
11136 			return 1;
11137 		else if (reg->umin_value >= val)
11138 			return 0;
11139 		break;
11140 	case BPF_JSLT:
11141 		if (reg->smax_value < sval)
11142 			return 1;
11143 		else if (reg->smin_value >= sval)
11144 			return 0;
11145 		break;
11146 	case BPF_JGE:
11147 		if (reg->umin_value >= val)
11148 			return 1;
11149 		else if (reg->umax_value < val)
11150 			return 0;
11151 		break;
11152 	case BPF_JSGE:
11153 		if (reg->smin_value >= sval)
11154 			return 1;
11155 		else if (reg->smax_value < sval)
11156 			return 0;
11157 		break;
11158 	case BPF_JLE:
11159 		if (reg->umax_value <= val)
11160 			return 1;
11161 		else if (reg->umin_value > val)
11162 			return 0;
11163 		break;
11164 	case BPF_JSLE:
11165 		if (reg->smax_value <= sval)
11166 			return 1;
11167 		else if (reg->smin_value > sval)
11168 			return 0;
11169 		break;
11170 	}
11171 
11172 	return -1;
11173 }
11174 
11175 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11176  * and return:
11177  *  1 - branch will be taken and "goto target" will be executed
11178  *  0 - branch will not be taken and fall-through to next insn
11179  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11180  *      range [0,10]
11181  */
11182 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11183 			   bool is_jmp32)
11184 {
11185 	if (__is_pointer_value(false, reg)) {
11186 		if (!reg_type_not_null(reg->type))
11187 			return -1;
11188 
11189 		/* If pointer is valid tests against zero will fail so we can
11190 		 * use this to direct branch taken.
11191 		 */
11192 		if (val != 0)
11193 			return -1;
11194 
11195 		switch (opcode) {
11196 		case BPF_JEQ:
11197 			return 0;
11198 		case BPF_JNE:
11199 			return 1;
11200 		default:
11201 			return -1;
11202 		}
11203 	}
11204 
11205 	if (is_jmp32)
11206 		return is_branch32_taken(reg, val, opcode);
11207 	return is_branch64_taken(reg, val, opcode);
11208 }
11209 
11210 static int flip_opcode(u32 opcode)
11211 {
11212 	/* How can we transform "a <op> b" into "b <op> a"? */
11213 	static const u8 opcode_flip[16] = {
11214 		/* these stay the same */
11215 		[BPF_JEQ  >> 4] = BPF_JEQ,
11216 		[BPF_JNE  >> 4] = BPF_JNE,
11217 		[BPF_JSET >> 4] = BPF_JSET,
11218 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11219 		[BPF_JGE  >> 4] = BPF_JLE,
11220 		[BPF_JGT  >> 4] = BPF_JLT,
11221 		[BPF_JLE  >> 4] = BPF_JGE,
11222 		[BPF_JLT  >> 4] = BPF_JGT,
11223 		[BPF_JSGE >> 4] = BPF_JSLE,
11224 		[BPF_JSGT >> 4] = BPF_JSLT,
11225 		[BPF_JSLE >> 4] = BPF_JSGE,
11226 		[BPF_JSLT >> 4] = BPF_JSGT
11227 	};
11228 	return opcode_flip[opcode >> 4];
11229 }
11230 
11231 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11232 				   struct bpf_reg_state *src_reg,
11233 				   u8 opcode)
11234 {
11235 	struct bpf_reg_state *pkt;
11236 
11237 	if (src_reg->type == PTR_TO_PACKET_END) {
11238 		pkt = dst_reg;
11239 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11240 		pkt = src_reg;
11241 		opcode = flip_opcode(opcode);
11242 	} else {
11243 		return -1;
11244 	}
11245 
11246 	if (pkt->range >= 0)
11247 		return -1;
11248 
11249 	switch (opcode) {
11250 	case BPF_JLE:
11251 		/* pkt <= pkt_end */
11252 		fallthrough;
11253 	case BPF_JGT:
11254 		/* pkt > pkt_end */
11255 		if (pkt->range == BEYOND_PKT_END)
11256 			/* pkt has at last one extra byte beyond pkt_end */
11257 			return opcode == BPF_JGT;
11258 		break;
11259 	case BPF_JLT:
11260 		/* pkt < pkt_end */
11261 		fallthrough;
11262 	case BPF_JGE:
11263 		/* pkt >= pkt_end */
11264 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11265 			return opcode == BPF_JGE;
11266 		break;
11267 	}
11268 	return -1;
11269 }
11270 
11271 /* Adjusts the register min/max values in the case that the dst_reg is the
11272  * variable register that we are working on, and src_reg is a constant or we're
11273  * simply doing a BPF_K check.
11274  * In JEQ/JNE cases we also adjust the var_off values.
11275  */
11276 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11277 			    struct bpf_reg_state *false_reg,
11278 			    u64 val, u32 val32,
11279 			    u8 opcode, bool is_jmp32)
11280 {
11281 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
11282 	struct tnum false_64off = false_reg->var_off;
11283 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
11284 	struct tnum true_64off = true_reg->var_off;
11285 	s64 sval = (s64)val;
11286 	s32 sval32 = (s32)val32;
11287 
11288 	/* If the dst_reg is a pointer, we can't learn anything about its
11289 	 * variable offset from the compare (unless src_reg were a pointer into
11290 	 * the same object, but we don't bother with that.
11291 	 * Since false_reg and true_reg have the same type by construction, we
11292 	 * only need to check one of them for pointerness.
11293 	 */
11294 	if (__is_pointer_value(false, false_reg))
11295 		return;
11296 
11297 	switch (opcode) {
11298 	/* JEQ/JNE comparison doesn't change the register equivalence.
11299 	 *
11300 	 * r1 = r2;
11301 	 * if (r1 == 42) goto label;
11302 	 * ...
11303 	 * label: // here both r1 and r2 are known to be 42.
11304 	 *
11305 	 * Hence when marking register as known preserve it's ID.
11306 	 */
11307 	case BPF_JEQ:
11308 		if (is_jmp32) {
11309 			__mark_reg32_known(true_reg, val32);
11310 			true_32off = tnum_subreg(true_reg->var_off);
11311 		} else {
11312 			___mark_reg_known(true_reg, val);
11313 			true_64off = true_reg->var_off;
11314 		}
11315 		break;
11316 	case BPF_JNE:
11317 		if (is_jmp32) {
11318 			__mark_reg32_known(false_reg, val32);
11319 			false_32off = tnum_subreg(false_reg->var_off);
11320 		} else {
11321 			___mark_reg_known(false_reg, val);
11322 			false_64off = false_reg->var_off;
11323 		}
11324 		break;
11325 	case BPF_JSET:
11326 		if (is_jmp32) {
11327 			false_32off = tnum_and(false_32off, tnum_const(~val32));
11328 			if (is_power_of_2(val32))
11329 				true_32off = tnum_or(true_32off,
11330 						     tnum_const(val32));
11331 		} else {
11332 			false_64off = tnum_and(false_64off, tnum_const(~val));
11333 			if (is_power_of_2(val))
11334 				true_64off = tnum_or(true_64off,
11335 						     tnum_const(val));
11336 		}
11337 		break;
11338 	case BPF_JGE:
11339 	case BPF_JGT:
11340 	{
11341 		if (is_jmp32) {
11342 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11343 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11344 
11345 			false_reg->u32_max_value = min(false_reg->u32_max_value,
11346 						       false_umax);
11347 			true_reg->u32_min_value = max(true_reg->u32_min_value,
11348 						      true_umin);
11349 		} else {
11350 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11351 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11352 
11353 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
11354 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
11355 		}
11356 		break;
11357 	}
11358 	case BPF_JSGE:
11359 	case BPF_JSGT:
11360 	{
11361 		if (is_jmp32) {
11362 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11363 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11364 
11365 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11366 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11367 		} else {
11368 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11369 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11370 
11371 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
11372 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
11373 		}
11374 		break;
11375 	}
11376 	case BPF_JLE:
11377 	case BPF_JLT:
11378 	{
11379 		if (is_jmp32) {
11380 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11381 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11382 
11383 			false_reg->u32_min_value = max(false_reg->u32_min_value,
11384 						       false_umin);
11385 			true_reg->u32_max_value = min(true_reg->u32_max_value,
11386 						      true_umax);
11387 		} else {
11388 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11389 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11390 
11391 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
11392 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
11393 		}
11394 		break;
11395 	}
11396 	case BPF_JSLE:
11397 	case BPF_JSLT:
11398 	{
11399 		if (is_jmp32) {
11400 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11401 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11402 
11403 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11404 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11405 		} else {
11406 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11407 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11408 
11409 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
11410 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
11411 		}
11412 		break;
11413 	}
11414 	default:
11415 		return;
11416 	}
11417 
11418 	if (is_jmp32) {
11419 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11420 					     tnum_subreg(false_32off));
11421 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11422 					    tnum_subreg(true_32off));
11423 		__reg_combine_32_into_64(false_reg);
11424 		__reg_combine_32_into_64(true_reg);
11425 	} else {
11426 		false_reg->var_off = false_64off;
11427 		true_reg->var_off = true_64off;
11428 		__reg_combine_64_into_32(false_reg);
11429 		__reg_combine_64_into_32(true_reg);
11430 	}
11431 }
11432 
11433 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11434  * the variable reg.
11435  */
11436 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11437 				struct bpf_reg_state *false_reg,
11438 				u64 val, u32 val32,
11439 				u8 opcode, bool is_jmp32)
11440 {
11441 	opcode = flip_opcode(opcode);
11442 	/* This uses zero as "not present in table"; luckily the zero opcode,
11443 	 * BPF_JA, can't get here.
11444 	 */
11445 	if (opcode)
11446 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11447 }
11448 
11449 /* Regs are known to be equal, so intersect their min/max/var_off */
11450 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11451 				  struct bpf_reg_state *dst_reg)
11452 {
11453 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11454 							dst_reg->umin_value);
11455 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11456 							dst_reg->umax_value);
11457 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11458 							dst_reg->smin_value);
11459 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11460 							dst_reg->smax_value);
11461 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11462 							     dst_reg->var_off);
11463 	reg_bounds_sync(src_reg);
11464 	reg_bounds_sync(dst_reg);
11465 }
11466 
11467 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11468 				struct bpf_reg_state *true_dst,
11469 				struct bpf_reg_state *false_src,
11470 				struct bpf_reg_state *false_dst,
11471 				u8 opcode)
11472 {
11473 	switch (opcode) {
11474 	case BPF_JEQ:
11475 		__reg_combine_min_max(true_src, true_dst);
11476 		break;
11477 	case BPF_JNE:
11478 		__reg_combine_min_max(false_src, false_dst);
11479 		break;
11480 	}
11481 }
11482 
11483 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11484 				 struct bpf_reg_state *reg, u32 id,
11485 				 bool is_null)
11486 {
11487 	if (type_may_be_null(reg->type) && reg->id == id &&
11488 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11489 		/* Old offset (both fixed and variable parts) should have been
11490 		 * known-zero, because we don't allow pointer arithmetic on
11491 		 * pointers that might be NULL. If we see this happening, don't
11492 		 * convert the register.
11493 		 *
11494 		 * But in some cases, some helpers that return local kptrs
11495 		 * advance offset for the returned pointer. In those cases, it
11496 		 * is fine to expect to see reg->off.
11497 		 */
11498 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11499 			return;
11500 		if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11501 			return;
11502 		if (is_null) {
11503 			reg->type = SCALAR_VALUE;
11504 			/* We don't need id and ref_obj_id from this point
11505 			 * onwards anymore, thus we should better reset it,
11506 			 * so that state pruning has chances to take effect.
11507 			 */
11508 			reg->id = 0;
11509 			reg->ref_obj_id = 0;
11510 
11511 			return;
11512 		}
11513 
11514 		mark_ptr_not_null_reg(reg);
11515 
11516 		if (!reg_may_point_to_spin_lock(reg)) {
11517 			/* For not-NULL ptr, reg->ref_obj_id will be reset
11518 			 * in release_reference().
11519 			 *
11520 			 * reg->id is still used by spin_lock ptr. Other
11521 			 * than spin_lock ptr type, reg->id can be reset.
11522 			 */
11523 			reg->id = 0;
11524 		}
11525 	}
11526 }
11527 
11528 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11529  * be folded together at some point.
11530  */
11531 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11532 				  bool is_null)
11533 {
11534 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11535 	struct bpf_reg_state *regs = state->regs, *reg;
11536 	u32 ref_obj_id = regs[regno].ref_obj_id;
11537 	u32 id = regs[regno].id;
11538 
11539 	if (ref_obj_id && ref_obj_id == id && is_null)
11540 		/* regs[regno] is in the " == NULL" branch.
11541 		 * No one could have freed the reference state before
11542 		 * doing the NULL check.
11543 		 */
11544 		WARN_ON_ONCE(release_reference_state(state, id));
11545 
11546 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11547 		mark_ptr_or_null_reg(state, reg, id, is_null);
11548 	}));
11549 }
11550 
11551 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11552 				   struct bpf_reg_state *dst_reg,
11553 				   struct bpf_reg_state *src_reg,
11554 				   struct bpf_verifier_state *this_branch,
11555 				   struct bpf_verifier_state *other_branch)
11556 {
11557 	if (BPF_SRC(insn->code) != BPF_X)
11558 		return false;
11559 
11560 	/* Pointers are always 64-bit. */
11561 	if (BPF_CLASS(insn->code) == BPF_JMP32)
11562 		return false;
11563 
11564 	switch (BPF_OP(insn->code)) {
11565 	case BPF_JGT:
11566 		if ((dst_reg->type == PTR_TO_PACKET &&
11567 		     src_reg->type == PTR_TO_PACKET_END) ||
11568 		    (dst_reg->type == PTR_TO_PACKET_META &&
11569 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11570 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11571 			find_good_pkt_pointers(this_branch, dst_reg,
11572 					       dst_reg->type, false);
11573 			mark_pkt_end(other_branch, insn->dst_reg, true);
11574 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11575 			    src_reg->type == PTR_TO_PACKET) ||
11576 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11577 			    src_reg->type == PTR_TO_PACKET_META)) {
11578 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
11579 			find_good_pkt_pointers(other_branch, src_reg,
11580 					       src_reg->type, true);
11581 			mark_pkt_end(this_branch, insn->src_reg, false);
11582 		} else {
11583 			return false;
11584 		}
11585 		break;
11586 	case BPF_JLT:
11587 		if ((dst_reg->type == PTR_TO_PACKET &&
11588 		     src_reg->type == PTR_TO_PACKET_END) ||
11589 		    (dst_reg->type == PTR_TO_PACKET_META &&
11590 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11591 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11592 			find_good_pkt_pointers(other_branch, dst_reg,
11593 					       dst_reg->type, true);
11594 			mark_pkt_end(this_branch, insn->dst_reg, false);
11595 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11596 			    src_reg->type == PTR_TO_PACKET) ||
11597 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11598 			    src_reg->type == PTR_TO_PACKET_META)) {
11599 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
11600 			find_good_pkt_pointers(this_branch, src_reg,
11601 					       src_reg->type, false);
11602 			mark_pkt_end(other_branch, insn->src_reg, true);
11603 		} else {
11604 			return false;
11605 		}
11606 		break;
11607 	case BPF_JGE:
11608 		if ((dst_reg->type == PTR_TO_PACKET &&
11609 		     src_reg->type == PTR_TO_PACKET_END) ||
11610 		    (dst_reg->type == PTR_TO_PACKET_META &&
11611 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11612 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11613 			find_good_pkt_pointers(this_branch, dst_reg,
11614 					       dst_reg->type, true);
11615 			mark_pkt_end(other_branch, insn->dst_reg, false);
11616 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11617 			    src_reg->type == PTR_TO_PACKET) ||
11618 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11619 			    src_reg->type == PTR_TO_PACKET_META)) {
11620 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11621 			find_good_pkt_pointers(other_branch, src_reg,
11622 					       src_reg->type, false);
11623 			mark_pkt_end(this_branch, insn->src_reg, true);
11624 		} else {
11625 			return false;
11626 		}
11627 		break;
11628 	case BPF_JLE:
11629 		if ((dst_reg->type == PTR_TO_PACKET &&
11630 		     src_reg->type == PTR_TO_PACKET_END) ||
11631 		    (dst_reg->type == PTR_TO_PACKET_META &&
11632 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11633 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11634 			find_good_pkt_pointers(other_branch, dst_reg,
11635 					       dst_reg->type, false);
11636 			mark_pkt_end(this_branch, insn->dst_reg, true);
11637 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11638 			    src_reg->type == PTR_TO_PACKET) ||
11639 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11640 			    src_reg->type == PTR_TO_PACKET_META)) {
11641 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11642 			find_good_pkt_pointers(this_branch, src_reg,
11643 					       src_reg->type, true);
11644 			mark_pkt_end(other_branch, insn->src_reg, false);
11645 		} else {
11646 			return false;
11647 		}
11648 		break;
11649 	default:
11650 		return false;
11651 	}
11652 
11653 	return true;
11654 }
11655 
11656 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11657 			       struct bpf_reg_state *known_reg)
11658 {
11659 	struct bpf_func_state *state;
11660 	struct bpf_reg_state *reg;
11661 
11662 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11663 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11664 			*reg = *known_reg;
11665 	}));
11666 }
11667 
11668 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11669 			     struct bpf_insn *insn, int *insn_idx)
11670 {
11671 	struct bpf_verifier_state *this_branch = env->cur_state;
11672 	struct bpf_verifier_state *other_branch;
11673 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11674 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11675 	struct bpf_reg_state *eq_branch_regs;
11676 	u8 opcode = BPF_OP(insn->code);
11677 	bool is_jmp32;
11678 	int pred = -1;
11679 	int err;
11680 
11681 	/* Only conditional jumps are expected to reach here. */
11682 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
11683 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11684 		return -EINVAL;
11685 	}
11686 
11687 	if (BPF_SRC(insn->code) == BPF_X) {
11688 		if (insn->imm != 0) {
11689 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11690 			return -EINVAL;
11691 		}
11692 
11693 		/* check src1 operand */
11694 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
11695 		if (err)
11696 			return err;
11697 
11698 		if (is_pointer_value(env, insn->src_reg)) {
11699 			verbose(env, "R%d pointer comparison prohibited\n",
11700 				insn->src_reg);
11701 			return -EACCES;
11702 		}
11703 		src_reg = &regs[insn->src_reg];
11704 	} else {
11705 		if (insn->src_reg != BPF_REG_0) {
11706 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11707 			return -EINVAL;
11708 		}
11709 	}
11710 
11711 	/* check src2 operand */
11712 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11713 	if (err)
11714 		return err;
11715 
11716 	dst_reg = &regs[insn->dst_reg];
11717 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11718 
11719 	if (BPF_SRC(insn->code) == BPF_K) {
11720 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11721 	} else if (src_reg->type == SCALAR_VALUE &&
11722 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11723 		pred = is_branch_taken(dst_reg,
11724 				       tnum_subreg(src_reg->var_off).value,
11725 				       opcode,
11726 				       is_jmp32);
11727 	} else if (src_reg->type == SCALAR_VALUE &&
11728 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11729 		pred = is_branch_taken(dst_reg,
11730 				       src_reg->var_off.value,
11731 				       opcode,
11732 				       is_jmp32);
11733 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
11734 		   reg_is_pkt_pointer_any(src_reg) &&
11735 		   !is_jmp32) {
11736 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11737 	}
11738 
11739 	if (pred >= 0) {
11740 		/* If we get here with a dst_reg pointer type it is because
11741 		 * above is_branch_taken() special cased the 0 comparison.
11742 		 */
11743 		if (!__is_pointer_value(false, dst_reg))
11744 			err = mark_chain_precision(env, insn->dst_reg);
11745 		if (BPF_SRC(insn->code) == BPF_X && !err &&
11746 		    !__is_pointer_value(false, src_reg))
11747 			err = mark_chain_precision(env, insn->src_reg);
11748 		if (err)
11749 			return err;
11750 	}
11751 
11752 	if (pred == 1) {
11753 		/* Only follow the goto, ignore fall-through. If needed, push
11754 		 * the fall-through branch for simulation under speculative
11755 		 * execution.
11756 		 */
11757 		if (!env->bypass_spec_v1 &&
11758 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
11759 					       *insn_idx))
11760 			return -EFAULT;
11761 		*insn_idx += insn->off;
11762 		return 0;
11763 	} else if (pred == 0) {
11764 		/* Only follow the fall-through branch, since that's where the
11765 		 * program will go. If needed, push the goto branch for
11766 		 * simulation under speculative execution.
11767 		 */
11768 		if (!env->bypass_spec_v1 &&
11769 		    !sanitize_speculative_path(env, insn,
11770 					       *insn_idx + insn->off + 1,
11771 					       *insn_idx))
11772 			return -EFAULT;
11773 		return 0;
11774 	}
11775 
11776 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11777 				  false);
11778 	if (!other_branch)
11779 		return -EFAULT;
11780 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11781 
11782 	/* detect if we are comparing against a constant value so we can adjust
11783 	 * our min/max values for our dst register.
11784 	 * this is only legit if both are scalars (or pointers to the same
11785 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11786 	 * because otherwise the different base pointers mean the offsets aren't
11787 	 * comparable.
11788 	 */
11789 	if (BPF_SRC(insn->code) == BPF_X) {
11790 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11791 
11792 		if (dst_reg->type == SCALAR_VALUE &&
11793 		    src_reg->type == SCALAR_VALUE) {
11794 			if (tnum_is_const(src_reg->var_off) ||
11795 			    (is_jmp32 &&
11796 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
11797 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
11798 						dst_reg,
11799 						src_reg->var_off.value,
11800 						tnum_subreg(src_reg->var_off).value,
11801 						opcode, is_jmp32);
11802 			else if (tnum_is_const(dst_reg->var_off) ||
11803 				 (is_jmp32 &&
11804 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
11805 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11806 						    src_reg,
11807 						    dst_reg->var_off.value,
11808 						    tnum_subreg(dst_reg->var_off).value,
11809 						    opcode, is_jmp32);
11810 			else if (!is_jmp32 &&
11811 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
11812 				/* Comparing for equality, we can combine knowledge */
11813 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
11814 						    &other_branch_regs[insn->dst_reg],
11815 						    src_reg, dst_reg, opcode);
11816 			if (src_reg->id &&
11817 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11818 				find_equal_scalars(this_branch, src_reg);
11819 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11820 			}
11821 
11822 		}
11823 	} else if (dst_reg->type == SCALAR_VALUE) {
11824 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
11825 					dst_reg, insn->imm, (u32)insn->imm,
11826 					opcode, is_jmp32);
11827 	}
11828 
11829 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11830 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11831 		find_equal_scalars(this_branch, dst_reg);
11832 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11833 	}
11834 
11835 	/* if one pointer register is compared to another pointer
11836 	 * register check if PTR_MAYBE_NULL could be lifted.
11837 	 * E.g. register A - maybe null
11838 	 *      register B - not null
11839 	 * for JNE A, B, ... - A is not null in the false branch;
11840 	 * for JEQ A, B, ... - A is not null in the true branch.
11841 	 *
11842 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
11843 	 * not need to be null checked by the BPF program, i.e.,
11844 	 * could be null even without PTR_MAYBE_NULL marking, so
11845 	 * only propagate nullness when neither reg is that type.
11846 	 */
11847 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11848 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11849 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
11850 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
11851 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
11852 		eq_branch_regs = NULL;
11853 		switch (opcode) {
11854 		case BPF_JEQ:
11855 			eq_branch_regs = other_branch_regs;
11856 			break;
11857 		case BPF_JNE:
11858 			eq_branch_regs = regs;
11859 			break;
11860 		default:
11861 			/* do nothing */
11862 			break;
11863 		}
11864 		if (eq_branch_regs) {
11865 			if (type_may_be_null(src_reg->type))
11866 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11867 			else
11868 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11869 		}
11870 	}
11871 
11872 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11873 	 * NOTE: these optimizations below are related with pointer comparison
11874 	 *       which will never be JMP32.
11875 	 */
11876 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11877 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11878 	    type_may_be_null(dst_reg->type)) {
11879 		/* Mark all identical registers in each branch as either
11880 		 * safe or unknown depending R == 0 or R != 0 conditional.
11881 		 */
11882 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11883 				      opcode == BPF_JNE);
11884 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11885 				      opcode == BPF_JEQ);
11886 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11887 					   this_branch, other_branch) &&
11888 		   is_pointer_value(env, insn->dst_reg)) {
11889 		verbose(env, "R%d pointer comparison prohibited\n",
11890 			insn->dst_reg);
11891 		return -EACCES;
11892 	}
11893 	if (env->log.level & BPF_LOG_LEVEL)
11894 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
11895 	return 0;
11896 }
11897 
11898 /* verify BPF_LD_IMM64 instruction */
11899 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11900 {
11901 	struct bpf_insn_aux_data *aux = cur_aux(env);
11902 	struct bpf_reg_state *regs = cur_regs(env);
11903 	struct bpf_reg_state *dst_reg;
11904 	struct bpf_map *map;
11905 	int err;
11906 
11907 	if (BPF_SIZE(insn->code) != BPF_DW) {
11908 		verbose(env, "invalid BPF_LD_IMM insn\n");
11909 		return -EINVAL;
11910 	}
11911 	if (insn->off != 0) {
11912 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11913 		return -EINVAL;
11914 	}
11915 
11916 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
11917 	if (err)
11918 		return err;
11919 
11920 	dst_reg = &regs[insn->dst_reg];
11921 	if (insn->src_reg == 0) {
11922 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11923 
11924 		dst_reg->type = SCALAR_VALUE;
11925 		__mark_reg_known(&regs[insn->dst_reg], imm);
11926 		return 0;
11927 	}
11928 
11929 	/* All special src_reg cases are listed below. From this point onwards
11930 	 * we either succeed and assign a corresponding dst_reg->type after
11931 	 * zeroing the offset, or fail and reject the program.
11932 	 */
11933 	mark_reg_known_zero(env, regs, insn->dst_reg);
11934 
11935 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11936 		dst_reg->type = aux->btf_var.reg_type;
11937 		switch (base_type(dst_reg->type)) {
11938 		case PTR_TO_MEM:
11939 			dst_reg->mem_size = aux->btf_var.mem_size;
11940 			break;
11941 		case PTR_TO_BTF_ID:
11942 			dst_reg->btf = aux->btf_var.btf;
11943 			dst_reg->btf_id = aux->btf_var.btf_id;
11944 			break;
11945 		default:
11946 			verbose(env, "bpf verifier is misconfigured\n");
11947 			return -EFAULT;
11948 		}
11949 		return 0;
11950 	}
11951 
11952 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
11953 		struct bpf_prog_aux *aux = env->prog->aux;
11954 		u32 subprogno = find_subprog(env,
11955 					     env->insn_idx + insn->imm + 1);
11956 
11957 		if (!aux->func_info) {
11958 			verbose(env, "missing btf func_info\n");
11959 			return -EINVAL;
11960 		}
11961 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11962 			verbose(env, "callback function not static\n");
11963 			return -EINVAL;
11964 		}
11965 
11966 		dst_reg->type = PTR_TO_FUNC;
11967 		dst_reg->subprogno = subprogno;
11968 		return 0;
11969 	}
11970 
11971 	map = env->used_maps[aux->map_index];
11972 	dst_reg->map_ptr = map;
11973 
11974 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11975 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11976 		dst_reg->type = PTR_TO_MAP_VALUE;
11977 		dst_reg->off = aux->map_off;
11978 		WARN_ON_ONCE(map->max_entries != 1);
11979 		/* We want reg->id to be same (0) as map_value is not distinct */
11980 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11981 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11982 		dst_reg->type = CONST_PTR_TO_MAP;
11983 	} else {
11984 		verbose(env, "bpf verifier is misconfigured\n");
11985 		return -EINVAL;
11986 	}
11987 
11988 	return 0;
11989 }
11990 
11991 static bool may_access_skb(enum bpf_prog_type type)
11992 {
11993 	switch (type) {
11994 	case BPF_PROG_TYPE_SOCKET_FILTER:
11995 	case BPF_PROG_TYPE_SCHED_CLS:
11996 	case BPF_PROG_TYPE_SCHED_ACT:
11997 		return true;
11998 	default:
11999 		return false;
12000 	}
12001 }
12002 
12003 /* verify safety of LD_ABS|LD_IND instructions:
12004  * - they can only appear in the programs where ctx == skb
12005  * - since they are wrappers of function calls, they scratch R1-R5 registers,
12006  *   preserve R6-R9, and store return value into R0
12007  *
12008  * Implicit input:
12009  *   ctx == skb == R6 == CTX
12010  *
12011  * Explicit input:
12012  *   SRC == any register
12013  *   IMM == 32-bit immediate
12014  *
12015  * Output:
12016  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12017  */
12018 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12019 {
12020 	struct bpf_reg_state *regs = cur_regs(env);
12021 	static const int ctx_reg = BPF_REG_6;
12022 	u8 mode = BPF_MODE(insn->code);
12023 	int i, err;
12024 
12025 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12026 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12027 		return -EINVAL;
12028 	}
12029 
12030 	if (!env->ops->gen_ld_abs) {
12031 		verbose(env, "bpf verifier is misconfigured\n");
12032 		return -EINVAL;
12033 	}
12034 
12035 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12036 	    BPF_SIZE(insn->code) == BPF_DW ||
12037 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12038 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12039 		return -EINVAL;
12040 	}
12041 
12042 	/* check whether implicit source operand (register R6) is readable */
12043 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12044 	if (err)
12045 		return err;
12046 
12047 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12048 	 * gen_ld_abs() may terminate the program at runtime, leading to
12049 	 * reference leak.
12050 	 */
12051 	err = check_reference_leak(env);
12052 	if (err) {
12053 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12054 		return err;
12055 	}
12056 
12057 	if (env->cur_state->active_lock.ptr) {
12058 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12059 		return -EINVAL;
12060 	}
12061 
12062 	if (env->cur_state->active_rcu_lock) {
12063 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12064 		return -EINVAL;
12065 	}
12066 
12067 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12068 		verbose(env,
12069 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12070 		return -EINVAL;
12071 	}
12072 
12073 	if (mode == BPF_IND) {
12074 		/* check explicit source operand */
12075 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12076 		if (err)
12077 			return err;
12078 	}
12079 
12080 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12081 	if (err < 0)
12082 		return err;
12083 
12084 	/* reset caller saved regs to unreadable */
12085 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12086 		mark_reg_not_init(env, regs, caller_saved[i]);
12087 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12088 	}
12089 
12090 	/* mark destination R0 register as readable, since it contains
12091 	 * the value fetched from the packet.
12092 	 * Already marked as written above.
12093 	 */
12094 	mark_reg_unknown(env, regs, BPF_REG_0);
12095 	/* ld_abs load up to 32-bit skb data. */
12096 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12097 	return 0;
12098 }
12099 
12100 static int check_return_code(struct bpf_verifier_env *env)
12101 {
12102 	struct tnum enforce_attach_type_range = tnum_unknown;
12103 	const struct bpf_prog *prog = env->prog;
12104 	struct bpf_reg_state *reg;
12105 	struct tnum range = tnum_range(0, 1);
12106 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12107 	int err;
12108 	struct bpf_func_state *frame = env->cur_state->frame[0];
12109 	const bool is_subprog = frame->subprogno;
12110 
12111 	/* LSM and struct_ops func-ptr's return type could be "void" */
12112 	if (!is_subprog) {
12113 		switch (prog_type) {
12114 		case BPF_PROG_TYPE_LSM:
12115 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12116 				/* See below, can be 0 or 0-1 depending on hook. */
12117 				break;
12118 			fallthrough;
12119 		case BPF_PROG_TYPE_STRUCT_OPS:
12120 			if (!prog->aux->attach_func_proto->type)
12121 				return 0;
12122 			break;
12123 		default:
12124 			break;
12125 		}
12126 	}
12127 
12128 	/* eBPF calling convention is such that R0 is used
12129 	 * to return the value from eBPF program.
12130 	 * Make sure that it's readable at this time
12131 	 * of bpf_exit, which means that program wrote
12132 	 * something into it earlier
12133 	 */
12134 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12135 	if (err)
12136 		return err;
12137 
12138 	if (is_pointer_value(env, BPF_REG_0)) {
12139 		verbose(env, "R0 leaks addr as return value\n");
12140 		return -EACCES;
12141 	}
12142 
12143 	reg = cur_regs(env) + BPF_REG_0;
12144 
12145 	if (frame->in_async_callback_fn) {
12146 		/* enforce return zero from async callbacks like timer */
12147 		if (reg->type != SCALAR_VALUE) {
12148 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12149 				reg_type_str(env, reg->type));
12150 			return -EINVAL;
12151 		}
12152 
12153 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12154 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12155 			return -EINVAL;
12156 		}
12157 		return 0;
12158 	}
12159 
12160 	if (is_subprog) {
12161 		if (reg->type != SCALAR_VALUE) {
12162 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12163 				reg_type_str(env, reg->type));
12164 			return -EINVAL;
12165 		}
12166 		return 0;
12167 	}
12168 
12169 	switch (prog_type) {
12170 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12171 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12172 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12173 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12174 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12175 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12176 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12177 			range = tnum_range(1, 1);
12178 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12179 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12180 			range = tnum_range(0, 3);
12181 		break;
12182 	case BPF_PROG_TYPE_CGROUP_SKB:
12183 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12184 			range = tnum_range(0, 3);
12185 			enforce_attach_type_range = tnum_range(2, 3);
12186 		}
12187 		break;
12188 	case BPF_PROG_TYPE_CGROUP_SOCK:
12189 	case BPF_PROG_TYPE_SOCK_OPS:
12190 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12191 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12192 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12193 		break;
12194 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12195 		if (!env->prog->aux->attach_btf_id)
12196 			return 0;
12197 		range = tnum_const(0);
12198 		break;
12199 	case BPF_PROG_TYPE_TRACING:
12200 		switch (env->prog->expected_attach_type) {
12201 		case BPF_TRACE_FENTRY:
12202 		case BPF_TRACE_FEXIT:
12203 			range = tnum_const(0);
12204 			break;
12205 		case BPF_TRACE_RAW_TP:
12206 		case BPF_MODIFY_RETURN:
12207 			return 0;
12208 		case BPF_TRACE_ITER:
12209 			break;
12210 		default:
12211 			return -ENOTSUPP;
12212 		}
12213 		break;
12214 	case BPF_PROG_TYPE_SK_LOOKUP:
12215 		range = tnum_range(SK_DROP, SK_PASS);
12216 		break;
12217 
12218 	case BPF_PROG_TYPE_LSM:
12219 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12220 			/* Regular BPF_PROG_TYPE_LSM programs can return
12221 			 * any value.
12222 			 */
12223 			return 0;
12224 		}
12225 		if (!env->prog->aux->attach_func_proto->type) {
12226 			/* Make sure programs that attach to void
12227 			 * hooks don't try to modify return value.
12228 			 */
12229 			range = tnum_range(1, 1);
12230 		}
12231 		break;
12232 
12233 	case BPF_PROG_TYPE_EXT:
12234 		/* freplace program can return anything as its return value
12235 		 * depends on the to-be-replaced kernel func or bpf program.
12236 		 */
12237 	default:
12238 		return 0;
12239 	}
12240 
12241 	if (reg->type != SCALAR_VALUE) {
12242 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12243 			reg_type_str(env, reg->type));
12244 		return -EINVAL;
12245 	}
12246 
12247 	if (!tnum_in(range, reg->var_off)) {
12248 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12249 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12250 		    prog_type == BPF_PROG_TYPE_LSM &&
12251 		    !prog->aux->attach_func_proto->type)
12252 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12253 		return -EINVAL;
12254 	}
12255 
12256 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12257 	    tnum_in(enforce_attach_type_range, reg->var_off))
12258 		env->prog->enforce_expected_attach_type = 1;
12259 	return 0;
12260 }
12261 
12262 /* non-recursive DFS pseudo code
12263  * 1  procedure DFS-iterative(G,v):
12264  * 2      label v as discovered
12265  * 3      let S be a stack
12266  * 4      S.push(v)
12267  * 5      while S is not empty
12268  * 6            t <- S.peek()
12269  * 7            if t is what we're looking for:
12270  * 8                return t
12271  * 9            for all edges e in G.adjacentEdges(t) do
12272  * 10               if edge e is already labelled
12273  * 11                   continue with the next edge
12274  * 12               w <- G.adjacentVertex(t,e)
12275  * 13               if vertex w is not discovered and not explored
12276  * 14                   label e as tree-edge
12277  * 15                   label w as discovered
12278  * 16                   S.push(w)
12279  * 17                   continue at 5
12280  * 18               else if vertex w is discovered
12281  * 19                   label e as back-edge
12282  * 20               else
12283  * 21                   // vertex w is explored
12284  * 22                   label e as forward- or cross-edge
12285  * 23           label t as explored
12286  * 24           S.pop()
12287  *
12288  * convention:
12289  * 0x10 - discovered
12290  * 0x11 - discovered and fall-through edge labelled
12291  * 0x12 - discovered and fall-through and branch edges labelled
12292  * 0x20 - explored
12293  */
12294 
12295 enum {
12296 	DISCOVERED = 0x10,
12297 	EXPLORED = 0x20,
12298 	FALLTHROUGH = 1,
12299 	BRANCH = 2,
12300 };
12301 
12302 static u32 state_htab_size(struct bpf_verifier_env *env)
12303 {
12304 	return env->prog->len;
12305 }
12306 
12307 static struct bpf_verifier_state_list **explored_state(
12308 					struct bpf_verifier_env *env,
12309 					int idx)
12310 {
12311 	struct bpf_verifier_state *cur = env->cur_state;
12312 	struct bpf_func_state *state = cur->frame[cur->curframe];
12313 
12314 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12315 }
12316 
12317 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
12318 {
12319 	env->insn_aux_data[idx].prune_point = true;
12320 }
12321 
12322 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
12323 {
12324 	return env->insn_aux_data[insn_idx].prune_point;
12325 }
12326 
12327 enum {
12328 	DONE_EXPLORING = 0,
12329 	KEEP_EXPLORING = 1,
12330 };
12331 
12332 /* t, w, e - match pseudo-code above:
12333  * t - index of current instruction
12334  * w - next instruction
12335  * e - edge
12336  */
12337 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12338 		     bool loop_ok)
12339 {
12340 	int *insn_stack = env->cfg.insn_stack;
12341 	int *insn_state = env->cfg.insn_state;
12342 
12343 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12344 		return DONE_EXPLORING;
12345 
12346 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12347 		return DONE_EXPLORING;
12348 
12349 	if (w < 0 || w >= env->prog->len) {
12350 		verbose_linfo(env, t, "%d: ", t);
12351 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
12352 		return -EINVAL;
12353 	}
12354 
12355 	if (e == BRANCH) {
12356 		/* mark branch target for state pruning */
12357 		mark_prune_point(env, w);
12358 		mark_jmp_point(env, w);
12359 	}
12360 
12361 	if (insn_state[w] == 0) {
12362 		/* tree-edge */
12363 		insn_state[t] = DISCOVERED | e;
12364 		insn_state[w] = DISCOVERED;
12365 		if (env->cfg.cur_stack >= env->prog->len)
12366 			return -E2BIG;
12367 		insn_stack[env->cfg.cur_stack++] = w;
12368 		return KEEP_EXPLORING;
12369 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12370 		if (loop_ok && env->bpf_capable)
12371 			return DONE_EXPLORING;
12372 		verbose_linfo(env, t, "%d: ", t);
12373 		verbose_linfo(env, w, "%d: ", w);
12374 		verbose(env, "back-edge from insn %d to %d\n", t, w);
12375 		return -EINVAL;
12376 	} else if (insn_state[w] == EXPLORED) {
12377 		/* forward- or cross-edge */
12378 		insn_state[t] = DISCOVERED | e;
12379 	} else {
12380 		verbose(env, "insn state internal bug\n");
12381 		return -EFAULT;
12382 	}
12383 	return DONE_EXPLORING;
12384 }
12385 
12386 static int visit_func_call_insn(int t, struct bpf_insn *insns,
12387 				struct bpf_verifier_env *env,
12388 				bool visit_callee)
12389 {
12390 	int ret;
12391 
12392 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12393 	if (ret)
12394 		return ret;
12395 
12396 	mark_prune_point(env, t + 1);
12397 	/* when we exit from subprog, we need to record non-linear history */
12398 	mark_jmp_point(env, t + 1);
12399 
12400 	if (visit_callee) {
12401 		mark_prune_point(env, t);
12402 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12403 				/* It's ok to allow recursion from CFG point of
12404 				 * view. __check_func_call() will do the actual
12405 				 * check.
12406 				 */
12407 				bpf_pseudo_func(insns + t));
12408 	}
12409 	return ret;
12410 }
12411 
12412 /* Visits the instruction at index t and returns one of the following:
12413  *  < 0 - an error occurred
12414  *  DONE_EXPLORING - the instruction was fully explored
12415  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12416  */
12417 static int visit_insn(int t, struct bpf_verifier_env *env)
12418 {
12419 	struct bpf_insn *insns = env->prog->insnsi;
12420 	int ret;
12421 
12422 	if (bpf_pseudo_func(insns + t))
12423 		return visit_func_call_insn(t, insns, env, true);
12424 
12425 	/* All non-branch instructions have a single fall-through edge. */
12426 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12427 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
12428 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
12429 
12430 	switch (BPF_OP(insns[t].code)) {
12431 	case BPF_EXIT:
12432 		return DONE_EXPLORING;
12433 
12434 	case BPF_CALL:
12435 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
12436 			/* Mark this call insn as a prune point to trigger
12437 			 * is_state_visited() check before call itself is
12438 			 * processed by __check_func_call(). Otherwise new
12439 			 * async state will be pushed for further exploration.
12440 			 */
12441 			mark_prune_point(env, t);
12442 		return visit_func_call_insn(t, insns, env,
12443 					    insns[t].src_reg == BPF_PSEUDO_CALL);
12444 
12445 	case BPF_JA:
12446 		if (BPF_SRC(insns[t].code) != BPF_K)
12447 			return -EINVAL;
12448 
12449 		/* unconditional jump with single edge */
12450 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12451 				true);
12452 		if (ret)
12453 			return ret;
12454 
12455 		mark_prune_point(env, t + insns[t].off + 1);
12456 		mark_jmp_point(env, t + insns[t].off + 1);
12457 
12458 		return ret;
12459 
12460 	default:
12461 		/* conditional jump with two edges */
12462 		mark_prune_point(env, t);
12463 
12464 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12465 		if (ret)
12466 			return ret;
12467 
12468 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12469 	}
12470 }
12471 
12472 /* non-recursive depth-first-search to detect loops in BPF program
12473  * loop == back-edge in directed graph
12474  */
12475 static int check_cfg(struct bpf_verifier_env *env)
12476 {
12477 	int insn_cnt = env->prog->len;
12478 	int *insn_stack, *insn_state;
12479 	int ret = 0;
12480 	int i;
12481 
12482 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12483 	if (!insn_state)
12484 		return -ENOMEM;
12485 
12486 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12487 	if (!insn_stack) {
12488 		kvfree(insn_state);
12489 		return -ENOMEM;
12490 	}
12491 
12492 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12493 	insn_stack[0] = 0; /* 0 is the first instruction */
12494 	env->cfg.cur_stack = 1;
12495 
12496 	while (env->cfg.cur_stack > 0) {
12497 		int t = insn_stack[env->cfg.cur_stack - 1];
12498 
12499 		ret = visit_insn(t, env);
12500 		switch (ret) {
12501 		case DONE_EXPLORING:
12502 			insn_state[t] = EXPLORED;
12503 			env->cfg.cur_stack--;
12504 			break;
12505 		case KEEP_EXPLORING:
12506 			break;
12507 		default:
12508 			if (ret > 0) {
12509 				verbose(env, "visit_insn internal bug\n");
12510 				ret = -EFAULT;
12511 			}
12512 			goto err_free;
12513 		}
12514 	}
12515 
12516 	if (env->cfg.cur_stack < 0) {
12517 		verbose(env, "pop stack internal bug\n");
12518 		ret = -EFAULT;
12519 		goto err_free;
12520 	}
12521 
12522 	for (i = 0; i < insn_cnt; i++) {
12523 		if (insn_state[i] != EXPLORED) {
12524 			verbose(env, "unreachable insn %d\n", i);
12525 			ret = -EINVAL;
12526 			goto err_free;
12527 		}
12528 	}
12529 	ret = 0; /* cfg looks good */
12530 
12531 err_free:
12532 	kvfree(insn_state);
12533 	kvfree(insn_stack);
12534 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
12535 	return ret;
12536 }
12537 
12538 static int check_abnormal_return(struct bpf_verifier_env *env)
12539 {
12540 	int i;
12541 
12542 	for (i = 1; i < env->subprog_cnt; i++) {
12543 		if (env->subprog_info[i].has_ld_abs) {
12544 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12545 			return -EINVAL;
12546 		}
12547 		if (env->subprog_info[i].has_tail_call) {
12548 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12549 			return -EINVAL;
12550 		}
12551 	}
12552 	return 0;
12553 }
12554 
12555 /* The minimum supported BTF func info size */
12556 #define MIN_BPF_FUNCINFO_SIZE	8
12557 #define MAX_FUNCINFO_REC_SIZE	252
12558 
12559 static int check_btf_func(struct bpf_verifier_env *env,
12560 			  const union bpf_attr *attr,
12561 			  bpfptr_t uattr)
12562 {
12563 	const struct btf_type *type, *func_proto, *ret_type;
12564 	u32 i, nfuncs, urec_size, min_size;
12565 	u32 krec_size = sizeof(struct bpf_func_info);
12566 	struct bpf_func_info *krecord;
12567 	struct bpf_func_info_aux *info_aux = NULL;
12568 	struct bpf_prog *prog;
12569 	const struct btf *btf;
12570 	bpfptr_t urecord;
12571 	u32 prev_offset = 0;
12572 	bool scalar_return;
12573 	int ret = -ENOMEM;
12574 
12575 	nfuncs = attr->func_info_cnt;
12576 	if (!nfuncs) {
12577 		if (check_abnormal_return(env))
12578 			return -EINVAL;
12579 		return 0;
12580 	}
12581 
12582 	if (nfuncs != env->subprog_cnt) {
12583 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12584 		return -EINVAL;
12585 	}
12586 
12587 	urec_size = attr->func_info_rec_size;
12588 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12589 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
12590 	    urec_size % sizeof(u32)) {
12591 		verbose(env, "invalid func info rec size %u\n", urec_size);
12592 		return -EINVAL;
12593 	}
12594 
12595 	prog = env->prog;
12596 	btf = prog->aux->btf;
12597 
12598 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12599 	min_size = min_t(u32, krec_size, urec_size);
12600 
12601 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12602 	if (!krecord)
12603 		return -ENOMEM;
12604 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12605 	if (!info_aux)
12606 		goto err_free;
12607 
12608 	for (i = 0; i < nfuncs; i++) {
12609 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12610 		if (ret) {
12611 			if (ret == -E2BIG) {
12612 				verbose(env, "nonzero tailing record in func info");
12613 				/* set the size kernel expects so loader can zero
12614 				 * out the rest of the record.
12615 				 */
12616 				if (copy_to_bpfptr_offset(uattr,
12617 							  offsetof(union bpf_attr, func_info_rec_size),
12618 							  &min_size, sizeof(min_size)))
12619 					ret = -EFAULT;
12620 			}
12621 			goto err_free;
12622 		}
12623 
12624 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12625 			ret = -EFAULT;
12626 			goto err_free;
12627 		}
12628 
12629 		/* check insn_off */
12630 		ret = -EINVAL;
12631 		if (i == 0) {
12632 			if (krecord[i].insn_off) {
12633 				verbose(env,
12634 					"nonzero insn_off %u for the first func info record",
12635 					krecord[i].insn_off);
12636 				goto err_free;
12637 			}
12638 		} else if (krecord[i].insn_off <= prev_offset) {
12639 			verbose(env,
12640 				"same or smaller insn offset (%u) than previous func info record (%u)",
12641 				krecord[i].insn_off, prev_offset);
12642 			goto err_free;
12643 		}
12644 
12645 		if (env->subprog_info[i].start != krecord[i].insn_off) {
12646 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12647 			goto err_free;
12648 		}
12649 
12650 		/* check type_id */
12651 		type = btf_type_by_id(btf, krecord[i].type_id);
12652 		if (!type || !btf_type_is_func(type)) {
12653 			verbose(env, "invalid type id %d in func info",
12654 				krecord[i].type_id);
12655 			goto err_free;
12656 		}
12657 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12658 
12659 		func_proto = btf_type_by_id(btf, type->type);
12660 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12661 			/* btf_func_check() already verified it during BTF load */
12662 			goto err_free;
12663 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12664 		scalar_return =
12665 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12666 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12667 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12668 			goto err_free;
12669 		}
12670 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12671 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12672 			goto err_free;
12673 		}
12674 
12675 		prev_offset = krecord[i].insn_off;
12676 		bpfptr_add(&urecord, urec_size);
12677 	}
12678 
12679 	prog->aux->func_info = krecord;
12680 	prog->aux->func_info_cnt = nfuncs;
12681 	prog->aux->func_info_aux = info_aux;
12682 	return 0;
12683 
12684 err_free:
12685 	kvfree(krecord);
12686 	kfree(info_aux);
12687 	return ret;
12688 }
12689 
12690 static void adjust_btf_func(struct bpf_verifier_env *env)
12691 {
12692 	struct bpf_prog_aux *aux = env->prog->aux;
12693 	int i;
12694 
12695 	if (!aux->func_info)
12696 		return;
12697 
12698 	for (i = 0; i < env->subprog_cnt; i++)
12699 		aux->func_info[i].insn_off = env->subprog_info[i].start;
12700 }
12701 
12702 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
12703 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
12704 
12705 static int check_btf_line(struct bpf_verifier_env *env,
12706 			  const union bpf_attr *attr,
12707 			  bpfptr_t uattr)
12708 {
12709 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12710 	struct bpf_subprog_info *sub;
12711 	struct bpf_line_info *linfo;
12712 	struct bpf_prog *prog;
12713 	const struct btf *btf;
12714 	bpfptr_t ulinfo;
12715 	int err;
12716 
12717 	nr_linfo = attr->line_info_cnt;
12718 	if (!nr_linfo)
12719 		return 0;
12720 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12721 		return -EINVAL;
12722 
12723 	rec_size = attr->line_info_rec_size;
12724 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12725 	    rec_size > MAX_LINEINFO_REC_SIZE ||
12726 	    rec_size & (sizeof(u32) - 1))
12727 		return -EINVAL;
12728 
12729 	/* Need to zero it in case the userspace may
12730 	 * pass in a smaller bpf_line_info object.
12731 	 */
12732 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12733 			 GFP_KERNEL | __GFP_NOWARN);
12734 	if (!linfo)
12735 		return -ENOMEM;
12736 
12737 	prog = env->prog;
12738 	btf = prog->aux->btf;
12739 
12740 	s = 0;
12741 	sub = env->subprog_info;
12742 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12743 	expected_size = sizeof(struct bpf_line_info);
12744 	ncopy = min_t(u32, expected_size, rec_size);
12745 	for (i = 0; i < nr_linfo; i++) {
12746 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12747 		if (err) {
12748 			if (err == -E2BIG) {
12749 				verbose(env, "nonzero tailing record in line_info");
12750 				if (copy_to_bpfptr_offset(uattr,
12751 							  offsetof(union bpf_attr, line_info_rec_size),
12752 							  &expected_size, sizeof(expected_size)))
12753 					err = -EFAULT;
12754 			}
12755 			goto err_free;
12756 		}
12757 
12758 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12759 			err = -EFAULT;
12760 			goto err_free;
12761 		}
12762 
12763 		/*
12764 		 * Check insn_off to ensure
12765 		 * 1) strictly increasing AND
12766 		 * 2) bounded by prog->len
12767 		 *
12768 		 * The linfo[0].insn_off == 0 check logically falls into
12769 		 * the later "missing bpf_line_info for func..." case
12770 		 * because the first linfo[0].insn_off must be the
12771 		 * first sub also and the first sub must have
12772 		 * subprog_info[0].start == 0.
12773 		 */
12774 		if ((i && linfo[i].insn_off <= prev_offset) ||
12775 		    linfo[i].insn_off >= prog->len) {
12776 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12777 				i, linfo[i].insn_off, prev_offset,
12778 				prog->len);
12779 			err = -EINVAL;
12780 			goto err_free;
12781 		}
12782 
12783 		if (!prog->insnsi[linfo[i].insn_off].code) {
12784 			verbose(env,
12785 				"Invalid insn code at line_info[%u].insn_off\n",
12786 				i);
12787 			err = -EINVAL;
12788 			goto err_free;
12789 		}
12790 
12791 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12792 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12793 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12794 			err = -EINVAL;
12795 			goto err_free;
12796 		}
12797 
12798 		if (s != env->subprog_cnt) {
12799 			if (linfo[i].insn_off == sub[s].start) {
12800 				sub[s].linfo_idx = i;
12801 				s++;
12802 			} else if (sub[s].start < linfo[i].insn_off) {
12803 				verbose(env, "missing bpf_line_info for func#%u\n", s);
12804 				err = -EINVAL;
12805 				goto err_free;
12806 			}
12807 		}
12808 
12809 		prev_offset = linfo[i].insn_off;
12810 		bpfptr_add(&ulinfo, rec_size);
12811 	}
12812 
12813 	if (s != env->subprog_cnt) {
12814 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12815 			env->subprog_cnt - s, s);
12816 		err = -EINVAL;
12817 		goto err_free;
12818 	}
12819 
12820 	prog->aux->linfo = linfo;
12821 	prog->aux->nr_linfo = nr_linfo;
12822 
12823 	return 0;
12824 
12825 err_free:
12826 	kvfree(linfo);
12827 	return err;
12828 }
12829 
12830 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
12831 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
12832 
12833 static int check_core_relo(struct bpf_verifier_env *env,
12834 			   const union bpf_attr *attr,
12835 			   bpfptr_t uattr)
12836 {
12837 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12838 	struct bpf_core_relo core_relo = {};
12839 	struct bpf_prog *prog = env->prog;
12840 	const struct btf *btf = prog->aux->btf;
12841 	struct bpf_core_ctx ctx = {
12842 		.log = &env->log,
12843 		.btf = btf,
12844 	};
12845 	bpfptr_t u_core_relo;
12846 	int err;
12847 
12848 	nr_core_relo = attr->core_relo_cnt;
12849 	if (!nr_core_relo)
12850 		return 0;
12851 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12852 		return -EINVAL;
12853 
12854 	rec_size = attr->core_relo_rec_size;
12855 	if (rec_size < MIN_CORE_RELO_SIZE ||
12856 	    rec_size > MAX_CORE_RELO_SIZE ||
12857 	    rec_size % sizeof(u32))
12858 		return -EINVAL;
12859 
12860 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12861 	expected_size = sizeof(struct bpf_core_relo);
12862 	ncopy = min_t(u32, expected_size, rec_size);
12863 
12864 	/* Unlike func_info and line_info, copy and apply each CO-RE
12865 	 * relocation record one at a time.
12866 	 */
12867 	for (i = 0; i < nr_core_relo; i++) {
12868 		/* future proofing when sizeof(bpf_core_relo) changes */
12869 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12870 		if (err) {
12871 			if (err == -E2BIG) {
12872 				verbose(env, "nonzero tailing record in core_relo");
12873 				if (copy_to_bpfptr_offset(uattr,
12874 							  offsetof(union bpf_attr, core_relo_rec_size),
12875 							  &expected_size, sizeof(expected_size)))
12876 					err = -EFAULT;
12877 			}
12878 			break;
12879 		}
12880 
12881 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12882 			err = -EFAULT;
12883 			break;
12884 		}
12885 
12886 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12887 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12888 				i, core_relo.insn_off, prog->len);
12889 			err = -EINVAL;
12890 			break;
12891 		}
12892 
12893 		err = bpf_core_apply(&ctx, &core_relo, i,
12894 				     &prog->insnsi[core_relo.insn_off / 8]);
12895 		if (err)
12896 			break;
12897 		bpfptr_add(&u_core_relo, rec_size);
12898 	}
12899 	return err;
12900 }
12901 
12902 static int check_btf_info(struct bpf_verifier_env *env,
12903 			  const union bpf_attr *attr,
12904 			  bpfptr_t uattr)
12905 {
12906 	struct btf *btf;
12907 	int err;
12908 
12909 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
12910 		if (check_abnormal_return(env))
12911 			return -EINVAL;
12912 		return 0;
12913 	}
12914 
12915 	btf = btf_get_by_fd(attr->prog_btf_fd);
12916 	if (IS_ERR(btf))
12917 		return PTR_ERR(btf);
12918 	if (btf_is_kernel(btf)) {
12919 		btf_put(btf);
12920 		return -EACCES;
12921 	}
12922 	env->prog->aux->btf = btf;
12923 
12924 	err = check_btf_func(env, attr, uattr);
12925 	if (err)
12926 		return err;
12927 
12928 	err = check_btf_line(env, attr, uattr);
12929 	if (err)
12930 		return err;
12931 
12932 	err = check_core_relo(env, attr, uattr);
12933 	if (err)
12934 		return err;
12935 
12936 	return 0;
12937 }
12938 
12939 /* check %cur's range satisfies %old's */
12940 static bool range_within(struct bpf_reg_state *old,
12941 			 struct bpf_reg_state *cur)
12942 {
12943 	return old->umin_value <= cur->umin_value &&
12944 	       old->umax_value >= cur->umax_value &&
12945 	       old->smin_value <= cur->smin_value &&
12946 	       old->smax_value >= cur->smax_value &&
12947 	       old->u32_min_value <= cur->u32_min_value &&
12948 	       old->u32_max_value >= cur->u32_max_value &&
12949 	       old->s32_min_value <= cur->s32_min_value &&
12950 	       old->s32_max_value >= cur->s32_max_value;
12951 }
12952 
12953 /* If in the old state two registers had the same id, then they need to have
12954  * the same id in the new state as well.  But that id could be different from
12955  * the old state, so we need to track the mapping from old to new ids.
12956  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12957  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12958  * regs with a different old id could still have new id 9, we don't care about
12959  * that.
12960  * So we look through our idmap to see if this old id has been seen before.  If
12961  * so, we require the new id to match; otherwise, we add the id pair to the map.
12962  */
12963 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12964 {
12965 	unsigned int i;
12966 
12967 	/* either both IDs should be set or both should be zero */
12968 	if (!!old_id != !!cur_id)
12969 		return false;
12970 
12971 	if (old_id == 0) /* cur_id == 0 as well */
12972 		return true;
12973 
12974 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12975 		if (!idmap[i].old) {
12976 			/* Reached an empty slot; haven't seen this id before */
12977 			idmap[i].old = old_id;
12978 			idmap[i].cur = cur_id;
12979 			return true;
12980 		}
12981 		if (idmap[i].old == old_id)
12982 			return idmap[i].cur == cur_id;
12983 	}
12984 	/* We ran out of idmap slots, which should be impossible */
12985 	WARN_ON_ONCE(1);
12986 	return false;
12987 }
12988 
12989 static void clean_func_state(struct bpf_verifier_env *env,
12990 			     struct bpf_func_state *st)
12991 {
12992 	enum bpf_reg_liveness live;
12993 	int i, j;
12994 
12995 	for (i = 0; i < BPF_REG_FP; i++) {
12996 		live = st->regs[i].live;
12997 		/* liveness must not touch this register anymore */
12998 		st->regs[i].live |= REG_LIVE_DONE;
12999 		if (!(live & REG_LIVE_READ))
13000 			/* since the register is unused, clear its state
13001 			 * to make further comparison simpler
13002 			 */
13003 			__mark_reg_not_init(env, &st->regs[i]);
13004 	}
13005 
13006 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
13007 		live = st->stack[i].spilled_ptr.live;
13008 		/* liveness must not touch this stack slot anymore */
13009 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13010 		if (!(live & REG_LIVE_READ)) {
13011 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13012 			for (j = 0; j < BPF_REG_SIZE; j++)
13013 				st->stack[i].slot_type[j] = STACK_INVALID;
13014 		}
13015 	}
13016 }
13017 
13018 static void clean_verifier_state(struct bpf_verifier_env *env,
13019 				 struct bpf_verifier_state *st)
13020 {
13021 	int i;
13022 
13023 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13024 		/* all regs in this state in all frames were already marked */
13025 		return;
13026 
13027 	for (i = 0; i <= st->curframe; i++)
13028 		clean_func_state(env, st->frame[i]);
13029 }
13030 
13031 /* the parentage chains form a tree.
13032  * the verifier states are added to state lists at given insn and
13033  * pushed into state stack for future exploration.
13034  * when the verifier reaches bpf_exit insn some of the verifer states
13035  * stored in the state lists have their final liveness state already,
13036  * but a lot of states will get revised from liveness point of view when
13037  * the verifier explores other branches.
13038  * Example:
13039  * 1: r0 = 1
13040  * 2: if r1 == 100 goto pc+1
13041  * 3: r0 = 2
13042  * 4: exit
13043  * when the verifier reaches exit insn the register r0 in the state list of
13044  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13045  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13046  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13047  *
13048  * Since the verifier pushes the branch states as it sees them while exploring
13049  * the program the condition of walking the branch instruction for the second
13050  * time means that all states below this branch were already explored and
13051  * their final liveness marks are already propagated.
13052  * Hence when the verifier completes the search of state list in is_state_visited()
13053  * we can call this clean_live_states() function to mark all liveness states
13054  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13055  * will not be used.
13056  * This function also clears the registers and stack for states that !READ
13057  * to simplify state merging.
13058  *
13059  * Important note here that walking the same branch instruction in the callee
13060  * doesn't meant that the states are DONE. The verifier has to compare
13061  * the callsites
13062  */
13063 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13064 			      struct bpf_verifier_state *cur)
13065 {
13066 	struct bpf_verifier_state_list *sl;
13067 	int i;
13068 
13069 	sl = *explored_state(env, insn);
13070 	while (sl) {
13071 		if (sl->state.branches)
13072 			goto next;
13073 		if (sl->state.insn_idx != insn ||
13074 		    sl->state.curframe != cur->curframe)
13075 			goto next;
13076 		for (i = 0; i <= cur->curframe; i++)
13077 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13078 				goto next;
13079 		clean_verifier_state(env, &sl->state);
13080 next:
13081 		sl = sl->next;
13082 	}
13083 }
13084 
13085 static bool regs_exact(const struct bpf_reg_state *rold,
13086 		       const struct bpf_reg_state *rcur,
13087 		       struct bpf_id_pair *idmap)
13088 {
13089 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13090 	       check_ids(rold->id, rcur->id, idmap) &&
13091 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13092 }
13093 
13094 /* Returns true if (rold safe implies rcur safe) */
13095 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13096 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13097 {
13098 	if (!(rold->live & REG_LIVE_READ))
13099 		/* explored state didn't use this */
13100 		return true;
13101 	if (rold->type == NOT_INIT)
13102 		/* explored state can't have used this */
13103 		return true;
13104 	if (rcur->type == NOT_INIT)
13105 		return false;
13106 
13107 	/* Enforce that register types have to match exactly, including their
13108 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13109 	 * rule.
13110 	 *
13111 	 * One can make a point that using a pointer register as unbounded
13112 	 * SCALAR would be technically acceptable, but this could lead to
13113 	 * pointer leaks because scalars are allowed to leak while pointers
13114 	 * are not. We could make this safe in special cases if root is
13115 	 * calling us, but it's probably not worth the hassle.
13116 	 *
13117 	 * Also, register types that are *not* MAYBE_NULL could technically be
13118 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13119 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13120 	 * to the same map).
13121 	 * However, if the old MAYBE_NULL register then got NULL checked,
13122 	 * doing so could have affected others with the same id, and we can't
13123 	 * check for that because we lost the id when we converted to
13124 	 * a non-MAYBE_NULL variant.
13125 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13126 	 * non-MAYBE_NULL registers as well.
13127 	 */
13128 	if (rold->type != rcur->type)
13129 		return false;
13130 
13131 	switch (base_type(rold->type)) {
13132 	case SCALAR_VALUE:
13133 		if (regs_exact(rold, rcur, idmap))
13134 			return true;
13135 		if (env->explore_alu_limits)
13136 			return false;
13137 		if (!rold->precise)
13138 			return true;
13139 		/* new val must satisfy old val knowledge */
13140 		return range_within(rold, rcur) &&
13141 		       tnum_in(rold->var_off, rcur->var_off);
13142 	case PTR_TO_MAP_KEY:
13143 	case PTR_TO_MAP_VALUE:
13144 		/* If the new min/max/var_off satisfy the old ones and
13145 		 * everything else matches, we are OK.
13146 		 */
13147 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13148 		       range_within(rold, rcur) &&
13149 		       tnum_in(rold->var_off, rcur->var_off) &&
13150 		       check_ids(rold->id, rcur->id, idmap);
13151 	case PTR_TO_PACKET_META:
13152 	case PTR_TO_PACKET:
13153 		/* We must have at least as much range as the old ptr
13154 		 * did, so that any accesses which were safe before are
13155 		 * still safe.  This is true even if old range < old off,
13156 		 * since someone could have accessed through (ptr - k), or
13157 		 * even done ptr -= k in a register, to get a safe access.
13158 		 */
13159 		if (rold->range > rcur->range)
13160 			return false;
13161 		/* If the offsets don't match, we can't trust our alignment;
13162 		 * nor can we be sure that we won't fall out of range.
13163 		 */
13164 		if (rold->off != rcur->off)
13165 			return false;
13166 		/* id relations must be preserved */
13167 		if (!check_ids(rold->id, rcur->id, idmap))
13168 			return false;
13169 		/* new val must satisfy old val knowledge */
13170 		return range_within(rold, rcur) &&
13171 		       tnum_in(rold->var_off, rcur->var_off);
13172 	case PTR_TO_STACK:
13173 		/* two stack pointers are equal only if they're pointing to
13174 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13175 		 */
13176 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13177 	default:
13178 		return regs_exact(rold, rcur, idmap);
13179 	}
13180 }
13181 
13182 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13183 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13184 {
13185 	int i, spi;
13186 
13187 	/* walk slots of the explored stack and ignore any additional
13188 	 * slots in the current stack, since explored(safe) state
13189 	 * didn't use them
13190 	 */
13191 	for (i = 0; i < old->allocated_stack; i++) {
13192 		spi = i / BPF_REG_SIZE;
13193 
13194 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13195 			i += BPF_REG_SIZE - 1;
13196 			/* explored state didn't use this */
13197 			continue;
13198 		}
13199 
13200 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13201 			continue;
13202 
13203 		/* explored stack has more populated slots than current stack
13204 		 * and these slots were used
13205 		 */
13206 		if (i >= cur->allocated_stack)
13207 			return false;
13208 
13209 		/* if old state was safe with misc data in the stack
13210 		 * it will be safe with zero-initialized stack.
13211 		 * The opposite is not true
13212 		 */
13213 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13214 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13215 			continue;
13216 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13217 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13218 			/* Ex: old explored (safe) state has STACK_SPILL in
13219 			 * this stack slot, but current has STACK_MISC ->
13220 			 * this verifier states are not equivalent,
13221 			 * return false to continue verification of this path
13222 			 */
13223 			return false;
13224 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13225 			continue;
13226 		if (!is_spilled_reg(&old->stack[spi]))
13227 			continue;
13228 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
13229 			     &cur->stack[spi].spilled_ptr, idmap))
13230 			/* when explored and current stack slot are both storing
13231 			 * spilled registers, check that stored pointers types
13232 			 * are the same as well.
13233 			 * Ex: explored safe path could have stored
13234 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13235 			 * but current path has stored:
13236 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13237 			 * such verifier states are not equivalent.
13238 			 * return false to continue verification of this path
13239 			 */
13240 			return false;
13241 	}
13242 	return true;
13243 }
13244 
13245 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
13246 		    struct bpf_id_pair *idmap)
13247 {
13248 	int i;
13249 
13250 	if (old->acquired_refs != cur->acquired_refs)
13251 		return false;
13252 
13253 	for (i = 0; i < old->acquired_refs; i++) {
13254 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
13255 			return false;
13256 	}
13257 
13258 	return true;
13259 }
13260 
13261 /* compare two verifier states
13262  *
13263  * all states stored in state_list are known to be valid, since
13264  * verifier reached 'bpf_exit' instruction through them
13265  *
13266  * this function is called when verifier exploring different branches of
13267  * execution popped from the state stack. If it sees an old state that has
13268  * more strict register state and more strict stack state then this execution
13269  * branch doesn't need to be explored further, since verifier already
13270  * concluded that more strict state leads to valid finish.
13271  *
13272  * Therefore two states are equivalent if register state is more conservative
13273  * and explored stack state is more conservative than the current one.
13274  * Example:
13275  *       explored                   current
13276  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13277  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13278  *
13279  * In other words if current stack state (one being explored) has more
13280  * valid slots than old one that already passed validation, it means
13281  * the verifier can stop exploring and conclude that current state is valid too
13282  *
13283  * Similarly with registers. If explored state has register type as invalid
13284  * whereas register type in current state is meaningful, it means that
13285  * the current state will reach 'bpf_exit' instruction safely
13286  */
13287 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13288 			      struct bpf_func_state *cur)
13289 {
13290 	int i;
13291 
13292 	for (i = 0; i < MAX_BPF_REG; i++)
13293 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
13294 			     env->idmap_scratch))
13295 			return false;
13296 
13297 	if (!stacksafe(env, old, cur, env->idmap_scratch))
13298 		return false;
13299 
13300 	if (!refsafe(old, cur, env->idmap_scratch))
13301 		return false;
13302 
13303 	return true;
13304 }
13305 
13306 static bool states_equal(struct bpf_verifier_env *env,
13307 			 struct bpf_verifier_state *old,
13308 			 struct bpf_verifier_state *cur)
13309 {
13310 	int i;
13311 
13312 	if (old->curframe != cur->curframe)
13313 		return false;
13314 
13315 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13316 
13317 	/* Verification state from speculative execution simulation
13318 	 * must never prune a non-speculative execution one.
13319 	 */
13320 	if (old->speculative && !cur->speculative)
13321 		return false;
13322 
13323 	if (old->active_lock.ptr != cur->active_lock.ptr)
13324 		return false;
13325 
13326 	/* Old and cur active_lock's have to be either both present
13327 	 * or both absent.
13328 	 */
13329 	if (!!old->active_lock.id != !!cur->active_lock.id)
13330 		return false;
13331 
13332 	if (old->active_lock.id &&
13333 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
13334 		return false;
13335 
13336 	if (old->active_rcu_lock != cur->active_rcu_lock)
13337 		return false;
13338 
13339 	/* for states to be equal callsites have to be the same
13340 	 * and all frame states need to be equivalent
13341 	 */
13342 	for (i = 0; i <= old->curframe; i++) {
13343 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
13344 			return false;
13345 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13346 			return false;
13347 	}
13348 	return true;
13349 }
13350 
13351 /* Return 0 if no propagation happened. Return negative error code if error
13352  * happened. Otherwise, return the propagated bit.
13353  */
13354 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13355 				  struct bpf_reg_state *reg,
13356 				  struct bpf_reg_state *parent_reg)
13357 {
13358 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13359 	u8 flag = reg->live & REG_LIVE_READ;
13360 	int err;
13361 
13362 	/* When comes here, read flags of PARENT_REG or REG could be any of
13363 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13364 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13365 	 */
13366 	if (parent_flag == REG_LIVE_READ64 ||
13367 	    /* Or if there is no read flag from REG. */
13368 	    !flag ||
13369 	    /* Or if the read flag from REG is the same as PARENT_REG. */
13370 	    parent_flag == flag)
13371 		return 0;
13372 
13373 	err = mark_reg_read(env, reg, parent_reg, flag);
13374 	if (err)
13375 		return err;
13376 
13377 	return flag;
13378 }
13379 
13380 /* A write screens off any subsequent reads; but write marks come from the
13381  * straight-line code between a state and its parent.  When we arrive at an
13382  * equivalent state (jump target or such) we didn't arrive by the straight-line
13383  * code, so read marks in the state must propagate to the parent regardless
13384  * of the state's write marks. That's what 'parent == state->parent' comparison
13385  * in mark_reg_read() is for.
13386  */
13387 static int propagate_liveness(struct bpf_verifier_env *env,
13388 			      const struct bpf_verifier_state *vstate,
13389 			      struct bpf_verifier_state *vparent)
13390 {
13391 	struct bpf_reg_state *state_reg, *parent_reg;
13392 	struct bpf_func_state *state, *parent;
13393 	int i, frame, err = 0;
13394 
13395 	if (vparent->curframe != vstate->curframe) {
13396 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
13397 		     vparent->curframe, vstate->curframe);
13398 		return -EFAULT;
13399 	}
13400 	/* Propagate read liveness of registers... */
13401 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13402 	for (frame = 0; frame <= vstate->curframe; frame++) {
13403 		parent = vparent->frame[frame];
13404 		state = vstate->frame[frame];
13405 		parent_reg = parent->regs;
13406 		state_reg = state->regs;
13407 		/* We don't need to worry about FP liveness, it's read-only */
13408 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13409 			err = propagate_liveness_reg(env, &state_reg[i],
13410 						     &parent_reg[i]);
13411 			if (err < 0)
13412 				return err;
13413 			if (err == REG_LIVE_READ64)
13414 				mark_insn_zext(env, &parent_reg[i]);
13415 		}
13416 
13417 		/* Propagate stack slots. */
13418 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13419 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13420 			parent_reg = &parent->stack[i].spilled_ptr;
13421 			state_reg = &state->stack[i].spilled_ptr;
13422 			err = propagate_liveness_reg(env, state_reg,
13423 						     parent_reg);
13424 			if (err < 0)
13425 				return err;
13426 		}
13427 	}
13428 	return 0;
13429 }
13430 
13431 /* find precise scalars in the previous equivalent state and
13432  * propagate them into the current state
13433  */
13434 static int propagate_precision(struct bpf_verifier_env *env,
13435 			       const struct bpf_verifier_state *old)
13436 {
13437 	struct bpf_reg_state *state_reg;
13438 	struct bpf_func_state *state;
13439 	int i, err = 0, fr;
13440 
13441 	for (fr = old->curframe; fr >= 0; fr--) {
13442 		state = old->frame[fr];
13443 		state_reg = state->regs;
13444 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13445 			if (state_reg->type != SCALAR_VALUE ||
13446 			    !state_reg->precise)
13447 				continue;
13448 			if (env->log.level & BPF_LOG_LEVEL2)
13449 				verbose(env, "frame %d: propagating r%d\n", i, fr);
13450 			err = mark_chain_precision_frame(env, fr, i);
13451 			if (err < 0)
13452 				return err;
13453 		}
13454 
13455 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13456 			if (!is_spilled_reg(&state->stack[i]))
13457 				continue;
13458 			state_reg = &state->stack[i].spilled_ptr;
13459 			if (state_reg->type != SCALAR_VALUE ||
13460 			    !state_reg->precise)
13461 				continue;
13462 			if (env->log.level & BPF_LOG_LEVEL2)
13463 				verbose(env, "frame %d: propagating fp%d\n",
13464 					(-i - 1) * BPF_REG_SIZE, fr);
13465 			err = mark_chain_precision_stack_frame(env, fr, i);
13466 			if (err < 0)
13467 				return err;
13468 		}
13469 	}
13470 	return 0;
13471 }
13472 
13473 static bool states_maybe_looping(struct bpf_verifier_state *old,
13474 				 struct bpf_verifier_state *cur)
13475 {
13476 	struct bpf_func_state *fold, *fcur;
13477 	int i, fr = cur->curframe;
13478 
13479 	if (old->curframe != fr)
13480 		return false;
13481 
13482 	fold = old->frame[fr];
13483 	fcur = cur->frame[fr];
13484 	for (i = 0; i < MAX_BPF_REG; i++)
13485 		if (memcmp(&fold->regs[i], &fcur->regs[i],
13486 			   offsetof(struct bpf_reg_state, parent)))
13487 			return false;
13488 	return true;
13489 }
13490 
13491 
13492 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13493 {
13494 	struct bpf_verifier_state_list *new_sl;
13495 	struct bpf_verifier_state_list *sl, **pprev;
13496 	struct bpf_verifier_state *cur = env->cur_state, *new;
13497 	int i, j, err, states_cnt = 0;
13498 	bool add_new_state = env->test_state_freq ? true : false;
13499 
13500 	/* bpf progs typically have pruning point every 4 instructions
13501 	 * http://vger.kernel.org/bpfconf2019.html#session-1
13502 	 * Do not add new state for future pruning if the verifier hasn't seen
13503 	 * at least 2 jumps and at least 8 instructions.
13504 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13505 	 * In tests that amounts to up to 50% reduction into total verifier
13506 	 * memory consumption and 20% verifier time speedup.
13507 	 */
13508 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13509 	    env->insn_processed - env->prev_insn_processed >= 8)
13510 		add_new_state = true;
13511 
13512 	pprev = explored_state(env, insn_idx);
13513 	sl = *pprev;
13514 
13515 	clean_live_states(env, insn_idx, cur);
13516 
13517 	while (sl) {
13518 		states_cnt++;
13519 		if (sl->state.insn_idx != insn_idx)
13520 			goto next;
13521 
13522 		if (sl->state.branches) {
13523 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13524 
13525 			if (frame->in_async_callback_fn &&
13526 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13527 				/* Different async_entry_cnt means that the verifier is
13528 				 * processing another entry into async callback.
13529 				 * Seeing the same state is not an indication of infinite
13530 				 * loop or infinite recursion.
13531 				 * But finding the same state doesn't mean that it's safe
13532 				 * to stop processing the current state. The previous state
13533 				 * hasn't yet reached bpf_exit, since state.branches > 0.
13534 				 * Checking in_async_callback_fn alone is not enough either.
13535 				 * Since the verifier still needs to catch infinite loops
13536 				 * inside async callbacks.
13537 				 */
13538 			} else if (states_maybe_looping(&sl->state, cur) &&
13539 				   states_equal(env, &sl->state, cur)) {
13540 				verbose_linfo(env, insn_idx, "; ");
13541 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13542 				return -EINVAL;
13543 			}
13544 			/* if the verifier is processing a loop, avoid adding new state
13545 			 * too often, since different loop iterations have distinct
13546 			 * states and may not help future pruning.
13547 			 * This threshold shouldn't be too low to make sure that
13548 			 * a loop with large bound will be rejected quickly.
13549 			 * The most abusive loop will be:
13550 			 * r1 += 1
13551 			 * if r1 < 1000000 goto pc-2
13552 			 * 1M insn_procssed limit / 100 == 10k peak states.
13553 			 * This threshold shouldn't be too high either, since states
13554 			 * at the end of the loop are likely to be useful in pruning.
13555 			 */
13556 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13557 			    env->insn_processed - env->prev_insn_processed < 100)
13558 				add_new_state = false;
13559 			goto miss;
13560 		}
13561 		if (states_equal(env, &sl->state, cur)) {
13562 			sl->hit_cnt++;
13563 			/* reached equivalent register/stack state,
13564 			 * prune the search.
13565 			 * Registers read by the continuation are read by us.
13566 			 * If we have any write marks in env->cur_state, they
13567 			 * will prevent corresponding reads in the continuation
13568 			 * from reaching our parent (an explored_state).  Our
13569 			 * own state will get the read marks recorded, but
13570 			 * they'll be immediately forgotten as we're pruning
13571 			 * this state and will pop a new one.
13572 			 */
13573 			err = propagate_liveness(env, &sl->state, cur);
13574 
13575 			/* if previous state reached the exit with precision and
13576 			 * current state is equivalent to it (except precsion marks)
13577 			 * the precision needs to be propagated back in
13578 			 * the current state.
13579 			 */
13580 			err = err ? : push_jmp_history(env, cur);
13581 			err = err ? : propagate_precision(env, &sl->state);
13582 			if (err)
13583 				return err;
13584 			return 1;
13585 		}
13586 miss:
13587 		/* when new state is not going to be added do not increase miss count.
13588 		 * Otherwise several loop iterations will remove the state
13589 		 * recorded earlier. The goal of these heuristics is to have
13590 		 * states from some iterations of the loop (some in the beginning
13591 		 * and some at the end) to help pruning.
13592 		 */
13593 		if (add_new_state)
13594 			sl->miss_cnt++;
13595 		/* heuristic to determine whether this state is beneficial
13596 		 * to keep checking from state equivalence point of view.
13597 		 * Higher numbers increase max_states_per_insn and verification time,
13598 		 * but do not meaningfully decrease insn_processed.
13599 		 */
13600 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13601 			/* the state is unlikely to be useful. Remove it to
13602 			 * speed up verification
13603 			 */
13604 			*pprev = sl->next;
13605 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13606 				u32 br = sl->state.branches;
13607 
13608 				WARN_ONCE(br,
13609 					  "BUG live_done but branches_to_explore %d\n",
13610 					  br);
13611 				free_verifier_state(&sl->state, false);
13612 				kfree(sl);
13613 				env->peak_states--;
13614 			} else {
13615 				/* cannot free this state, since parentage chain may
13616 				 * walk it later. Add it for free_list instead to
13617 				 * be freed at the end of verification
13618 				 */
13619 				sl->next = env->free_list;
13620 				env->free_list = sl;
13621 			}
13622 			sl = *pprev;
13623 			continue;
13624 		}
13625 next:
13626 		pprev = &sl->next;
13627 		sl = *pprev;
13628 	}
13629 
13630 	if (env->max_states_per_insn < states_cnt)
13631 		env->max_states_per_insn = states_cnt;
13632 
13633 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13634 		return 0;
13635 
13636 	if (!add_new_state)
13637 		return 0;
13638 
13639 	/* There were no equivalent states, remember the current one.
13640 	 * Technically the current state is not proven to be safe yet,
13641 	 * but it will either reach outer most bpf_exit (which means it's safe)
13642 	 * or it will be rejected. When there are no loops the verifier won't be
13643 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13644 	 * again on the way to bpf_exit.
13645 	 * When looping the sl->state.branches will be > 0 and this state
13646 	 * will not be considered for equivalence until branches == 0.
13647 	 */
13648 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13649 	if (!new_sl)
13650 		return -ENOMEM;
13651 	env->total_states++;
13652 	env->peak_states++;
13653 	env->prev_jmps_processed = env->jmps_processed;
13654 	env->prev_insn_processed = env->insn_processed;
13655 
13656 	/* forget precise markings we inherited, see __mark_chain_precision */
13657 	if (env->bpf_capable)
13658 		mark_all_scalars_imprecise(env, cur);
13659 
13660 	/* add new state to the head of linked list */
13661 	new = &new_sl->state;
13662 	err = copy_verifier_state(new, cur);
13663 	if (err) {
13664 		free_verifier_state(new, false);
13665 		kfree(new_sl);
13666 		return err;
13667 	}
13668 	new->insn_idx = insn_idx;
13669 	WARN_ONCE(new->branches != 1,
13670 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13671 
13672 	cur->parent = new;
13673 	cur->first_insn_idx = insn_idx;
13674 	clear_jmp_history(cur);
13675 	new_sl->next = *explored_state(env, insn_idx);
13676 	*explored_state(env, insn_idx) = new_sl;
13677 	/* connect new state to parentage chain. Current frame needs all
13678 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
13679 	 * to the stack implicitly by JITs) so in callers' frames connect just
13680 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13681 	 * the state of the call instruction (with WRITTEN set), and r0 comes
13682 	 * from callee with its full parentage chain, anyway.
13683 	 */
13684 	/* clear write marks in current state: the writes we did are not writes
13685 	 * our child did, so they don't screen off its reads from us.
13686 	 * (There are no read marks in current state, because reads always mark
13687 	 * their parent and current state never has children yet.  Only
13688 	 * explored_states can get read marks.)
13689 	 */
13690 	for (j = 0; j <= cur->curframe; j++) {
13691 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13692 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13693 		for (i = 0; i < BPF_REG_FP; i++)
13694 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13695 	}
13696 
13697 	/* all stack frames are accessible from callee, clear them all */
13698 	for (j = 0; j <= cur->curframe; j++) {
13699 		struct bpf_func_state *frame = cur->frame[j];
13700 		struct bpf_func_state *newframe = new->frame[j];
13701 
13702 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13703 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13704 			frame->stack[i].spilled_ptr.parent =
13705 						&newframe->stack[i].spilled_ptr;
13706 		}
13707 	}
13708 	return 0;
13709 }
13710 
13711 /* Return true if it's OK to have the same insn return a different type. */
13712 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13713 {
13714 	switch (base_type(type)) {
13715 	case PTR_TO_CTX:
13716 	case PTR_TO_SOCKET:
13717 	case PTR_TO_SOCK_COMMON:
13718 	case PTR_TO_TCP_SOCK:
13719 	case PTR_TO_XDP_SOCK:
13720 	case PTR_TO_BTF_ID:
13721 		return false;
13722 	default:
13723 		return true;
13724 	}
13725 }
13726 
13727 /* If an instruction was previously used with particular pointer types, then we
13728  * need to be careful to avoid cases such as the below, where it may be ok
13729  * for one branch accessing the pointer, but not ok for the other branch:
13730  *
13731  * R1 = sock_ptr
13732  * goto X;
13733  * ...
13734  * R1 = some_other_valid_ptr;
13735  * goto X;
13736  * ...
13737  * R2 = *(u32 *)(R1 + 0);
13738  */
13739 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13740 {
13741 	return src != prev && (!reg_type_mismatch_ok(src) ||
13742 			       !reg_type_mismatch_ok(prev));
13743 }
13744 
13745 static int do_check(struct bpf_verifier_env *env)
13746 {
13747 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13748 	struct bpf_verifier_state *state = env->cur_state;
13749 	struct bpf_insn *insns = env->prog->insnsi;
13750 	struct bpf_reg_state *regs;
13751 	int insn_cnt = env->prog->len;
13752 	bool do_print_state = false;
13753 	int prev_insn_idx = -1;
13754 
13755 	for (;;) {
13756 		struct bpf_insn *insn;
13757 		u8 class;
13758 		int err;
13759 
13760 		env->prev_insn_idx = prev_insn_idx;
13761 		if (env->insn_idx >= insn_cnt) {
13762 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
13763 				env->insn_idx, insn_cnt);
13764 			return -EFAULT;
13765 		}
13766 
13767 		insn = &insns[env->insn_idx];
13768 		class = BPF_CLASS(insn->code);
13769 
13770 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13771 			verbose(env,
13772 				"BPF program is too large. Processed %d insn\n",
13773 				env->insn_processed);
13774 			return -E2BIG;
13775 		}
13776 
13777 		state->last_insn_idx = env->prev_insn_idx;
13778 
13779 		if (is_prune_point(env, env->insn_idx)) {
13780 			err = is_state_visited(env, env->insn_idx);
13781 			if (err < 0)
13782 				return err;
13783 			if (err == 1) {
13784 				/* found equivalent state, can prune the search */
13785 				if (env->log.level & BPF_LOG_LEVEL) {
13786 					if (do_print_state)
13787 						verbose(env, "\nfrom %d to %d%s: safe\n",
13788 							env->prev_insn_idx, env->insn_idx,
13789 							env->cur_state->speculative ?
13790 							" (speculative execution)" : "");
13791 					else
13792 						verbose(env, "%d: safe\n", env->insn_idx);
13793 				}
13794 				goto process_bpf_exit;
13795 			}
13796 		}
13797 
13798 		if (is_jmp_point(env, env->insn_idx)) {
13799 			err = push_jmp_history(env, state);
13800 			if (err)
13801 				return err;
13802 		}
13803 
13804 		if (signal_pending(current))
13805 			return -EAGAIN;
13806 
13807 		if (need_resched())
13808 			cond_resched();
13809 
13810 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13811 			verbose(env, "\nfrom %d to %d%s:",
13812 				env->prev_insn_idx, env->insn_idx,
13813 				env->cur_state->speculative ?
13814 				" (speculative execution)" : "");
13815 			print_verifier_state(env, state->frame[state->curframe], true);
13816 			do_print_state = false;
13817 		}
13818 
13819 		if (env->log.level & BPF_LOG_LEVEL) {
13820 			const struct bpf_insn_cbs cbs = {
13821 				.cb_call	= disasm_kfunc_name,
13822 				.cb_print	= verbose,
13823 				.private_data	= env,
13824 			};
13825 
13826 			if (verifier_state_scratched(env))
13827 				print_insn_state(env, state->frame[state->curframe]);
13828 
13829 			verbose_linfo(env, env->insn_idx, "; ");
13830 			env->prev_log_len = env->log.len_used;
13831 			verbose(env, "%d: ", env->insn_idx);
13832 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13833 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13834 			env->prev_log_len = env->log.len_used;
13835 		}
13836 
13837 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
13838 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13839 							   env->prev_insn_idx);
13840 			if (err)
13841 				return err;
13842 		}
13843 
13844 		regs = cur_regs(env);
13845 		sanitize_mark_insn_seen(env);
13846 		prev_insn_idx = env->insn_idx;
13847 
13848 		if (class == BPF_ALU || class == BPF_ALU64) {
13849 			err = check_alu_op(env, insn);
13850 			if (err)
13851 				return err;
13852 
13853 		} else if (class == BPF_LDX) {
13854 			enum bpf_reg_type *prev_src_type, src_reg_type;
13855 
13856 			/* check for reserved fields is already done */
13857 
13858 			/* check src operand */
13859 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13860 			if (err)
13861 				return err;
13862 
13863 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13864 			if (err)
13865 				return err;
13866 
13867 			src_reg_type = regs[insn->src_reg].type;
13868 
13869 			/* check that memory (src_reg + off) is readable,
13870 			 * the state of dst_reg will be updated by this func
13871 			 */
13872 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
13873 					       insn->off, BPF_SIZE(insn->code),
13874 					       BPF_READ, insn->dst_reg, false);
13875 			if (err)
13876 				return err;
13877 
13878 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13879 
13880 			if (*prev_src_type == NOT_INIT) {
13881 				/* saw a valid insn
13882 				 * dst_reg = *(u32 *)(src_reg + off)
13883 				 * save type to validate intersecting paths
13884 				 */
13885 				*prev_src_type = src_reg_type;
13886 
13887 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13888 				/* ABuser program is trying to use the same insn
13889 				 * dst_reg = *(u32*) (src_reg + off)
13890 				 * with different pointer types:
13891 				 * src_reg == ctx in one branch and
13892 				 * src_reg == stack|map in some other branch.
13893 				 * Reject it.
13894 				 */
13895 				verbose(env, "same insn cannot be used with different pointers\n");
13896 				return -EINVAL;
13897 			}
13898 
13899 		} else if (class == BPF_STX) {
13900 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
13901 
13902 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13903 				err = check_atomic(env, env->insn_idx, insn);
13904 				if (err)
13905 					return err;
13906 				env->insn_idx++;
13907 				continue;
13908 			}
13909 
13910 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13911 				verbose(env, "BPF_STX uses reserved fields\n");
13912 				return -EINVAL;
13913 			}
13914 
13915 			/* check src1 operand */
13916 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13917 			if (err)
13918 				return err;
13919 			/* check src2 operand */
13920 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13921 			if (err)
13922 				return err;
13923 
13924 			dst_reg_type = regs[insn->dst_reg].type;
13925 
13926 			/* check that memory (dst_reg + off) is writeable */
13927 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13928 					       insn->off, BPF_SIZE(insn->code),
13929 					       BPF_WRITE, insn->src_reg, false);
13930 			if (err)
13931 				return err;
13932 
13933 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13934 
13935 			if (*prev_dst_type == NOT_INIT) {
13936 				*prev_dst_type = dst_reg_type;
13937 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13938 				verbose(env, "same insn cannot be used with different pointers\n");
13939 				return -EINVAL;
13940 			}
13941 
13942 		} else if (class == BPF_ST) {
13943 			if (BPF_MODE(insn->code) != BPF_MEM ||
13944 			    insn->src_reg != BPF_REG_0) {
13945 				verbose(env, "BPF_ST uses reserved fields\n");
13946 				return -EINVAL;
13947 			}
13948 			/* check src operand */
13949 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13950 			if (err)
13951 				return err;
13952 
13953 			if (is_ctx_reg(env, insn->dst_reg)) {
13954 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13955 					insn->dst_reg,
13956 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13957 				return -EACCES;
13958 			}
13959 
13960 			/* check that memory (dst_reg + off) is writeable */
13961 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13962 					       insn->off, BPF_SIZE(insn->code),
13963 					       BPF_WRITE, -1, false);
13964 			if (err)
13965 				return err;
13966 
13967 		} else if (class == BPF_JMP || class == BPF_JMP32) {
13968 			u8 opcode = BPF_OP(insn->code);
13969 
13970 			env->jmps_processed++;
13971 			if (opcode == BPF_CALL) {
13972 				if (BPF_SRC(insn->code) != BPF_K ||
13973 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13974 				     && insn->off != 0) ||
13975 				    (insn->src_reg != BPF_REG_0 &&
13976 				     insn->src_reg != BPF_PSEUDO_CALL &&
13977 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13978 				    insn->dst_reg != BPF_REG_0 ||
13979 				    class == BPF_JMP32) {
13980 					verbose(env, "BPF_CALL uses reserved fields\n");
13981 					return -EINVAL;
13982 				}
13983 
13984 				if (env->cur_state->active_lock.ptr) {
13985 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13986 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
13987 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13988 					     (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13989 						verbose(env, "function calls are not allowed while holding a lock\n");
13990 						return -EINVAL;
13991 					}
13992 				}
13993 				if (insn->src_reg == BPF_PSEUDO_CALL)
13994 					err = check_func_call(env, insn, &env->insn_idx);
13995 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13996 					err = check_kfunc_call(env, insn, &env->insn_idx);
13997 				else
13998 					err = check_helper_call(env, insn, &env->insn_idx);
13999 				if (err)
14000 					return err;
14001 			} else if (opcode == BPF_JA) {
14002 				if (BPF_SRC(insn->code) != BPF_K ||
14003 				    insn->imm != 0 ||
14004 				    insn->src_reg != BPF_REG_0 ||
14005 				    insn->dst_reg != BPF_REG_0 ||
14006 				    class == BPF_JMP32) {
14007 					verbose(env, "BPF_JA uses reserved fields\n");
14008 					return -EINVAL;
14009 				}
14010 
14011 				env->insn_idx += insn->off + 1;
14012 				continue;
14013 
14014 			} else if (opcode == BPF_EXIT) {
14015 				if (BPF_SRC(insn->code) != BPF_K ||
14016 				    insn->imm != 0 ||
14017 				    insn->src_reg != BPF_REG_0 ||
14018 				    insn->dst_reg != BPF_REG_0 ||
14019 				    class == BPF_JMP32) {
14020 					verbose(env, "BPF_EXIT uses reserved fields\n");
14021 					return -EINVAL;
14022 				}
14023 
14024 				if (env->cur_state->active_lock.ptr) {
14025 					verbose(env, "bpf_spin_unlock is missing\n");
14026 					return -EINVAL;
14027 				}
14028 
14029 				if (env->cur_state->active_rcu_lock) {
14030 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14031 					return -EINVAL;
14032 				}
14033 
14034 				/* We must do check_reference_leak here before
14035 				 * prepare_func_exit to handle the case when
14036 				 * state->curframe > 0, it may be a callback
14037 				 * function, for which reference_state must
14038 				 * match caller reference state when it exits.
14039 				 */
14040 				err = check_reference_leak(env);
14041 				if (err)
14042 					return err;
14043 
14044 				if (state->curframe) {
14045 					/* exit from nested function */
14046 					err = prepare_func_exit(env, &env->insn_idx);
14047 					if (err)
14048 						return err;
14049 					do_print_state = true;
14050 					continue;
14051 				}
14052 
14053 				err = check_return_code(env);
14054 				if (err)
14055 					return err;
14056 process_bpf_exit:
14057 				mark_verifier_state_scratched(env);
14058 				update_branch_counts(env, env->cur_state);
14059 				err = pop_stack(env, &prev_insn_idx,
14060 						&env->insn_idx, pop_log);
14061 				if (err < 0) {
14062 					if (err != -ENOENT)
14063 						return err;
14064 					break;
14065 				} else {
14066 					do_print_state = true;
14067 					continue;
14068 				}
14069 			} else {
14070 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14071 				if (err)
14072 					return err;
14073 			}
14074 		} else if (class == BPF_LD) {
14075 			u8 mode = BPF_MODE(insn->code);
14076 
14077 			if (mode == BPF_ABS || mode == BPF_IND) {
14078 				err = check_ld_abs(env, insn);
14079 				if (err)
14080 					return err;
14081 
14082 			} else if (mode == BPF_IMM) {
14083 				err = check_ld_imm(env, insn);
14084 				if (err)
14085 					return err;
14086 
14087 				env->insn_idx++;
14088 				sanitize_mark_insn_seen(env);
14089 			} else {
14090 				verbose(env, "invalid BPF_LD mode\n");
14091 				return -EINVAL;
14092 			}
14093 		} else {
14094 			verbose(env, "unknown insn class %d\n", class);
14095 			return -EINVAL;
14096 		}
14097 
14098 		env->insn_idx++;
14099 	}
14100 
14101 	return 0;
14102 }
14103 
14104 static int find_btf_percpu_datasec(struct btf *btf)
14105 {
14106 	const struct btf_type *t;
14107 	const char *tname;
14108 	int i, n;
14109 
14110 	/*
14111 	 * Both vmlinux and module each have their own ".data..percpu"
14112 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14113 	 * types to look at only module's own BTF types.
14114 	 */
14115 	n = btf_nr_types(btf);
14116 	if (btf_is_module(btf))
14117 		i = btf_nr_types(btf_vmlinux);
14118 	else
14119 		i = 1;
14120 
14121 	for(; i < n; i++) {
14122 		t = btf_type_by_id(btf, i);
14123 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14124 			continue;
14125 
14126 		tname = btf_name_by_offset(btf, t->name_off);
14127 		if (!strcmp(tname, ".data..percpu"))
14128 			return i;
14129 	}
14130 
14131 	return -ENOENT;
14132 }
14133 
14134 /* replace pseudo btf_id with kernel symbol address */
14135 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14136 			       struct bpf_insn *insn,
14137 			       struct bpf_insn_aux_data *aux)
14138 {
14139 	const struct btf_var_secinfo *vsi;
14140 	const struct btf_type *datasec;
14141 	struct btf_mod_pair *btf_mod;
14142 	const struct btf_type *t;
14143 	const char *sym_name;
14144 	bool percpu = false;
14145 	u32 type, id = insn->imm;
14146 	struct btf *btf;
14147 	s32 datasec_id;
14148 	u64 addr;
14149 	int i, btf_fd, err;
14150 
14151 	btf_fd = insn[1].imm;
14152 	if (btf_fd) {
14153 		btf = btf_get_by_fd(btf_fd);
14154 		if (IS_ERR(btf)) {
14155 			verbose(env, "invalid module BTF object FD specified.\n");
14156 			return -EINVAL;
14157 		}
14158 	} else {
14159 		if (!btf_vmlinux) {
14160 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14161 			return -EINVAL;
14162 		}
14163 		btf = btf_vmlinux;
14164 		btf_get(btf);
14165 	}
14166 
14167 	t = btf_type_by_id(btf, id);
14168 	if (!t) {
14169 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14170 		err = -ENOENT;
14171 		goto err_put;
14172 	}
14173 
14174 	if (!btf_type_is_var(t)) {
14175 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14176 		err = -EINVAL;
14177 		goto err_put;
14178 	}
14179 
14180 	sym_name = btf_name_by_offset(btf, t->name_off);
14181 	addr = kallsyms_lookup_name(sym_name);
14182 	if (!addr) {
14183 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14184 			sym_name);
14185 		err = -ENOENT;
14186 		goto err_put;
14187 	}
14188 
14189 	datasec_id = find_btf_percpu_datasec(btf);
14190 	if (datasec_id > 0) {
14191 		datasec = btf_type_by_id(btf, datasec_id);
14192 		for_each_vsi(i, datasec, vsi) {
14193 			if (vsi->type == id) {
14194 				percpu = true;
14195 				break;
14196 			}
14197 		}
14198 	}
14199 
14200 	insn[0].imm = (u32)addr;
14201 	insn[1].imm = addr >> 32;
14202 
14203 	type = t->type;
14204 	t = btf_type_skip_modifiers(btf, type, NULL);
14205 	if (percpu) {
14206 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14207 		aux->btf_var.btf = btf;
14208 		aux->btf_var.btf_id = type;
14209 	} else if (!btf_type_is_struct(t)) {
14210 		const struct btf_type *ret;
14211 		const char *tname;
14212 		u32 tsize;
14213 
14214 		/* resolve the type size of ksym. */
14215 		ret = btf_resolve_size(btf, t, &tsize);
14216 		if (IS_ERR(ret)) {
14217 			tname = btf_name_by_offset(btf, t->name_off);
14218 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14219 				tname, PTR_ERR(ret));
14220 			err = -EINVAL;
14221 			goto err_put;
14222 		}
14223 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14224 		aux->btf_var.mem_size = tsize;
14225 	} else {
14226 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14227 		aux->btf_var.btf = btf;
14228 		aux->btf_var.btf_id = type;
14229 	}
14230 
14231 	/* check whether we recorded this BTF (and maybe module) already */
14232 	for (i = 0; i < env->used_btf_cnt; i++) {
14233 		if (env->used_btfs[i].btf == btf) {
14234 			btf_put(btf);
14235 			return 0;
14236 		}
14237 	}
14238 
14239 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14240 		err = -E2BIG;
14241 		goto err_put;
14242 	}
14243 
14244 	btf_mod = &env->used_btfs[env->used_btf_cnt];
14245 	btf_mod->btf = btf;
14246 	btf_mod->module = NULL;
14247 
14248 	/* if we reference variables from kernel module, bump its refcount */
14249 	if (btf_is_module(btf)) {
14250 		btf_mod->module = btf_try_get_module(btf);
14251 		if (!btf_mod->module) {
14252 			err = -ENXIO;
14253 			goto err_put;
14254 		}
14255 	}
14256 
14257 	env->used_btf_cnt++;
14258 
14259 	return 0;
14260 err_put:
14261 	btf_put(btf);
14262 	return err;
14263 }
14264 
14265 static bool is_tracing_prog_type(enum bpf_prog_type type)
14266 {
14267 	switch (type) {
14268 	case BPF_PROG_TYPE_KPROBE:
14269 	case BPF_PROG_TYPE_TRACEPOINT:
14270 	case BPF_PROG_TYPE_PERF_EVENT:
14271 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14272 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14273 		return true;
14274 	default:
14275 		return false;
14276 	}
14277 }
14278 
14279 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14280 					struct bpf_map *map,
14281 					struct bpf_prog *prog)
14282 
14283 {
14284 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14285 
14286 	if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14287 		if (is_tracing_prog_type(prog_type)) {
14288 			verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14289 			return -EINVAL;
14290 		}
14291 	}
14292 
14293 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14294 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14295 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14296 			return -EINVAL;
14297 		}
14298 
14299 		if (is_tracing_prog_type(prog_type)) {
14300 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14301 			return -EINVAL;
14302 		}
14303 
14304 		if (prog->aux->sleepable) {
14305 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14306 			return -EINVAL;
14307 		}
14308 	}
14309 
14310 	if (btf_record_has_field(map->record, BPF_TIMER)) {
14311 		if (is_tracing_prog_type(prog_type)) {
14312 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
14313 			return -EINVAL;
14314 		}
14315 	}
14316 
14317 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
14318 	    !bpf_offload_prog_map_match(prog, map)) {
14319 		verbose(env, "offload device mismatch between prog and map\n");
14320 		return -EINVAL;
14321 	}
14322 
14323 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14324 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14325 		return -EINVAL;
14326 	}
14327 
14328 	if (prog->aux->sleepable)
14329 		switch (map->map_type) {
14330 		case BPF_MAP_TYPE_HASH:
14331 		case BPF_MAP_TYPE_LRU_HASH:
14332 		case BPF_MAP_TYPE_ARRAY:
14333 		case BPF_MAP_TYPE_PERCPU_HASH:
14334 		case BPF_MAP_TYPE_PERCPU_ARRAY:
14335 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14336 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14337 		case BPF_MAP_TYPE_HASH_OF_MAPS:
14338 		case BPF_MAP_TYPE_RINGBUF:
14339 		case BPF_MAP_TYPE_USER_RINGBUF:
14340 		case BPF_MAP_TYPE_INODE_STORAGE:
14341 		case BPF_MAP_TYPE_SK_STORAGE:
14342 		case BPF_MAP_TYPE_TASK_STORAGE:
14343 		case BPF_MAP_TYPE_CGRP_STORAGE:
14344 			break;
14345 		default:
14346 			verbose(env,
14347 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14348 			return -EINVAL;
14349 		}
14350 
14351 	return 0;
14352 }
14353 
14354 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14355 {
14356 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14357 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14358 }
14359 
14360 /* find and rewrite pseudo imm in ld_imm64 instructions:
14361  *
14362  * 1. if it accesses map FD, replace it with actual map pointer.
14363  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14364  *
14365  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14366  */
14367 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14368 {
14369 	struct bpf_insn *insn = env->prog->insnsi;
14370 	int insn_cnt = env->prog->len;
14371 	int i, j, err;
14372 
14373 	err = bpf_prog_calc_tag(env->prog);
14374 	if (err)
14375 		return err;
14376 
14377 	for (i = 0; i < insn_cnt; i++, insn++) {
14378 		if (BPF_CLASS(insn->code) == BPF_LDX &&
14379 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14380 			verbose(env, "BPF_LDX uses reserved fields\n");
14381 			return -EINVAL;
14382 		}
14383 
14384 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14385 			struct bpf_insn_aux_data *aux;
14386 			struct bpf_map *map;
14387 			struct fd f;
14388 			u64 addr;
14389 			u32 fd;
14390 
14391 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
14392 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14393 			    insn[1].off != 0) {
14394 				verbose(env, "invalid bpf_ld_imm64 insn\n");
14395 				return -EINVAL;
14396 			}
14397 
14398 			if (insn[0].src_reg == 0)
14399 				/* valid generic load 64-bit imm */
14400 				goto next_insn;
14401 
14402 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14403 				aux = &env->insn_aux_data[i];
14404 				err = check_pseudo_btf_id(env, insn, aux);
14405 				if (err)
14406 					return err;
14407 				goto next_insn;
14408 			}
14409 
14410 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14411 				aux = &env->insn_aux_data[i];
14412 				aux->ptr_type = PTR_TO_FUNC;
14413 				goto next_insn;
14414 			}
14415 
14416 			/* In final convert_pseudo_ld_imm64() step, this is
14417 			 * converted into regular 64-bit imm load insn.
14418 			 */
14419 			switch (insn[0].src_reg) {
14420 			case BPF_PSEUDO_MAP_VALUE:
14421 			case BPF_PSEUDO_MAP_IDX_VALUE:
14422 				break;
14423 			case BPF_PSEUDO_MAP_FD:
14424 			case BPF_PSEUDO_MAP_IDX:
14425 				if (insn[1].imm == 0)
14426 					break;
14427 				fallthrough;
14428 			default:
14429 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14430 				return -EINVAL;
14431 			}
14432 
14433 			switch (insn[0].src_reg) {
14434 			case BPF_PSEUDO_MAP_IDX_VALUE:
14435 			case BPF_PSEUDO_MAP_IDX:
14436 				if (bpfptr_is_null(env->fd_array)) {
14437 					verbose(env, "fd_idx without fd_array is invalid\n");
14438 					return -EPROTO;
14439 				}
14440 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
14441 							    insn[0].imm * sizeof(fd),
14442 							    sizeof(fd)))
14443 					return -EFAULT;
14444 				break;
14445 			default:
14446 				fd = insn[0].imm;
14447 				break;
14448 			}
14449 
14450 			f = fdget(fd);
14451 			map = __bpf_map_get(f);
14452 			if (IS_ERR(map)) {
14453 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
14454 					insn[0].imm);
14455 				return PTR_ERR(map);
14456 			}
14457 
14458 			err = check_map_prog_compatibility(env, map, env->prog);
14459 			if (err) {
14460 				fdput(f);
14461 				return err;
14462 			}
14463 
14464 			aux = &env->insn_aux_data[i];
14465 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14466 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14467 				addr = (unsigned long)map;
14468 			} else {
14469 				u32 off = insn[1].imm;
14470 
14471 				if (off >= BPF_MAX_VAR_OFF) {
14472 					verbose(env, "direct value offset of %u is not allowed\n", off);
14473 					fdput(f);
14474 					return -EINVAL;
14475 				}
14476 
14477 				if (!map->ops->map_direct_value_addr) {
14478 					verbose(env, "no direct value access support for this map type\n");
14479 					fdput(f);
14480 					return -EINVAL;
14481 				}
14482 
14483 				err = map->ops->map_direct_value_addr(map, &addr, off);
14484 				if (err) {
14485 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14486 						map->value_size, off);
14487 					fdput(f);
14488 					return err;
14489 				}
14490 
14491 				aux->map_off = off;
14492 				addr += off;
14493 			}
14494 
14495 			insn[0].imm = (u32)addr;
14496 			insn[1].imm = addr >> 32;
14497 
14498 			/* check whether we recorded this map already */
14499 			for (j = 0; j < env->used_map_cnt; j++) {
14500 				if (env->used_maps[j] == map) {
14501 					aux->map_index = j;
14502 					fdput(f);
14503 					goto next_insn;
14504 				}
14505 			}
14506 
14507 			if (env->used_map_cnt >= MAX_USED_MAPS) {
14508 				fdput(f);
14509 				return -E2BIG;
14510 			}
14511 
14512 			/* hold the map. If the program is rejected by verifier,
14513 			 * the map will be released by release_maps() or it
14514 			 * will be used by the valid program until it's unloaded
14515 			 * and all maps are released in free_used_maps()
14516 			 */
14517 			bpf_map_inc(map);
14518 
14519 			aux->map_index = env->used_map_cnt;
14520 			env->used_maps[env->used_map_cnt++] = map;
14521 
14522 			if (bpf_map_is_cgroup_storage(map) &&
14523 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
14524 				verbose(env, "only one cgroup storage of each type is allowed\n");
14525 				fdput(f);
14526 				return -EBUSY;
14527 			}
14528 
14529 			fdput(f);
14530 next_insn:
14531 			insn++;
14532 			i++;
14533 			continue;
14534 		}
14535 
14536 		/* Basic sanity check before we invest more work here. */
14537 		if (!bpf_opcode_in_insntable(insn->code)) {
14538 			verbose(env, "unknown opcode %02x\n", insn->code);
14539 			return -EINVAL;
14540 		}
14541 	}
14542 
14543 	/* now all pseudo BPF_LD_IMM64 instructions load valid
14544 	 * 'struct bpf_map *' into a register instead of user map_fd.
14545 	 * These pointers will be used later by verifier to validate map access.
14546 	 */
14547 	return 0;
14548 }
14549 
14550 /* drop refcnt of maps used by the rejected program */
14551 static void release_maps(struct bpf_verifier_env *env)
14552 {
14553 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
14554 			     env->used_map_cnt);
14555 }
14556 
14557 /* drop refcnt of maps used by the rejected program */
14558 static void release_btfs(struct bpf_verifier_env *env)
14559 {
14560 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14561 			     env->used_btf_cnt);
14562 }
14563 
14564 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14565 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14566 {
14567 	struct bpf_insn *insn = env->prog->insnsi;
14568 	int insn_cnt = env->prog->len;
14569 	int i;
14570 
14571 	for (i = 0; i < insn_cnt; i++, insn++) {
14572 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14573 			continue;
14574 		if (insn->src_reg == BPF_PSEUDO_FUNC)
14575 			continue;
14576 		insn->src_reg = 0;
14577 	}
14578 }
14579 
14580 /* single env->prog->insni[off] instruction was replaced with the range
14581  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14582  * [0, off) and [off, end) to new locations, so the patched range stays zero
14583  */
14584 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14585 				 struct bpf_insn_aux_data *new_data,
14586 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
14587 {
14588 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14589 	struct bpf_insn *insn = new_prog->insnsi;
14590 	u32 old_seen = old_data[off].seen;
14591 	u32 prog_len;
14592 	int i;
14593 
14594 	/* aux info at OFF always needs adjustment, no matter fast path
14595 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14596 	 * original insn at old prog.
14597 	 */
14598 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14599 
14600 	if (cnt == 1)
14601 		return;
14602 	prog_len = new_prog->len;
14603 
14604 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14605 	memcpy(new_data + off + cnt - 1, old_data + off,
14606 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14607 	for (i = off; i < off + cnt - 1; i++) {
14608 		/* Expand insni[off]'s seen count to the patched range. */
14609 		new_data[i].seen = old_seen;
14610 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
14611 	}
14612 	env->insn_aux_data = new_data;
14613 	vfree(old_data);
14614 }
14615 
14616 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14617 {
14618 	int i;
14619 
14620 	if (len == 1)
14621 		return;
14622 	/* NOTE: fake 'exit' subprog should be updated as well. */
14623 	for (i = 0; i <= env->subprog_cnt; i++) {
14624 		if (env->subprog_info[i].start <= off)
14625 			continue;
14626 		env->subprog_info[i].start += len - 1;
14627 	}
14628 }
14629 
14630 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14631 {
14632 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14633 	int i, sz = prog->aux->size_poke_tab;
14634 	struct bpf_jit_poke_descriptor *desc;
14635 
14636 	for (i = 0; i < sz; i++) {
14637 		desc = &tab[i];
14638 		if (desc->insn_idx <= off)
14639 			continue;
14640 		desc->insn_idx += len - 1;
14641 	}
14642 }
14643 
14644 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14645 					    const struct bpf_insn *patch, u32 len)
14646 {
14647 	struct bpf_prog *new_prog;
14648 	struct bpf_insn_aux_data *new_data = NULL;
14649 
14650 	if (len > 1) {
14651 		new_data = vzalloc(array_size(env->prog->len + len - 1,
14652 					      sizeof(struct bpf_insn_aux_data)));
14653 		if (!new_data)
14654 			return NULL;
14655 	}
14656 
14657 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14658 	if (IS_ERR(new_prog)) {
14659 		if (PTR_ERR(new_prog) == -ERANGE)
14660 			verbose(env,
14661 				"insn %d cannot be patched due to 16-bit range\n",
14662 				env->insn_aux_data[off].orig_idx);
14663 		vfree(new_data);
14664 		return NULL;
14665 	}
14666 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
14667 	adjust_subprog_starts(env, off, len);
14668 	adjust_poke_descs(new_prog, off, len);
14669 	return new_prog;
14670 }
14671 
14672 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14673 					      u32 off, u32 cnt)
14674 {
14675 	int i, j;
14676 
14677 	/* find first prog starting at or after off (first to remove) */
14678 	for (i = 0; i < env->subprog_cnt; i++)
14679 		if (env->subprog_info[i].start >= off)
14680 			break;
14681 	/* find first prog starting at or after off + cnt (first to stay) */
14682 	for (j = i; j < env->subprog_cnt; j++)
14683 		if (env->subprog_info[j].start >= off + cnt)
14684 			break;
14685 	/* if j doesn't start exactly at off + cnt, we are just removing
14686 	 * the front of previous prog
14687 	 */
14688 	if (env->subprog_info[j].start != off + cnt)
14689 		j--;
14690 
14691 	if (j > i) {
14692 		struct bpf_prog_aux *aux = env->prog->aux;
14693 		int move;
14694 
14695 		/* move fake 'exit' subprog as well */
14696 		move = env->subprog_cnt + 1 - j;
14697 
14698 		memmove(env->subprog_info + i,
14699 			env->subprog_info + j,
14700 			sizeof(*env->subprog_info) * move);
14701 		env->subprog_cnt -= j - i;
14702 
14703 		/* remove func_info */
14704 		if (aux->func_info) {
14705 			move = aux->func_info_cnt - j;
14706 
14707 			memmove(aux->func_info + i,
14708 				aux->func_info + j,
14709 				sizeof(*aux->func_info) * move);
14710 			aux->func_info_cnt -= j - i;
14711 			/* func_info->insn_off is set after all code rewrites,
14712 			 * in adjust_btf_func() - no need to adjust
14713 			 */
14714 		}
14715 	} else {
14716 		/* convert i from "first prog to remove" to "first to adjust" */
14717 		if (env->subprog_info[i].start == off)
14718 			i++;
14719 	}
14720 
14721 	/* update fake 'exit' subprog as well */
14722 	for (; i <= env->subprog_cnt; i++)
14723 		env->subprog_info[i].start -= cnt;
14724 
14725 	return 0;
14726 }
14727 
14728 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14729 				      u32 cnt)
14730 {
14731 	struct bpf_prog *prog = env->prog;
14732 	u32 i, l_off, l_cnt, nr_linfo;
14733 	struct bpf_line_info *linfo;
14734 
14735 	nr_linfo = prog->aux->nr_linfo;
14736 	if (!nr_linfo)
14737 		return 0;
14738 
14739 	linfo = prog->aux->linfo;
14740 
14741 	/* find first line info to remove, count lines to be removed */
14742 	for (i = 0; i < nr_linfo; i++)
14743 		if (linfo[i].insn_off >= off)
14744 			break;
14745 
14746 	l_off = i;
14747 	l_cnt = 0;
14748 	for (; i < nr_linfo; i++)
14749 		if (linfo[i].insn_off < off + cnt)
14750 			l_cnt++;
14751 		else
14752 			break;
14753 
14754 	/* First live insn doesn't match first live linfo, it needs to "inherit"
14755 	 * last removed linfo.  prog is already modified, so prog->len == off
14756 	 * means no live instructions after (tail of the program was removed).
14757 	 */
14758 	if (prog->len != off && l_cnt &&
14759 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14760 		l_cnt--;
14761 		linfo[--i].insn_off = off + cnt;
14762 	}
14763 
14764 	/* remove the line info which refer to the removed instructions */
14765 	if (l_cnt) {
14766 		memmove(linfo + l_off, linfo + i,
14767 			sizeof(*linfo) * (nr_linfo - i));
14768 
14769 		prog->aux->nr_linfo -= l_cnt;
14770 		nr_linfo = prog->aux->nr_linfo;
14771 	}
14772 
14773 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
14774 	for (i = l_off; i < nr_linfo; i++)
14775 		linfo[i].insn_off -= cnt;
14776 
14777 	/* fix up all subprogs (incl. 'exit') which start >= off */
14778 	for (i = 0; i <= env->subprog_cnt; i++)
14779 		if (env->subprog_info[i].linfo_idx > l_off) {
14780 			/* program may have started in the removed region but
14781 			 * may not be fully removed
14782 			 */
14783 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14784 				env->subprog_info[i].linfo_idx -= l_cnt;
14785 			else
14786 				env->subprog_info[i].linfo_idx = l_off;
14787 		}
14788 
14789 	return 0;
14790 }
14791 
14792 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14793 {
14794 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14795 	unsigned int orig_prog_len = env->prog->len;
14796 	int err;
14797 
14798 	if (bpf_prog_is_dev_bound(env->prog->aux))
14799 		bpf_prog_offload_remove_insns(env, off, cnt);
14800 
14801 	err = bpf_remove_insns(env->prog, off, cnt);
14802 	if (err)
14803 		return err;
14804 
14805 	err = adjust_subprog_starts_after_remove(env, off, cnt);
14806 	if (err)
14807 		return err;
14808 
14809 	err = bpf_adj_linfo_after_remove(env, off, cnt);
14810 	if (err)
14811 		return err;
14812 
14813 	memmove(aux_data + off,	aux_data + off + cnt,
14814 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
14815 
14816 	return 0;
14817 }
14818 
14819 /* The verifier does more data flow analysis than llvm and will not
14820  * explore branches that are dead at run time. Malicious programs can
14821  * have dead code too. Therefore replace all dead at-run-time code
14822  * with 'ja -1'.
14823  *
14824  * Just nops are not optimal, e.g. if they would sit at the end of the
14825  * program and through another bug we would manage to jump there, then
14826  * we'd execute beyond program memory otherwise. Returning exception
14827  * code also wouldn't work since we can have subprogs where the dead
14828  * code could be located.
14829  */
14830 static void sanitize_dead_code(struct bpf_verifier_env *env)
14831 {
14832 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14833 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14834 	struct bpf_insn *insn = env->prog->insnsi;
14835 	const int insn_cnt = env->prog->len;
14836 	int i;
14837 
14838 	for (i = 0; i < insn_cnt; i++) {
14839 		if (aux_data[i].seen)
14840 			continue;
14841 		memcpy(insn + i, &trap, sizeof(trap));
14842 		aux_data[i].zext_dst = false;
14843 	}
14844 }
14845 
14846 static bool insn_is_cond_jump(u8 code)
14847 {
14848 	u8 op;
14849 
14850 	if (BPF_CLASS(code) == BPF_JMP32)
14851 		return true;
14852 
14853 	if (BPF_CLASS(code) != BPF_JMP)
14854 		return false;
14855 
14856 	op = BPF_OP(code);
14857 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14858 }
14859 
14860 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14861 {
14862 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14863 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14864 	struct bpf_insn *insn = env->prog->insnsi;
14865 	const int insn_cnt = env->prog->len;
14866 	int i;
14867 
14868 	for (i = 0; i < insn_cnt; i++, insn++) {
14869 		if (!insn_is_cond_jump(insn->code))
14870 			continue;
14871 
14872 		if (!aux_data[i + 1].seen)
14873 			ja.off = insn->off;
14874 		else if (!aux_data[i + 1 + insn->off].seen)
14875 			ja.off = 0;
14876 		else
14877 			continue;
14878 
14879 		if (bpf_prog_is_dev_bound(env->prog->aux))
14880 			bpf_prog_offload_replace_insn(env, i, &ja);
14881 
14882 		memcpy(insn, &ja, sizeof(ja));
14883 	}
14884 }
14885 
14886 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14887 {
14888 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14889 	int insn_cnt = env->prog->len;
14890 	int i, err;
14891 
14892 	for (i = 0; i < insn_cnt; i++) {
14893 		int j;
14894 
14895 		j = 0;
14896 		while (i + j < insn_cnt && !aux_data[i + j].seen)
14897 			j++;
14898 		if (!j)
14899 			continue;
14900 
14901 		err = verifier_remove_insns(env, i, j);
14902 		if (err)
14903 			return err;
14904 		insn_cnt = env->prog->len;
14905 	}
14906 
14907 	return 0;
14908 }
14909 
14910 static int opt_remove_nops(struct bpf_verifier_env *env)
14911 {
14912 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14913 	struct bpf_insn *insn = env->prog->insnsi;
14914 	int insn_cnt = env->prog->len;
14915 	int i, err;
14916 
14917 	for (i = 0; i < insn_cnt; i++) {
14918 		if (memcmp(&insn[i], &ja, sizeof(ja)))
14919 			continue;
14920 
14921 		err = verifier_remove_insns(env, i, 1);
14922 		if (err)
14923 			return err;
14924 		insn_cnt--;
14925 		i--;
14926 	}
14927 
14928 	return 0;
14929 }
14930 
14931 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14932 					 const union bpf_attr *attr)
14933 {
14934 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14935 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
14936 	int i, patch_len, delta = 0, len = env->prog->len;
14937 	struct bpf_insn *insns = env->prog->insnsi;
14938 	struct bpf_prog *new_prog;
14939 	bool rnd_hi32;
14940 
14941 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14942 	zext_patch[1] = BPF_ZEXT_REG(0);
14943 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14944 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14945 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14946 	for (i = 0; i < len; i++) {
14947 		int adj_idx = i + delta;
14948 		struct bpf_insn insn;
14949 		int load_reg;
14950 
14951 		insn = insns[adj_idx];
14952 		load_reg = insn_def_regno(&insn);
14953 		if (!aux[adj_idx].zext_dst) {
14954 			u8 code, class;
14955 			u32 imm_rnd;
14956 
14957 			if (!rnd_hi32)
14958 				continue;
14959 
14960 			code = insn.code;
14961 			class = BPF_CLASS(code);
14962 			if (load_reg == -1)
14963 				continue;
14964 
14965 			/* NOTE: arg "reg" (the fourth one) is only used for
14966 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
14967 			 *       here.
14968 			 */
14969 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14970 				if (class == BPF_LD &&
14971 				    BPF_MODE(code) == BPF_IMM)
14972 					i++;
14973 				continue;
14974 			}
14975 
14976 			/* ctx load could be transformed into wider load. */
14977 			if (class == BPF_LDX &&
14978 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
14979 				continue;
14980 
14981 			imm_rnd = get_random_u32();
14982 			rnd_hi32_patch[0] = insn;
14983 			rnd_hi32_patch[1].imm = imm_rnd;
14984 			rnd_hi32_patch[3].dst_reg = load_reg;
14985 			patch = rnd_hi32_patch;
14986 			patch_len = 4;
14987 			goto apply_patch_buffer;
14988 		}
14989 
14990 		/* Add in an zero-extend instruction if a) the JIT has requested
14991 		 * it or b) it's a CMPXCHG.
14992 		 *
14993 		 * The latter is because: BPF_CMPXCHG always loads a value into
14994 		 * R0, therefore always zero-extends. However some archs'
14995 		 * equivalent instruction only does this load when the
14996 		 * comparison is successful. This detail of CMPXCHG is
14997 		 * orthogonal to the general zero-extension behaviour of the
14998 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
14999 		 */
15000 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
15001 			continue;
15002 
15003 		/* Zero-extension is done by the caller. */
15004 		if (bpf_pseudo_kfunc_call(&insn))
15005 			continue;
15006 
15007 		if (WARN_ON(load_reg == -1)) {
15008 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15009 			return -EFAULT;
15010 		}
15011 
15012 		zext_patch[0] = insn;
15013 		zext_patch[1].dst_reg = load_reg;
15014 		zext_patch[1].src_reg = load_reg;
15015 		patch = zext_patch;
15016 		patch_len = 2;
15017 apply_patch_buffer:
15018 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15019 		if (!new_prog)
15020 			return -ENOMEM;
15021 		env->prog = new_prog;
15022 		insns = new_prog->insnsi;
15023 		aux = env->insn_aux_data;
15024 		delta += patch_len - 1;
15025 	}
15026 
15027 	return 0;
15028 }
15029 
15030 /* convert load instructions that access fields of a context type into a
15031  * sequence of instructions that access fields of the underlying structure:
15032  *     struct __sk_buff    -> struct sk_buff
15033  *     struct bpf_sock_ops -> struct sock
15034  */
15035 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15036 {
15037 	const struct bpf_verifier_ops *ops = env->ops;
15038 	int i, cnt, size, ctx_field_size, delta = 0;
15039 	const int insn_cnt = env->prog->len;
15040 	struct bpf_insn insn_buf[16], *insn;
15041 	u32 target_size, size_default, off;
15042 	struct bpf_prog *new_prog;
15043 	enum bpf_access_type type;
15044 	bool is_narrower_load;
15045 
15046 	if (ops->gen_prologue || env->seen_direct_write) {
15047 		if (!ops->gen_prologue) {
15048 			verbose(env, "bpf verifier is misconfigured\n");
15049 			return -EINVAL;
15050 		}
15051 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15052 					env->prog);
15053 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15054 			verbose(env, "bpf verifier is misconfigured\n");
15055 			return -EINVAL;
15056 		} else if (cnt) {
15057 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15058 			if (!new_prog)
15059 				return -ENOMEM;
15060 
15061 			env->prog = new_prog;
15062 			delta += cnt - 1;
15063 		}
15064 	}
15065 
15066 	if (bpf_prog_is_dev_bound(env->prog->aux))
15067 		return 0;
15068 
15069 	insn = env->prog->insnsi + delta;
15070 
15071 	for (i = 0; i < insn_cnt; i++, insn++) {
15072 		bpf_convert_ctx_access_t convert_ctx_access;
15073 		bool ctx_access;
15074 
15075 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15076 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15077 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15078 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15079 			type = BPF_READ;
15080 			ctx_access = true;
15081 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15082 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15083 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15084 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15085 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15086 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15087 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15088 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15089 			type = BPF_WRITE;
15090 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15091 		} else {
15092 			continue;
15093 		}
15094 
15095 		if (type == BPF_WRITE &&
15096 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15097 			struct bpf_insn patch[] = {
15098 				*insn,
15099 				BPF_ST_NOSPEC(),
15100 			};
15101 
15102 			cnt = ARRAY_SIZE(patch);
15103 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15104 			if (!new_prog)
15105 				return -ENOMEM;
15106 
15107 			delta    += cnt - 1;
15108 			env->prog = new_prog;
15109 			insn      = new_prog->insnsi + i + delta;
15110 			continue;
15111 		}
15112 
15113 		if (!ctx_access)
15114 			continue;
15115 
15116 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15117 		case PTR_TO_CTX:
15118 			if (!ops->convert_ctx_access)
15119 				continue;
15120 			convert_ctx_access = ops->convert_ctx_access;
15121 			break;
15122 		case PTR_TO_SOCKET:
15123 		case PTR_TO_SOCK_COMMON:
15124 			convert_ctx_access = bpf_sock_convert_ctx_access;
15125 			break;
15126 		case PTR_TO_TCP_SOCK:
15127 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15128 			break;
15129 		case PTR_TO_XDP_SOCK:
15130 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15131 			break;
15132 		case PTR_TO_BTF_ID:
15133 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15134 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15135 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15136 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15137 		 * any faults for loads into such types. BPF_WRITE is disallowed
15138 		 * for this case.
15139 		 */
15140 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15141 			if (type == BPF_READ) {
15142 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15143 					BPF_SIZE((insn)->code);
15144 				env->prog->aux->num_exentries++;
15145 			}
15146 			continue;
15147 		default:
15148 			continue;
15149 		}
15150 
15151 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15152 		size = BPF_LDST_BYTES(insn);
15153 
15154 		/* If the read access is a narrower load of the field,
15155 		 * convert to a 4/8-byte load, to minimum program type specific
15156 		 * convert_ctx_access changes. If conversion is successful,
15157 		 * we will apply proper mask to the result.
15158 		 */
15159 		is_narrower_load = size < ctx_field_size;
15160 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15161 		off = insn->off;
15162 		if (is_narrower_load) {
15163 			u8 size_code;
15164 
15165 			if (type == BPF_WRITE) {
15166 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15167 				return -EINVAL;
15168 			}
15169 
15170 			size_code = BPF_H;
15171 			if (ctx_field_size == 4)
15172 				size_code = BPF_W;
15173 			else if (ctx_field_size == 8)
15174 				size_code = BPF_DW;
15175 
15176 			insn->off = off & ~(size_default - 1);
15177 			insn->code = BPF_LDX | BPF_MEM | size_code;
15178 		}
15179 
15180 		target_size = 0;
15181 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15182 					 &target_size);
15183 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15184 		    (ctx_field_size && !target_size)) {
15185 			verbose(env, "bpf verifier is misconfigured\n");
15186 			return -EINVAL;
15187 		}
15188 
15189 		if (is_narrower_load && size < target_size) {
15190 			u8 shift = bpf_ctx_narrow_access_offset(
15191 				off, size, size_default) * 8;
15192 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15193 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15194 				return -EINVAL;
15195 			}
15196 			if (ctx_field_size <= 4) {
15197 				if (shift)
15198 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15199 									insn->dst_reg,
15200 									shift);
15201 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15202 								(1 << size * 8) - 1);
15203 			} else {
15204 				if (shift)
15205 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15206 									insn->dst_reg,
15207 									shift);
15208 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15209 								(1ULL << size * 8) - 1);
15210 			}
15211 		}
15212 
15213 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15214 		if (!new_prog)
15215 			return -ENOMEM;
15216 
15217 		delta += cnt - 1;
15218 
15219 		/* keep walking new program and skip insns we just inserted */
15220 		env->prog = new_prog;
15221 		insn      = new_prog->insnsi + i + delta;
15222 	}
15223 
15224 	return 0;
15225 }
15226 
15227 static int jit_subprogs(struct bpf_verifier_env *env)
15228 {
15229 	struct bpf_prog *prog = env->prog, **func, *tmp;
15230 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15231 	struct bpf_map *map_ptr;
15232 	struct bpf_insn *insn;
15233 	void *old_bpf_func;
15234 	int err, num_exentries;
15235 
15236 	if (env->subprog_cnt <= 1)
15237 		return 0;
15238 
15239 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15240 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15241 			continue;
15242 
15243 		/* Upon error here we cannot fall back to interpreter but
15244 		 * need a hard reject of the program. Thus -EFAULT is
15245 		 * propagated in any case.
15246 		 */
15247 		subprog = find_subprog(env, i + insn->imm + 1);
15248 		if (subprog < 0) {
15249 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15250 				  i + insn->imm + 1);
15251 			return -EFAULT;
15252 		}
15253 		/* temporarily remember subprog id inside insn instead of
15254 		 * aux_data, since next loop will split up all insns into funcs
15255 		 */
15256 		insn->off = subprog;
15257 		/* remember original imm in case JIT fails and fallback
15258 		 * to interpreter will be needed
15259 		 */
15260 		env->insn_aux_data[i].call_imm = insn->imm;
15261 		/* point imm to __bpf_call_base+1 from JITs point of view */
15262 		insn->imm = 1;
15263 		if (bpf_pseudo_func(insn))
15264 			/* jit (e.g. x86_64) may emit fewer instructions
15265 			 * if it learns a u32 imm is the same as a u64 imm.
15266 			 * Force a non zero here.
15267 			 */
15268 			insn[1].imm = 1;
15269 	}
15270 
15271 	err = bpf_prog_alloc_jited_linfo(prog);
15272 	if (err)
15273 		goto out_undo_insn;
15274 
15275 	err = -ENOMEM;
15276 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15277 	if (!func)
15278 		goto out_undo_insn;
15279 
15280 	for (i = 0; i < env->subprog_cnt; i++) {
15281 		subprog_start = subprog_end;
15282 		subprog_end = env->subprog_info[i + 1].start;
15283 
15284 		len = subprog_end - subprog_start;
15285 		/* bpf_prog_run() doesn't call subprogs directly,
15286 		 * hence main prog stats include the runtime of subprogs.
15287 		 * subprogs don't have IDs and not reachable via prog_get_next_id
15288 		 * func[i]->stats will never be accessed and stays NULL
15289 		 */
15290 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15291 		if (!func[i])
15292 			goto out_free;
15293 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15294 		       len * sizeof(struct bpf_insn));
15295 		func[i]->type = prog->type;
15296 		func[i]->len = len;
15297 		if (bpf_prog_calc_tag(func[i]))
15298 			goto out_free;
15299 		func[i]->is_func = 1;
15300 		func[i]->aux->func_idx = i;
15301 		/* Below members will be freed only at prog->aux */
15302 		func[i]->aux->btf = prog->aux->btf;
15303 		func[i]->aux->func_info = prog->aux->func_info;
15304 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15305 		func[i]->aux->poke_tab = prog->aux->poke_tab;
15306 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15307 
15308 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
15309 			struct bpf_jit_poke_descriptor *poke;
15310 
15311 			poke = &prog->aux->poke_tab[j];
15312 			if (poke->insn_idx < subprog_end &&
15313 			    poke->insn_idx >= subprog_start)
15314 				poke->aux = func[i]->aux;
15315 		}
15316 
15317 		func[i]->aux->name[0] = 'F';
15318 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15319 		func[i]->jit_requested = 1;
15320 		func[i]->blinding_requested = prog->blinding_requested;
15321 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15322 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15323 		func[i]->aux->linfo = prog->aux->linfo;
15324 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15325 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15326 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15327 		num_exentries = 0;
15328 		insn = func[i]->insnsi;
15329 		for (j = 0; j < func[i]->len; j++, insn++) {
15330 			if (BPF_CLASS(insn->code) == BPF_LDX &&
15331 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
15332 				num_exentries++;
15333 		}
15334 		func[i]->aux->num_exentries = num_exentries;
15335 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15336 		func[i] = bpf_int_jit_compile(func[i]);
15337 		if (!func[i]->jited) {
15338 			err = -ENOTSUPP;
15339 			goto out_free;
15340 		}
15341 		cond_resched();
15342 	}
15343 
15344 	/* at this point all bpf functions were successfully JITed
15345 	 * now populate all bpf_calls with correct addresses and
15346 	 * run last pass of JIT
15347 	 */
15348 	for (i = 0; i < env->subprog_cnt; i++) {
15349 		insn = func[i]->insnsi;
15350 		for (j = 0; j < func[i]->len; j++, insn++) {
15351 			if (bpf_pseudo_func(insn)) {
15352 				subprog = insn->off;
15353 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15354 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15355 				continue;
15356 			}
15357 			if (!bpf_pseudo_call(insn))
15358 				continue;
15359 			subprog = insn->off;
15360 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15361 		}
15362 
15363 		/* we use the aux data to keep a list of the start addresses
15364 		 * of the JITed images for each function in the program
15365 		 *
15366 		 * for some architectures, such as powerpc64, the imm field
15367 		 * might not be large enough to hold the offset of the start
15368 		 * address of the callee's JITed image from __bpf_call_base
15369 		 *
15370 		 * in such cases, we can lookup the start address of a callee
15371 		 * by using its subprog id, available from the off field of
15372 		 * the call instruction, as an index for this list
15373 		 */
15374 		func[i]->aux->func = func;
15375 		func[i]->aux->func_cnt = env->subprog_cnt;
15376 	}
15377 	for (i = 0; i < env->subprog_cnt; i++) {
15378 		old_bpf_func = func[i]->bpf_func;
15379 		tmp = bpf_int_jit_compile(func[i]);
15380 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15381 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15382 			err = -ENOTSUPP;
15383 			goto out_free;
15384 		}
15385 		cond_resched();
15386 	}
15387 
15388 	/* finally lock prog and jit images for all functions and
15389 	 * populate kallsysm
15390 	 */
15391 	for (i = 0; i < env->subprog_cnt; i++) {
15392 		bpf_prog_lock_ro(func[i]);
15393 		bpf_prog_kallsyms_add(func[i]);
15394 	}
15395 
15396 	/* Last step: make now unused interpreter insns from main
15397 	 * prog consistent for later dump requests, so they can
15398 	 * later look the same as if they were interpreted only.
15399 	 */
15400 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15401 		if (bpf_pseudo_func(insn)) {
15402 			insn[0].imm = env->insn_aux_data[i].call_imm;
15403 			insn[1].imm = insn->off;
15404 			insn->off = 0;
15405 			continue;
15406 		}
15407 		if (!bpf_pseudo_call(insn))
15408 			continue;
15409 		insn->off = env->insn_aux_data[i].call_imm;
15410 		subprog = find_subprog(env, i + insn->off + 1);
15411 		insn->imm = subprog;
15412 	}
15413 
15414 	prog->jited = 1;
15415 	prog->bpf_func = func[0]->bpf_func;
15416 	prog->jited_len = func[0]->jited_len;
15417 	prog->aux->func = func;
15418 	prog->aux->func_cnt = env->subprog_cnt;
15419 	bpf_prog_jit_attempt_done(prog);
15420 	return 0;
15421 out_free:
15422 	/* We failed JIT'ing, so at this point we need to unregister poke
15423 	 * descriptors from subprogs, so that kernel is not attempting to
15424 	 * patch it anymore as we're freeing the subprog JIT memory.
15425 	 */
15426 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15427 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15428 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15429 	}
15430 	/* At this point we're guaranteed that poke descriptors are not
15431 	 * live anymore. We can just unlink its descriptor table as it's
15432 	 * released with the main prog.
15433 	 */
15434 	for (i = 0; i < env->subprog_cnt; i++) {
15435 		if (!func[i])
15436 			continue;
15437 		func[i]->aux->poke_tab = NULL;
15438 		bpf_jit_free(func[i]);
15439 	}
15440 	kfree(func);
15441 out_undo_insn:
15442 	/* cleanup main prog to be interpreted */
15443 	prog->jit_requested = 0;
15444 	prog->blinding_requested = 0;
15445 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15446 		if (!bpf_pseudo_call(insn))
15447 			continue;
15448 		insn->off = 0;
15449 		insn->imm = env->insn_aux_data[i].call_imm;
15450 	}
15451 	bpf_prog_jit_attempt_done(prog);
15452 	return err;
15453 }
15454 
15455 static int fixup_call_args(struct bpf_verifier_env *env)
15456 {
15457 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15458 	struct bpf_prog *prog = env->prog;
15459 	struct bpf_insn *insn = prog->insnsi;
15460 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15461 	int i, depth;
15462 #endif
15463 	int err = 0;
15464 
15465 	if (env->prog->jit_requested &&
15466 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
15467 		err = jit_subprogs(env);
15468 		if (err == 0)
15469 			return 0;
15470 		if (err == -EFAULT)
15471 			return err;
15472 	}
15473 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15474 	if (has_kfunc_call) {
15475 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15476 		return -EINVAL;
15477 	}
15478 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15479 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
15480 		 * have to be rejected, since interpreter doesn't support them yet.
15481 		 */
15482 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15483 		return -EINVAL;
15484 	}
15485 	for (i = 0; i < prog->len; i++, insn++) {
15486 		if (bpf_pseudo_func(insn)) {
15487 			/* When JIT fails the progs with callback calls
15488 			 * have to be rejected, since interpreter doesn't support them yet.
15489 			 */
15490 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
15491 			return -EINVAL;
15492 		}
15493 
15494 		if (!bpf_pseudo_call(insn))
15495 			continue;
15496 		depth = get_callee_stack_depth(env, insn, i);
15497 		if (depth < 0)
15498 			return depth;
15499 		bpf_patch_call_args(insn, depth);
15500 	}
15501 	err = 0;
15502 #endif
15503 	return err;
15504 }
15505 
15506 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15507 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15508 {
15509 	const struct bpf_kfunc_desc *desc;
15510 
15511 	if (!insn->imm) {
15512 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15513 		return -EINVAL;
15514 	}
15515 
15516 	/* insn->imm has the btf func_id. Replace it with
15517 	 * an address (relative to __bpf_call_base).
15518 	 */
15519 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15520 	if (!desc) {
15521 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15522 			insn->imm);
15523 		return -EFAULT;
15524 	}
15525 
15526 	*cnt = 0;
15527 	insn->imm = desc->imm;
15528 	if (insn->off)
15529 		return 0;
15530 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15531 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15532 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15533 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15534 
15535 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15536 		insn_buf[1] = addr[0];
15537 		insn_buf[2] = addr[1];
15538 		insn_buf[3] = *insn;
15539 		*cnt = 4;
15540 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15541 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15542 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15543 
15544 		insn_buf[0] = addr[0];
15545 		insn_buf[1] = addr[1];
15546 		insn_buf[2] = *insn;
15547 		*cnt = 3;
15548 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15549 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15550 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15551 		*cnt = 1;
15552 	}
15553 	return 0;
15554 }
15555 
15556 /* Do various post-verification rewrites in a single program pass.
15557  * These rewrites simplify JIT and interpreter implementations.
15558  */
15559 static int do_misc_fixups(struct bpf_verifier_env *env)
15560 {
15561 	struct bpf_prog *prog = env->prog;
15562 	enum bpf_attach_type eatype = prog->expected_attach_type;
15563 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15564 	struct bpf_insn *insn = prog->insnsi;
15565 	const struct bpf_func_proto *fn;
15566 	const int insn_cnt = prog->len;
15567 	const struct bpf_map_ops *ops;
15568 	struct bpf_insn_aux_data *aux;
15569 	struct bpf_insn insn_buf[16];
15570 	struct bpf_prog *new_prog;
15571 	struct bpf_map *map_ptr;
15572 	int i, ret, cnt, delta = 0;
15573 
15574 	for (i = 0; i < insn_cnt; i++, insn++) {
15575 		/* Make divide-by-zero exceptions impossible. */
15576 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15577 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15578 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15579 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15580 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15581 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15582 			struct bpf_insn *patchlet;
15583 			struct bpf_insn chk_and_div[] = {
15584 				/* [R,W]x div 0 -> 0 */
15585 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15586 					     BPF_JNE | BPF_K, insn->src_reg,
15587 					     0, 2, 0),
15588 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15589 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15590 				*insn,
15591 			};
15592 			struct bpf_insn chk_and_mod[] = {
15593 				/* [R,W]x mod 0 -> [R,W]x */
15594 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15595 					     BPF_JEQ | BPF_K, insn->src_reg,
15596 					     0, 1 + (is64 ? 0 : 1), 0),
15597 				*insn,
15598 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15599 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15600 			};
15601 
15602 			patchlet = isdiv ? chk_and_div : chk_and_mod;
15603 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15604 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15605 
15606 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15607 			if (!new_prog)
15608 				return -ENOMEM;
15609 
15610 			delta    += cnt - 1;
15611 			env->prog = prog = new_prog;
15612 			insn      = new_prog->insnsi + i + delta;
15613 			continue;
15614 		}
15615 
15616 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15617 		if (BPF_CLASS(insn->code) == BPF_LD &&
15618 		    (BPF_MODE(insn->code) == BPF_ABS ||
15619 		     BPF_MODE(insn->code) == BPF_IND)) {
15620 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
15621 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15622 				verbose(env, "bpf verifier is misconfigured\n");
15623 				return -EINVAL;
15624 			}
15625 
15626 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15627 			if (!new_prog)
15628 				return -ENOMEM;
15629 
15630 			delta    += cnt - 1;
15631 			env->prog = prog = new_prog;
15632 			insn      = new_prog->insnsi + i + delta;
15633 			continue;
15634 		}
15635 
15636 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
15637 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15638 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15639 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15640 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15641 			struct bpf_insn *patch = &insn_buf[0];
15642 			bool issrc, isneg, isimm;
15643 			u32 off_reg;
15644 
15645 			aux = &env->insn_aux_data[i + delta];
15646 			if (!aux->alu_state ||
15647 			    aux->alu_state == BPF_ALU_NON_POINTER)
15648 				continue;
15649 
15650 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15651 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15652 				BPF_ALU_SANITIZE_SRC;
15653 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15654 
15655 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
15656 			if (isimm) {
15657 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15658 			} else {
15659 				if (isneg)
15660 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15661 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15662 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15663 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15664 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15665 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15666 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15667 			}
15668 			if (!issrc)
15669 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15670 			insn->src_reg = BPF_REG_AX;
15671 			if (isneg)
15672 				insn->code = insn->code == code_add ?
15673 					     code_sub : code_add;
15674 			*patch++ = *insn;
15675 			if (issrc && isneg && !isimm)
15676 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15677 			cnt = patch - insn_buf;
15678 
15679 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15680 			if (!new_prog)
15681 				return -ENOMEM;
15682 
15683 			delta    += cnt - 1;
15684 			env->prog = prog = new_prog;
15685 			insn      = new_prog->insnsi + i + delta;
15686 			continue;
15687 		}
15688 
15689 		if (insn->code != (BPF_JMP | BPF_CALL))
15690 			continue;
15691 		if (insn->src_reg == BPF_PSEUDO_CALL)
15692 			continue;
15693 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15694 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15695 			if (ret)
15696 				return ret;
15697 			if (cnt == 0)
15698 				continue;
15699 
15700 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15701 			if (!new_prog)
15702 				return -ENOMEM;
15703 
15704 			delta	 += cnt - 1;
15705 			env->prog = prog = new_prog;
15706 			insn	  = new_prog->insnsi + i + delta;
15707 			continue;
15708 		}
15709 
15710 		if (insn->imm == BPF_FUNC_get_route_realm)
15711 			prog->dst_needed = 1;
15712 		if (insn->imm == BPF_FUNC_get_prandom_u32)
15713 			bpf_user_rnd_init_once();
15714 		if (insn->imm == BPF_FUNC_override_return)
15715 			prog->kprobe_override = 1;
15716 		if (insn->imm == BPF_FUNC_tail_call) {
15717 			/* If we tail call into other programs, we
15718 			 * cannot make any assumptions since they can
15719 			 * be replaced dynamically during runtime in
15720 			 * the program array.
15721 			 */
15722 			prog->cb_access = 1;
15723 			if (!allow_tail_call_in_subprogs(env))
15724 				prog->aux->stack_depth = MAX_BPF_STACK;
15725 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15726 
15727 			/* mark bpf_tail_call as different opcode to avoid
15728 			 * conditional branch in the interpreter for every normal
15729 			 * call and to prevent accidental JITing by JIT compiler
15730 			 * that doesn't support bpf_tail_call yet
15731 			 */
15732 			insn->imm = 0;
15733 			insn->code = BPF_JMP | BPF_TAIL_CALL;
15734 
15735 			aux = &env->insn_aux_data[i + delta];
15736 			if (env->bpf_capable && !prog->blinding_requested &&
15737 			    prog->jit_requested &&
15738 			    !bpf_map_key_poisoned(aux) &&
15739 			    !bpf_map_ptr_poisoned(aux) &&
15740 			    !bpf_map_ptr_unpriv(aux)) {
15741 				struct bpf_jit_poke_descriptor desc = {
15742 					.reason = BPF_POKE_REASON_TAIL_CALL,
15743 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15744 					.tail_call.key = bpf_map_key_immediate(aux),
15745 					.insn_idx = i + delta,
15746 				};
15747 
15748 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
15749 				if (ret < 0) {
15750 					verbose(env, "adding tail call poke descriptor failed\n");
15751 					return ret;
15752 				}
15753 
15754 				insn->imm = ret + 1;
15755 				continue;
15756 			}
15757 
15758 			if (!bpf_map_ptr_unpriv(aux))
15759 				continue;
15760 
15761 			/* instead of changing every JIT dealing with tail_call
15762 			 * emit two extra insns:
15763 			 * if (index >= max_entries) goto out;
15764 			 * index &= array->index_mask;
15765 			 * to avoid out-of-bounds cpu speculation
15766 			 */
15767 			if (bpf_map_ptr_poisoned(aux)) {
15768 				verbose(env, "tail_call abusing map_ptr\n");
15769 				return -EINVAL;
15770 			}
15771 
15772 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15773 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15774 						  map_ptr->max_entries, 2);
15775 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15776 						    container_of(map_ptr,
15777 								 struct bpf_array,
15778 								 map)->index_mask);
15779 			insn_buf[2] = *insn;
15780 			cnt = 3;
15781 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15782 			if (!new_prog)
15783 				return -ENOMEM;
15784 
15785 			delta    += cnt - 1;
15786 			env->prog = prog = new_prog;
15787 			insn      = new_prog->insnsi + i + delta;
15788 			continue;
15789 		}
15790 
15791 		if (insn->imm == BPF_FUNC_timer_set_callback) {
15792 			/* The verifier will process callback_fn as many times as necessary
15793 			 * with different maps and the register states prepared by
15794 			 * set_timer_callback_state will be accurate.
15795 			 *
15796 			 * The following use case is valid:
15797 			 *   map1 is shared by prog1, prog2, prog3.
15798 			 *   prog1 calls bpf_timer_init for some map1 elements
15799 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
15800 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
15801 			 *   prog3 calls bpf_timer_start for some map1 elements.
15802 			 *     Those that were not both bpf_timer_init-ed and
15803 			 *     bpf_timer_set_callback-ed will return -EINVAL.
15804 			 */
15805 			struct bpf_insn ld_addrs[2] = {
15806 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15807 			};
15808 
15809 			insn_buf[0] = ld_addrs[0];
15810 			insn_buf[1] = ld_addrs[1];
15811 			insn_buf[2] = *insn;
15812 			cnt = 3;
15813 
15814 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15815 			if (!new_prog)
15816 				return -ENOMEM;
15817 
15818 			delta    += cnt - 1;
15819 			env->prog = prog = new_prog;
15820 			insn      = new_prog->insnsi + i + delta;
15821 			goto patch_call_imm;
15822 		}
15823 
15824 		if (is_storage_get_function(insn->imm)) {
15825 			if (!env->prog->aux->sleepable ||
15826 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
15827 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15828 			else
15829 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15830 			insn_buf[1] = *insn;
15831 			cnt = 2;
15832 
15833 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15834 			if (!new_prog)
15835 				return -ENOMEM;
15836 
15837 			delta += cnt - 1;
15838 			env->prog = prog = new_prog;
15839 			insn = new_prog->insnsi + i + delta;
15840 			goto patch_call_imm;
15841 		}
15842 
15843 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15844 		 * and other inlining handlers are currently limited to 64 bit
15845 		 * only.
15846 		 */
15847 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15848 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
15849 		     insn->imm == BPF_FUNC_map_update_elem ||
15850 		     insn->imm == BPF_FUNC_map_delete_elem ||
15851 		     insn->imm == BPF_FUNC_map_push_elem   ||
15852 		     insn->imm == BPF_FUNC_map_pop_elem    ||
15853 		     insn->imm == BPF_FUNC_map_peek_elem   ||
15854 		     insn->imm == BPF_FUNC_redirect_map    ||
15855 		     insn->imm == BPF_FUNC_for_each_map_elem ||
15856 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15857 			aux = &env->insn_aux_data[i + delta];
15858 			if (bpf_map_ptr_poisoned(aux))
15859 				goto patch_call_imm;
15860 
15861 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15862 			ops = map_ptr->ops;
15863 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
15864 			    ops->map_gen_lookup) {
15865 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15866 				if (cnt == -EOPNOTSUPP)
15867 					goto patch_map_ops_generic;
15868 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15869 					verbose(env, "bpf verifier is misconfigured\n");
15870 					return -EINVAL;
15871 				}
15872 
15873 				new_prog = bpf_patch_insn_data(env, i + delta,
15874 							       insn_buf, cnt);
15875 				if (!new_prog)
15876 					return -ENOMEM;
15877 
15878 				delta    += cnt - 1;
15879 				env->prog = prog = new_prog;
15880 				insn      = new_prog->insnsi + i + delta;
15881 				continue;
15882 			}
15883 
15884 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15885 				     (void *(*)(struct bpf_map *map, void *key))NULL));
15886 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15887 				     (int (*)(struct bpf_map *map, void *key))NULL));
15888 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15889 				     (int (*)(struct bpf_map *map, void *key, void *value,
15890 					      u64 flags))NULL));
15891 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15892 				     (int (*)(struct bpf_map *map, void *value,
15893 					      u64 flags))NULL));
15894 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15895 				     (int (*)(struct bpf_map *map, void *value))NULL));
15896 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15897 				     (int (*)(struct bpf_map *map, void *value))NULL));
15898 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
15899 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15900 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15901 				     (int (*)(struct bpf_map *map,
15902 					      bpf_callback_t callback_fn,
15903 					      void *callback_ctx,
15904 					      u64 flags))NULL));
15905 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15906 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15907 
15908 patch_map_ops_generic:
15909 			switch (insn->imm) {
15910 			case BPF_FUNC_map_lookup_elem:
15911 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15912 				continue;
15913 			case BPF_FUNC_map_update_elem:
15914 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15915 				continue;
15916 			case BPF_FUNC_map_delete_elem:
15917 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15918 				continue;
15919 			case BPF_FUNC_map_push_elem:
15920 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15921 				continue;
15922 			case BPF_FUNC_map_pop_elem:
15923 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15924 				continue;
15925 			case BPF_FUNC_map_peek_elem:
15926 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15927 				continue;
15928 			case BPF_FUNC_redirect_map:
15929 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
15930 				continue;
15931 			case BPF_FUNC_for_each_map_elem:
15932 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15933 				continue;
15934 			case BPF_FUNC_map_lookup_percpu_elem:
15935 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15936 				continue;
15937 			}
15938 
15939 			goto patch_call_imm;
15940 		}
15941 
15942 		/* Implement bpf_jiffies64 inline. */
15943 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15944 		    insn->imm == BPF_FUNC_jiffies64) {
15945 			struct bpf_insn ld_jiffies_addr[2] = {
15946 				BPF_LD_IMM64(BPF_REG_0,
15947 					     (unsigned long)&jiffies),
15948 			};
15949 
15950 			insn_buf[0] = ld_jiffies_addr[0];
15951 			insn_buf[1] = ld_jiffies_addr[1];
15952 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15953 						  BPF_REG_0, 0);
15954 			cnt = 3;
15955 
15956 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15957 						       cnt);
15958 			if (!new_prog)
15959 				return -ENOMEM;
15960 
15961 			delta    += cnt - 1;
15962 			env->prog = prog = new_prog;
15963 			insn      = new_prog->insnsi + i + delta;
15964 			continue;
15965 		}
15966 
15967 		/* Implement bpf_get_func_arg inline. */
15968 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15969 		    insn->imm == BPF_FUNC_get_func_arg) {
15970 			/* Load nr_args from ctx - 8 */
15971 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15972 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15973 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15974 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15975 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15976 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15977 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15978 			insn_buf[7] = BPF_JMP_A(1);
15979 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15980 			cnt = 9;
15981 
15982 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15983 			if (!new_prog)
15984 				return -ENOMEM;
15985 
15986 			delta    += cnt - 1;
15987 			env->prog = prog = new_prog;
15988 			insn      = new_prog->insnsi + i + delta;
15989 			continue;
15990 		}
15991 
15992 		/* Implement bpf_get_func_ret inline. */
15993 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15994 		    insn->imm == BPF_FUNC_get_func_ret) {
15995 			if (eatype == BPF_TRACE_FEXIT ||
15996 			    eatype == BPF_MODIFY_RETURN) {
15997 				/* Load nr_args from ctx - 8 */
15998 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15999 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
16000 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
16001 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16002 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
16003 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
16004 				cnt = 6;
16005 			} else {
16006 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
16007 				cnt = 1;
16008 			}
16009 
16010 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16011 			if (!new_prog)
16012 				return -ENOMEM;
16013 
16014 			delta    += cnt - 1;
16015 			env->prog = prog = new_prog;
16016 			insn      = new_prog->insnsi + i + delta;
16017 			continue;
16018 		}
16019 
16020 		/* Implement get_func_arg_cnt inline. */
16021 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16022 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16023 			/* Load nr_args from ctx - 8 */
16024 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16025 
16026 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16027 			if (!new_prog)
16028 				return -ENOMEM;
16029 
16030 			env->prog = prog = new_prog;
16031 			insn      = new_prog->insnsi + i + delta;
16032 			continue;
16033 		}
16034 
16035 		/* Implement bpf_get_func_ip inline. */
16036 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16037 		    insn->imm == BPF_FUNC_get_func_ip) {
16038 			/* Load IP address from ctx - 16 */
16039 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16040 
16041 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16042 			if (!new_prog)
16043 				return -ENOMEM;
16044 
16045 			env->prog = prog = new_prog;
16046 			insn      = new_prog->insnsi + i + delta;
16047 			continue;
16048 		}
16049 
16050 patch_call_imm:
16051 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16052 		/* all functions that have prototype and verifier allowed
16053 		 * programs to call them, must be real in-kernel functions
16054 		 */
16055 		if (!fn->func) {
16056 			verbose(env,
16057 				"kernel subsystem misconfigured func %s#%d\n",
16058 				func_id_name(insn->imm), insn->imm);
16059 			return -EFAULT;
16060 		}
16061 		insn->imm = fn->func - __bpf_call_base;
16062 	}
16063 
16064 	/* Since poke tab is now finalized, publish aux to tracker. */
16065 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16066 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16067 		if (!map_ptr->ops->map_poke_track ||
16068 		    !map_ptr->ops->map_poke_untrack ||
16069 		    !map_ptr->ops->map_poke_run) {
16070 			verbose(env, "bpf verifier is misconfigured\n");
16071 			return -EINVAL;
16072 		}
16073 
16074 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16075 		if (ret < 0) {
16076 			verbose(env, "tracking tail call prog failed\n");
16077 			return ret;
16078 		}
16079 	}
16080 
16081 	sort_kfunc_descs_by_imm(env->prog);
16082 
16083 	return 0;
16084 }
16085 
16086 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16087 					int position,
16088 					s32 stack_base,
16089 					u32 callback_subprogno,
16090 					u32 *cnt)
16091 {
16092 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16093 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16094 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16095 	int reg_loop_max = BPF_REG_6;
16096 	int reg_loop_cnt = BPF_REG_7;
16097 	int reg_loop_ctx = BPF_REG_8;
16098 
16099 	struct bpf_prog *new_prog;
16100 	u32 callback_start;
16101 	u32 call_insn_offset;
16102 	s32 callback_offset;
16103 
16104 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16105 	 * be careful to modify this code in sync.
16106 	 */
16107 	struct bpf_insn insn_buf[] = {
16108 		/* Return error and jump to the end of the patch if
16109 		 * expected number of iterations is too big.
16110 		 */
16111 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16112 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16113 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16114 		/* spill R6, R7, R8 to use these as loop vars */
16115 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16116 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16117 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16118 		/* initialize loop vars */
16119 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16120 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16121 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16122 		/* loop header,
16123 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16124 		 */
16125 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16126 		/* callback call,
16127 		 * correct callback offset would be set after patching
16128 		 */
16129 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16130 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16131 		BPF_CALL_REL(0),
16132 		/* increment loop counter */
16133 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16134 		/* jump to loop header if callback returned 0 */
16135 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16136 		/* return value of bpf_loop,
16137 		 * set R0 to the number of iterations
16138 		 */
16139 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16140 		/* restore original values of R6, R7, R8 */
16141 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16142 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16143 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16144 	};
16145 
16146 	*cnt = ARRAY_SIZE(insn_buf);
16147 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16148 	if (!new_prog)
16149 		return new_prog;
16150 
16151 	/* callback start is known only after patching */
16152 	callback_start = env->subprog_info[callback_subprogno].start;
16153 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16154 	call_insn_offset = position + 12;
16155 	callback_offset = callback_start - call_insn_offset - 1;
16156 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16157 
16158 	return new_prog;
16159 }
16160 
16161 static bool is_bpf_loop_call(struct bpf_insn *insn)
16162 {
16163 	return insn->code == (BPF_JMP | BPF_CALL) &&
16164 		insn->src_reg == 0 &&
16165 		insn->imm == BPF_FUNC_loop;
16166 }
16167 
16168 /* For all sub-programs in the program (including main) check
16169  * insn_aux_data to see if there are bpf_loop calls that require
16170  * inlining. If such calls are found the calls are replaced with a
16171  * sequence of instructions produced by `inline_bpf_loop` function and
16172  * subprog stack_depth is increased by the size of 3 registers.
16173  * This stack space is used to spill values of the R6, R7, R8.  These
16174  * registers are used to store the loop bound, counter and context
16175  * variables.
16176  */
16177 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16178 {
16179 	struct bpf_subprog_info *subprogs = env->subprog_info;
16180 	int i, cur_subprog = 0, cnt, delta = 0;
16181 	struct bpf_insn *insn = env->prog->insnsi;
16182 	int insn_cnt = env->prog->len;
16183 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16184 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16185 	u16 stack_depth_extra = 0;
16186 
16187 	for (i = 0; i < insn_cnt; i++, insn++) {
16188 		struct bpf_loop_inline_state *inline_state =
16189 			&env->insn_aux_data[i + delta].loop_inline_state;
16190 
16191 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16192 			struct bpf_prog *new_prog;
16193 
16194 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16195 			new_prog = inline_bpf_loop(env,
16196 						   i + delta,
16197 						   -(stack_depth + stack_depth_extra),
16198 						   inline_state->callback_subprogno,
16199 						   &cnt);
16200 			if (!new_prog)
16201 				return -ENOMEM;
16202 
16203 			delta     += cnt - 1;
16204 			env->prog  = new_prog;
16205 			insn       = new_prog->insnsi + i + delta;
16206 		}
16207 
16208 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16209 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16210 			cur_subprog++;
16211 			stack_depth = subprogs[cur_subprog].stack_depth;
16212 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16213 			stack_depth_extra = 0;
16214 		}
16215 	}
16216 
16217 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16218 
16219 	return 0;
16220 }
16221 
16222 static void free_states(struct bpf_verifier_env *env)
16223 {
16224 	struct bpf_verifier_state_list *sl, *sln;
16225 	int i;
16226 
16227 	sl = env->free_list;
16228 	while (sl) {
16229 		sln = sl->next;
16230 		free_verifier_state(&sl->state, false);
16231 		kfree(sl);
16232 		sl = sln;
16233 	}
16234 	env->free_list = NULL;
16235 
16236 	if (!env->explored_states)
16237 		return;
16238 
16239 	for (i = 0; i < state_htab_size(env); i++) {
16240 		sl = env->explored_states[i];
16241 
16242 		while (sl) {
16243 			sln = sl->next;
16244 			free_verifier_state(&sl->state, false);
16245 			kfree(sl);
16246 			sl = sln;
16247 		}
16248 		env->explored_states[i] = NULL;
16249 	}
16250 }
16251 
16252 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16253 {
16254 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16255 	struct bpf_verifier_state *state;
16256 	struct bpf_reg_state *regs;
16257 	int ret, i;
16258 
16259 	env->prev_linfo = NULL;
16260 	env->pass_cnt++;
16261 
16262 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16263 	if (!state)
16264 		return -ENOMEM;
16265 	state->curframe = 0;
16266 	state->speculative = false;
16267 	state->branches = 1;
16268 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16269 	if (!state->frame[0]) {
16270 		kfree(state);
16271 		return -ENOMEM;
16272 	}
16273 	env->cur_state = state;
16274 	init_func_state(env, state->frame[0],
16275 			BPF_MAIN_FUNC /* callsite */,
16276 			0 /* frameno */,
16277 			subprog);
16278 	state->first_insn_idx = env->subprog_info[subprog].start;
16279 	state->last_insn_idx = -1;
16280 
16281 	regs = state->frame[state->curframe]->regs;
16282 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16283 		ret = btf_prepare_func_args(env, subprog, regs);
16284 		if (ret)
16285 			goto out;
16286 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16287 			if (regs[i].type == PTR_TO_CTX)
16288 				mark_reg_known_zero(env, regs, i);
16289 			else if (regs[i].type == SCALAR_VALUE)
16290 				mark_reg_unknown(env, regs, i);
16291 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
16292 				const u32 mem_size = regs[i].mem_size;
16293 
16294 				mark_reg_known_zero(env, regs, i);
16295 				regs[i].mem_size = mem_size;
16296 				regs[i].id = ++env->id_gen;
16297 			}
16298 		}
16299 	} else {
16300 		/* 1st arg to a function */
16301 		regs[BPF_REG_1].type = PTR_TO_CTX;
16302 		mark_reg_known_zero(env, regs, BPF_REG_1);
16303 		ret = btf_check_subprog_arg_match(env, subprog, regs);
16304 		if (ret == -EFAULT)
16305 			/* unlikely verifier bug. abort.
16306 			 * ret == 0 and ret < 0 are sadly acceptable for
16307 			 * main() function due to backward compatibility.
16308 			 * Like socket filter program may be written as:
16309 			 * int bpf_prog(struct pt_regs *ctx)
16310 			 * and never dereference that ctx in the program.
16311 			 * 'struct pt_regs' is a type mismatch for socket
16312 			 * filter that should be using 'struct __sk_buff'.
16313 			 */
16314 			goto out;
16315 	}
16316 
16317 	ret = do_check(env);
16318 out:
16319 	/* check for NULL is necessary, since cur_state can be freed inside
16320 	 * do_check() under memory pressure.
16321 	 */
16322 	if (env->cur_state) {
16323 		free_verifier_state(env->cur_state, true);
16324 		env->cur_state = NULL;
16325 	}
16326 	while (!pop_stack(env, NULL, NULL, false));
16327 	if (!ret && pop_log)
16328 		bpf_vlog_reset(&env->log, 0);
16329 	free_states(env);
16330 	return ret;
16331 }
16332 
16333 /* Verify all global functions in a BPF program one by one based on their BTF.
16334  * All global functions must pass verification. Otherwise the whole program is rejected.
16335  * Consider:
16336  * int bar(int);
16337  * int foo(int f)
16338  * {
16339  *    return bar(f);
16340  * }
16341  * int bar(int b)
16342  * {
16343  *    ...
16344  * }
16345  * foo() will be verified first for R1=any_scalar_value. During verification it
16346  * will be assumed that bar() already verified successfully and call to bar()
16347  * from foo() will be checked for type match only. Later bar() will be verified
16348  * independently to check that it's safe for R1=any_scalar_value.
16349  */
16350 static int do_check_subprogs(struct bpf_verifier_env *env)
16351 {
16352 	struct bpf_prog_aux *aux = env->prog->aux;
16353 	int i, ret;
16354 
16355 	if (!aux->func_info)
16356 		return 0;
16357 
16358 	for (i = 1; i < env->subprog_cnt; i++) {
16359 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16360 			continue;
16361 		env->insn_idx = env->subprog_info[i].start;
16362 		WARN_ON_ONCE(env->insn_idx == 0);
16363 		ret = do_check_common(env, i);
16364 		if (ret) {
16365 			return ret;
16366 		} else if (env->log.level & BPF_LOG_LEVEL) {
16367 			verbose(env,
16368 				"Func#%d is safe for any args that match its prototype\n",
16369 				i);
16370 		}
16371 	}
16372 	return 0;
16373 }
16374 
16375 static int do_check_main(struct bpf_verifier_env *env)
16376 {
16377 	int ret;
16378 
16379 	env->insn_idx = 0;
16380 	ret = do_check_common(env, 0);
16381 	if (!ret)
16382 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16383 	return ret;
16384 }
16385 
16386 
16387 static void print_verification_stats(struct bpf_verifier_env *env)
16388 {
16389 	int i;
16390 
16391 	if (env->log.level & BPF_LOG_STATS) {
16392 		verbose(env, "verification time %lld usec\n",
16393 			div_u64(env->verification_time, 1000));
16394 		verbose(env, "stack depth ");
16395 		for (i = 0; i < env->subprog_cnt; i++) {
16396 			u32 depth = env->subprog_info[i].stack_depth;
16397 
16398 			verbose(env, "%d", depth);
16399 			if (i + 1 < env->subprog_cnt)
16400 				verbose(env, "+");
16401 		}
16402 		verbose(env, "\n");
16403 	}
16404 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16405 		"total_states %d peak_states %d mark_read %d\n",
16406 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16407 		env->max_states_per_insn, env->total_states,
16408 		env->peak_states, env->longest_mark_read_walk);
16409 }
16410 
16411 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16412 {
16413 	const struct btf_type *t, *func_proto;
16414 	const struct bpf_struct_ops *st_ops;
16415 	const struct btf_member *member;
16416 	struct bpf_prog *prog = env->prog;
16417 	u32 btf_id, member_idx;
16418 	const char *mname;
16419 
16420 	if (!prog->gpl_compatible) {
16421 		verbose(env, "struct ops programs must have a GPL compatible license\n");
16422 		return -EINVAL;
16423 	}
16424 
16425 	btf_id = prog->aux->attach_btf_id;
16426 	st_ops = bpf_struct_ops_find(btf_id);
16427 	if (!st_ops) {
16428 		verbose(env, "attach_btf_id %u is not a supported struct\n",
16429 			btf_id);
16430 		return -ENOTSUPP;
16431 	}
16432 
16433 	t = st_ops->type;
16434 	member_idx = prog->expected_attach_type;
16435 	if (member_idx >= btf_type_vlen(t)) {
16436 		verbose(env, "attach to invalid member idx %u of struct %s\n",
16437 			member_idx, st_ops->name);
16438 		return -EINVAL;
16439 	}
16440 
16441 	member = &btf_type_member(t)[member_idx];
16442 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16443 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16444 					       NULL);
16445 	if (!func_proto) {
16446 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16447 			mname, member_idx, st_ops->name);
16448 		return -EINVAL;
16449 	}
16450 
16451 	if (st_ops->check_member) {
16452 		int err = st_ops->check_member(t, member);
16453 
16454 		if (err) {
16455 			verbose(env, "attach to unsupported member %s of struct %s\n",
16456 				mname, st_ops->name);
16457 			return err;
16458 		}
16459 	}
16460 
16461 	prog->aux->attach_func_proto = func_proto;
16462 	prog->aux->attach_func_name = mname;
16463 	env->ops = st_ops->verifier_ops;
16464 
16465 	return 0;
16466 }
16467 #define SECURITY_PREFIX "security_"
16468 
16469 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16470 {
16471 	if (within_error_injection_list(addr) ||
16472 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16473 		return 0;
16474 
16475 	return -EINVAL;
16476 }
16477 
16478 /* list of non-sleepable functions that are otherwise on
16479  * ALLOW_ERROR_INJECTION list
16480  */
16481 BTF_SET_START(btf_non_sleepable_error_inject)
16482 /* Three functions below can be called from sleepable and non-sleepable context.
16483  * Assume non-sleepable from bpf safety point of view.
16484  */
16485 BTF_ID(func, __filemap_add_folio)
16486 BTF_ID(func, should_fail_alloc_page)
16487 BTF_ID(func, should_failslab)
16488 BTF_SET_END(btf_non_sleepable_error_inject)
16489 
16490 static int check_non_sleepable_error_inject(u32 btf_id)
16491 {
16492 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16493 }
16494 
16495 int bpf_check_attach_target(struct bpf_verifier_log *log,
16496 			    const struct bpf_prog *prog,
16497 			    const struct bpf_prog *tgt_prog,
16498 			    u32 btf_id,
16499 			    struct bpf_attach_target_info *tgt_info)
16500 {
16501 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16502 	const char prefix[] = "btf_trace_";
16503 	int ret = 0, subprog = -1, i;
16504 	const struct btf_type *t;
16505 	bool conservative = true;
16506 	const char *tname;
16507 	struct btf *btf;
16508 	long addr = 0;
16509 
16510 	if (!btf_id) {
16511 		bpf_log(log, "Tracing programs must provide btf_id\n");
16512 		return -EINVAL;
16513 	}
16514 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16515 	if (!btf) {
16516 		bpf_log(log,
16517 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16518 		return -EINVAL;
16519 	}
16520 	t = btf_type_by_id(btf, btf_id);
16521 	if (!t) {
16522 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16523 		return -EINVAL;
16524 	}
16525 	tname = btf_name_by_offset(btf, t->name_off);
16526 	if (!tname) {
16527 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16528 		return -EINVAL;
16529 	}
16530 	if (tgt_prog) {
16531 		struct bpf_prog_aux *aux = tgt_prog->aux;
16532 
16533 		for (i = 0; i < aux->func_info_cnt; i++)
16534 			if (aux->func_info[i].type_id == btf_id) {
16535 				subprog = i;
16536 				break;
16537 			}
16538 		if (subprog == -1) {
16539 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
16540 			return -EINVAL;
16541 		}
16542 		conservative = aux->func_info_aux[subprog].unreliable;
16543 		if (prog_extension) {
16544 			if (conservative) {
16545 				bpf_log(log,
16546 					"Cannot replace static functions\n");
16547 				return -EINVAL;
16548 			}
16549 			if (!prog->jit_requested) {
16550 				bpf_log(log,
16551 					"Extension programs should be JITed\n");
16552 				return -EINVAL;
16553 			}
16554 		}
16555 		if (!tgt_prog->jited) {
16556 			bpf_log(log, "Can attach to only JITed progs\n");
16557 			return -EINVAL;
16558 		}
16559 		if (tgt_prog->type == prog->type) {
16560 			/* Cannot fentry/fexit another fentry/fexit program.
16561 			 * Cannot attach program extension to another extension.
16562 			 * It's ok to attach fentry/fexit to extension program.
16563 			 */
16564 			bpf_log(log, "Cannot recursively attach\n");
16565 			return -EINVAL;
16566 		}
16567 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16568 		    prog_extension &&
16569 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16570 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16571 			/* Program extensions can extend all program types
16572 			 * except fentry/fexit. The reason is the following.
16573 			 * The fentry/fexit programs are used for performance
16574 			 * analysis, stats and can be attached to any program
16575 			 * type except themselves. When extension program is
16576 			 * replacing XDP function it is necessary to allow
16577 			 * performance analysis of all functions. Both original
16578 			 * XDP program and its program extension. Hence
16579 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16580 			 * allowed. If extending of fentry/fexit was allowed it
16581 			 * would be possible to create long call chain
16582 			 * fentry->extension->fentry->extension beyond
16583 			 * reasonable stack size. Hence extending fentry is not
16584 			 * allowed.
16585 			 */
16586 			bpf_log(log, "Cannot extend fentry/fexit\n");
16587 			return -EINVAL;
16588 		}
16589 	} else {
16590 		if (prog_extension) {
16591 			bpf_log(log, "Cannot replace kernel functions\n");
16592 			return -EINVAL;
16593 		}
16594 	}
16595 
16596 	switch (prog->expected_attach_type) {
16597 	case BPF_TRACE_RAW_TP:
16598 		if (tgt_prog) {
16599 			bpf_log(log,
16600 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16601 			return -EINVAL;
16602 		}
16603 		if (!btf_type_is_typedef(t)) {
16604 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
16605 				btf_id);
16606 			return -EINVAL;
16607 		}
16608 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16609 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16610 				btf_id, tname);
16611 			return -EINVAL;
16612 		}
16613 		tname += sizeof(prefix) - 1;
16614 		t = btf_type_by_id(btf, t->type);
16615 		if (!btf_type_is_ptr(t))
16616 			/* should never happen in valid vmlinux build */
16617 			return -EINVAL;
16618 		t = btf_type_by_id(btf, t->type);
16619 		if (!btf_type_is_func_proto(t))
16620 			/* should never happen in valid vmlinux build */
16621 			return -EINVAL;
16622 
16623 		break;
16624 	case BPF_TRACE_ITER:
16625 		if (!btf_type_is_func(t)) {
16626 			bpf_log(log, "attach_btf_id %u is not a function\n",
16627 				btf_id);
16628 			return -EINVAL;
16629 		}
16630 		t = btf_type_by_id(btf, t->type);
16631 		if (!btf_type_is_func_proto(t))
16632 			return -EINVAL;
16633 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16634 		if (ret)
16635 			return ret;
16636 		break;
16637 	default:
16638 		if (!prog_extension)
16639 			return -EINVAL;
16640 		fallthrough;
16641 	case BPF_MODIFY_RETURN:
16642 	case BPF_LSM_MAC:
16643 	case BPF_LSM_CGROUP:
16644 	case BPF_TRACE_FENTRY:
16645 	case BPF_TRACE_FEXIT:
16646 		if (!btf_type_is_func(t)) {
16647 			bpf_log(log, "attach_btf_id %u is not a function\n",
16648 				btf_id);
16649 			return -EINVAL;
16650 		}
16651 		if (prog_extension &&
16652 		    btf_check_type_match(log, prog, btf, t))
16653 			return -EINVAL;
16654 		t = btf_type_by_id(btf, t->type);
16655 		if (!btf_type_is_func_proto(t))
16656 			return -EINVAL;
16657 
16658 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16659 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16660 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16661 			return -EINVAL;
16662 
16663 		if (tgt_prog && conservative)
16664 			t = NULL;
16665 
16666 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16667 		if (ret < 0)
16668 			return ret;
16669 
16670 		if (tgt_prog) {
16671 			if (subprog == 0)
16672 				addr = (long) tgt_prog->bpf_func;
16673 			else
16674 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16675 		} else {
16676 			addr = kallsyms_lookup_name(tname);
16677 			if (!addr) {
16678 				bpf_log(log,
16679 					"The address of function %s cannot be found\n",
16680 					tname);
16681 				return -ENOENT;
16682 			}
16683 		}
16684 
16685 		if (prog->aux->sleepable) {
16686 			ret = -EINVAL;
16687 			switch (prog->type) {
16688 			case BPF_PROG_TYPE_TRACING:
16689 
16690 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
16691 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16692 				 */
16693 				if (!check_non_sleepable_error_inject(btf_id) &&
16694 				    within_error_injection_list(addr))
16695 					ret = 0;
16696 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
16697 				 * in the fmodret id set with the KF_SLEEPABLE flag.
16698 				 */
16699 				else {
16700 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
16701 
16702 					if (flags && (*flags & KF_SLEEPABLE))
16703 						ret = 0;
16704 				}
16705 				break;
16706 			case BPF_PROG_TYPE_LSM:
16707 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
16708 				 * Only some of them are sleepable.
16709 				 */
16710 				if (bpf_lsm_is_sleepable_hook(btf_id))
16711 					ret = 0;
16712 				break;
16713 			default:
16714 				break;
16715 			}
16716 			if (ret) {
16717 				bpf_log(log, "%s is not sleepable\n", tname);
16718 				return ret;
16719 			}
16720 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16721 			if (tgt_prog) {
16722 				bpf_log(log, "can't modify return codes of BPF programs\n");
16723 				return -EINVAL;
16724 			}
16725 			ret = -EINVAL;
16726 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
16727 			    !check_attach_modify_return(addr, tname))
16728 				ret = 0;
16729 			if (ret) {
16730 				bpf_log(log, "%s() is not modifiable\n", tname);
16731 				return ret;
16732 			}
16733 		}
16734 
16735 		break;
16736 	}
16737 	tgt_info->tgt_addr = addr;
16738 	tgt_info->tgt_name = tname;
16739 	tgt_info->tgt_type = t;
16740 	return 0;
16741 }
16742 
16743 BTF_SET_START(btf_id_deny)
16744 BTF_ID_UNUSED
16745 #ifdef CONFIG_SMP
16746 BTF_ID(func, migrate_disable)
16747 BTF_ID(func, migrate_enable)
16748 #endif
16749 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16750 BTF_ID(func, rcu_read_unlock_strict)
16751 #endif
16752 BTF_SET_END(btf_id_deny)
16753 
16754 static int check_attach_btf_id(struct bpf_verifier_env *env)
16755 {
16756 	struct bpf_prog *prog = env->prog;
16757 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16758 	struct bpf_attach_target_info tgt_info = {};
16759 	u32 btf_id = prog->aux->attach_btf_id;
16760 	struct bpf_trampoline *tr;
16761 	int ret;
16762 	u64 key;
16763 
16764 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16765 		if (prog->aux->sleepable)
16766 			/* attach_btf_id checked to be zero already */
16767 			return 0;
16768 		verbose(env, "Syscall programs can only be sleepable\n");
16769 		return -EINVAL;
16770 	}
16771 
16772 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16773 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16774 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16775 		return -EINVAL;
16776 	}
16777 
16778 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16779 		return check_struct_ops_btf_id(env);
16780 
16781 	if (prog->type != BPF_PROG_TYPE_TRACING &&
16782 	    prog->type != BPF_PROG_TYPE_LSM &&
16783 	    prog->type != BPF_PROG_TYPE_EXT)
16784 		return 0;
16785 
16786 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16787 	if (ret)
16788 		return ret;
16789 
16790 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16791 		/* to make freplace equivalent to their targets, they need to
16792 		 * inherit env->ops and expected_attach_type for the rest of the
16793 		 * verification
16794 		 */
16795 		env->ops = bpf_verifier_ops[tgt_prog->type];
16796 		prog->expected_attach_type = tgt_prog->expected_attach_type;
16797 	}
16798 
16799 	/* store info about the attachment target that will be used later */
16800 	prog->aux->attach_func_proto = tgt_info.tgt_type;
16801 	prog->aux->attach_func_name = tgt_info.tgt_name;
16802 
16803 	if (tgt_prog) {
16804 		prog->aux->saved_dst_prog_type = tgt_prog->type;
16805 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16806 	}
16807 
16808 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16809 		prog->aux->attach_btf_trace = true;
16810 		return 0;
16811 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16812 		if (!bpf_iter_prog_supported(prog))
16813 			return -EINVAL;
16814 		return 0;
16815 	}
16816 
16817 	if (prog->type == BPF_PROG_TYPE_LSM) {
16818 		ret = bpf_lsm_verify_prog(&env->log, prog);
16819 		if (ret < 0)
16820 			return ret;
16821 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
16822 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
16823 		return -EINVAL;
16824 	}
16825 
16826 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16827 	tr = bpf_trampoline_get(key, &tgt_info);
16828 	if (!tr)
16829 		return -ENOMEM;
16830 
16831 	prog->aux->dst_trampoline = tr;
16832 	return 0;
16833 }
16834 
16835 struct btf *bpf_get_btf_vmlinux(void)
16836 {
16837 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16838 		mutex_lock(&bpf_verifier_lock);
16839 		if (!btf_vmlinux)
16840 			btf_vmlinux = btf_parse_vmlinux();
16841 		mutex_unlock(&bpf_verifier_lock);
16842 	}
16843 	return btf_vmlinux;
16844 }
16845 
16846 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16847 {
16848 	u64 start_time = ktime_get_ns();
16849 	struct bpf_verifier_env *env;
16850 	struct bpf_verifier_log *log;
16851 	int i, len, ret = -EINVAL;
16852 	bool is_priv;
16853 
16854 	/* no program is valid */
16855 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16856 		return -EINVAL;
16857 
16858 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
16859 	 * allocate/free it every time bpf_check() is called
16860 	 */
16861 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16862 	if (!env)
16863 		return -ENOMEM;
16864 	log = &env->log;
16865 
16866 	len = (*prog)->len;
16867 	env->insn_aux_data =
16868 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16869 	ret = -ENOMEM;
16870 	if (!env->insn_aux_data)
16871 		goto err_free_env;
16872 	for (i = 0; i < len; i++)
16873 		env->insn_aux_data[i].orig_idx = i;
16874 	env->prog = *prog;
16875 	env->ops = bpf_verifier_ops[env->prog->type];
16876 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16877 	is_priv = bpf_capable();
16878 
16879 	bpf_get_btf_vmlinux();
16880 
16881 	/* grab the mutex to protect few globals used by verifier */
16882 	if (!is_priv)
16883 		mutex_lock(&bpf_verifier_lock);
16884 
16885 	if (attr->log_level || attr->log_buf || attr->log_size) {
16886 		/* user requested verbose verifier output
16887 		 * and supplied buffer to store the verification trace
16888 		 */
16889 		log->level = attr->log_level;
16890 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16891 		log->len_total = attr->log_size;
16892 
16893 		/* log attributes have to be sane */
16894 		if (!bpf_verifier_log_attr_valid(log)) {
16895 			ret = -EINVAL;
16896 			goto err_unlock;
16897 		}
16898 	}
16899 
16900 	mark_verifier_state_clean(env);
16901 
16902 	if (IS_ERR(btf_vmlinux)) {
16903 		/* Either gcc or pahole or kernel are broken. */
16904 		verbose(env, "in-kernel BTF is malformed\n");
16905 		ret = PTR_ERR(btf_vmlinux);
16906 		goto skip_full_check;
16907 	}
16908 
16909 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16910 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16911 		env->strict_alignment = true;
16912 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16913 		env->strict_alignment = false;
16914 
16915 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16916 	env->allow_uninit_stack = bpf_allow_uninit_stack();
16917 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
16918 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
16919 	env->bpf_capable = bpf_capable();
16920 	env->rcu_tag_supported = btf_vmlinux &&
16921 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
16922 
16923 	if (is_priv)
16924 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16925 
16926 	env->explored_states = kvcalloc(state_htab_size(env),
16927 				       sizeof(struct bpf_verifier_state_list *),
16928 				       GFP_USER);
16929 	ret = -ENOMEM;
16930 	if (!env->explored_states)
16931 		goto skip_full_check;
16932 
16933 	ret = add_subprog_and_kfunc(env);
16934 	if (ret < 0)
16935 		goto skip_full_check;
16936 
16937 	ret = check_subprogs(env);
16938 	if (ret < 0)
16939 		goto skip_full_check;
16940 
16941 	ret = check_btf_info(env, attr, uattr);
16942 	if (ret < 0)
16943 		goto skip_full_check;
16944 
16945 	ret = check_attach_btf_id(env);
16946 	if (ret)
16947 		goto skip_full_check;
16948 
16949 	ret = resolve_pseudo_ldimm64(env);
16950 	if (ret < 0)
16951 		goto skip_full_check;
16952 
16953 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
16954 		ret = bpf_prog_offload_verifier_prep(env->prog);
16955 		if (ret)
16956 			goto skip_full_check;
16957 	}
16958 
16959 	ret = check_cfg(env);
16960 	if (ret < 0)
16961 		goto skip_full_check;
16962 
16963 	ret = do_check_subprogs(env);
16964 	ret = ret ?: do_check_main(env);
16965 
16966 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16967 		ret = bpf_prog_offload_finalize(env);
16968 
16969 skip_full_check:
16970 	kvfree(env->explored_states);
16971 
16972 	if (ret == 0)
16973 		ret = check_max_stack_depth(env);
16974 
16975 	/* instruction rewrites happen after this point */
16976 	if (ret == 0)
16977 		ret = optimize_bpf_loop(env);
16978 
16979 	if (is_priv) {
16980 		if (ret == 0)
16981 			opt_hard_wire_dead_code_branches(env);
16982 		if (ret == 0)
16983 			ret = opt_remove_dead_code(env);
16984 		if (ret == 0)
16985 			ret = opt_remove_nops(env);
16986 	} else {
16987 		if (ret == 0)
16988 			sanitize_dead_code(env);
16989 	}
16990 
16991 	if (ret == 0)
16992 		/* program is valid, convert *(u32*)(ctx + off) accesses */
16993 		ret = convert_ctx_accesses(env);
16994 
16995 	if (ret == 0)
16996 		ret = do_misc_fixups(env);
16997 
16998 	/* do 32-bit optimization after insn patching has done so those patched
16999 	 * insns could be handled correctly.
17000 	 */
17001 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
17002 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
17003 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
17004 								     : false;
17005 	}
17006 
17007 	if (ret == 0)
17008 		ret = fixup_call_args(env);
17009 
17010 	env->verification_time = ktime_get_ns() - start_time;
17011 	print_verification_stats(env);
17012 	env->prog->aux->verified_insns = env->insn_processed;
17013 
17014 	if (log->level && bpf_verifier_log_full(log))
17015 		ret = -ENOSPC;
17016 	if (log->level && !log->ubuf) {
17017 		ret = -EFAULT;
17018 		goto err_release_maps;
17019 	}
17020 
17021 	if (ret)
17022 		goto err_release_maps;
17023 
17024 	if (env->used_map_cnt) {
17025 		/* if program passed verifier, update used_maps in bpf_prog_info */
17026 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17027 							  sizeof(env->used_maps[0]),
17028 							  GFP_KERNEL);
17029 
17030 		if (!env->prog->aux->used_maps) {
17031 			ret = -ENOMEM;
17032 			goto err_release_maps;
17033 		}
17034 
17035 		memcpy(env->prog->aux->used_maps, env->used_maps,
17036 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17037 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17038 	}
17039 	if (env->used_btf_cnt) {
17040 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17041 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17042 							  sizeof(env->used_btfs[0]),
17043 							  GFP_KERNEL);
17044 		if (!env->prog->aux->used_btfs) {
17045 			ret = -ENOMEM;
17046 			goto err_release_maps;
17047 		}
17048 
17049 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17050 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17051 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17052 	}
17053 	if (env->used_map_cnt || env->used_btf_cnt) {
17054 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17055 		 * bpf_ld_imm64 instructions
17056 		 */
17057 		convert_pseudo_ld_imm64(env);
17058 	}
17059 
17060 	adjust_btf_func(env);
17061 
17062 err_release_maps:
17063 	if (!env->prog->aux->used_maps)
17064 		/* if we didn't copy map pointers into bpf_prog_info, release
17065 		 * them now. Otherwise free_used_maps() will release them.
17066 		 */
17067 		release_maps(env);
17068 	if (!env->prog->aux->used_btfs)
17069 		release_btfs(env);
17070 
17071 	/* extension progs temporarily inherit the attach_type of their targets
17072 	   for verification purposes, so set it back to zero before returning
17073 	 */
17074 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17075 		env->prog->expected_attach_type = 0;
17076 
17077 	*prog = env->prog;
17078 err_unlock:
17079 	if (!is_priv)
17080 		mutex_unlock(&bpf_verifier_lock);
17081 	vfree(env->insn_aux_data);
17082 err_free_env:
17083 	kfree(env);
17084 	return ret;
17085 }
17086