xref: /linux-6.15/kernel/bpf/verifier.c (revision 8403bf04)
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 dynptr_id;
259 	int map_uid;
260 	int func_id;
261 	struct btf *btf;
262 	u32 btf_id;
263 	struct btf *ret_btf;
264 	u32 ret_btf_id;
265 	u32 subprogno;
266 	struct btf_field *kptr_field;
267 	u8 uninit_dynptr_regno;
268 };
269 
270 struct btf *btf_vmlinux;
271 
272 static DEFINE_MUTEX(bpf_verifier_lock);
273 
274 static const struct bpf_line_info *
275 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
276 {
277 	const struct bpf_line_info *linfo;
278 	const struct bpf_prog *prog;
279 	u32 i, nr_linfo;
280 
281 	prog = env->prog;
282 	nr_linfo = prog->aux->nr_linfo;
283 
284 	if (!nr_linfo || insn_off >= prog->len)
285 		return NULL;
286 
287 	linfo = prog->aux->linfo;
288 	for (i = 1; i < nr_linfo; i++)
289 		if (insn_off < linfo[i].insn_off)
290 			break;
291 
292 	return &linfo[i - 1];
293 }
294 
295 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
296 		       va_list args)
297 {
298 	unsigned int n;
299 
300 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
301 
302 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
303 		  "verifier log line truncated - local buffer too short\n");
304 
305 	if (log->level == BPF_LOG_KERNEL) {
306 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
307 
308 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
309 		return;
310 	}
311 
312 	n = min(log->len_total - log->len_used - 1, n);
313 	log->kbuf[n] = '\0';
314 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
315 		log->len_used += n;
316 	else
317 		log->ubuf = NULL;
318 }
319 
320 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
321 {
322 	char zero = 0;
323 
324 	if (!bpf_verifier_log_needed(log))
325 		return;
326 
327 	log->len_used = new_pos;
328 	if (put_user(zero, log->ubuf + new_pos))
329 		log->ubuf = NULL;
330 }
331 
332 /* log_level controls verbosity level of eBPF verifier.
333  * bpf_verifier_log_write() is used to dump the verification trace to the log,
334  * so the user can figure out what's wrong with the program
335  */
336 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
337 					   const char *fmt, ...)
338 {
339 	va_list args;
340 
341 	if (!bpf_verifier_log_needed(&env->log))
342 		return;
343 
344 	va_start(args, fmt);
345 	bpf_verifier_vlog(&env->log, fmt, args);
346 	va_end(args);
347 }
348 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
349 
350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
351 {
352 	struct bpf_verifier_env *env = private_data;
353 	va_list args;
354 
355 	if (!bpf_verifier_log_needed(&env->log))
356 		return;
357 
358 	va_start(args, fmt);
359 	bpf_verifier_vlog(&env->log, fmt, args);
360 	va_end(args);
361 }
362 
363 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
364 			    const char *fmt, ...)
365 {
366 	va_list args;
367 
368 	if (!bpf_verifier_log_needed(log))
369 		return;
370 
371 	va_start(args, fmt);
372 	bpf_verifier_vlog(log, fmt, args);
373 	va_end(args);
374 }
375 EXPORT_SYMBOL_GPL(bpf_log);
376 
377 static const char *ltrim(const char *s)
378 {
379 	while (isspace(*s))
380 		s++;
381 
382 	return s;
383 }
384 
385 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
386 					 u32 insn_off,
387 					 const char *prefix_fmt, ...)
388 {
389 	const struct bpf_line_info *linfo;
390 
391 	if (!bpf_verifier_log_needed(&env->log))
392 		return;
393 
394 	linfo = find_linfo(env, insn_off);
395 	if (!linfo || linfo == env->prev_linfo)
396 		return;
397 
398 	if (prefix_fmt) {
399 		va_list args;
400 
401 		va_start(args, prefix_fmt);
402 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
403 		va_end(args);
404 	}
405 
406 	verbose(env, "%s\n",
407 		ltrim(btf_name_by_offset(env->prog->aux->btf,
408 					 linfo->line_off)));
409 
410 	env->prev_linfo = linfo;
411 }
412 
413 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
414 				   struct bpf_reg_state *reg,
415 				   struct tnum *range, const char *ctx,
416 				   const char *reg_name)
417 {
418 	char tn_buf[48];
419 
420 	verbose(env, "At %s the register %s ", ctx, reg_name);
421 	if (!tnum_is_unknown(reg->var_off)) {
422 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
423 		verbose(env, "has value %s", tn_buf);
424 	} else {
425 		verbose(env, "has unknown scalar value");
426 	}
427 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
428 	verbose(env, " should have been in %s\n", tn_buf);
429 }
430 
431 static bool type_is_pkt_pointer(enum bpf_reg_type type)
432 {
433 	type = base_type(type);
434 	return type == PTR_TO_PACKET ||
435 	       type == PTR_TO_PACKET_META;
436 }
437 
438 static bool type_is_sk_pointer(enum bpf_reg_type type)
439 {
440 	return type == PTR_TO_SOCKET ||
441 		type == PTR_TO_SOCK_COMMON ||
442 		type == PTR_TO_TCP_SOCK ||
443 		type == PTR_TO_XDP_SOCK;
444 }
445 
446 static bool reg_type_not_null(enum bpf_reg_type type)
447 {
448 	return type == PTR_TO_SOCKET ||
449 		type == PTR_TO_TCP_SOCK ||
450 		type == PTR_TO_MAP_VALUE ||
451 		type == PTR_TO_MAP_KEY ||
452 		type == PTR_TO_SOCK_COMMON;
453 }
454 
455 static bool type_is_ptr_alloc_obj(u32 type)
456 {
457 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
458 }
459 
460 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
461 {
462 	struct btf_record *rec = NULL;
463 	struct btf_struct_meta *meta;
464 
465 	if (reg->type == PTR_TO_MAP_VALUE) {
466 		rec = reg->map_ptr->record;
467 	} else if (type_is_ptr_alloc_obj(reg->type)) {
468 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
469 		if (meta)
470 			rec = meta->record;
471 	}
472 	return rec;
473 }
474 
475 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
476 {
477 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
478 }
479 
480 static bool type_is_rdonly_mem(u32 type)
481 {
482 	return type & MEM_RDONLY;
483 }
484 
485 static bool type_may_be_null(u32 type)
486 {
487 	return type & PTR_MAYBE_NULL;
488 }
489 
490 static bool is_acquire_function(enum bpf_func_id func_id,
491 				const struct bpf_map *map)
492 {
493 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
494 
495 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
496 	    func_id == BPF_FUNC_sk_lookup_udp ||
497 	    func_id == BPF_FUNC_skc_lookup_tcp ||
498 	    func_id == BPF_FUNC_ringbuf_reserve ||
499 	    func_id == BPF_FUNC_kptr_xchg)
500 		return true;
501 
502 	if (func_id == BPF_FUNC_map_lookup_elem &&
503 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
504 	     map_type == BPF_MAP_TYPE_SOCKHASH))
505 		return true;
506 
507 	return false;
508 }
509 
510 static bool is_ptr_cast_function(enum bpf_func_id func_id)
511 {
512 	return func_id == BPF_FUNC_tcp_sock ||
513 		func_id == BPF_FUNC_sk_fullsock ||
514 		func_id == BPF_FUNC_skc_to_tcp_sock ||
515 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
516 		func_id == BPF_FUNC_skc_to_udp6_sock ||
517 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
518 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
519 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
520 }
521 
522 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
523 {
524 	return func_id == BPF_FUNC_dynptr_data;
525 }
526 
527 static bool is_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_for_each_map_elem ||
530 	       func_id == BPF_FUNC_timer_set_callback ||
531 	       func_id == BPF_FUNC_find_vma ||
532 	       func_id == BPF_FUNC_loop ||
533 	       func_id == BPF_FUNC_user_ringbuf_drain;
534 }
535 
536 static bool is_storage_get_function(enum bpf_func_id func_id)
537 {
538 	return func_id == BPF_FUNC_sk_storage_get ||
539 	       func_id == BPF_FUNC_inode_storage_get ||
540 	       func_id == BPF_FUNC_task_storage_get ||
541 	       func_id == BPF_FUNC_cgrp_storage_get;
542 }
543 
544 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
545 					const struct bpf_map *map)
546 {
547 	int ref_obj_uses = 0;
548 
549 	if (is_ptr_cast_function(func_id))
550 		ref_obj_uses++;
551 	if (is_acquire_function(func_id, map))
552 		ref_obj_uses++;
553 	if (is_dynptr_ref_function(func_id))
554 		ref_obj_uses++;
555 
556 	return ref_obj_uses > 1;
557 }
558 
559 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
560 {
561 	return BPF_CLASS(insn->code) == BPF_STX &&
562 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
563 	       insn->imm == BPF_CMPXCHG;
564 }
565 
566 /* string representation of 'enum bpf_reg_type'
567  *
568  * Note that reg_type_str() can not appear more than once in a single verbose()
569  * statement.
570  */
571 static const char *reg_type_str(struct bpf_verifier_env *env,
572 				enum bpf_reg_type type)
573 {
574 	char postfix[16] = {0}, prefix[64] = {0};
575 	static const char * const str[] = {
576 		[NOT_INIT]		= "?",
577 		[SCALAR_VALUE]		= "scalar",
578 		[PTR_TO_CTX]		= "ctx",
579 		[CONST_PTR_TO_MAP]	= "map_ptr",
580 		[PTR_TO_MAP_VALUE]	= "map_value",
581 		[PTR_TO_STACK]		= "fp",
582 		[PTR_TO_PACKET]		= "pkt",
583 		[PTR_TO_PACKET_META]	= "pkt_meta",
584 		[PTR_TO_PACKET_END]	= "pkt_end",
585 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
586 		[PTR_TO_SOCKET]		= "sock",
587 		[PTR_TO_SOCK_COMMON]	= "sock_common",
588 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
589 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
590 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
591 		[PTR_TO_BTF_ID]		= "ptr_",
592 		[PTR_TO_MEM]		= "mem",
593 		[PTR_TO_BUF]		= "buf",
594 		[PTR_TO_FUNC]		= "func",
595 		[PTR_TO_MAP_KEY]	= "map_key",
596 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
597 	};
598 
599 	if (type & PTR_MAYBE_NULL) {
600 		if (base_type(type) == PTR_TO_BTF_ID)
601 			strncpy(postfix, "or_null_", 16);
602 		else
603 			strncpy(postfix, "_or_null", 16);
604 	}
605 
606 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
607 		 type & MEM_RDONLY ? "rdonly_" : "",
608 		 type & MEM_RINGBUF ? "ringbuf_" : "",
609 		 type & MEM_USER ? "user_" : "",
610 		 type & MEM_PERCPU ? "percpu_" : "",
611 		 type & MEM_RCU ? "rcu_" : "",
612 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
613 		 type & PTR_TRUSTED ? "trusted_" : ""
614 	);
615 
616 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
617 		 prefix, str[base_type(type)], postfix);
618 	return env->type_str_buf;
619 }
620 
621 static char slot_type_char[] = {
622 	[STACK_INVALID]	= '?',
623 	[STACK_SPILL]	= 'r',
624 	[STACK_MISC]	= 'm',
625 	[STACK_ZERO]	= '0',
626 	[STACK_DYNPTR]	= 'd',
627 };
628 
629 static void print_liveness(struct bpf_verifier_env *env,
630 			   enum bpf_reg_liveness live)
631 {
632 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
633 	    verbose(env, "_");
634 	if (live & REG_LIVE_READ)
635 		verbose(env, "r");
636 	if (live & REG_LIVE_WRITTEN)
637 		verbose(env, "w");
638 	if (live & REG_LIVE_DONE)
639 		verbose(env, "D");
640 }
641 
642 static int __get_spi(s32 off)
643 {
644 	return (-off - 1) / BPF_REG_SIZE;
645 }
646 
647 static struct bpf_func_state *func(struct bpf_verifier_env *env,
648 				   const struct bpf_reg_state *reg)
649 {
650 	struct bpf_verifier_state *cur = env->cur_state;
651 
652 	return cur->frame[reg->frameno];
653 }
654 
655 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
656 {
657        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
658 
659        /* We need to check that slots between [spi - nr_slots + 1, spi] are
660 	* within [0, allocated_stack).
661 	*
662 	* Please note that the spi grows downwards. For example, a dynptr
663 	* takes the size of two stack slots; the first slot will be at
664 	* spi and the second slot will be at spi - 1.
665 	*/
666        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
667 }
668 
669 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
670 {
671 	int off, spi;
672 
673 	if (!tnum_is_const(reg->var_off)) {
674 		verbose(env, "dynptr has to be at a constant offset\n");
675 		return -EINVAL;
676 	}
677 
678 	off = reg->off + reg->var_off.value;
679 	if (off % BPF_REG_SIZE) {
680 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
681 		return -EINVAL;
682 	}
683 
684 	spi = __get_spi(off);
685 	if (spi < 1) {
686 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
687 		return -EINVAL;
688 	}
689 
690 	if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS))
691 		return -ERANGE;
692 	return spi;
693 }
694 
695 static const char *kernel_type_name(const struct btf* btf, u32 id)
696 {
697 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
698 }
699 
700 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
701 {
702 	env->scratched_regs |= 1U << regno;
703 }
704 
705 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
706 {
707 	env->scratched_stack_slots |= 1ULL << spi;
708 }
709 
710 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
711 {
712 	return (env->scratched_regs >> regno) & 1;
713 }
714 
715 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
716 {
717 	return (env->scratched_stack_slots >> regno) & 1;
718 }
719 
720 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
721 {
722 	return env->scratched_regs || env->scratched_stack_slots;
723 }
724 
725 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
726 {
727 	env->scratched_regs = 0U;
728 	env->scratched_stack_slots = 0ULL;
729 }
730 
731 /* Used for printing the entire verifier state. */
732 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
733 {
734 	env->scratched_regs = ~0U;
735 	env->scratched_stack_slots = ~0ULL;
736 }
737 
738 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
739 {
740 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
741 	case DYNPTR_TYPE_LOCAL:
742 		return BPF_DYNPTR_TYPE_LOCAL;
743 	case DYNPTR_TYPE_RINGBUF:
744 		return BPF_DYNPTR_TYPE_RINGBUF;
745 	default:
746 		return BPF_DYNPTR_TYPE_INVALID;
747 	}
748 }
749 
750 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
751 {
752 	return type == BPF_DYNPTR_TYPE_RINGBUF;
753 }
754 
755 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
756 			      enum bpf_dynptr_type type,
757 			      bool first_slot, int dynptr_id);
758 
759 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
760 				struct bpf_reg_state *reg);
761 
762 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
763 				   struct bpf_reg_state *sreg1,
764 				   struct bpf_reg_state *sreg2,
765 				   enum bpf_dynptr_type type)
766 {
767 	int id = ++env->id_gen;
768 
769 	__mark_dynptr_reg(sreg1, type, true, id);
770 	__mark_dynptr_reg(sreg2, type, false, id);
771 }
772 
773 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
774 			       struct bpf_reg_state *reg,
775 			       enum bpf_dynptr_type type)
776 {
777 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
778 }
779 
780 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
781 				        struct bpf_func_state *state, int spi);
782 
783 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
784 				   enum bpf_arg_type arg_type, int insn_idx)
785 {
786 	struct bpf_func_state *state = func(env, reg);
787 	enum bpf_dynptr_type type;
788 	int spi, i, id, err;
789 
790 	spi = dynptr_get_spi(env, reg);
791 	if (spi < 0)
792 		return spi;
793 
794 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
795 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
796 	 * to ensure that for the following example:
797 	 *	[d1][d1][d2][d2]
798 	 * spi    3   2   1   0
799 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
800 	 * case they do belong to same dynptr, second call won't see slot_type
801 	 * as STACK_DYNPTR and will simply skip destruction.
802 	 */
803 	err = destroy_if_dynptr_stack_slot(env, state, spi);
804 	if (err)
805 		return err;
806 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
807 	if (err)
808 		return err;
809 
810 	for (i = 0; i < BPF_REG_SIZE; i++) {
811 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
812 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
813 	}
814 
815 	type = arg_to_dynptr_type(arg_type);
816 	if (type == BPF_DYNPTR_TYPE_INVALID)
817 		return -EINVAL;
818 
819 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
820 			       &state->stack[spi - 1].spilled_ptr, type);
821 
822 	if (dynptr_type_refcounted(type)) {
823 		/* The id is used to track proper releasing */
824 		id = acquire_reference_state(env, insn_idx);
825 		if (id < 0)
826 			return id;
827 
828 		state->stack[spi].spilled_ptr.ref_obj_id = id;
829 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
830 	}
831 
832 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
833 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
834 
835 	return 0;
836 }
837 
838 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
839 {
840 	struct bpf_func_state *state = func(env, reg);
841 	int spi, i;
842 
843 	spi = dynptr_get_spi(env, reg);
844 	if (spi < 0)
845 		return spi;
846 
847 	for (i = 0; i < BPF_REG_SIZE; i++) {
848 		state->stack[spi].slot_type[i] = STACK_INVALID;
849 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
850 	}
851 
852 	/* Invalidate any slices associated with this dynptr */
853 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
854 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
855 
856 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
857 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
858 
859 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
860 	 *
861 	 * While we don't allow reading STACK_INVALID, it is still possible to
862 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
863 	 * helpers or insns can do partial read of that part without failing,
864 	 * but check_stack_range_initialized, check_stack_read_var_off, and
865 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
866 	 * the slot conservatively. Hence we need to prevent those liveness
867 	 * marking walks.
868 	 *
869 	 * This was not a problem before because STACK_INVALID is only set by
870 	 * default (where the default reg state has its reg->parent as NULL), or
871 	 * in clean_live_states after REG_LIVE_DONE (at which point
872 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
873 	 * verifier state exploration (like we did above). Hence, for our case
874 	 * parentage chain will still be live (i.e. reg->parent may be
875 	 * non-NULL), while earlier reg->parent was NULL, so we need
876 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
877 	 * done later on reads or by mark_dynptr_read as well to unnecessary
878 	 * mark registers in verifier state.
879 	 */
880 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
881 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
882 
883 	return 0;
884 }
885 
886 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
887 			       struct bpf_reg_state *reg);
888 
889 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
890 				        struct bpf_func_state *state, int spi)
891 {
892 	struct bpf_func_state *fstate;
893 	struct bpf_reg_state *dreg;
894 	int i, dynptr_id;
895 
896 	/* We always ensure that STACK_DYNPTR is never set partially,
897 	 * hence just checking for slot_type[0] is enough. This is
898 	 * different for STACK_SPILL, where it may be only set for
899 	 * 1 byte, so code has to use is_spilled_reg.
900 	 */
901 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
902 		return 0;
903 
904 	/* Reposition spi to first slot */
905 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
906 		spi = spi + 1;
907 
908 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
909 		verbose(env, "cannot overwrite referenced dynptr\n");
910 		return -EINVAL;
911 	}
912 
913 	mark_stack_slot_scratched(env, spi);
914 	mark_stack_slot_scratched(env, spi - 1);
915 
916 	/* Writing partially to one dynptr stack slot destroys both. */
917 	for (i = 0; i < BPF_REG_SIZE; i++) {
918 		state->stack[spi].slot_type[i] = STACK_INVALID;
919 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
920 	}
921 
922 	dynptr_id = state->stack[spi].spilled_ptr.id;
923 	/* Invalidate any slices associated with this dynptr */
924 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
925 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
926 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
927 			continue;
928 		if (dreg->dynptr_id == dynptr_id) {
929 			if (!env->allow_ptr_leaks)
930 				__mark_reg_not_init(env, dreg);
931 			else
932 				__mark_reg_unknown(env, dreg);
933 		}
934 	}));
935 
936 	/* Do not release reference state, we are destroying dynptr on stack,
937 	 * not using some helper to release it. Just reset register.
938 	 */
939 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
940 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
941 
942 	/* Same reason as unmark_stack_slots_dynptr above */
943 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
944 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
945 
946 	return 0;
947 }
948 
949 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
950 				       int spi)
951 {
952 	if (reg->type == CONST_PTR_TO_DYNPTR)
953 		return false;
954 
955 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
956 	 * will do check_mem_access to check and update stack bounds later, so
957 	 * return true for that case.
958 	 */
959 	if (spi < 0)
960 		return spi == -ERANGE;
961 	/* We allow overwriting existing unreferenced STACK_DYNPTR slots, see
962 	 * mark_stack_slots_dynptr which calls destroy_if_dynptr_stack_slot to
963 	 * ensure dynptr objects at the slots we are touching are completely
964 	 * destructed before we reinitialize them for a new one. For referenced
965 	 * ones, destroy_if_dynptr_stack_slot returns an error early instead of
966 	 * delaying it until the end where the user will get "Unreleased
967 	 * reference" error.
968 	 */
969 	return true;
970 }
971 
972 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
973 				     int spi)
974 {
975 	struct bpf_func_state *state = func(env, reg);
976 	int i;
977 
978 	/* This already represents first slot of initialized bpf_dynptr */
979 	if (reg->type == CONST_PTR_TO_DYNPTR)
980 		return true;
981 
982 	if (spi < 0)
983 		return false;
984 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
985 		return false;
986 
987 	for (i = 0; i < BPF_REG_SIZE; i++) {
988 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
989 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
990 			return false;
991 	}
992 
993 	return true;
994 }
995 
996 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
997 				    enum bpf_arg_type arg_type)
998 {
999 	struct bpf_func_state *state = func(env, reg);
1000 	enum bpf_dynptr_type dynptr_type;
1001 	int spi;
1002 
1003 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1004 	if (arg_type == ARG_PTR_TO_DYNPTR)
1005 		return true;
1006 
1007 	dynptr_type = arg_to_dynptr_type(arg_type);
1008 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1009 		return reg->dynptr.type == dynptr_type;
1010 	} else {
1011 		spi = dynptr_get_spi(env, reg);
1012 		if (spi < 0)
1013 			return false;
1014 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1015 	}
1016 }
1017 
1018 /* The reg state of a pointer or a bounded scalar was saved when
1019  * it was spilled to the stack.
1020  */
1021 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1022 {
1023 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1024 }
1025 
1026 static void scrub_spilled_slot(u8 *stype)
1027 {
1028 	if (*stype != STACK_INVALID)
1029 		*stype = STACK_MISC;
1030 }
1031 
1032 static void print_verifier_state(struct bpf_verifier_env *env,
1033 				 const struct bpf_func_state *state,
1034 				 bool print_all)
1035 {
1036 	const struct bpf_reg_state *reg;
1037 	enum bpf_reg_type t;
1038 	int i;
1039 
1040 	if (state->frameno)
1041 		verbose(env, " frame%d:", state->frameno);
1042 	for (i = 0; i < MAX_BPF_REG; i++) {
1043 		reg = &state->regs[i];
1044 		t = reg->type;
1045 		if (t == NOT_INIT)
1046 			continue;
1047 		if (!print_all && !reg_scratched(env, i))
1048 			continue;
1049 		verbose(env, " R%d", i);
1050 		print_liveness(env, reg->live);
1051 		verbose(env, "=");
1052 		if (t == SCALAR_VALUE && reg->precise)
1053 			verbose(env, "P");
1054 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1055 		    tnum_is_const(reg->var_off)) {
1056 			/* reg->off should be 0 for SCALAR_VALUE */
1057 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1058 			verbose(env, "%lld", reg->var_off.value + reg->off);
1059 		} else {
1060 			const char *sep = "";
1061 
1062 			verbose(env, "%s", reg_type_str(env, t));
1063 			if (base_type(t) == PTR_TO_BTF_ID)
1064 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1065 			verbose(env, "(");
1066 /*
1067  * _a stands for append, was shortened to avoid multiline statements below.
1068  * This macro is used to output a comma separated list of attributes.
1069  */
1070 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1071 
1072 			if (reg->id)
1073 				verbose_a("id=%d", reg->id);
1074 			if (reg->ref_obj_id)
1075 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1076 			if (t != SCALAR_VALUE)
1077 				verbose_a("off=%d", reg->off);
1078 			if (type_is_pkt_pointer(t))
1079 				verbose_a("r=%d", reg->range);
1080 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1081 				 base_type(t) == PTR_TO_MAP_KEY ||
1082 				 base_type(t) == PTR_TO_MAP_VALUE)
1083 				verbose_a("ks=%d,vs=%d",
1084 					  reg->map_ptr->key_size,
1085 					  reg->map_ptr->value_size);
1086 			if (tnum_is_const(reg->var_off)) {
1087 				/* Typically an immediate SCALAR_VALUE, but
1088 				 * could be a pointer whose offset is too big
1089 				 * for reg->off
1090 				 */
1091 				verbose_a("imm=%llx", reg->var_off.value);
1092 			} else {
1093 				if (reg->smin_value != reg->umin_value &&
1094 				    reg->smin_value != S64_MIN)
1095 					verbose_a("smin=%lld", (long long)reg->smin_value);
1096 				if (reg->smax_value != reg->umax_value &&
1097 				    reg->smax_value != S64_MAX)
1098 					verbose_a("smax=%lld", (long long)reg->smax_value);
1099 				if (reg->umin_value != 0)
1100 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1101 				if (reg->umax_value != U64_MAX)
1102 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1103 				if (!tnum_is_unknown(reg->var_off)) {
1104 					char tn_buf[48];
1105 
1106 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1107 					verbose_a("var_off=%s", tn_buf);
1108 				}
1109 				if (reg->s32_min_value != reg->smin_value &&
1110 				    reg->s32_min_value != S32_MIN)
1111 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1112 				if (reg->s32_max_value != reg->smax_value &&
1113 				    reg->s32_max_value != S32_MAX)
1114 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1115 				if (reg->u32_min_value != reg->umin_value &&
1116 				    reg->u32_min_value != U32_MIN)
1117 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1118 				if (reg->u32_max_value != reg->umax_value &&
1119 				    reg->u32_max_value != U32_MAX)
1120 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1121 			}
1122 #undef verbose_a
1123 
1124 			verbose(env, ")");
1125 		}
1126 	}
1127 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1128 		char types_buf[BPF_REG_SIZE + 1];
1129 		bool valid = false;
1130 		int j;
1131 
1132 		for (j = 0; j < BPF_REG_SIZE; j++) {
1133 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1134 				valid = true;
1135 			types_buf[j] = slot_type_char[
1136 					state->stack[i].slot_type[j]];
1137 		}
1138 		types_buf[BPF_REG_SIZE] = 0;
1139 		if (!valid)
1140 			continue;
1141 		if (!print_all && !stack_slot_scratched(env, i))
1142 			continue;
1143 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1144 		print_liveness(env, state->stack[i].spilled_ptr.live);
1145 		if (is_spilled_reg(&state->stack[i])) {
1146 			reg = &state->stack[i].spilled_ptr;
1147 			t = reg->type;
1148 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1149 			if (t == SCALAR_VALUE && reg->precise)
1150 				verbose(env, "P");
1151 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1152 				verbose(env, "%lld", reg->var_off.value + reg->off);
1153 		} else {
1154 			verbose(env, "=%s", types_buf);
1155 		}
1156 	}
1157 	if (state->acquired_refs && state->refs[0].id) {
1158 		verbose(env, " refs=%d", state->refs[0].id);
1159 		for (i = 1; i < state->acquired_refs; i++)
1160 			if (state->refs[i].id)
1161 				verbose(env, ",%d", state->refs[i].id);
1162 	}
1163 	if (state->in_callback_fn)
1164 		verbose(env, " cb");
1165 	if (state->in_async_callback_fn)
1166 		verbose(env, " async_cb");
1167 	verbose(env, "\n");
1168 	mark_verifier_state_clean(env);
1169 }
1170 
1171 static inline u32 vlog_alignment(u32 pos)
1172 {
1173 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1174 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1175 }
1176 
1177 static void print_insn_state(struct bpf_verifier_env *env,
1178 			     const struct bpf_func_state *state)
1179 {
1180 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1181 		/* remove new line character */
1182 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1183 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1184 	} else {
1185 		verbose(env, "%d:", env->insn_idx);
1186 	}
1187 	print_verifier_state(env, state, false);
1188 }
1189 
1190 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1191  * small to hold src. This is different from krealloc since we don't want to preserve
1192  * the contents of dst.
1193  *
1194  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1195  * not be allocated.
1196  */
1197 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1198 {
1199 	size_t alloc_bytes;
1200 	void *orig = dst;
1201 	size_t bytes;
1202 
1203 	if (ZERO_OR_NULL_PTR(src))
1204 		goto out;
1205 
1206 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1207 		return NULL;
1208 
1209 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1210 	dst = krealloc(orig, alloc_bytes, flags);
1211 	if (!dst) {
1212 		kfree(orig);
1213 		return NULL;
1214 	}
1215 
1216 	memcpy(dst, src, bytes);
1217 out:
1218 	return dst ? dst : ZERO_SIZE_PTR;
1219 }
1220 
1221 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1222  * small to hold new_n items. new items are zeroed out if the array grows.
1223  *
1224  * Contrary to krealloc_array, does not free arr if new_n is zero.
1225  */
1226 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1227 {
1228 	size_t alloc_size;
1229 	void *new_arr;
1230 
1231 	if (!new_n || old_n == new_n)
1232 		goto out;
1233 
1234 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1235 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1236 	if (!new_arr) {
1237 		kfree(arr);
1238 		return NULL;
1239 	}
1240 	arr = new_arr;
1241 
1242 	if (new_n > old_n)
1243 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1244 
1245 out:
1246 	return arr ? arr : ZERO_SIZE_PTR;
1247 }
1248 
1249 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1250 {
1251 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1252 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1253 	if (!dst->refs)
1254 		return -ENOMEM;
1255 
1256 	dst->acquired_refs = src->acquired_refs;
1257 	return 0;
1258 }
1259 
1260 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1261 {
1262 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1263 
1264 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1265 				GFP_KERNEL);
1266 	if (!dst->stack)
1267 		return -ENOMEM;
1268 
1269 	dst->allocated_stack = src->allocated_stack;
1270 	return 0;
1271 }
1272 
1273 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1274 {
1275 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1276 				    sizeof(struct bpf_reference_state));
1277 	if (!state->refs)
1278 		return -ENOMEM;
1279 
1280 	state->acquired_refs = n;
1281 	return 0;
1282 }
1283 
1284 static int grow_stack_state(struct bpf_func_state *state, int size)
1285 {
1286 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1287 
1288 	if (old_n >= n)
1289 		return 0;
1290 
1291 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1292 	if (!state->stack)
1293 		return -ENOMEM;
1294 
1295 	state->allocated_stack = size;
1296 	return 0;
1297 }
1298 
1299 /* Acquire a pointer id from the env and update the state->refs to include
1300  * this new pointer reference.
1301  * On success, returns a valid pointer id to associate with the register
1302  * On failure, returns a negative errno.
1303  */
1304 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1305 {
1306 	struct bpf_func_state *state = cur_func(env);
1307 	int new_ofs = state->acquired_refs;
1308 	int id, err;
1309 
1310 	err = resize_reference_state(state, state->acquired_refs + 1);
1311 	if (err)
1312 		return err;
1313 	id = ++env->id_gen;
1314 	state->refs[new_ofs].id = id;
1315 	state->refs[new_ofs].insn_idx = insn_idx;
1316 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1317 
1318 	return id;
1319 }
1320 
1321 /* release function corresponding to acquire_reference_state(). Idempotent. */
1322 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1323 {
1324 	int i, last_idx;
1325 
1326 	last_idx = state->acquired_refs - 1;
1327 	for (i = 0; i < state->acquired_refs; i++) {
1328 		if (state->refs[i].id == ptr_id) {
1329 			/* Cannot release caller references in callbacks */
1330 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1331 				return -EINVAL;
1332 			if (last_idx && i != last_idx)
1333 				memcpy(&state->refs[i], &state->refs[last_idx],
1334 				       sizeof(*state->refs));
1335 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1336 			state->acquired_refs--;
1337 			return 0;
1338 		}
1339 	}
1340 	return -EINVAL;
1341 }
1342 
1343 static void free_func_state(struct bpf_func_state *state)
1344 {
1345 	if (!state)
1346 		return;
1347 	kfree(state->refs);
1348 	kfree(state->stack);
1349 	kfree(state);
1350 }
1351 
1352 static void clear_jmp_history(struct bpf_verifier_state *state)
1353 {
1354 	kfree(state->jmp_history);
1355 	state->jmp_history = NULL;
1356 	state->jmp_history_cnt = 0;
1357 }
1358 
1359 static void free_verifier_state(struct bpf_verifier_state *state,
1360 				bool free_self)
1361 {
1362 	int i;
1363 
1364 	for (i = 0; i <= state->curframe; i++) {
1365 		free_func_state(state->frame[i]);
1366 		state->frame[i] = NULL;
1367 	}
1368 	clear_jmp_history(state);
1369 	if (free_self)
1370 		kfree(state);
1371 }
1372 
1373 /* copy verifier state from src to dst growing dst stack space
1374  * when necessary to accommodate larger src stack
1375  */
1376 static int copy_func_state(struct bpf_func_state *dst,
1377 			   const struct bpf_func_state *src)
1378 {
1379 	int err;
1380 
1381 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1382 	err = copy_reference_state(dst, src);
1383 	if (err)
1384 		return err;
1385 	return copy_stack_state(dst, src);
1386 }
1387 
1388 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1389 			       const struct bpf_verifier_state *src)
1390 {
1391 	struct bpf_func_state *dst;
1392 	int i, err;
1393 
1394 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1395 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1396 					    GFP_USER);
1397 	if (!dst_state->jmp_history)
1398 		return -ENOMEM;
1399 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1400 
1401 	/* if dst has more stack frames then src frame, free them */
1402 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1403 		free_func_state(dst_state->frame[i]);
1404 		dst_state->frame[i] = NULL;
1405 	}
1406 	dst_state->speculative = src->speculative;
1407 	dst_state->active_rcu_lock = src->active_rcu_lock;
1408 	dst_state->curframe = src->curframe;
1409 	dst_state->active_lock.ptr = src->active_lock.ptr;
1410 	dst_state->active_lock.id = src->active_lock.id;
1411 	dst_state->branches = src->branches;
1412 	dst_state->parent = src->parent;
1413 	dst_state->first_insn_idx = src->first_insn_idx;
1414 	dst_state->last_insn_idx = src->last_insn_idx;
1415 	for (i = 0; i <= src->curframe; i++) {
1416 		dst = dst_state->frame[i];
1417 		if (!dst) {
1418 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1419 			if (!dst)
1420 				return -ENOMEM;
1421 			dst_state->frame[i] = dst;
1422 		}
1423 		err = copy_func_state(dst, src->frame[i]);
1424 		if (err)
1425 			return err;
1426 	}
1427 	return 0;
1428 }
1429 
1430 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1431 {
1432 	while (st) {
1433 		u32 br = --st->branches;
1434 
1435 		/* WARN_ON(br > 1) technically makes sense here,
1436 		 * but see comment in push_stack(), hence:
1437 		 */
1438 		WARN_ONCE((int)br < 0,
1439 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1440 			  br);
1441 		if (br)
1442 			break;
1443 		st = st->parent;
1444 	}
1445 }
1446 
1447 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1448 		     int *insn_idx, bool pop_log)
1449 {
1450 	struct bpf_verifier_state *cur = env->cur_state;
1451 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1452 	int err;
1453 
1454 	if (env->head == NULL)
1455 		return -ENOENT;
1456 
1457 	if (cur) {
1458 		err = copy_verifier_state(cur, &head->st);
1459 		if (err)
1460 			return err;
1461 	}
1462 	if (pop_log)
1463 		bpf_vlog_reset(&env->log, head->log_pos);
1464 	if (insn_idx)
1465 		*insn_idx = head->insn_idx;
1466 	if (prev_insn_idx)
1467 		*prev_insn_idx = head->prev_insn_idx;
1468 	elem = head->next;
1469 	free_verifier_state(&head->st, false);
1470 	kfree(head);
1471 	env->head = elem;
1472 	env->stack_size--;
1473 	return 0;
1474 }
1475 
1476 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1477 					     int insn_idx, int prev_insn_idx,
1478 					     bool speculative)
1479 {
1480 	struct bpf_verifier_state *cur = env->cur_state;
1481 	struct bpf_verifier_stack_elem *elem;
1482 	int err;
1483 
1484 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1485 	if (!elem)
1486 		goto err;
1487 
1488 	elem->insn_idx = insn_idx;
1489 	elem->prev_insn_idx = prev_insn_idx;
1490 	elem->next = env->head;
1491 	elem->log_pos = env->log.len_used;
1492 	env->head = elem;
1493 	env->stack_size++;
1494 	err = copy_verifier_state(&elem->st, cur);
1495 	if (err)
1496 		goto err;
1497 	elem->st.speculative |= speculative;
1498 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1499 		verbose(env, "The sequence of %d jumps is too complex.\n",
1500 			env->stack_size);
1501 		goto err;
1502 	}
1503 	if (elem->st.parent) {
1504 		++elem->st.parent->branches;
1505 		/* WARN_ON(branches > 2) technically makes sense here,
1506 		 * but
1507 		 * 1. speculative states will bump 'branches' for non-branch
1508 		 * instructions
1509 		 * 2. is_state_visited() heuristics may decide not to create
1510 		 * a new state for a sequence of branches and all such current
1511 		 * and cloned states will be pointing to a single parent state
1512 		 * which might have large 'branches' count.
1513 		 */
1514 	}
1515 	return &elem->st;
1516 err:
1517 	free_verifier_state(env->cur_state, true);
1518 	env->cur_state = NULL;
1519 	/* pop all elements and return */
1520 	while (!pop_stack(env, NULL, NULL, false));
1521 	return NULL;
1522 }
1523 
1524 #define CALLER_SAVED_REGS 6
1525 static const int caller_saved[CALLER_SAVED_REGS] = {
1526 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1527 };
1528 
1529 /* This helper doesn't clear reg->id */
1530 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1531 {
1532 	reg->var_off = tnum_const(imm);
1533 	reg->smin_value = (s64)imm;
1534 	reg->smax_value = (s64)imm;
1535 	reg->umin_value = imm;
1536 	reg->umax_value = imm;
1537 
1538 	reg->s32_min_value = (s32)imm;
1539 	reg->s32_max_value = (s32)imm;
1540 	reg->u32_min_value = (u32)imm;
1541 	reg->u32_max_value = (u32)imm;
1542 }
1543 
1544 /* Mark the unknown part of a register (variable offset or scalar value) as
1545  * known to have the value @imm.
1546  */
1547 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1548 {
1549 	/* Clear off and union(map_ptr, range) */
1550 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1551 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1552 	reg->id = 0;
1553 	reg->ref_obj_id = 0;
1554 	___mark_reg_known(reg, imm);
1555 }
1556 
1557 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1558 {
1559 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1560 	reg->s32_min_value = (s32)imm;
1561 	reg->s32_max_value = (s32)imm;
1562 	reg->u32_min_value = (u32)imm;
1563 	reg->u32_max_value = (u32)imm;
1564 }
1565 
1566 /* Mark the 'variable offset' part of a register as zero.  This should be
1567  * used only on registers holding a pointer type.
1568  */
1569 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1570 {
1571 	__mark_reg_known(reg, 0);
1572 }
1573 
1574 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1575 {
1576 	__mark_reg_known(reg, 0);
1577 	reg->type = SCALAR_VALUE;
1578 }
1579 
1580 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1581 				struct bpf_reg_state *regs, u32 regno)
1582 {
1583 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1584 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1585 		/* Something bad happened, let's kill all regs */
1586 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1587 			__mark_reg_not_init(env, regs + regno);
1588 		return;
1589 	}
1590 	__mark_reg_known_zero(regs + regno);
1591 }
1592 
1593 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1594 			      bool first_slot, int dynptr_id)
1595 {
1596 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1597 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1598 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1599 	 */
1600 	__mark_reg_known_zero(reg);
1601 	reg->type = CONST_PTR_TO_DYNPTR;
1602 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1603 	reg->id = dynptr_id;
1604 	reg->dynptr.type = type;
1605 	reg->dynptr.first_slot = first_slot;
1606 }
1607 
1608 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1609 {
1610 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1611 		const struct bpf_map *map = reg->map_ptr;
1612 
1613 		if (map->inner_map_meta) {
1614 			reg->type = CONST_PTR_TO_MAP;
1615 			reg->map_ptr = map->inner_map_meta;
1616 			/* transfer reg's id which is unique for every map_lookup_elem
1617 			 * as UID of the inner map.
1618 			 */
1619 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1620 				reg->map_uid = reg->id;
1621 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1622 			reg->type = PTR_TO_XDP_SOCK;
1623 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1624 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1625 			reg->type = PTR_TO_SOCKET;
1626 		} else {
1627 			reg->type = PTR_TO_MAP_VALUE;
1628 		}
1629 		return;
1630 	}
1631 
1632 	reg->type &= ~PTR_MAYBE_NULL;
1633 }
1634 
1635 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1636 {
1637 	return type_is_pkt_pointer(reg->type);
1638 }
1639 
1640 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1641 {
1642 	return reg_is_pkt_pointer(reg) ||
1643 	       reg->type == PTR_TO_PACKET_END;
1644 }
1645 
1646 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1647 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1648 				    enum bpf_reg_type which)
1649 {
1650 	/* The register can already have a range from prior markings.
1651 	 * This is fine as long as it hasn't been advanced from its
1652 	 * origin.
1653 	 */
1654 	return reg->type == which &&
1655 	       reg->id == 0 &&
1656 	       reg->off == 0 &&
1657 	       tnum_equals_const(reg->var_off, 0);
1658 }
1659 
1660 /* Reset the min/max bounds of a register */
1661 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1662 {
1663 	reg->smin_value = S64_MIN;
1664 	reg->smax_value = S64_MAX;
1665 	reg->umin_value = 0;
1666 	reg->umax_value = U64_MAX;
1667 
1668 	reg->s32_min_value = S32_MIN;
1669 	reg->s32_max_value = S32_MAX;
1670 	reg->u32_min_value = 0;
1671 	reg->u32_max_value = U32_MAX;
1672 }
1673 
1674 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1675 {
1676 	reg->smin_value = S64_MIN;
1677 	reg->smax_value = S64_MAX;
1678 	reg->umin_value = 0;
1679 	reg->umax_value = U64_MAX;
1680 }
1681 
1682 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1683 {
1684 	reg->s32_min_value = S32_MIN;
1685 	reg->s32_max_value = S32_MAX;
1686 	reg->u32_min_value = 0;
1687 	reg->u32_max_value = U32_MAX;
1688 }
1689 
1690 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1691 {
1692 	struct tnum var32_off = tnum_subreg(reg->var_off);
1693 
1694 	/* min signed is max(sign bit) | min(other bits) */
1695 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1696 			var32_off.value | (var32_off.mask & S32_MIN));
1697 	/* max signed is min(sign bit) | max(other bits) */
1698 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1699 			var32_off.value | (var32_off.mask & S32_MAX));
1700 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1701 	reg->u32_max_value = min(reg->u32_max_value,
1702 				 (u32)(var32_off.value | var32_off.mask));
1703 }
1704 
1705 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1706 {
1707 	/* min signed is max(sign bit) | min(other bits) */
1708 	reg->smin_value = max_t(s64, reg->smin_value,
1709 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1710 	/* max signed is min(sign bit) | max(other bits) */
1711 	reg->smax_value = min_t(s64, reg->smax_value,
1712 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1713 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1714 	reg->umax_value = min(reg->umax_value,
1715 			      reg->var_off.value | reg->var_off.mask);
1716 }
1717 
1718 static void __update_reg_bounds(struct bpf_reg_state *reg)
1719 {
1720 	__update_reg32_bounds(reg);
1721 	__update_reg64_bounds(reg);
1722 }
1723 
1724 /* Uses signed min/max values to inform unsigned, and vice-versa */
1725 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1726 {
1727 	/* Learn sign from signed bounds.
1728 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1729 	 * are the same, so combine.  This works even in the negative case, e.g.
1730 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1731 	 */
1732 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1733 		reg->s32_min_value = reg->u32_min_value =
1734 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1735 		reg->s32_max_value = reg->u32_max_value =
1736 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1737 		return;
1738 	}
1739 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1740 	 * boundary, so we must be careful.
1741 	 */
1742 	if ((s32)reg->u32_max_value >= 0) {
1743 		/* Positive.  We can't learn anything from the smin, but smax
1744 		 * is positive, hence safe.
1745 		 */
1746 		reg->s32_min_value = reg->u32_min_value;
1747 		reg->s32_max_value = reg->u32_max_value =
1748 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1749 	} else if ((s32)reg->u32_min_value < 0) {
1750 		/* Negative.  We can't learn anything from the smax, but smin
1751 		 * is negative, hence safe.
1752 		 */
1753 		reg->s32_min_value = reg->u32_min_value =
1754 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1755 		reg->s32_max_value = reg->u32_max_value;
1756 	}
1757 }
1758 
1759 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1760 {
1761 	/* Learn sign from signed bounds.
1762 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1763 	 * are the same, so combine.  This works even in the negative case, e.g.
1764 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1765 	 */
1766 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1767 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1768 							  reg->umin_value);
1769 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1770 							  reg->umax_value);
1771 		return;
1772 	}
1773 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1774 	 * boundary, so we must be careful.
1775 	 */
1776 	if ((s64)reg->umax_value >= 0) {
1777 		/* Positive.  We can't learn anything from the smin, but smax
1778 		 * is positive, hence safe.
1779 		 */
1780 		reg->smin_value = reg->umin_value;
1781 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1782 							  reg->umax_value);
1783 	} else if ((s64)reg->umin_value < 0) {
1784 		/* Negative.  We can't learn anything from the smax, but smin
1785 		 * is negative, hence safe.
1786 		 */
1787 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1788 							  reg->umin_value);
1789 		reg->smax_value = reg->umax_value;
1790 	}
1791 }
1792 
1793 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1794 {
1795 	__reg32_deduce_bounds(reg);
1796 	__reg64_deduce_bounds(reg);
1797 }
1798 
1799 /* Attempts to improve var_off based on unsigned min/max information */
1800 static void __reg_bound_offset(struct bpf_reg_state *reg)
1801 {
1802 	struct tnum var64_off = tnum_intersect(reg->var_off,
1803 					       tnum_range(reg->umin_value,
1804 							  reg->umax_value));
1805 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1806 						tnum_range(reg->u32_min_value,
1807 							   reg->u32_max_value));
1808 
1809 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1810 }
1811 
1812 static void reg_bounds_sync(struct bpf_reg_state *reg)
1813 {
1814 	/* We might have learned new bounds from the var_off. */
1815 	__update_reg_bounds(reg);
1816 	/* We might have learned something about the sign bit. */
1817 	__reg_deduce_bounds(reg);
1818 	/* We might have learned some bits from the bounds. */
1819 	__reg_bound_offset(reg);
1820 	/* Intersecting with the old var_off might have improved our bounds
1821 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1822 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1823 	 */
1824 	__update_reg_bounds(reg);
1825 }
1826 
1827 static bool __reg32_bound_s64(s32 a)
1828 {
1829 	return a >= 0 && a <= S32_MAX;
1830 }
1831 
1832 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1833 {
1834 	reg->umin_value = reg->u32_min_value;
1835 	reg->umax_value = reg->u32_max_value;
1836 
1837 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1838 	 * be positive otherwise set to worse case bounds and refine later
1839 	 * from tnum.
1840 	 */
1841 	if (__reg32_bound_s64(reg->s32_min_value) &&
1842 	    __reg32_bound_s64(reg->s32_max_value)) {
1843 		reg->smin_value = reg->s32_min_value;
1844 		reg->smax_value = reg->s32_max_value;
1845 	} else {
1846 		reg->smin_value = 0;
1847 		reg->smax_value = U32_MAX;
1848 	}
1849 }
1850 
1851 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1852 {
1853 	/* special case when 64-bit register has upper 32-bit register
1854 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1855 	 * allowing us to use 32-bit bounds directly,
1856 	 */
1857 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1858 		__reg_assign_32_into_64(reg);
1859 	} else {
1860 		/* Otherwise the best we can do is push lower 32bit known and
1861 		 * unknown bits into register (var_off set from jmp logic)
1862 		 * then learn as much as possible from the 64-bit tnum
1863 		 * known and unknown bits. The previous smin/smax bounds are
1864 		 * invalid here because of jmp32 compare so mark them unknown
1865 		 * so they do not impact tnum bounds calculation.
1866 		 */
1867 		__mark_reg64_unbounded(reg);
1868 	}
1869 	reg_bounds_sync(reg);
1870 }
1871 
1872 static bool __reg64_bound_s32(s64 a)
1873 {
1874 	return a >= S32_MIN && a <= S32_MAX;
1875 }
1876 
1877 static bool __reg64_bound_u32(u64 a)
1878 {
1879 	return a >= U32_MIN && a <= U32_MAX;
1880 }
1881 
1882 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1883 {
1884 	__mark_reg32_unbounded(reg);
1885 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1886 		reg->s32_min_value = (s32)reg->smin_value;
1887 		reg->s32_max_value = (s32)reg->smax_value;
1888 	}
1889 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1890 		reg->u32_min_value = (u32)reg->umin_value;
1891 		reg->u32_max_value = (u32)reg->umax_value;
1892 	}
1893 	reg_bounds_sync(reg);
1894 }
1895 
1896 /* Mark a register as having a completely unknown (scalar) value. */
1897 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1898 			       struct bpf_reg_state *reg)
1899 {
1900 	/*
1901 	 * Clear type, off, and union(map_ptr, range) and
1902 	 * padding between 'type' and union
1903 	 */
1904 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1905 	reg->type = SCALAR_VALUE;
1906 	reg->id = 0;
1907 	reg->ref_obj_id = 0;
1908 	reg->var_off = tnum_unknown;
1909 	reg->frameno = 0;
1910 	reg->precise = !env->bpf_capable;
1911 	__mark_reg_unbounded(reg);
1912 }
1913 
1914 static void mark_reg_unknown(struct bpf_verifier_env *env,
1915 			     struct bpf_reg_state *regs, u32 regno)
1916 {
1917 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1918 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1919 		/* Something bad happened, let's kill all regs except FP */
1920 		for (regno = 0; regno < BPF_REG_FP; regno++)
1921 			__mark_reg_not_init(env, regs + regno);
1922 		return;
1923 	}
1924 	__mark_reg_unknown(env, regs + regno);
1925 }
1926 
1927 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1928 				struct bpf_reg_state *reg)
1929 {
1930 	__mark_reg_unknown(env, reg);
1931 	reg->type = NOT_INIT;
1932 }
1933 
1934 static void mark_reg_not_init(struct bpf_verifier_env *env,
1935 			      struct bpf_reg_state *regs, u32 regno)
1936 {
1937 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1938 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1939 		/* Something bad happened, let's kill all regs except FP */
1940 		for (regno = 0; regno < BPF_REG_FP; regno++)
1941 			__mark_reg_not_init(env, regs + regno);
1942 		return;
1943 	}
1944 	__mark_reg_not_init(env, regs + regno);
1945 }
1946 
1947 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1948 			    struct bpf_reg_state *regs, u32 regno,
1949 			    enum bpf_reg_type reg_type,
1950 			    struct btf *btf, u32 btf_id,
1951 			    enum bpf_type_flag flag)
1952 {
1953 	if (reg_type == SCALAR_VALUE) {
1954 		mark_reg_unknown(env, regs, regno);
1955 		return;
1956 	}
1957 	mark_reg_known_zero(env, regs, regno);
1958 	regs[regno].type = PTR_TO_BTF_ID | flag;
1959 	regs[regno].btf = btf;
1960 	regs[regno].btf_id = btf_id;
1961 }
1962 
1963 #define DEF_NOT_SUBREG	(0)
1964 static void init_reg_state(struct bpf_verifier_env *env,
1965 			   struct bpf_func_state *state)
1966 {
1967 	struct bpf_reg_state *regs = state->regs;
1968 	int i;
1969 
1970 	for (i = 0; i < MAX_BPF_REG; i++) {
1971 		mark_reg_not_init(env, regs, i);
1972 		regs[i].live = REG_LIVE_NONE;
1973 		regs[i].parent = NULL;
1974 		regs[i].subreg_def = DEF_NOT_SUBREG;
1975 	}
1976 
1977 	/* frame pointer */
1978 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1979 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1980 	regs[BPF_REG_FP].frameno = state->frameno;
1981 }
1982 
1983 #define BPF_MAIN_FUNC (-1)
1984 static void init_func_state(struct bpf_verifier_env *env,
1985 			    struct bpf_func_state *state,
1986 			    int callsite, int frameno, int subprogno)
1987 {
1988 	state->callsite = callsite;
1989 	state->frameno = frameno;
1990 	state->subprogno = subprogno;
1991 	state->callback_ret_range = tnum_range(0, 0);
1992 	init_reg_state(env, state);
1993 	mark_verifier_state_scratched(env);
1994 }
1995 
1996 /* Similar to push_stack(), but for async callbacks */
1997 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1998 						int insn_idx, int prev_insn_idx,
1999 						int subprog)
2000 {
2001 	struct bpf_verifier_stack_elem *elem;
2002 	struct bpf_func_state *frame;
2003 
2004 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2005 	if (!elem)
2006 		goto err;
2007 
2008 	elem->insn_idx = insn_idx;
2009 	elem->prev_insn_idx = prev_insn_idx;
2010 	elem->next = env->head;
2011 	elem->log_pos = env->log.len_used;
2012 	env->head = elem;
2013 	env->stack_size++;
2014 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2015 		verbose(env,
2016 			"The sequence of %d jumps is too complex for async cb.\n",
2017 			env->stack_size);
2018 		goto err;
2019 	}
2020 	/* Unlike push_stack() do not copy_verifier_state().
2021 	 * The caller state doesn't matter.
2022 	 * This is async callback. It starts in a fresh stack.
2023 	 * Initialize it similar to do_check_common().
2024 	 */
2025 	elem->st.branches = 1;
2026 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2027 	if (!frame)
2028 		goto err;
2029 	init_func_state(env, frame,
2030 			BPF_MAIN_FUNC /* callsite */,
2031 			0 /* frameno within this callchain */,
2032 			subprog /* subprog number within this prog */);
2033 	elem->st.frame[0] = frame;
2034 	return &elem->st;
2035 err:
2036 	free_verifier_state(env->cur_state, true);
2037 	env->cur_state = NULL;
2038 	/* pop all elements and return */
2039 	while (!pop_stack(env, NULL, NULL, false));
2040 	return NULL;
2041 }
2042 
2043 
2044 enum reg_arg_type {
2045 	SRC_OP,		/* register is used as source operand */
2046 	DST_OP,		/* register is used as destination operand */
2047 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2048 };
2049 
2050 static int cmp_subprogs(const void *a, const void *b)
2051 {
2052 	return ((struct bpf_subprog_info *)a)->start -
2053 	       ((struct bpf_subprog_info *)b)->start;
2054 }
2055 
2056 static int find_subprog(struct bpf_verifier_env *env, int off)
2057 {
2058 	struct bpf_subprog_info *p;
2059 
2060 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2061 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2062 	if (!p)
2063 		return -ENOENT;
2064 	return p - env->subprog_info;
2065 
2066 }
2067 
2068 static int add_subprog(struct bpf_verifier_env *env, int off)
2069 {
2070 	int insn_cnt = env->prog->len;
2071 	int ret;
2072 
2073 	if (off >= insn_cnt || off < 0) {
2074 		verbose(env, "call to invalid destination\n");
2075 		return -EINVAL;
2076 	}
2077 	ret = find_subprog(env, off);
2078 	if (ret >= 0)
2079 		return ret;
2080 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2081 		verbose(env, "too many subprograms\n");
2082 		return -E2BIG;
2083 	}
2084 	/* determine subprog starts. The end is one before the next starts */
2085 	env->subprog_info[env->subprog_cnt++].start = off;
2086 	sort(env->subprog_info, env->subprog_cnt,
2087 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2088 	return env->subprog_cnt - 1;
2089 }
2090 
2091 #define MAX_KFUNC_DESCS 256
2092 #define MAX_KFUNC_BTFS	256
2093 
2094 struct bpf_kfunc_desc {
2095 	struct btf_func_model func_model;
2096 	u32 func_id;
2097 	s32 imm;
2098 	u16 offset;
2099 };
2100 
2101 struct bpf_kfunc_btf {
2102 	struct btf *btf;
2103 	struct module *module;
2104 	u16 offset;
2105 };
2106 
2107 struct bpf_kfunc_desc_tab {
2108 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2109 	u32 nr_descs;
2110 };
2111 
2112 struct bpf_kfunc_btf_tab {
2113 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2114 	u32 nr_descs;
2115 };
2116 
2117 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2118 {
2119 	const struct bpf_kfunc_desc *d0 = a;
2120 	const struct bpf_kfunc_desc *d1 = b;
2121 
2122 	/* func_id is not greater than BTF_MAX_TYPE */
2123 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2124 }
2125 
2126 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2127 {
2128 	const struct bpf_kfunc_btf *d0 = a;
2129 	const struct bpf_kfunc_btf *d1 = b;
2130 
2131 	return d0->offset - d1->offset;
2132 }
2133 
2134 static const struct bpf_kfunc_desc *
2135 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2136 {
2137 	struct bpf_kfunc_desc desc = {
2138 		.func_id = func_id,
2139 		.offset = offset,
2140 	};
2141 	struct bpf_kfunc_desc_tab *tab;
2142 
2143 	tab = prog->aux->kfunc_tab;
2144 	return bsearch(&desc, tab->descs, tab->nr_descs,
2145 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2146 }
2147 
2148 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2149 					 s16 offset)
2150 {
2151 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2152 	struct bpf_kfunc_btf_tab *tab;
2153 	struct bpf_kfunc_btf *b;
2154 	struct module *mod;
2155 	struct btf *btf;
2156 	int btf_fd;
2157 
2158 	tab = env->prog->aux->kfunc_btf_tab;
2159 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2160 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2161 	if (!b) {
2162 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2163 			verbose(env, "too many different module BTFs\n");
2164 			return ERR_PTR(-E2BIG);
2165 		}
2166 
2167 		if (bpfptr_is_null(env->fd_array)) {
2168 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2169 			return ERR_PTR(-EPROTO);
2170 		}
2171 
2172 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2173 					    offset * sizeof(btf_fd),
2174 					    sizeof(btf_fd)))
2175 			return ERR_PTR(-EFAULT);
2176 
2177 		btf = btf_get_by_fd(btf_fd);
2178 		if (IS_ERR(btf)) {
2179 			verbose(env, "invalid module BTF fd specified\n");
2180 			return btf;
2181 		}
2182 
2183 		if (!btf_is_module(btf)) {
2184 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2185 			btf_put(btf);
2186 			return ERR_PTR(-EINVAL);
2187 		}
2188 
2189 		mod = btf_try_get_module(btf);
2190 		if (!mod) {
2191 			btf_put(btf);
2192 			return ERR_PTR(-ENXIO);
2193 		}
2194 
2195 		b = &tab->descs[tab->nr_descs++];
2196 		b->btf = btf;
2197 		b->module = mod;
2198 		b->offset = offset;
2199 
2200 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2201 		     kfunc_btf_cmp_by_off, NULL);
2202 	}
2203 	return b->btf;
2204 }
2205 
2206 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2207 {
2208 	if (!tab)
2209 		return;
2210 
2211 	while (tab->nr_descs--) {
2212 		module_put(tab->descs[tab->nr_descs].module);
2213 		btf_put(tab->descs[tab->nr_descs].btf);
2214 	}
2215 	kfree(tab);
2216 }
2217 
2218 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2219 {
2220 	if (offset) {
2221 		if (offset < 0) {
2222 			/* In the future, this can be allowed to increase limit
2223 			 * of fd index into fd_array, interpreted as u16.
2224 			 */
2225 			verbose(env, "negative offset disallowed for kernel module function call\n");
2226 			return ERR_PTR(-EINVAL);
2227 		}
2228 
2229 		return __find_kfunc_desc_btf(env, offset);
2230 	}
2231 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2232 }
2233 
2234 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2235 {
2236 	const struct btf_type *func, *func_proto;
2237 	struct bpf_kfunc_btf_tab *btf_tab;
2238 	struct bpf_kfunc_desc_tab *tab;
2239 	struct bpf_prog_aux *prog_aux;
2240 	struct bpf_kfunc_desc *desc;
2241 	const char *func_name;
2242 	struct btf *desc_btf;
2243 	unsigned long call_imm;
2244 	unsigned long addr;
2245 	int err;
2246 
2247 	prog_aux = env->prog->aux;
2248 	tab = prog_aux->kfunc_tab;
2249 	btf_tab = prog_aux->kfunc_btf_tab;
2250 	if (!tab) {
2251 		if (!btf_vmlinux) {
2252 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2253 			return -ENOTSUPP;
2254 		}
2255 
2256 		if (!env->prog->jit_requested) {
2257 			verbose(env, "JIT is required for calling kernel function\n");
2258 			return -ENOTSUPP;
2259 		}
2260 
2261 		if (!bpf_jit_supports_kfunc_call()) {
2262 			verbose(env, "JIT does not support calling kernel function\n");
2263 			return -ENOTSUPP;
2264 		}
2265 
2266 		if (!env->prog->gpl_compatible) {
2267 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2268 			return -EINVAL;
2269 		}
2270 
2271 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2272 		if (!tab)
2273 			return -ENOMEM;
2274 		prog_aux->kfunc_tab = tab;
2275 	}
2276 
2277 	/* func_id == 0 is always invalid, but instead of returning an error, be
2278 	 * conservative and wait until the code elimination pass before returning
2279 	 * error, so that invalid calls that get pruned out can be in BPF programs
2280 	 * loaded from userspace.  It is also required that offset be untouched
2281 	 * for such calls.
2282 	 */
2283 	if (!func_id && !offset)
2284 		return 0;
2285 
2286 	if (!btf_tab && offset) {
2287 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2288 		if (!btf_tab)
2289 			return -ENOMEM;
2290 		prog_aux->kfunc_btf_tab = btf_tab;
2291 	}
2292 
2293 	desc_btf = find_kfunc_desc_btf(env, offset);
2294 	if (IS_ERR(desc_btf)) {
2295 		verbose(env, "failed to find BTF for kernel function\n");
2296 		return PTR_ERR(desc_btf);
2297 	}
2298 
2299 	if (find_kfunc_desc(env->prog, func_id, offset))
2300 		return 0;
2301 
2302 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2303 		verbose(env, "too many different kernel function calls\n");
2304 		return -E2BIG;
2305 	}
2306 
2307 	func = btf_type_by_id(desc_btf, func_id);
2308 	if (!func || !btf_type_is_func(func)) {
2309 		verbose(env, "kernel btf_id %u is not a function\n",
2310 			func_id);
2311 		return -EINVAL;
2312 	}
2313 	func_proto = btf_type_by_id(desc_btf, func->type);
2314 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2315 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2316 			func_id);
2317 		return -EINVAL;
2318 	}
2319 
2320 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2321 	addr = kallsyms_lookup_name(func_name);
2322 	if (!addr) {
2323 		verbose(env, "cannot find address for kernel function %s\n",
2324 			func_name);
2325 		return -EINVAL;
2326 	}
2327 
2328 	call_imm = BPF_CALL_IMM(addr);
2329 	/* Check whether or not the relative offset overflows desc->imm */
2330 	if ((unsigned long)(s32)call_imm != call_imm) {
2331 		verbose(env, "address of kernel function %s is out of range\n",
2332 			func_name);
2333 		return -EINVAL;
2334 	}
2335 
2336 	if (bpf_dev_bound_kfunc_id(func_id)) {
2337 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2338 		if (err)
2339 			return err;
2340 	}
2341 
2342 	desc = &tab->descs[tab->nr_descs++];
2343 	desc->func_id = func_id;
2344 	desc->imm = call_imm;
2345 	desc->offset = offset;
2346 	err = btf_distill_func_proto(&env->log, desc_btf,
2347 				     func_proto, func_name,
2348 				     &desc->func_model);
2349 	if (!err)
2350 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2351 		     kfunc_desc_cmp_by_id_off, NULL);
2352 	return err;
2353 }
2354 
2355 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2356 {
2357 	const struct bpf_kfunc_desc *d0 = a;
2358 	const struct bpf_kfunc_desc *d1 = b;
2359 
2360 	if (d0->imm > d1->imm)
2361 		return 1;
2362 	else if (d0->imm < d1->imm)
2363 		return -1;
2364 	return 0;
2365 }
2366 
2367 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2368 {
2369 	struct bpf_kfunc_desc_tab *tab;
2370 
2371 	tab = prog->aux->kfunc_tab;
2372 	if (!tab)
2373 		return;
2374 
2375 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2376 	     kfunc_desc_cmp_by_imm, NULL);
2377 }
2378 
2379 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2380 {
2381 	return !!prog->aux->kfunc_tab;
2382 }
2383 
2384 const struct btf_func_model *
2385 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2386 			 const struct bpf_insn *insn)
2387 {
2388 	const struct bpf_kfunc_desc desc = {
2389 		.imm = insn->imm,
2390 	};
2391 	const struct bpf_kfunc_desc *res;
2392 	struct bpf_kfunc_desc_tab *tab;
2393 
2394 	tab = prog->aux->kfunc_tab;
2395 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2396 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2397 
2398 	return res ? &res->func_model : NULL;
2399 }
2400 
2401 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2402 {
2403 	struct bpf_subprog_info *subprog = env->subprog_info;
2404 	struct bpf_insn *insn = env->prog->insnsi;
2405 	int i, ret, insn_cnt = env->prog->len;
2406 
2407 	/* Add entry function. */
2408 	ret = add_subprog(env, 0);
2409 	if (ret)
2410 		return ret;
2411 
2412 	for (i = 0; i < insn_cnt; i++, insn++) {
2413 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2414 		    !bpf_pseudo_kfunc_call(insn))
2415 			continue;
2416 
2417 		if (!env->bpf_capable) {
2418 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2419 			return -EPERM;
2420 		}
2421 
2422 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2423 			ret = add_subprog(env, i + insn->imm + 1);
2424 		else
2425 			ret = add_kfunc_call(env, insn->imm, insn->off);
2426 
2427 		if (ret < 0)
2428 			return ret;
2429 	}
2430 
2431 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2432 	 * logic. 'subprog_cnt' should not be increased.
2433 	 */
2434 	subprog[env->subprog_cnt].start = insn_cnt;
2435 
2436 	if (env->log.level & BPF_LOG_LEVEL2)
2437 		for (i = 0; i < env->subprog_cnt; i++)
2438 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2439 
2440 	return 0;
2441 }
2442 
2443 static int check_subprogs(struct bpf_verifier_env *env)
2444 {
2445 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2446 	struct bpf_subprog_info *subprog = env->subprog_info;
2447 	struct bpf_insn *insn = env->prog->insnsi;
2448 	int insn_cnt = env->prog->len;
2449 
2450 	/* now check that all jumps are within the same subprog */
2451 	subprog_start = subprog[cur_subprog].start;
2452 	subprog_end = subprog[cur_subprog + 1].start;
2453 	for (i = 0; i < insn_cnt; i++) {
2454 		u8 code = insn[i].code;
2455 
2456 		if (code == (BPF_JMP | BPF_CALL) &&
2457 		    insn[i].imm == BPF_FUNC_tail_call &&
2458 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2459 			subprog[cur_subprog].has_tail_call = true;
2460 		if (BPF_CLASS(code) == BPF_LD &&
2461 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2462 			subprog[cur_subprog].has_ld_abs = true;
2463 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2464 			goto next;
2465 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2466 			goto next;
2467 		off = i + insn[i].off + 1;
2468 		if (off < subprog_start || off >= subprog_end) {
2469 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2470 			return -EINVAL;
2471 		}
2472 next:
2473 		if (i == subprog_end - 1) {
2474 			/* to avoid fall-through from one subprog into another
2475 			 * the last insn of the subprog should be either exit
2476 			 * or unconditional jump back
2477 			 */
2478 			if (code != (BPF_JMP | BPF_EXIT) &&
2479 			    code != (BPF_JMP | BPF_JA)) {
2480 				verbose(env, "last insn is not an exit or jmp\n");
2481 				return -EINVAL;
2482 			}
2483 			subprog_start = subprog_end;
2484 			cur_subprog++;
2485 			if (cur_subprog < env->subprog_cnt)
2486 				subprog_end = subprog[cur_subprog + 1].start;
2487 		}
2488 	}
2489 	return 0;
2490 }
2491 
2492 /* Parentage chain of this register (or stack slot) should take care of all
2493  * issues like callee-saved registers, stack slot allocation time, etc.
2494  */
2495 static int mark_reg_read(struct bpf_verifier_env *env,
2496 			 const struct bpf_reg_state *state,
2497 			 struct bpf_reg_state *parent, u8 flag)
2498 {
2499 	bool writes = parent == state->parent; /* Observe write marks */
2500 	int cnt = 0;
2501 
2502 	while (parent) {
2503 		/* if read wasn't screened by an earlier write ... */
2504 		if (writes && state->live & REG_LIVE_WRITTEN)
2505 			break;
2506 		if (parent->live & REG_LIVE_DONE) {
2507 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2508 				reg_type_str(env, parent->type),
2509 				parent->var_off.value, parent->off);
2510 			return -EFAULT;
2511 		}
2512 		/* The first condition is more likely to be true than the
2513 		 * second, checked it first.
2514 		 */
2515 		if ((parent->live & REG_LIVE_READ) == flag ||
2516 		    parent->live & REG_LIVE_READ64)
2517 			/* The parentage chain never changes and
2518 			 * this parent was already marked as LIVE_READ.
2519 			 * There is no need to keep walking the chain again and
2520 			 * keep re-marking all parents as LIVE_READ.
2521 			 * This case happens when the same register is read
2522 			 * multiple times without writes into it in-between.
2523 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2524 			 * then no need to set the weak REG_LIVE_READ32.
2525 			 */
2526 			break;
2527 		/* ... then we depend on parent's value */
2528 		parent->live |= flag;
2529 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2530 		if (flag == REG_LIVE_READ64)
2531 			parent->live &= ~REG_LIVE_READ32;
2532 		state = parent;
2533 		parent = state->parent;
2534 		writes = true;
2535 		cnt++;
2536 	}
2537 
2538 	if (env->longest_mark_read_walk < cnt)
2539 		env->longest_mark_read_walk = cnt;
2540 	return 0;
2541 }
2542 
2543 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2544 {
2545 	struct bpf_func_state *state = func(env, reg);
2546 	int spi, ret;
2547 
2548 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2549 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2550 	 * check_kfunc_call.
2551 	 */
2552 	if (reg->type == CONST_PTR_TO_DYNPTR)
2553 		return 0;
2554 	spi = dynptr_get_spi(env, reg);
2555 	if (spi < 0)
2556 		return spi;
2557 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2558 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2559 	 * read.
2560 	 */
2561 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2562 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2563 	if (ret)
2564 		return ret;
2565 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2566 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2567 }
2568 
2569 /* This function is supposed to be used by the following 32-bit optimization
2570  * code only. It returns TRUE if the source or destination register operates
2571  * on 64-bit, otherwise return FALSE.
2572  */
2573 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2574 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2575 {
2576 	u8 code, class, op;
2577 
2578 	code = insn->code;
2579 	class = BPF_CLASS(code);
2580 	op = BPF_OP(code);
2581 	if (class == BPF_JMP) {
2582 		/* BPF_EXIT for "main" will reach here. Return TRUE
2583 		 * conservatively.
2584 		 */
2585 		if (op == BPF_EXIT)
2586 			return true;
2587 		if (op == BPF_CALL) {
2588 			/* BPF to BPF call will reach here because of marking
2589 			 * caller saved clobber with DST_OP_NO_MARK for which we
2590 			 * don't care the register def because they are anyway
2591 			 * marked as NOT_INIT already.
2592 			 */
2593 			if (insn->src_reg == BPF_PSEUDO_CALL)
2594 				return false;
2595 			/* Helper call will reach here because of arg type
2596 			 * check, conservatively return TRUE.
2597 			 */
2598 			if (t == SRC_OP)
2599 				return true;
2600 
2601 			return false;
2602 		}
2603 	}
2604 
2605 	if (class == BPF_ALU64 || class == BPF_JMP ||
2606 	    /* BPF_END always use BPF_ALU class. */
2607 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2608 		return true;
2609 
2610 	if (class == BPF_ALU || class == BPF_JMP32)
2611 		return false;
2612 
2613 	if (class == BPF_LDX) {
2614 		if (t != SRC_OP)
2615 			return BPF_SIZE(code) == BPF_DW;
2616 		/* LDX source must be ptr. */
2617 		return true;
2618 	}
2619 
2620 	if (class == BPF_STX) {
2621 		/* BPF_STX (including atomic variants) has multiple source
2622 		 * operands, one of which is a ptr. Check whether the caller is
2623 		 * asking about it.
2624 		 */
2625 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2626 			return true;
2627 		return BPF_SIZE(code) == BPF_DW;
2628 	}
2629 
2630 	if (class == BPF_LD) {
2631 		u8 mode = BPF_MODE(code);
2632 
2633 		/* LD_IMM64 */
2634 		if (mode == BPF_IMM)
2635 			return true;
2636 
2637 		/* Both LD_IND and LD_ABS return 32-bit data. */
2638 		if (t != SRC_OP)
2639 			return  false;
2640 
2641 		/* Implicit ctx ptr. */
2642 		if (regno == BPF_REG_6)
2643 			return true;
2644 
2645 		/* Explicit source could be any width. */
2646 		return true;
2647 	}
2648 
2649 	if (class == BPF_ST)
2650 		/* The only source register for BPF_ST is a ptr. */
2651 		return true;
2652 
2653 	/* Conservatively return true at default. */
2654 	return true;
2655 }
2656 
2657 /* Return the regno defined by the insn, or -1. */
2658 static int insn_def_regno(const struct bpf_insn *insn)
2659 {
2660 	switch (BPF_CLASS(insn->code)) {
2661 	case BPF_JMP:
2662 	case BPF_JMP32:
2663 	case BPF_ST:
2664 		return -1;
2665 	case BPF_STX:
2666 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2667 		    (insn->imm & BPF_FETCH)) {
2668 			if (insn->imm == BPF_CMPXCHG)
2669 				return BPF_REG_0;
2670 			else
2671 				return insn->src_reg;
2672 		} else {
2673 			return -1;
2674 		}
2675 	default:
2676 		return insn->dst_reg;
2677 	}
2678 }
2679 
2680 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2681 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2682 {
2683 	int dst_reg = insn_def_regno(insn);
2684 
2685 	if (dst_reg == -1)
2686 		return false;
2687 
2688 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2689 }
2690 
2691 static void mark_insn_zext(struct bpf_verifier_env *env,
2692 			   struct bpf_reg_state *reg)
2693 {
2694 	s32 def_idx = reg->subreg_def;
2695 
2696 	if (def_idx == DEF_NOT_SUBREG)
2697 		return;
2698 
2699 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2700 	/* The dst will be zero extended, so won't be sub-register anymore. */
2701 	reg->subreg_def = DEF_NOT_SUBREG;
2702 }
2703 
2704 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2705 			 enum reg_arg_type t)
2706 {
2707 	struct bpf_verifier_state *vstate = env->cur_state;
2708 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2709 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2710 	struct bpf_reg_state *reg, *regs = state->regs;
2711 	bool rw64;
2712 
2713 	if (regno >= MAX_BPF_REG) {
2714 		verbose(env, "R%d is invalid\n", regno);
2715 		return -EINVAL;
2716 	}
2717 
2718 	mark_reg_scratched(env, regno);
2719 
2720 	reg = &regs[regno];
2721 	rw64 = is_reg64(env, insn, regno, reg, t);
2722 	if (t == SRC_OP) {
2723 		/* check whether register used as source operand can be read */
2724 		if (reg->type == NOT_INIT) {
2725 			verbose(env, "R%d !read_ok\n", regno);
2726 			return -EACCES;
2727 		}
2728 		/* We don't need to worry about FP liveness because it's read-only */
2729 		if (regno == BPF_REG_FP)
2730 			return 0;
2731 
2732 		if (rw64)
2733 			mark_insn_zext(env, reg);
2734 
2735 		return mark_reg_read(env, reg, reg->parent,
2736 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2737 	} else {
2738 		/* check whether register used as dest operand can be written to */
2739 		if (regno == BPF_REG_FP) {
2740 			verbose(env, "frame pointer is read only\n");
2741 			return -EACCES;
2742 		}
2743 		reg->live |= REG_LIVE_WRITTEN;
2744 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2745 		if (t == DST_OP)
2746 			mark_reg_unknown(env, regs, regno);
2747 	}
2748 	return 0;
2749 }
2750 
2751 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2752 {
2753 	env->insn_aux_data[idx].jmp_point = true;
2754 }
2755 
2756 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2757 {
2758 	return env->insn_aux_data[insn_idx].jmp_point;
2759 }
2760 
2761 /* for any branch, call, exit record the history of jmps in the given state */
2762 static int push_jmp_history(struct bpf_verifier_env *env,
2763 			    struct bpf_verifier_state *cur)
2764 {
2765 	u32 cnt = cur->jmp_history_cnt;
2766 	struct bpf_idx_pair *p;
2767 	size_t alloc_size;
2768 
2769 	if (!is_jmp_point(env, env->insn_idx))
2770 		return 0;
2771 
2772 	cnt++;
2773 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2774 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2775 	if (!p)
2776 		return -ENOMEM;
2777 	p[cnt - 1].idx = env->insn_idx;
2778 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2779 	cur->jmp_history = p;
2780 	cur->jmp_history_cnt = cnt;
2781 	return 0;
2782 }
2783 
2784 /* Backtrack one insn at a time. If idx is not at the top of recorded
2785  * history then previous instruction came from straight line execution.
2786  */
2787 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2788 			     u32 *history)
2789 {
2790 	u32 cnt = *history;
2791 
2792 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2793 		i = st->jmp_history[cnt - 1].prev_idx;
2794 		(*history)--;
2795 	} else {
2796 		i--;
2797 	}
2798 	return i;
2799 }
2800 
2801 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2802 {
2803 	const struct btf_type *func;
2804 	struct btf *desc_btf;
2805 
2806 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2807 		return NULL;
2808 
2809 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2810 	if (IS_ERR(desc_btf))
2811 		return "<error>";
2812 
2813 	func = btf_type_by_id(desc_btf, insn->imm);
2814 	return btf_name_by_offset(desc_btf, func->name_off);
2815 }
2816 
2817 /* For given verifier state backtrack_insn() is called from the last insn to
2818  * the first insn. Its purpose is to compute a bitmask of registers and
2819  * stack slots that needs precision in the parent verifier state.
2820  */
2821 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2822 			  u32 *reg_mask, u64 *stack_mask)
2823 {
2824 	const struct bpf_insn_cbs cbs = {
2825 		.cb_call	= disasm_kfunc_name,
2826 		.cb_print	= verbose,
2827 		.private_data	= env,
2828 	};
2829 	struct bpf_insn *insn = env->prog->insnsi + idx;
2830 	u8 class = BPF_CLASS(insn->code);
2831 	u8 opcode = BPF_OP(insn->code);
2832 	u8 mode = BPF_MODE(insn->code);
2833 	u32 dreg = 1u << insn->dst_reg;
2834 	u32 sreg = 1u << insn->src_reg;
2835 	u32 spi;
2836 
2837 	if (insn->code == 0)
2838 		return 0;
2839 	if (env->log.level & BPF_LOG_LEVEL2) {
2840 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2841 		verbose(env, "%d: ", idx);
2842 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2843 	}
2844 
2845 	if (class == BPF_ALU || class == BPF_ALU64) {
2846 		if (!(*reg_mask & dreg))
2847 			return 0;
2848 		if (opcode == BPF_MOV) {
2849 			if (BPF_SRC(insn->code) == BPF_X) {
2850 				/* dreg = sreg
2851 				 * dreg needs precision after this insn
2852 				 * sreg needs precision before this insn
2853 				 */
2854 				*reg_mask &= ~dreg;
2855 				*reg_mask |= sreg;
2856 			} else {
2857 				/* dreg = K
2858 				 * dreg needs precision after this insn.
2859 				 * Corresponding register is already marked
2860 				 * as precise=true in this verifier state.
2861 				 * No further markings in parent are necessary
2862 				 */
2863 				*reg_mask &= ~dreg;
2864 			}
2865 		} else {
2866 			if (BPF_SRC(insn->code) == BPF_X) {
2867 				/* dreg += sreg
2868 				 * both dreg and sreg need precision
2869 				 * before this insn
2870 				 */
2871 				*reg_mask |= sreg;
2872 			} /* else dreg += K
2873 			   * dreg still needs precision before this insn
2874 			   */
2875 		}
2876 	} else if (class == BPF_LDX) {
2877 		if (!(*reg_mask & dreg))
2878 			return 0;
2879 		*reg_mask &= ~dreg;
2880 
2881 		/* scalars can only be spilled into stack w/o losing precision.
2882 		 * Load from any other memory can be zero extended.
2883 		 * The desire to keep that precision is already indicated
2884 		 * by 'precise' mark in corresponding register of this state.
2885 		 * No further tracking necessary.
2886 		 */
2887 		if (insn->src_reg != BPF_REG_FP)
2888 			return 0;
2889 
2890 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2891 		 * that [fp - off] slot contains scalar that needs to be
2892 		 * tracked with precision
2893 		 */
2894 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2895 		if (spi >= 64) {
2896 			verbose(env, "BUG spi %d\n", spi);
2897 			WARN_ONCE(1, "verifier backtracking bug");
2898 			return -EFAULT;
2899 		}
2900 		*stack_mask |= 1ull << spi;
2901 	} else if (class == BPF_STX || class == BPF_ST) {
2902 		if (*reg_mask & dreg)
2903 			/* stx & st shouldn't be using _scalar_ dst_reg
2904 			 * to access memory. It means backtracking
2905 			 * encountered a case of pointer subtraction.
2906 			 */
2907 			return -ENOTSUPP;
2908 		/* scalars can only be spilled into stack */
2909 		if (insn->dst_reg != BPF_REG_FP)
2910 			return 0;
2911 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2912 		if (spi >= 64) {
2913 			verbose(env, "BUG spi %d\n", spi);
2914 			WARN_ONCE(1, "verifier backtracking bug");
2915 			return -EFAULT;
2916 		}
2917 		if (!(*stack_mask & (1ull << spi)))
2918 			return 0;
2919 		*stack_mask &= ~(1ull << spi);
2920 		if (class == BPF_STX)
2921 			*reg_mask |= sreg;
2922 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2923 		if (opcode == BPF_CALL) {
2924 			if (insn->src_reg == BPF_PSEUDO_CALL)
2925 				return -ENOTSUPP;
2926 			/* BPF helpers that invoke callback subprogs are
2927 			 * equivalent to BPF_PSEUDO_CALL above
2928 			 */
2929 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2930 				return -ENOTSUPP;
2931 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2932 			 * catch this error later. Make backtracking conservative
2933 			 * with ENOTSUPP.
2934 			 */
2935 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2936 				return -ENOTSUPP;
2937 			/* regular helper call sets R0 */
2938 			*reg_mask &= ~1;
2939 			if (*reg_mask & 0x3f) {
2940 				/* if backtracing was looking for registers R1-R5
2941 				 * they should have been found already.
2942 				 */
2943 				verbose(env, "BUG regs %x\n", *reg_mask);
2944 				WARN_ONCE(1, "verifier backtracking bug");
2945 				return -EFAULT;
2946 			}
2947 		} else if (opcode == BPF_EXIT) {
2948 			return -ENOTSUPP;
2949 		}
2950 	} else if (class == BPF_LD) {
2951 		if (!(*reg_mask & dreg))
2952 			return 0;
2953 		*reg_mask &= ~dreg;
2954 		/* It's ld_imm64 or ld_abs or ld_ind.
2955 		 * For ld_imm64 no further tracking of precision
2956 		 * into parent is necessary
2957 		 */
2958 		if (mode == BPF_IND || mode == BPF_ABS)
2959 			/* to be analyzed */
2960 			return -ENOTSUPP;
2961 	}
2962 	return 0;
2963 }
2964 
2965 /* the scalar precision tracking algorithm:
2966  * . at the start all registers have precise=false.
2967  * . scalar ranges are tracked as normal through alu and jmp insns.
2968  * . once precise value of the scalar register is used in:
2969  *   .  ptr + scalar alu
2970  *   . if (scalar cond K|scalar)
2971  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2972  *   backtrack through the verifier states and mark all registers and
2973  *   stack slots with spilled constants that these scalar regisers
2974  *   should be precise.
2975  * . during state pruning two registers (or spilled stack slots)
2976  *   are equivalent if both are not precise.
2977  *
2978  * Note the verifier cannot simply walk register parentage chain,
2979  * since many different registers and stack slots could have been
2980  * used to compute single precise scalar.
2981  *
2982  * The approach of starting with precise=true for all registers and then
2983  * backtrack to mark a register as not precise when the verifier detects
2984  * that program doesn't care about specific value (e.g., when helper
2985  * takes register as ARG_ANYTHING parameter) is not safe.
2986  *
2987  * It's ok to walk single parentage chain of the verifier states.
2988  * It's possible that this backtracking will go all the way till 1st insn.
2989  * All other branches will be explored for needing precision later.
2990  *
2991  * The backtracking needs to deal with cases like:
2992  *   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)
2993  * r9 -= r8
2994  * r5 = r9
2995  * if r5 > 0x79f goto pc+7
2996  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2997  * r5 += 1
2998  * ...
2999  * call bpf_perf_event_output#25
3000  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3001  *
3002  * and this case:
3003  * r6 = 1
3004  * call foo // uses callee's r6 inside to compute r0
3005  * r0 += r6
3006  * if r0 == 0 goto
3007  *
3008  * to track above reg_mask/stack_mask needs to be independent for each frame.
3009  *
3010  * Also if parent's curframe > frame where backtracking started,
3011  * the verifier need to mark registers in both frames, otherwise callees
3012  * may incorrectly prune callers. This is similar to
3013  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3014  *
3015  * For now backtracking falls back into conservative marking.
3016  */
3017 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3018 				     struct bpf_verifier_state *st)
3019 {
3020 	struct bpf_func_state *func;
3021 	struct bpf_reg_state *reg;
3022 	int i, j;
3023 
3024 	/* big hammer: mark all scalars precise in this path.
3025 	 * pop_stack may still get !precise scalars.
3026 	 * We also skip current state and go straight to first parent state,
3027 	 * because precision markings in current non-checkpointed state are
3028 	 * not needed. See why in the comment in __mark_chain_precision below.
3029 	 */
3030 	for (st = st->parent; st; st = st->parent) {
3031 		for (i = 0; i <= st->curframe; i++) {
3032 			func = st->frame[i];
3033 			for (j = 0; j < BPF_REG_FP; j++) {
3034 				reg = &func->regs[j];
3035 				if (reg->type != SCALAR_VALUE)
3036 					continue;
3037 				reg->precise = true;
3038 			}
3039 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3040 				if (!is_spilled_reg(&func->stack[j]))
3041 					continue;
3042 				reg = &func->stack[j].spilled_ptr;
3043 				if (reg->type != SCALAR_VALUE)
3044 					continue;
3045 				reg->precise = true;
3046 			}
3047 		}
3048 	}
3049 }
3050 
3051 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3052 {
3053 	struct bpf_func_state *func;
3054 	struct bpf_reg_state *reg;
3055 	int i, j;
3056 
3057 	for (i = 0; i <= st->curframe; i++) {
3058 		func = st->frame[i];
3059 		for (j = 0; j < BPF_REG_FP; j++) {
3060 			reg = &func->regs[j];
3061 			if (reg->type != SCALAR_VALUE)
3062 				continue;
3063 			reg->precise = false;
3064 		}
3065 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3066 			if (!is_spilled_reg(&func->stack[j]))
3067 				continue;
3068 			reg = &func->stack[j].spilled_ptr;
3069 			if (reg->type != SCALAR_VALUE)
3070 				continue;
3071 			reg->precise = false;
3072 		}
3073 	}
3074 }
3075 
3076 /*
3077  * __mark_chain_precision() backtracks BPF program instruction sequence and
3078  * chain of verifier states making sure that register *regno* (if regno >= 0)
3079  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3080  * SCALARS, as well as any other registers and slots that contribute to
3081  * a tracked state of given registers/stack slots, depending on specific BPF
3082  * assembly instructions (see backtrack_insns() for exact instruction handling
3083  * logic). This backtracking relies on recorded jmp_history and is able to
3084  * traverse entire chain of parent states. This process ends only when all the
3085  * necessary registers/slots and their transitive dependencies are marked as
3086  * precise.
3087  *
3088  * One important and subtle aspect is that precise marks *do not matter* in
3089  * the currently verified state (current state). It is important to understand
3090  * why this is the case.
3091  *
3092  * First, note that current state is the state that is not yet "checkpointed",
3093  * i.e., it is not yet put into env->explored_states, and it has no children
3094  * states as well. It's ephemeral, and can end up either a) being discarded if
3095  * compatible explored state is found at some point or BPF_EXIT instruction is
3096  * reached or b) checkpointed and put into env->explored_states, branching out
3097  * into one or more children states.
3098  *
3099  * In the former case, precise markings in current state are completely
3100  * ignored by state comparison code (see regsafe() for details). Only
3101  * checkpointed ("old") state precise markings are important, and if old
3102  * state's register/slot is precise, regsafe() assumes current state's
3103  * register/slot as precise and checks value ranges exactly and precisely. If
3104  * states turn out to be compatible, current state's necessary precise
3105  * markings and any required parent states' precise markings are enforced
3106  * after the fact with propagate_precision() logic, after the fact. But it's
3107  * important to realize that in this case, even after marking current state
3108  * registers/slots as precise, we immediately discard current state. So what
3109  * actually matters is any of the precise markings propagated into current
3110  * state's parent states, which are always checkpointed (due to b) case above).
3111  * As such, for scenario a) it doesn't matter if current state has precise
3112  * markings set or not.
3113  *
3114  * Now, for the scenario b), checkpointing and forking into child(ren)
3115  * state(s). Note that before current state gets to checkpointing step, any
3116  * processed instruction always assumes precise SCALAR register/slot
3117  * knowledge: if precise value or range is useful to prune jump branch, BPF
3118  * verifier takes this opportunity enthusiastically. Similarly, when
3119  * register's value is used to calculate offset or memory address, exact
3120  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3121  * what we mentioned above about state comparison ignoring precise markings
3122  * during state comparison, BPF verifier ignores and also assumes precise
3123  * markings *at will* during instruction verification process. But as verifier
3124  * assumes precision, it also propagates any precision dependencies across
3125  * parent states, which are not yet finalized, so can be further restricted
3126  * based on new knowledge gained from restrictions enforced by their children
3127  * states. This is so that once those parent states are finalized, i.e., when
3128  * they have no more active children state, state comparison logic in
3129  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3130  * required for correctness.
3131  *
3132  * To build a bit more intuition, note also that once a state is checkpointed,
3133  * the path we took to get to that state is not important. This is crucial
3134  * property for state pruning. When state is checkpointed and finalized at
3135  * some instruction index, it can be correctly and safely used to "short
3136  * circuit" any *compatible* state that reaches exactly the same instruction
3137  * index. I.e., if we jumped to that instruction from a completely different
3138  * code path than original finalized state was derived from, it doesn't
3139  * matter, current state can be discarded because from that instruction
3140  * forward having a compatible state will ensure we will safely reach the
3141  * exit. States describe preconditions for further exploration, but completely
3142  * forget the history of how we got here.
3143  *
3144  * This also means that even if we needed precise SCALAR range to get to
3145  * finalized state, but from that point forward *that same* SCALAR register is
3146  * never used in a precise context (i.e., it's precise value is not needed for
3147  * correctness), it's correct and safe to mark such register as "imprecise"
3148  * (i.e., precise marking set to false). This is what we rely on when we do
3149  * not set precise marking in current state. If no child state requires
3150  * precision for any given SCALAR register, it's safe to dictate that it can
3151  * be imprecise. If any child state does require this register to be precise,
3152  * we'll mark it precise later retroactively during precise markings
3153  * propagation from child state to parent states.
3154  *
3155  * Skipping precise marking setting in current state is a mild version of
3156  * relying on the above observation. But we can utilize this property even
3157  * more aggressively by proactively forgetting any precise marking in the
3158  * current state (which we inherited from the parent state), right before we
3159  * checkpoint it and branch off into new child state. This is done by
3160  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3161  * finalized states which help in short circuiting more future states.
3162  */
3163 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3164 				  int spi)
3165 {
3166 	struct bpf_verifier_state *st = env->cur_state;
3167 	int first_idx = st->first_insn_idx;
3168 	int last_idx = env->insn_idx;
3169 	struct bpf_func_state *func;
3170 	struct bpf_reg_state *reg;
3171 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3172 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3173 	bool skip_first = true;
3174 	bool new_marks = false;
3175 	int i, err;
3176 
3177 	if (!env->bpf_capable)
3178 		return 0;
3179 
3180 	/* Do sanity checks against current state of register and/or stack
3181 	 * slot, but don't set precise flag in current state, as precision
3182 	 * tracking in the current state is unnecessary.
3183 	 */
3184 	func = st->frame[frame];
3185 	if (regno >= 0) {
3186 		reg = &func->regs[regno];
3187 		if (reg->type != SCALAR_VALUE) {
3188 			WARN_ONCE(1, "backtracing misuse");
3189 			return -EFAULT;
3190 		}
3191 		new_marks = true;
3192 	}
3193 
3194 	while (spi >= 0) {
3195 		if (!is_spilled_reg(&func->stack[spi])) {
3196 			stack_mask = 0;
3197 			break;
3198 		}
3199 		reg = &func->stack[spi].spilled_ptr;
3200 		if (reg->type != SCALAR_VALUE) {
3201 			stack_mask = 0;
3202 			break;
3203 		}
3204 		new_marks = true;
3205 		break;
3206 	}
3207 
3208 	if (!new_marks)
3209 		return 0;
3210 	if (!reg_mask && !stack_mask)
3211 		return 0;
3212 
3213 	for (;;) {
3214 		DECLARE_BITMAP(mask, 64);
3215 		u32 history = st->jmp_history_cnt;
3216 
3217 		if (env->log.level & BPF_LOG_LEVEL2)
3218 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3219 
3220 		if (last_idx < 0) {
3221 			/* we are at the entry into subprog, which
3222 			 * is expected for global funcs, but only if
3223 			 * requested precise registers are R1-R5
3224 			 * (which are global func's input arguments)
3225 			 */
3226 			if (st->curframe == 0 &&
3227 			    st->frame[0]->subprogno > 0 &&
3228 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3229 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3230 				bitmap_from_u64(mask, reg_mask);
3231 				for_each_set_bit(i, mask, 32) {
3232 					reg = &st->frame[0]->regs[i];
3233 					if (reg->type != SCALAR_VALUE) {
3234 						reg_mask &= ~(1u << i);
3235 						continue;
3236 					}
3237 					reg->precise = true;
3238 				}
3239 				return 0;
3240 			}
3241 
3242 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3243 				st->frame[0]->subprogno, reg_mask, stack_mask);
3244 			WARN_ONCE(1, "verifier backtracking bug");
3245 			return -EFAULT;
3246 		}
3247 
3248 		for (i = last_idx;;) {
3249 			if (skip_first) {
3250 				err = 0;
3251 				skip_first = false;
3252 			} else {
3253 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3254 			}
3255 			if (err == -ENOTSUPP) {
3256 				mark_all_scalars_precise(env, st);
3257 				return 0;
3258 			} else if (err) {
3259 				return err;
3260 			}
3261 			if (!reg_mask && !stack_mask)
3262 				/* Found assignment(s) into tracked register in this state.
3263 				 * Since this state is already marked, just return.
3264 				 * Nothing to be tracked further in the parent state.
3265 				 */
3266 				return 0;
3267 			if (i == first_idx)
3268 				break;
3269 			i = get_prev_insn_idx(st, i, &history);
3270 			if (i >= env->prog->len) {
3271 				/* This can happen if backtracking reached insn 0
3272 				 * and there are still reg_mask or stack_mask
3273 				 * to backtrack.
3274 				 * It means the backtracking missed the spot where
3275 				 * particular register was initialized with a constant.
3276 				 */
3277 				verbose(env, "BUG backtracking idx %d\n", i);
3278 				WARN_ONCE(1, "verifier backtracking bug");
3279 				return -EFAULT;
3280 			}
3281 		}
3282 		st = st->parent;
3283 		if (!st)
3284 			break;
3285 
3286 		new_marks = false;
3287 		func = st->frame[frame];
3288 		bitmap_from_u64(mask, reg_mask);
3289 		for_each_set_bit(i, mask, 32) {
3290 			reg = &func->regs[i];
3291 			if (reg->type != SCALAR_VALUE) {
3292 				reg_mask &= ~(1u << i);
3293 				continue;
3294 			}
3295 			if (!reg->precise)
3296 				new_marks = true;
3297 			reg->precise = true;
3298 		}
3299 
3300 		bitmap_from_u64(mask, stack_mask);
3301 		for_each_set_bit(i, mask, 64) {
3302 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3303 				/* the sequence of instructions:
3304 				 * 2: (bf) r3 = r10
3305 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3306 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3307 				 * doesn't contain jmps. It's backtracked
3308 				 * as a single block.
3309 				 * During backtracking insn 3 is not recognized as
3310 				 * stack access, so at the end of backtracking
3311 				 * stack slot fp-8 is still marked in stack_mask.
3312 				 * However the parent state may not have accessed
3313 				 * fp-8 and it's "unallocated" stack space.
3314 				 * In such case fallback to conservative.
3315 				 */
3316 				mark_all_scalars_precise(env, st);
3317 				return 0;
3318 			}
3319 
3320 			if (!is_spilled_reg(&func->stack[i])) {
3321 				stack_mask &= ~(1ull << i);
3322 				continue;
3323 			}
3324 			reg = &func->stack[i].spilled_ptr;
3325 			if (reg->type != SCALAR_VALUE) {
3326 				stack_mask &= ~(1ull << i);
3327 				continue;
3328 			}
3329 			if (!reg->precise)
3330 				new_marks = true;
3331 			reg->precise = true;
3332 		}
3333 		if (env->log.level & BPF_LOG_LEVEL2) {
3334 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3335 				new_marks ? "didn't have" : "already had",
3336 				reg_mask, stack_mask);
3337 			print_verifier_state(env, func, true);
3338 		}
3339 
3340 		if (!reg_mask && !stack_mask)
3341 			break;
3342 		if (!new_marks)
3343 			break;
3344 
3345 		last_idx = st->last_insn_idx;
3346 		first_idx = st->first_insn_idx;
3347 	}
3348 	return 0;
3349 }
3350 
3351 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3352 {
3353 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3354 }
3355 
3356 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3357 {
3358 	return __mark_chain_precision(env, frame, regno, -1);
3359 }
3360 
3361 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3362 {
3363 	return __mark_chain_precision(env, frame, -1, spi);
3364 }
3365 
3366 static bool is_spillable_regtype(enum bpf_reg_type type)
3367 {
3368 	switch (base_type(type)) {
3369 	case PTR_TO_MAP_VALUE:
3370 	case PTR_TO_STACK:
3371 	case PTR_TO_CTX:
3372 	case PTR_TO_PACKET:
3373 	case PTR_TO_PACKET_META:
3374 	case PTR_TO_PACKET_END:
3375 	case PTR_TO_FLOW_KEYS:
3376 	case CONST_PTR_TO_MAP:
3377 	case PTR_TO_SOCKET:
3378 	case PTR_TO_SOCK_COMMON:
3379 	case PTR_TO_TCP_SOCK:
3380 	case PTR_TO_XDP_SOCK:
3381 	case PTR_TO_BTF_ID:
3382 	case PTR_TO_BUF:
3383 	case PTR_TO_MEM:
3384 	case PTR_TO_FUNC:
3385 	case PTR_TO_MAP_KEY:
3386 		return true;
3387 	default:
3388 		return false;
3389 	}
3390 }
3391 
3392 /* Does this register contain a constant zero? */
3393 static bool register_is_null(struct bpf_reg_state *reg)
3394 {
3395 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3396 }
3397 
3398 static bool register_is_const(struct bpf_reg_state *reg)
3399 {
3400 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3401 }
3402 
3403 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3404 {
3405 	return tnum_is_unknown(reg->var_off) &&
3406 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3407 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3408 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3409 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3410 }
3411 
3412 static bool register_is_bounded(struct bpf_reg_state *reg)
3413 {
3414 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3415 }
3416 
3417 static bool __is_pointer_value(bool allow_ptr_leaks,
3418 			       const struct bpf_reg_state *reg)
3419 {
3420 	if (allow_ptr_leaks)
3421 		return false;
3422 
3423 	return reg->type != SCALAR_VALUE;
3424 }
3425 
3426 static void save_register_state(struct bpf_func_state *state,
3427 				int spi, struct bpf_reg_state *reg,
3428 				int size)
3429 {
3430 	int i;
3431 
3432 	state->stack[spi].spilled_ptr = *reg;
3433 	if (size == BPF_REG_SIZE)
3434 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3435 
3436 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3437 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3438 
3439 	/* size < 8 bytes spill */
3440 	for (; i; i--)
3441 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3442 }
3443 
3444 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3445  * stack boundary and alignment are checked in check_mem_access()
3446  */
3447 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3448 				       /* stack frame we're writing to */
3449 				       struct bpf_func_state *state,
3450 				       int off, int size, int value_regno,
3451 				       int insn_idx)
3452 {
3453 	struct bpf_func_state *cur; /* state of the current function */
3454 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3455 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3456 	struct bpf_reg_state *reg = NULL;
3457 
3458 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3459 	if (err)
3460 		return err;
3461 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3462 	 * so it's aligned access and [off, off + size) are within stack limits
3463 	 */
3464 	if (!env->allow_ptr_leaks &&
3465 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3466 	    size != BPF_REG_SIZE) {
3467 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3468 		return -EACCES;
3469 	}
3470 
3471 	cur = env->cur_state->frame[env->cur_state->curframe];
3472 	if (value_regno >= 0)
3473 		reg = &cur->regs[value_regno];
3474 	if (!env->bypass_spec_v4) {
3475 		bool sanitize = reg && is_spillable_regtype(reg->type);
3476 
3477 		for (i = 0; i < size; i++) {
3478 			u8 type = state->stack[spi].slot_type[i];
3479 
3480 			if (type != STACK_MISC && type != STACK_ZERO) {
3481 				sanitize = true;
3482 				break;
3483 			}
3484 		}
3485 
3486 		if (sanitize)
3487 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3488 	}
3489 
3490 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3491 	if (err)
3492 		return err;
3493 
3494 	mark_stack_slot_scratched(env, spi);
3495 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3496 	    !register_is_null(reg) && env->bpf_capable) {
3497 		if (dst_reg != BPF_REG_FP) {
3498 			/* The backtracking logic can only recognize explicit
3499 			 * stack slot address like [fp - 8]. Other spill of
3500 			 * scalar via different register has to be conservative.
3501 			 * Backtrack from here and mark all registers as precise
3502 			 * that contributed into 'reg' being a constant.
3503 			 */
3504 			err = mark_chain_precision(env, value_regno);
3505 			if (err)
3506 				return err;
3507 		}
3508 		save_register_state(state, spi, reg, size);
3509 	} else if (reg && is_spillable_regtype(reg->type)) {
3510 		/* register containing pointer is being spilled into stack */
3511 		if (size != BPF_REG_SIZE) {
3512 			verbose_linfo(env, insn_idx, "; ");
3513 			verbose(env, "invalid size of register spill\n");
3514 			return -EACCES;
3515 		}
3516 		if (state != cur && reg->type == PTR_TO_STACK) {
3517 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3518 			return -EINVAL;
3519 		}
3520 		save_register_state(state, spi, reg, size);
3521 	} else {
3522 		u8 type = STACK_MISC;
3523 
3524 		/* regular write of data into stack destroys any spilled ptr */
3525 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3526 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3527 		if (is_spilled_reg(&state->stack[spi]))
3528 			for (i = 0; i < BPF_REG_SIZE; i++)
3529 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3530 
3531 		/* only mark the slot as written if all 8 bytes were written
3532 		 * otherwise read propagation may incorrectly stop too soon
3533 		 * when stack slots are partially written.
3534 		 * This heuristic means that read propagation will be
3535 		 * conservative, since it will add reg_live_read marks
3536 		 * to stack slots all the way to first state when programs
3537 		 * writes+reads less than 8 bytes
3538 		 */
3539 		if (size == BPF_REG_SIZE)
3540 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3541 
3542 		/* when we zero initialize stack slots mark them as such */
3543 		if (reg && register_is_null(reg)) {
3544 			/* backtracking doesn't work for STACK_ZERO yet. */
3545 			err = mark_chain_precision(env, value_regno);
3546 			if (err)
3547 				return err;
3548 			type = STACK_ZERO;
3549 		}
3550 
3551 		/* Mark slots affected by this stack write. */
3552 		for (i = 0; i < size; i++)
3553 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3554 				type;
3555 	}
3556 	return 0;
3557 }
3558 
3559 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3560  * known to contain a variable offset.
3561  * This function checks whether the write is permitted and conservatively
3562  * tracks the effects of the write, considering that each stack slot in the
3563  * dynamic range is potentially written to.
3564  *
3565  * 'off' includes 'regno->off'.
3566  * 'value_regno' can be -1, meaning that an unknown value is being written to
3567  * the stack.
3568  *
3569  * Spilled pointers in range are not marked as written because we don't know
3570  * what's going to be actually written. This means that read propagation for
3571  * future reads cannot be terminated by this write.
3572  *
3573  * For privileged programs, uninitialized stack slots are considered
3574  * initialized by this write (even though we don't know exactly what offsets
3575  * are going to be written to). The idea is that we don't want the verifier to
3576  * reject future reads that access slots written to through variable offsets.
3577  */
3578 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3579 				     /* func where register points to */
3580 				     struct bpf_func_state *state,
3581 				     int ptr_regno, int off, int size,
3582 				     int value_regno, int insn_idx)
3583 {
3584 	struct bpf_func_state *cur; /* state of the current function */
3585 	int min_off, max_off;
3586 	int i, err;
3587 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3588 	bool writing_zero = false;
3589 	/* set if the fact that we're writing a zero is used to let any
3590 	 * stack slots remain STACK_ZERO
3591 	 */
3592 	bool zero_used = false;
3593 
3594 	cur = env->cur_state->frame[env->cur_state->curframe];
3595 	ptr_reg = &cur->regs[ptr_regno];
3596 	min_off = ptr_reg->smin_value + off;
3597 	max_off = ptr_reg->smax_value + off + size;
3598 	if (value_regno >= 0)
3599 		value_reg = &cur->regs[value_regno];
3600 	if (value_reg && register_is_null(value_reg))
3601 		writing_zero = true;
3602 
3603 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3604 	if (err)
3605 		return err;
3606 
3607 	for (i = min_off; i < max_off; i++) {
3608 		int spi;
3609 
3610 		spi = __get_spi(i);
3611 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3612 		if (err)
3613 			return err;
3614 	}
3615 
3616 	/* Variable offset writes destroy any spilled pointers in range. */
3617 	for (i = min_off; i < max_off; i++) {
3618 		u8 new_type, *stype;
3619 		int slot, spi;
3620 
3621 		slot = -i - 1;
3622 		spi = slot / BPF_REG_SIZE;
3623 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3624 		mark_stack_slot_scratched(env, spi);
3625 
3626 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3627 			/* Reject the write if range we may write to has not
3628 			 * been initialized beforehand. If we didn't reject
3629 			 * here, the ptr status would be erased below (even
3630 			 * though not all slots are actually overwritten),
3631 			 * possibly opening the door to leaks.
3632 			 *
3633 			 * We do however catch STACK_INVALID case below, and
3634 			 * only allow reading possibly uninitialized memory
3635 			 * later for CAP_PERFMON, as the write may not happen to
3636 			 * that slot.
3637 			 */
3638 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3639 				insn_idx, i);
3640 			return -EINVAL;
3641 		}
3642 
3643 		/* Erase all spilled pointers. */
3644 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3645 
3646 		/* Update the slot type. */
3647 		new_type = STACK_MISC;
3648 		if (writing_zero && *stype == STACK_ZERO) {
3649 			new_type = STACK_ZERO;
3650 			zero_used = true;
3651 		}
3652 		/* If the slot is STACK_INVALID, we check whether it's OK to
3653 		 * pretend that it will be initialized by this write. The slot
3654 		 * might not actually be written to, and so if we mark it as
3655 		 * initialized future reads might leak uninitialized memory.
3656 		 * For privileged programs, we will accept such reads to slots
3657 		 * that may or may not be written because, if we're reject
3658 		 * them, the error would be too confusing.
3659 		 */
3660 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3661 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3662 					insn_idx, i);
3663 			return -EINVAL;
3664 		}
3665 		*stype = new_type;
3666 	}
3667 	if (zero_used) {
3668 		/* backtracking doesn't work for STACK_ZERO yet. */
3669 		err = mark_chain_precision(env, value_regno);
3670 		if (err)
3671 			return err;
3672 	}
3673 	return 0;
3674 }
3675 
3676 /* When register 'dst_regno' is assigned some values from stack[min_off,
3677  * max_off), we set the register's type according to the types of the
3678  * respective stack slots. If all the stack values are known to be zeros, then
3679  * so is the destination reg. Otherwise, the register is considered to be
3680  * SCALAR. This function does not deal with register filling; the caller must
3681  * ensure that all spilled registers in the stack range have been marked as
3682  * read.
3683  */
3684 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3685 				/* func where src register points to */
3686 				struct bpf_func_state *ptr_state,
3687 				int min_off, int max_off, int dst_regno)
3688 {
3689 	struct bpf_verifier_state *vstate = env->cur_state;
3690 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3691 	int i, slot, spi;
3692 	u8 *stype;
3693 	int zeros = 0;
3694 
3695 	for (i = min_off; i < max_off; i++) {
3696 		slot = -i - 1;
3697 		spi = slot / BPF_REG_SIZE;
3698 		stype = ptr_state->stack[spi].slot_type;
3699 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3700 			break;
3701 		zeros++;
3702 	}
3703 	if (zeros == max_off - min_off) {
3704 		/* any access_size read into register is zero extended,
3705 		 * so the whole register == const_zero
3706 		 */
3707 		__mark_reg_const_zero(&state->regs[dst_regno]);
3708 		/* backtracking doesn't support STACK_ZERO yet,
3709 		 * so mark it precise here, so that later
3710 		 * backtracking can stop here.
3711 		 * Backtracking may not need this if this register
3712 		 * doesn't participate in pointer adjustment.
3713 		 * Forward propagation of precise flag is not
3714 		 * necessary either. This mark is only to stop
3715 		 * backtracking. Any register that contributed
3716 		 * to const 0 was marked precise before spill.
3717 		 */
3718 		state->regs[dst_regno].precise = true;
3719 	} else {
3720 		/* have read misc data from the stack */
3721 		mark_reg_unknown(env, state->regs, dst_regno);
3722 	}
3723 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3724 }
3725 
3726 /* Read the stack at 'off' and put the results into the register indicated by
3727  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3728  * spilled reg.
3729  *
3730  * 'dst_regno' can be -1, meaning that the read value is not going to a
3731  * register.
3732  *
3733  * The access is assumed to be within the current stack bounds.
3734  */
3735 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3736 				      /* func where src register points to */
3737 				      struct bpf_func_state *reg_state,
3738 				      int off, int size, int dst_regno)
3739 {
3740 	struct bpf_verifier_state *vstate = env->cur_state;
3741 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3742 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3743 	struct bpf_reg_state *reg;
3744 	u8 *stype, type;
3745 
3746 	stype = reg_state->stack[spi].slot_type;
3747 	reg = &reg_state->stack[spi].spilled_ptr;
3748 
3749 	if (is_spilled_reg(&reg_state->stack[spi])) {
3750 		u8 spill_size = 1;
3751 
3752 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3753 			spill_size++;
3754 
3755 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3756 			if (reg->type != SCALAR_VALUE) {
3757 				verbose_linfo(env, env->insn_idx, "; ");
3758 				verbose(env, "invalid size of register fill\n");
3759 				return -EACCES;
3760 			}
3761 
3762 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3763 			if (dst_regno < 0)
3764 				return 0;
3765 
3766 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3767 				/* The earlier check_reg_arg() has decided the
3768 				 * subreg_def for this insn.  Save it first.
3769 				 */
3770 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3771 
3772 				state->regs[dst_regno] = *reg;
3773 				state->regs[dst_regno].subreg_def = subreg_def;
3774 			} else {
3775 				for (i = 0; i < size; i++) {
3776 					type = stype[(slot - i) % BPF_REG_SIZE];
3777 					if (type == STACK_SPILL)
3778 						continue;
3779 					if (type == STACK_MISC)
3780 						continue;
3781 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3782 						off, i, size);
3783 					return -EACCES;
3784 				}
3785 				mark_reg_unknown(env, state->regs, dst_regno);
3786 			}
3787 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3788 			return 0;
3789 		}
3790 
3791 		if (dst_regno >= 0) {
3792 			/* restore register state from stack */
3793 			state->regs[dst_regno] = *reg;
3794 			/* mark reg as written since spilled pointer state likely
3795 			 * has its liveness marks cleared by is_state_visited()
3796 			 * which resets stack/reg liveness for state transitions
3797 			 */
3798 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3799 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3800 			/* If dst_regno==-1, the caller is asking us whether
3801 			 * it is acceptable to use this value as a SCALAR_VALUE
3802 			 * (e.g. for XADD).
3803 			 * We must not allow unprivileged callers to do that
3804 			 * with spilled pointers.
3805 			 */
3806 			verbose(env, "leaking pointer from stack off %d\n",
3807 				off);
3808 			return -EACCES;
3809 		}
3810 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3811 	} else {
3812 		for (i = 0; i < size; i++) {
3813 			type = stype[(slot - i) % BPF_REG_SIZE];
3814 			if (type == STACK_MISC)
3815 				continue;
3816 			if (type == STACK_ZERO)
3817 				continue;
3818 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3819 				off, i, size);
3820 			return -EACCES;
3821 		}
3822 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3823 		if (dst_regno >= 0)
3824 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3825 	}
3826 	return 0;
3827 }
3828 
3829 enum bpf_access_src {
3830 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3831 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3832 };
3833 
3834 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3835 					 int regno, int off, int access_size,
3836 					 bool zero_size_allowed,
3837 					 enum bpf_access_src type,
3838 					 struct bpf_call_arg_meta *meta);
3839 
3840 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3841 {
3842 	return cur_regs(env) + regno;
3843 }
3844 
3845 /* Read the stack at 'ptr_regno + off' and put the result into the register
3846  * 'dst_regno'.
3847  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3848  * but not its variable offset.
3849  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3850  *
3851  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3852  * filling registers (i.e. reads of spilled register cannot be detected when
3853  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3854  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3855  * offset; for a fixed offset check_stack_read_fixed_off should be used
3856  * instead.
3857  */
3858 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3859 				    int ptr_regno, int off, int size, int dst_regno)
3860 {
3861 	/* The state of the source register. */
3862 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3863 	struct bpf_func_state *ptr_state = func(env, reg);
3864 	int err;
3865 	int min_off, max_off;
3866 
3867 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3868 	 */
3869 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3870 					    false, ACCESS_DIRECT, NULL);
3871 	if (err)
3872 		return err;
3873 
3874 	min_off = reg->smin_value + off;
3875 	max_off = reg->smax_value + off;
3876 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3877 	return 0;
3878 }
3879 
3880 /* check_stack_read dispatches to check_stack_read_fixed_off or
3881  * check_stack_read_var_off.
3882  *
3883  * The caller must ensure that the offset falls within the allocated stack
3884  * bounds.
3885  *
3886  * 'dst_regno' is a register which will receive the value from the stack. It
3887  * can be -1, meaning that the read value is not going to a register.
3888  */
3889 static int check_stack_read(struct bpf_verifier_env *env,
3890 			    int ptr_regno, int off, int size,
3891 			    int dst_regno)
3892 {
3893 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3894 	struct bpf_func_state *state = func(env, reg);
3895 	int err;
3896 	/* Some accesses are only permitted with a static offset. */
3897 	bool var_off = !tnum_is_const(reg->var_off);
3898 
3899 	/* The offset is required to be static when reads don't go to a
3900 	 * register, in order to not leak pointers (see
3901 	 * check_stack_read_fixed_off).
3902 	 */
3903 	if (dst_regno < 0 && var_off) {
3904 		char tn_buf[48];
3905 
3906 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3907 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3908 			tn_buf, off, size);
3909 		return -EACCES;
3910 	}
3911 	/* Variable offset is prohibited for unprivileged mode for simplicity
3912 	 * since it requires corresponding support in Spectre masking for stack
3913 	 * ALU. See also retrieve_ptr_limit().
3914 	 */
3915 	if (!env->bypass_spec_v1 && var_off) {
3916 		char tn_buf[48];
3917 
3918 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3919 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3920 				ptr_regno, tn_buf);
3921 		return -EACCES;
3922 	}
3923 
3924 	if (!var_off) {
3925 		off += reg->var_off.value;
3926 		err = check_stack_read_fixed_off(env, state, off, size,
3927 						 dst_regno);
3928 	} else {
3929 		/* Variable offset stack reads need more conservative handling
3930 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3931 		 * branch.
3932 		 */
3933 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3934 					       dst_regno);
3935 	}
3936 	return err;
3937 }
3938 
3939 
3940 /* check_stack_write dispatches to check_stack_write_fixed_off or
3941  * check_stack_write_var_off.
3942  *
3943  * 'ptr_regno' is the register used as a pointer into the stack.
3944  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3945  * 'value_regno' is the register whose value we're writing to the stack. It can
3946  * be -1, meaning that we're not writing from a register.
3947  *
3948  * The caller must ensure that the offset falls within the maximum stack size.
3949  */
3950 static int check_stack_write(struct bpf_verifier_env *env,
3951 			     int ptr_regno, int off, int size,
3952 			     int value_regno, int insn_idx)
3953 {
3954 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3955 	struct bpf_func_state *state = func(env, reg);
3956 	int err;
3957 
3958 	if (tnum_is_const(reg->var_off)) {
3959 		off += reg->var_off.value;
3960 		err = check_stack_write_fixed_off(env, state, off, size,
3961 						  value_regno, insn_idx);
3962 	} else {
3963 		/* Variable offset stack reads need more conservative handling
3964 		 * than fixed offset ones.
3965 		 */
3966 		err = check_stack_write_var_off(env, state,
3967 						ptr_regno, off, size,
3968 						value_regno, insn_idx);
3969 	}
3970 	return err;
3971 }
3972 
3973 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3974 				 int off, int size, enum bpf_access_type type)
3975 {
3976 	struct bpf_reg_state *regs = cur_regs(env);
3977 	struct bpf_map *map = regs[regno].map_ptr;
3978 	u32 cap = bpf_map_flags_to_cap(map);
3979 
3980 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3981 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3982 			map->value_size, off, size);
3983 		return -EACCES;
3984 	}
3985 
3986 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3987 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3988 			map->value_size, off, size);
3989 		return -EACCES;
3990 	}
3991 
3992 	return 0;
3993 }
3994 
3995 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3996 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3997 			      int off, int size, u32 mem_size,
3998 			      bool zero_size_allowed)
3999 {
4000 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4001 	struct bpf_reg_state *reg;
4002 
4003 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4004 		return 0;
4005 
4006 	reg = &cur_regs(env)[regno];
4007 	switch (reg->type) {
4008 	case PTR_TO_MAP_KEY:
4009 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4010 			mem_size, off, size);
4011 		break;
4012 	case PTR_TO_MAP_VALUE:
4013 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4014 			mem_size, off, size);
4015 		break;
4016 	case PTR_TO_PACKET:
4017 	case PTR_TO_PACKET_META:
4018 	case PTR_TO_PACKET_END:
4019 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4020 			off, size, regno, reg->id, off, mem_size);
4021 		break;
4022 	case PTR_TO_MEM:
4023 	default:
4024 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4025 			mem_size, off, size);
4026 	}
4027 
4028 	return -EACCES;
4029 }
4030 
4031 /* check read/write into a memory region with possible variable offset */
4032 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4033 				   int off, int size, u32 mem_size,
4034 				   bool zero_size_allowed)
4035 {
4036 	struct bpf_verifier_state *vstate = env->cur_state;
4037 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4038 	struct bpf_reg_state *reg = &state->regs[regno];
4039 	int err;
4040 
4041 	/* We may have adjusted the register pointing to memory region, so we
4042 	 * need to try adding each of min_value and max_value to off
4043 	 * to make sure our theoretical access will be safe.
4044 	 *
4045 	 * The minimum value is only important with signed
4046 	 * comparisons where we can't assume the floor of a
4047 	 * value is 0.  If we are using signed variables for our
4048 	 * index'es we need to make sure that whatever we use
4049 	 * will have a set floor within our range.
4050 	 */
4051 	if (reg->smin_value < 0 &&
4052 	    (reg->smin_value == S64_MIN ||
4053 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4054 	      reg->smin_value + off < 0)) {
4055 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4056 			regno);
4057 		return -EACCES;
4058 	}
4059 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4060 				 mem_size, zero_size_allowed);
4061 	if (err) {
4062 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4063 			regno);
4064 		return err;
4065 	}
4066 
4067 	/* If we haven't set a max value then we need to bail since we can't be
4068 	 * sure we won't do bad things.
4069 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4070 	 */
4071 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4072 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4073 			regno);
4074 		return -EACCES;
4075 	}
4076 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4077 				 mem_size, zero_size_allowed);
4078 	if (err) {
4079 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4080 			regno);
4081 		return err;
4082 	}
4083 
4084 	return 0;
4085 }
4086 
4087 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4088 			       const struct bpf_reg_state *reg, int regno,
4089 			       bool fixed_off_ok)
4090 {
4091 	/* Access to this pointer-typed register or passing it to a helper
4092 	 * is only allowed in its original, unmodified form.
4093 	 */
4094 
4095 	if (reg->off < 0) {
4096 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4097 			reg_type_str(env, reg->type), regno, reg->off);
4098 		return -EACCES;
4099 	}
4100 
4101 	if (!fixed_off_ok && reg->off) {
4102 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4103 			reg_type_str(env, reg->type), regno, reg->off);
4104 		return -EACCES;
4105 	}
4106 
4107 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4108 		char tn_buf[48];
4109 
4110 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4111 		verbose(env, "variable %s access var_off=%s disallowed\n",
4112 			reg_type_str(env, reg->type), tn_buf);
4113 		return -EACCES;
4114 	}
4115 
4116 	return 0;
4117 }
4118 
4119 int check_ptr_off_reg(struct bpf_verifier_env *env,
4120 		      const struct bpf_reg_state *reg, int regno)
4121 {
4122 	return __check_ptr_off_reg(env, reg, regno, false);
4123 }
4124 
4125 static int map_kptr_match_type(struct bpf_verifier_env *env,
4126 			       struct btf_field *kptr_field,
4127 			       struct bpf_reg_state *reg, u32 regno)
4128 {
4129 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4130 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
4131 	const char *reg_name = "";
4132 
4133 	/* Only unreferenced case accepts untrusted pointers */
4134 	if (kptr_field->type == BPF_KPTR_UNREF)
4135 		perm_flags |= PTR_UNTRUSTED;
4136 
4137 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4138 		goto bad_type;
4139 
4140 	if (!btf_is_kernel(reg->btf)) {
4141 		verbose(env, "R%d must point to kernel BTF\n", regno);
4142 		return -EINVAL;
4143 	}
4144 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4145 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
4146 
4147 	/* For ref_ptr case, release function check should ensure we get one
4148 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4149 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4150 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4151 	 * reg->off and reg->ref_obj_id are not needed here.
4152 	 */
4153 	if (__check_ptr_off_reg(env, reg, regno, true))
4154 		return -EACCES;
4155 
4156 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4157 	 * we also need to take into account the reg->off.
4158 	 *
4159 	 * We want to support cases like:
4160 	 *
4161 	 * struct foo {
4162 	 *         struct bar br;
4163 	 *         struct baz bz;
4164 	 * };
4165 	 *
4166 	 * struct foo *v;
4167 	 * v = func();	      // PTR_TO_BTF_ID
4168 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4169 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4170 	 *                    // first member type of struct after comparison fails
4171 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4172 	 *                    // to match type
4173 	 *
4174 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4175 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4176 	 * the struct to match type against first member of struct, i.e. reject
4177 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4178 	 * strict mode to true for type match.
4179 	 */
4180 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4181 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4182 				  kptr_field->type == BPF_KPTR_REF))
4183 		goto bad_type;
4184 	return 0;
4185 bad_type:
4186 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4187 		reg_type_str(env, reg->type), reg_name);
4188 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4189 	if (kptr_field->type == BPF_KPTR_UNREF)
4190 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4191 			targ_name);
4192 	else
4193 		verbose(env, "\n");
4194 	return -EINVAL;
4195 }
4196 
4197 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4198 				 int value_regno, int insn_idx,
4199 				 struct btf_field *kptr_field)
4200 {
4201 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4202 	int class = BPF_CLASS(insn->code);
4203 	struct bpf_reg_state *val_reg;
4204 
4205 	/* Things we already checked for in check_map_access and caller:
4206 	 *  - Reject cases where variable offset may touch kptr
4207 	 *  - size of access (must be BPF_DW)
4208 	 *  - tnum_is_const(reg->var_off)
4209 	 *  - kptr_field->offset == off + reg->var_off.value
4210 	 */
4211 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4212 	if (BPF_MODE(insn->code) != BPF_MEM) {
4213 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4214 		return -EACCES;
4215 	}
4216 
4217 	/* We only allow loading referenced kptr, since it will be marked as
4218 	 * untrusted, similar to unreferenced kptr.
4219 	 */
4220 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4221 		verbose(env, "store to referenced kptr disallowed\n");
4222 		return -EACCES;
4223 	}
4224 
4225 	if (class == BPF_LDX) {
4226 		val_reg = reg_state(env, value_regno);
4227 		/* We can simply mark the value_regno receiving the pointer
4228 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4229 		 */
4230 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4231 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4232 		/* For mark_ptr_or_null_reg */
4233 		val_reg->id = ++env->id_gen;
4234 	} else if (class == BPF_STX) {
4235 		val_reg = reg_state(env, value_regno);
4236 		if (!register_is_null(val_reg) &&
4237 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4238 			return -EACCES;
4239 	} else if (class == BPF_ST) {
4240 		if (insn->imm) {
4241 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4242 				kptr_field->offset);
4243 			return -EACCES;
4244 		}
4245 	} else {
4246 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4247 		return -EACCES;
4248 	}
4249 	return 0;
4250 }
4251 
4252 /* check read/write into a map element with possible variable offset */
4253 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4254 			    int off, int size, bool zero_size_allowed,
4255 			    enum bpf_access_src src)
4256 {
4257 	struct bpf_verifier_state *vstate = env->cur_state;
4258 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4259 	struct bpf_reg_state *reg = &state->regs[regno];
4260 	struct bpf_map *map = reg->map_ptr;
4261 	struct btf_record *rec;
4262 	int err, i;
4263 
4264 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4265 				      zero_size_allowed);
4266 	if (err)
4267 		return err;
4268 
4269 	if (IS_ERR_OR_NULL(map->record))
4270 		return 0;
4271 	rec = map->record;
4272 	for (i = 0; i < rec->cnt; i++) {
4273 		struct btf_field *field = &rec->fields[i];
4274 		u32 p = field->offset;
4275 
4276 		/* If any part of a field  can be touched by load/store, reject
4277 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4278 		 * it is sufficient to check x1 < y2 && y1 < x2.
4279 		 */
4280 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4281 		    p < reg->umax_value + off + size) {
4282 			switch (field->type) {
4283 			case BPF_KPTR_UNREF:
4284 			case BPF_KPTR_REF:
4285 				if (src != ACCESS_DIRECT) {
4286 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4287 					return -EACCES;
4288 				}
4289 				if (!tnum_is_const(reg->var_off)) {
4290 					verbose(env, "kptr access cannot have variable offset\n");
4291 					return -EACCES;
4292 				}
4293 				if (p != off + reg->var_off.value) {
4294 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4295 						p, off + reg->var_off.value);
4296 					return -EACCES;
4297 				}
4298 				if (size != bpf_size_to_bytes(BPF_DW)) {
4299 					verbose(env, "kptr access size must be BPF_DW\n");
4300 					return -EACCES;
4301 				}
4302 				break;
4303 			default:
4304 				verbose(env, "%s cannot be accessed directly by load/store\n",
4305 					btf_field_type_name(field->type));
4306 				return -EACCES;
4307 			}
4308 		}
4309 	}
4310 	return 0;
4311 }
4312 
4313 #define MAX_PACKET_OFF 0xffff
4314 
4315 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4316 				       const struct bpf_call_arg_meta *meta,
4317 				       enum bpf_access_type t)
4318 {
4319 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4320 
4321 	switch (prog_type) {
4322 	/* Program types only with direct read access go here! */
4323 	case BPF_PROG_TYPE_LWT_IN:
4324 	case BPF_PROG_TYPE_LWT_OUT:
4325 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4326 	case BPF_PROG_TYPE_SK_REUSEPORT:
4327 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4328 	case BPF_PROG_TYPE_CGROUP_SKB:
4329 		if (t == BPF_WRITE)
4330 			return false;
4331 		fallthrough;
4332 
4333 	/* Program types with direct read + write access go here! */
4334 	case BPF_PROG_TYPE_SCHED_CLS:
4335 	case BPF_PROG_TYPE_SCHED_ACT:
4336 	case BPF_PROG_TYPE_XDP:
4337 	case BPF_PROG_TYPE_LWT_XMIT:
4338 	case BPF_PROG_TYPE_SK_SKB:
4339 	case BPF_PROG_TYPE_SK_MSG:
4340 		if (meta)
4341 			return meta->pkt_access;
4342 
4343 		env->seen_direct_write = true;
4344 		return true;
4345 
4346 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4347 		if (t == BPF_WRITE)
4348 			env->seen_direct_write = true;
4349 
4350 		return true;
4351 
4352 	default:
4353 		return false;
4354 	}
4355 }
4356 
4357 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4358 			       int size, bool zero_size_allowed)
4359 {
4360 	struct bpf_reg_state *regs = cur_regs(env);
4361 	struct bpf_reg_state *reg = &regs[regno];
4362 	int err;
4363 
4364 	/* We may have added a variable offset to the packet pointer; but any
4365 	 * reg->range we have comes after that.  We are only checking the fixed
4366 	 * offset.
4367 	 */
4368 
4369 	/* We don't allow negative numbers, because we aren't tracking enough
4370 	 * detail to prove they're safe.
4371 	 */
4372 	if (reg->smin_value < 0) {
4373 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4374 			regno);
4375 		return -EACCES;
4376 	}
4377 
4378 	err = reg->range < 0 ? -EINVAL :
4379 	      __check_mem_access(env, regno, off, size, reg->range,
4380 				 zero_size_allowed);
4381 	if (err) {
4382 		verbose(env, "R%d offset is outside of the packet\n", regno);
4383 		return err;
4384 	}
4385 
4386 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4387 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4388 	 * otherwise find_good_pkt_pointers would have refused to set range info
4389 	 * that __check_mem_access would have rejected this pkt access.
4390 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4391 	 */
4392 	env->prog->aux->max_pkt_offset =
4393 		max_t(u32, env->prog->aux->max_pkt_offset,
4394 		      off + reg->umax_value + size - 1);
4395 
4396 	return err;
4397 }
4398 
4399 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4400 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4401 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4402 			    struct btf **btf, u32 *btf_id)
4403 {
4404 	struct bpf_insn_access_aux info = {
4405 		.reg_type = *reg_type,
4406 		.log = &env->log,
4407 	};
4408 
4409 	if (env->ops->is_valid_access &&
4410 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4411 		/* A non zero info.ctx_field_size indicates that this field is a
4412 		 * candidate for later verifier transformation to load the whole
4413 		 * field and then apply a mask when accessed with a narrower
4414 		 * access than actual ctx access size. A zero info.ctx_field_size
4415 		 * will only allow for whole field access and rejects any other
4416 		 * type of narrower access.
4417 		 */
4418 		*reg_type = info.reg_type;
4419 
4420 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4421 			*btf = info.btf;
4422 			*btf_id = info.btf_id;
4423 		} else {
4424 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4425 		}
4426 		/* remember the offset of last byte accessed in ctx */
4427 		if (env->prog->aux->max_ctx_offset < off + size)
4428 			env->prog->aux->max_ctx_offset = off + size;
4429 		return 0;
4430 	}
4431 
4432 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4433 	return -EACCES;
4434 }
4435 
4436 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4437 				  int size)
4438 {
4439 	if (size < 0 || off < 0 ||
4440 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4441 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4442 			off, size);
4443 		return -EACCES;
4444 	}
4445 	return 0;
4446 }
4447 
4448 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4449 			     u32 regno, int off, int size,
4450 			     enum bpf_access_type t)
4451 {
4452 	struct bpf_reg_state *regs = cur_regs(env);
4453 	struct bpf_reg_state *reg = &regs[regno];
4454 	struct bpf_insn_access_aux info = {};
4455 	bool valid;
4456 
4457 	if (reg->smin_value < 0) {
4458 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4459 			regno);
4460 		return -EACCES;
4461 	}
4462 
4463 	switch (reg->type) {
4464 	case PTR_TO_SOCK_COMMON:
4465 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4466 		break;
4467 	case PTR_TO_SOCKET:
4468 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4469 		break;
4470 	case PTR_TO_TCP_SOCK:
4471 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4472 		break;
4473 	case PTR_TO_XDP_SOCK:
4474 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4475 		break;
4476 	default:
4477 		valid = false;
4478 	}
4479 
4480 
4481 	if (valid) {
4482 		env->insn_aux_data[insn_idx].ctx_field_size =
4483 			info.ctx_field_size;
4484 		return 0;
4485 	}
4486 
4487 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4488 		regno, reg_type_str(env, reg->type), off, size);
4489 
4490 	return -EACCES;
4491 }
4492 
4493 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4494 {
4495 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4496 }
4497 
4498 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4499 {
4500 	const struct bpf_reg_state *reg = reg_state(env, regno);
4501 
4502 	return reg->type == PTR_TO_CTX;
4503 }
4504 
4505 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4506 {
4507 	const struct bpf_reg_state *reg = reg_state(env, regno);
4508 
4509 	return type_is_sk_pointer(reg->type);
4510 }
4511 
4512 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4513 {
4514 	const struct bpf_reg_state *reg = reg_state(env, regno);
4515 
4516 	return type_is_pkt_pointer(reg->type);
4517 }
4518 
4519 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4520 {
4521 	const struct bpf_reg_state *reg = reg_state(env, regno);
4522 
4523 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4524 	return reg->type == PTR_TO_FLOW_KEYS;
4525 }
4526 
4527 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4528 {
4529 	/* A referenced register is always trusted. */
4530 	if (reg->ref_obj_id)
4531 		return true;
4532 
4533 	/* If a register is not referenced, it is trusted if it has the
4534 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4535 	 * other type modifiers may be safe, but we elect to take an opt-in
4536 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4537 	 * not.
4538 	 *
4539 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4540 	 * for whether a register is trusted.
4541 	 */
4542 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4543 	       !bpf_type_has_unsafe_modifiers(reg->type);
4544 }
4545 
4546 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4547 {
4548 	return reg->type & MEM_RCU;
4549 }
4550 
4551 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4552 				   const struct bpf_reg_state *reg,
4553 				   int off, int size, bool strict)
4554 {
4555 	struct tnum reg_off;
4556 	int ip_align;
4557 
4558 	/* Byte size accesses are always allowed. */
4559 	if (!strict || size == 1)
4560 		return 0;
4561 
4562 	/* For platforms that do not have a Kconfig enabling
4563 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4564 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4565 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4566 	 * to this code only in strict mode where we want to emulate
4567 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4568 	 * unconditional IP align value of '2'.
4569 	 */
4570 	ip_align = 2;
4571 
4572 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4573 	if (!tnum_is_aligned(reg_off, size)) {
4574 		char tn_buf[48];
4575 
4576 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4577 		verbose(env,
4578 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4579 			ip_align, tn_buf, reg->off, off, size);
4580 		return -EACCES;
4581 	}
4582 
4583 	return 0;
4584 }
4585 
4586 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4587 				       const struct bpf_reg_state *reg,
4588 				       const char *pointer_desc,
4589 				       int off, int size, bool strict)
4590 {
4591 	struct tnum reg_off;
4592 
4593 	/* Byte size accesses are always allowed. */
4594 	if (!strict || size == 1)
4595 		return 0;
4596 
4597 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4598 	if (!tnum_is_aligned(reg_off, size)) {
4599 		char tn_buf[48];
4600 
4601 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4602 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4603 			pointer_desc, tn_buf, reg->off, off, size);
4604 		return -EACCES;
4605 	}
4606 
4607 	return 0;
4608 }
4609 
4610 static int check_ptr_alignment(struct bpf_verifier_env *env,
4611 			       const struct bpf_reg_state *reg, int off,
4612 			       int size, bool strict_alignment_once)
4613 {
4614 	bool strict = env->strict_alignment || strict_alignment_once;
4615 	const char *pointer_desc = "";
4616 
4617 	switch (reg->type) {
4618 	case PTR_TO_PACKET:
4619 	case PTR_TO_PACKET_META:
4620 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4621 		 * right in front, treat it the very same way.
4622 		 */
4623 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4624 	case PTR_TO_FLOW_KEYS:
4625 		pointer_desc = "flow keys ";
4626 		break;
4627 	case PTR_TO_MAP_KEY:
4628 		pointer_desc = "key ";
4629 		break;
4630 	case PTR_TO_MAP_VALUE:
4631 		pointer_desc = "value ";
4632 		break;
4633 	case PTR_TO_CTX:
4634 		pointer_desc = "context ";
4635 		break;
4636 	case PTR_TO_STACK:
4637 		pointer_desc = "stack ";
4638 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4639 		 * and check_stack_read_fixed_off() relies on stack accesses being
4640 		 * aligned.
4641 		 */
4642 		strict = true;
4643 		break;
4644 	case PTR_TO_SOCKET:
4645 		pointer_desc = "sock ";
4646 		break;
4647 	case PTR_TO_SOCK_COMMON:
4648 		pointer_desc = "sock_common ";
4649 		break;
4650 	case PTR_TO_TCP_SOCK:
4651 		pointer_desc = "tcp_sock ";
4652 		break;
4653 	case PTR_TO_XDP_SOCK:
4654 		pointer_desc = "xdp_sock ";
4655 		break;
4656 	default:
4657 		break;
4658 	}
4659 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4660 					   strict);
4661 }
4662 
4663 static int update_stack_depth(struct bpf_verifier_env *env,
4664 			      const struct bpf_func_state *func,
4665 			      int off)
4666 {
4667 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4668 
4669 	if (stack >= -off)
4670 		return 0;
4671 
4672 	/* update known max for given subprogram */
4673 	env->subprog_info[func->subprogno].stack_depth = -off;
4674 	return 0;
4675 }
4676 
4677 /* starting from main bpf function walk all instructions of the function
4678  * and recursively walk all callees that given function can call.
4679  * Ignore jump and exit insns.
4680  * Since recursion is prevented by check_cfg() this algorithm
4681  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4682  */
4683 static int check_max_stack_depth(struct bpf_verifier_env *env)
4684 {
4685 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4686 	struct bpf_subprog_info *subprog = env->subprog_info;
4687 	struct bpf_insn *insn = env->prog->insnsi;
4688 	bool tail_call_reachable = false;
4689 	int ret_insn[MAX_CALL_FRAMES];
4690 	int ret_prog[MAX_CALL_FRAMES];
4691 	int j;
4692 
4693 process_func:
4694 	/* protect against potential stack overflow that might happen when
4695 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4696 	 * depth for such case down to 256 so that the worst case scenario
4697 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4698 	 * 8k).
4699 	 *
4700 	 * To get the idea what might happen, see an example:
4701 	 * func1 -> sub rsp, 128
4702 	 *  subfunc1 -> sub rsp, 256
4703 	 *  tailcall1 -> add rsp, 256
4704 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4705 	 *   subfunc2 -> sub rsp, 64
4706 	 *   subfunc22 -> sub rsp, 128
4707 	 *   tailcall2 -> add rsp, 128
4708 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4709 	 *
4710 	 * tailcall will unwind the current stack frame but it will not get rid
4711 	 * of caller's stack as shown on the example above.
4712 	 */
4713 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4714 		verbose(env,
4715 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4716 			depth);
4717 		return -EACCES;
4718 	}
4719 	/* round up to 32-bytes, since this is granularity
4720 	 * of interpreter stack size
4721 	 */
4722 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4723 	if (depth > MAX_BPF_STACK) {
4724 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4725 			frame + 1, depth);
4726 		return -EACCES;
4727 	}
4728 continue_func:
4729 	subprog_end = subprog[idx + 1].start;
4730 	for (; i < subprog_end; i++) {
4731 		int next_insn;
4732 
4733 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4734 			continue;
4735 		/* remember insn and function to return to */
4736 		ret_insn[frame] = i + 1;
4737 		ret_prog[frame] = idx;
4738 
4739 		/* find the callee */
4740 		next_insn = i + insn[i].imm + 1;
4741 		idx = find_subprog(env, next_insn);
4742 		if (idx < 0) {
4743 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4744 				  next_insn);
4745 			return -EFAULT;
4746 		}
4747 		if (subprog[idx].is_async_cb) {
4748 			if (subprog[idx].has_tail_call) {
4749 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4750 				return -EFAULT;
4751 			}
4752 			 /* async callbacks don't increase bpf prog stack size */
4753 			continue;
4754 		}
4755 		i = next_insn;
4756 
4757 		if (subprog[idx].has_tail_call)
4758 			tail_call_reachable = true;
4759 
4760 		frame++;
4761 		if (frame >= MAX_CALL_FRAMES) {
4762 			verbose(env, "the call stack of %d frames is too deep !\n",
4763 				frame);
4764 			return -E2BIG;
4765 		}
4766 		goto process_func;
4767 	}
4768 	/* if tail call got detected across bpf2bpf calls then mark each of the
4769 	 * currently present subprog frames as tail call reachable subprogs;
4770 	 * this info will be utilized by JIT so that we will be preserving the
4771 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4772 	 */
4773 	if (tail_call_reachable)
4774 		for (j = 0; j < frame; j++)
4775 			subprog[ret_prog[j]].tail_call_reachable = true;
4776 	if (subprog[0].tail_call_reachable)
4777 		env->prog->aux->tail_call_reachable = true;
4778 
4779 	/* end of for() loop means the last insn of the 'subprog'
4780 	 * was reached. Doesn't matter whether it was JA or EXIT
4781 	 */
4782 	if (frame == 0)
4783 		return 0;
4784 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4785 	frame--;
4786 	i = ret_insn[frame];
4787 	idx = ret_prog[frame];
4788 	goto continue_func;
4789 }
4790 
4791 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4792 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4793 				  const struct bpf_insn *insn, int idx)
4794 {
4795 	int start = idx + insn->imm + 1, subprog;
4796 
4797 	subprog = find_subprog(env, start);
4798 	if (subprog < 0) {
4799 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4800 			  start);
4801 		return -EFAULT;
4802 	}
4803 	return env->subprog_info[subprog].stack_depth;
4804 }
4805 #endif
4806 
4807 static int __check_buffer_access(struct bpf_verifier_env *env,
4808 				 const char *buf_info,
4809 				 const struct bpf_reg_state *reg,
4810 				 int regno, int off, int size)
4811 {
4812 	if (off < 0) {
4813 		verbose(env,
4814 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4815 			regno, buf_info, off, size);
4816 		return -EACCES;
4817 	}
4818 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4819 		char tn_buf[48];
4820 
4821 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4822 		verbose(env,
4823 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4824 			regno, off, tn_buf);
4825 		return -EACCES;
4826 	}
4827 
4828 	return 0;
4829 }
4830 
4831 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4832 				  const struct bpf_reg_state *reg,
4833 				  int regno, int off, int size)
4834 {
4835 	int err;
4836 
4837 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4838 	if (err)
4839 		return err;
4840 
4841 	if (off + size > env->prog->aux->max_tp_access)
4842 		env->prog->aux->max_tp_access = off + size;
4843 
4844 	return 0;
4845 }
4846 
4847 static int check_buffer_access(struct bpf_verifier_env *env,
4848 			       const struct bpf_reg_state *reg,
4849 			       int regno, int off, int size,
4850 			       bool zero_size_allowed,
4851 			       u32 *max_access)
4852 {
4853 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4854 	int err;
4855 
4856 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4857 	if (err)
4858 		return err;
4859 
4860 	if (off + size > *max_access)
4861 		*max_access = off + size;
4862 
4863 	return 0;
4864 }
4865 
4866 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4867 static void zext_32_to_64(struct bpf_reg_state *reg)
4868 {
4869 	reg->var_off = tnum_subreg(reg->var_off);
4870 	__reg_assign_32_into_64(reg);
4871 }
4872 
4873 /* truncate register to smaller size (in bytes)
4874  * must be called with size < BPF_REG_SIZE
4875  */
4876 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4877 {
4878 	u64 mask;
4879 
4880 	/* clear high bits in bit representation */
4881 	reg->var_off = tnum_cast(reg->var_off, size);
4882 
4883 	/* fix arithmetic bounds */
4884 	mask = ((u64)1 << (size * 8)) - 1;
4885 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4886 		reg->umin_value &= mask;
4887 		reg->umax_value &= mask;
4888 	} else {
4889 		reg->umin_value = 0;
4890 		reg->umax_value = mask;
4891 	}
4892 	reg->smin_value = reg->umin_value;
4893 	reg->smax_value = reg->umax_value;
4894 
4895 	/* If size is smaller than 32bit register the 32bit register
4896 	 * values are also truncated so we push 64-bit bounds into
4897 	 * 32-bit bounds. Above were truncated < 32-bits already.
4898 	 */
4899 	if (size >= 4)
4900 		return;
4901 	__reg_combine_64_into_32(reg);
4902 }
4903 
4904 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4905 {
4906 	/* A map is considered read-only if the following condition are true:
4907 	 *
4908 	 * 1) BPF program side cannot change any of the map content. The
4909 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4910 	 *    and was set at map creation time.
4911 	 * 2) The map value(s) have been initialized from user space by a
4912 	 *    loader and then "frozen", such that no new map update/delete
4913 	 *    operations from syscall side are possible for the rest of
4914 	 *    the map's lifetime from that point onwards.
4915 	 * 3) Any parallel/pending map update/delete operations from syscall
4916 	 *    side have been completed. Only after that point, it's safe to
4917 	 *    assume that map value(s) are immutable.
4918 	 */
4919 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4920 	       READ_ONCE(map->frozen) &&
4921 	       !bpf_map_write_active(map);
4922 }
4923 
4924 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4925 {
4926 	void *ptr;
4927 	u64 addr;
4928 	int err;
4929 
4930 	err = map->ops->map_direct_value_addr(map, &addr, off);
4931 	if (err)
4932 		return err;
4933 	ptr = (void *)(long)addr + off;
4934 
4935 	switch (size) {
4936 	case sizeof(u8):
4937 		*val = (u64)*(u8 *)ptr;
4938 		break;
4939 	case sizeof(u16):
4940 		*val = (u64)*(u16 *)ptr;
4941 		break;
4942 	case sizeof(u32):
4943 		*val = (u64)*(u32 *)ptr;
4944 		break;
4945 	case sizeof(u64):
4946 		*val = *(u64 *)ptr;
4947 		break;
4948 	default:
4949 		return -EINVAL;
4950 	}
4951 	return 0;
4952 }
4953 
4954 #define BTF_TYPE_SAFE_NESTED(__type)  __PASTE(__type, __safe_fields)
4955 
4956 BTF_TYPE_SAFE_NESTED(struct task_struct) {
4957 	const cpumask_t *cpus_ptr;
4958 };
4959 
4960 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env,
4961 				  struct bpf_reg_state *reg,
4962 				  int off)
4963 {
4964 	/* If its parent is not trusted, it can't regain its trusted status. */
4965 	if (!is_trusted_reg(reg))
4966 		return false;
4967 
4968 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct));
4969 
4970 	return btf_nested_type_is_trusted(&env->log, reg, off);
4971 }
4972 
4973 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4974 				   struct bpf_reg_state *regs,
4975 				   int regno, int off, int size,
4976 				   enum bpf_access_type atype,
4977 				   int value_regno)
4978 {
4979 	struct bpf_reg_state *reg = regs + regno;
4980 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4981 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4982 	enum bpf_type_flag flag = 0;
4983 	u32 btf_id;
4984 	int ret;
4985 
4986 	if (!env->allow_ptr_leaks) {
4987 		verbose(env,
4988 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4989 			tname);
4990 		return -EPERM;
4991 	}
4992 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4993 		verbose(env,
4994 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4995 			tname);
4996 		return -EINVAL;
4997 	}
4998 	if (off < 0) {
4999 		verbose(env,
5000 			"R%d is ptr_%s invalid negative access: off=%d\n",
5001 			regno, tname, off);
5002 		return -EACCES;
5003 	}
5004 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5005 		char tn_buf[48];
5006 
5007 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5008 		verbose(env,
5009 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5010 			regno, tname, off, tn_buf);
5011 		return -EACCES;
5012 	}
5013 
5014 	if (reg->type & MEM_USER) {
5015 		verbose(env,
5016 			"R%d is ptr_%s access user memory: off=%d\n",
5017 			regno, tname, off);
5018 		return -EACCES;
5019 	}
5020 
5021 	if (reg->type & MEM_PERCPU) {
5022 		verbose(env,
5023 			"R%d is ptr_%s access percpu memory: off=%d\n",
5024 			regno, tname, off);
5025 		return -EACCES;
5026 	}
5027 
5028 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5029 		if (!btf_is_kernel(reg->btf)) {
5030 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5031 			return -EFAULT;
5032 		}
5033 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5034 	} else {
5035 		/* Writes are permitted with default btf_struct_access for
5036 		 * program allocated objects (which always have ref_obj_id > 0),
5037 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5038 		 */
5039 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5040 			verbose(env, "only read is supported\n");
5041 			return -EACCES;
5042 		}
5043 
5044 		if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
5045 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5046 			return -EFAULT;
5047 		}
5048 
5049 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5050 	}
5051 
5052 	if (ret < 0)
5053 		return ret;
5054 
5055 	/* If this is an untrusted pointer, all pointers formed by walking it
5056 	 * also inherit the untrusted flag.
5057 	 */
5058 	if (type_flag(reg->type) & PTR_UNTRUSTED)
5059 		flag |= PTR_UNTRUSTED;
5060 
5061 	/* By default any pointer obtained from walking a trusted pointer is no
5062 	 * longer trusted, unless the field being accessed has explicitly been
5063 	 * marked as inheriting its parent's state of trust.
5064 	 *
5065 	 * An RCU-protected pointer can also be deemed trusted if we are in an
5066 	 * RCU read region. This case is handled below.
5067 	 */
5068 	if (nested_ptr_is_trusted(env, reg, off))
5069 		flag |= PTR_TRUSTED;
5070 	else
5071 		flag &= ~PTR_TRUSTED;
5072 
5073 	if (flag & MEM_RCU) {
5074 		/* Mark value register as MEM_RCU only if it is protected by
5075 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
5076 		 * itself can already indicate trustedness inside the rcu
5077 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
5078 		 * it could be null in some cases.
5079 		 */
5080 		if (!env->cur_state->active_rcu_lock ||
5081 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
5082 			flag &= ~MEM_RCU;
5083 		else
5084 			flag |= PTR_MAYBE_NULL;
5085 	} else if (reg->type & MEM_RCU) {
5086 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
5087 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
5088 		 */
5089 		flag |= PTR_UNTRUSTED;
5090 	}
5091 
5092 	if (atype == BPF_READ && value_regno >= 0)
5093 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5094 
5095 	return 0;
5096 }
5097 
5098 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5099 				   struct bpf_reg_state *regs,
5100 				   int regno, int off, int size,
5101 				   enum bpf_access_type atype,
5102 				   int value_regno)
5103 {
5104 	struct bpf_reg_state *reg = regs + regno;
5105 	struct bpf_map *map = reg->map_ptr;
5106 	struct bpf_reg_state map_reg;
5107 	enum bpf_type_flag flag = 0;
5108 	const struct btf_type *t;
5109 	const char *tname;
5110 	u32 btf_id;
5111 	int ret;
5112 
5113 	if (!btf_vmlinux) {
5114 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5115 		return -ENOTSUPP;
5116 	}
5117 
5118 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5119 		verbose(env, "map_ptr access not supported for map type %d\n",
5120 			map->map_type);
5121 		return -ENOTSUPP;
5122 	}
5123 
5124 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5125 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5126 
5127 	if (!env->allow_ptr_leaks) {
5128 		verbose(env,
5129 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5130 			tname);
5131 		return -EPERM;
5132 	}
5133 
5134 	if (off < 0) {
5135 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5136 			regno, tname, off);
5137 		return -EACCES;
5138 	}
5139 
5140 	if (atype != BPF_READ) {
5141 		verbose(env, "only read from %s is supported\n", tname);
5142 		return -EACCES;
5143 	}
5144 
5145 	/* Simulate access to a PTR_TO_BTF_ID */
5146 	memset(&map_reg, 0, sizeof(map_reg));
5147 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5148 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5149 	if (ret < 0)
5150 		return ret;
5151 
5152 	if (value_regno >= 0)
5153 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5154 
5155 	return 0;
5156 }
5157 
5158 /* Check that the stack access at the given offset is within bounds. The
5159  * maximum valid offset is -1.
5160  *
5161  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5162  * -state->allocated_stack for reads.
5163  */
5164 static int check_stack_slot_within_bounds(int off,
5165 					  struct bpf_func_state *state,
5166 					  enum bpf_access_type t)
5167 {
5168 	int min_valid_off;
5169 
5170 	if (t == BPF_WRITE)
5171 		min_valid_off = -MAX_BPF_STACK;
5172 	else
5173 		min_valid_off = -state->allocated_stack;
5174 
5175 	if (off < min_valid_off || off > -1)
5176 		return -EACCES;
5177 	return 0;
5178 }
5179 
5180 /* Check that the stack access at 'regno + off' falls within the maximum stack
5181  * bounds.
5182  *
5183  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5184  */
5185 static int check_stack_access_within_bounds(
5186 		struct bpf_verifier_env *env,
5187 		int regno, int off, int access_size,
5188 		enum bpf_access_src src, enum bpf_access_type type)
5189 {
5190 	struct bpf_reg_state *regs = cur_regs(env);
5191 	struct bpf_reg_state *reg = regs + regno;
5192 	struct bpf_func_state *state = func(env, reg);
5193 	int min_off, max_off;
5194 	int err;
5195 	char *err_extra;
5196 
5197 	if (src == ACCESS_HELPER)
5198 		/* We don't know if helpers are reading or writing (or both). */
5199 		err_extra = " indirect access to";
5200 	else if (type == BPF_READ)
5201 		err_extra = " read from";
5202 	else
5203 		err_extra = " write to";
5204 
5205 	if (tnum_is_const(reg->var_off)) {
5206 		min_off = reg->var_off.value + off;
5207 		if (access_size > 0)
5208 			max_off = min_off + access_size - 1;
5209 		else
5210 			max_off = min_off;
5211 	} else {
5212 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5213 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5214 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5215 				err_extra, regno);
5216 			return -EACCES;
5217 		}
5218 		min_off = reg->smin_value + off;
5219 		if (access_size > 0)
5220 			max_off = reg->smax_value + off + access_size - 1;
5221 		else
5222 			max_off = min_off;
5223 	}
5224 
5225 	err = check_stack_slot_within_bounds(min_off, state, type);
5226 	if (!err)
5227 		err = check_stack_slot_within_bounds(max_off, state, type);
5228 
5229 	if (err) {
5230 		if (tnum_is_const(reg->var_off)) {
5231 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5232 				err_extra, regno, off, access_size);
5233 		} else {
5234 			char tn_buf[48];
5235 
5236 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5237 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5238 				err_extra, regno, tn_buf, access_size);
5239 		}
5240 	}
5241 	return err;
5242 }
5243 
5244 /* check whether memory at (regno + off) is accessible for t = (read | write)
5245  * if t==write, value_regno is a register which value is stored into memory
5246  * if t==read, value_regno is a register which will receive the value from memory
5247  * if t==write && value_regno==-1, some unknown value is stored into memory
5248  * if t==read && value_regno==-1, don't care what we read from memory
5249  */
5250 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5251 			    int off, int bpf_size, enum bpf_access_type t,
5252 			    int value_regno, bool strict_alignment_once)
5253 {
5254 	struct bpf_reg_state *regs = cur_regs(env);
5255 	struct bpf_reg_state *reg = regs + regno;
5256 	struct bpf_func_state *state;
5257 	int size, err = 0;
5258 
5259 	size = bpf_size_to_bytes(bpf_size);
5260 	if (size < 0)
5261 		return size;
5262 
5263 	/* alignment checks will add in reg->off themselves */
5264 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5265 	if (err)
5266 		return err;
5267 
5268 	/* for access checks, reg->off is just part of off */
5269 	off += reg->off;
5270 
5271 	if (reg->type == PTR_TO_MAP_KEY) {
5272 		if (t == BPF_WRITE) {
5273 			verbose(env, "write to change key R%d not allowed\n", regno);
5274 			return -EACCES;
5275 		}
5276 
5277 		err = check_mem_region_access(env, regno, off, size,
5278 					      reg->map_ptr->key_size, false);
5279 		if (err)
5280 			return err;
5281 		if (value_regno >= 0)
5282 			mark_reg_unknown(env, regs, value_regno);
5283 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5284 		struct btf_field *kptr_field = NULL;
5285 
5286 		if (t == BPF_WRITE && value_regno >= 0 &&
5287 		    is_pointer_value(env, value_regno)) {
5288 			verbose(env, "R%d leaks addr into map\n", value_regno);
5289 			return -EACCES;
5290 		}
5291 		err = check_map_access_type(env, regno, off, size, t);
5292 		if (err)
5293 			return err;
5294 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5295 		if (err)
5296 			return err;
5297 		if (tnum_is_const(reg->var_off))
5298 			kptr_field = btf_record_find(reg->map_ptr->record,
5299 						     off + reg->var_off.value, BPF_KPTR);
5300 		if (kptr_field) {
5301 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5302 		} else if (t == BPF_READ && value_regno >= 0) {
5303 			struct bpf_map *map = reg->map_ptr;
5304 
5305 			/* if map is read-only, track its contents as scalars */
5306 			if (tnum_is_const(reg->var_off) &&
5307 			    bpf_map_is_rdonly(map) &&
5308 			    map->ops->map_direct_value_addr) {
5309 				int map_off = off + reg->var_off.value;
5310 				u64 val = 0;
5311 
5312 				err = bpf_map_direct_read(map, map_off, size,
5313 							  &val);
5314 				if (err)
5315 					return err;
5316 
5317 				regs[value_regno].type = SCALAR_VALUE;
5318 				__mark_reg_known(&regs[value_regno], val);
5319 			} else {
5320 				mark_reg_unknown(env, regs, value_regno);
5321 			}
5322 		}
5323 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5324 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5325 
5326 		if (type_may_be_null(reg->type)) {
5327 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5328 				reg_type_str(env, reg->type));
5329 			return -EACCES;
5330 		}
5331 
5332 		if (t == BPF_WRITE && rdonly_mem) {
5333 			verbose(env, "R%d cannot write into %s\n",
5334 				regno, reg_type_str(env, reg->type));
5335 			return -EACCES;
5336 		}
5337 
5338 		if (t == BPF_WRITE && value_regno >= 0 &&
5339 		    is_pointer_value(env, value_regno)) {
5340 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5341 			return -EACCES;
5342 		}
5343 
5344 		err = check_mem_region_access(env, regno, off, size,
5345 					      reg->mem_size, false);
5346 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5347 			mark_reg_unknown(env, regs, value_regno);
5348 	} else if (reg->type == PTR_TO_CTX) {
5349 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5350 		struct btf *btf = NULL;
5351 		u32 btf_id = 0;
5352 
5353 		if (t == BPF_WRITE && value_regno >= 0 &&
5354 		    is_pointer_value(env, value_regno)) {
5355 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5356 			return -EACCES;
5357 		}
5358 
5359 		err = check_ptr_off_reg(env, reg, regno);
5360 		if (err < 0)
5361 			return err;
5362 
5363 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5364 				       &btf_id);
5365 		if (err)
5366 			verbose_linfo(env, insn_idx, "; ");
5367 		if (!err && t == BPF_READ && value_regno >= 0) {
5368 			/* ctx access returns either a scalar, or a
5369 			 * PTR_TO_PACKET[_META,_END]. In the latter
5370 			 * case, we know the offset is zero.
5371 			 */
5372 			if (reg_type == SCALAR_VALUE) {
5373 				mark_reg_unknown(env, regs, value_regno);
5374 			} else {
5375 				mark_reg_known_zero(env, regs,
5376 						    value_regno);
5377 				if (type_may_be_null(reg_type))
5378 					regs[value_regno].id = ++env->id_gen;
5379 				/* A load of ctx field could have different
5380 				 * actual load size with the one encoded in the
5381 				 * insn. When the dst is PTR, it is for sure not
5382 				 * a sub-register.
5383 				 */
5384 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5385 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5386 					regs[value_regno].btf = btf;
5387 					regs[value_regno].btf_id = btf_id;
5388 				}
5389 			}
5390 			regs[value_regno].type = reg_type;
5391 		}
5392 
5393 	} else if (reg->type == PTR_TO_STACK) {
5394 		/* Basic bounds checks. */
5395 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5396 		if (err)
5397 			return err;
5398 
5399 		state = func(env, reg);
5400 		err = update_stack_depth(env, state, off);
5401 		if (err)
5402 			return err;
5403 
5404 		if (t == BPF_READ)
5405 			err = check_stack_read(env, regno, off, size,
5406 					       value_regno);
5407 		else
5408 			err = check_stack_write(env, regno, off, size,
5409 						value_regno, insn_idx);
5410 	} else if (reg_is_pkt_pointer(reg)) {
5411 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5412 			verbose(env, "cannot write into packet\n");
5413 			return -EACCES;
5414 		}
5415 		if (t == BPF_WRITE && value_regno >= 0 &&
5416 		    is_pointer_value(env, value_regno)) {
5417 			verbose(env, "R%d leaks addr into packet\n",
5418 				value_regno);
5419 			return -EACCES;
5420 		}
5421 		err = check_packet_access(env, regno, off, size, false);
5422 		if (!err && t == BPF_READ && value_regno >= 0)
5423 			mark_reg_unknown(env, regs, value_regno);
5424 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5425 		if (t == BPF_WRITE && value_regno >= 0 &&
5426 		    is_pointer_value(env, value_regno)) {
5427 			verbose(env, "R%d leaks addr into flow keys\n",
5428 				value_regno);
5429 			return -EACCES;
5430 		}
5431 
5432 		err = check_flow_keys_access(env, off, size);
5433 		if (!err && t == BPF_READ && value_regno >= 0)
5434 			mark_reg_unknown(env, regs, value_regno);
5435 	} else if (type_is_sk_pointer(reg->type)) {
5436 		if (t == BPF_WRITE) {
5437 			verbose(env, "R%d cannot write into %s\n",
5438 				regno, reg_type_str(env, reg->type));
5439 			return -EACCES;
5440 		}
5441 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5442 		if (!err && value_regno >= 0)
5443 			mark_reg_unknown(env, regs, value_regno);
5444 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5445 		err = check_tp_buffer_access(env, reg, regno, off, size);
5446 		if (!err && t == BPF_READ && value_regno >= 0)
5447 			mark_reg_unknown(env, regs, value_regno);
5448 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5449 		   !type_may_be_null(reg->type)) {
5450 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5451 					      value_regno);
5452 	} else if (reg->type == CONST_PTR_TO_MAP) {
5453 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5454 					      value_regno);
5455 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5456 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5457 		u32 *max_access;
5458 
5459 		if (rdonly_mem) {
5460 			if (t == BPF_WRITE) {
5461 				verbose(env, "R%d cannot write into %s\n",
5462 					regno, reg_type_str(env, reg->type));
5463 				return -EACCES;
5464 			}
5465 			max_access = &env->prog->aux->max_rdonly_access;
5466 		} else {
5467 			max_access = &env->prog->aux->max_rdwr_access;
5468 		}
5469 
5470 		err = check_buffer_access(env, reg, regno, off, size, false,
5471 					  max_access);
5472 
5473 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5474 			mark_reg_unknown(env, regs, value_regno);
5475 	} else {
5476 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5477 			reg_type_str(env, reg->type));
5478 		return -EACCES;
5479 	}
5480 
5481 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5482 	    regs[value_regno].type == SCALAR_VALUE) {
5483 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5484 		coerce_reg_to_size(&regs[value_regno], size);
5485 	}
5486 	return err;
5487 }
5488 
5489 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5490 {
5491 	int load_reg;
5492 	int err;
5493 
5494 	switch (insn->imm) {
5495 	case BPF_ADD:
5496 	case BPF_ADD | BPF_FETCH:
5497 	case BPF_AND:
5498 	case BPF_AND | BPF_FETCH:
5499 	case BPF_OR:
5500 	case BPF_OR | BPF_FETCH:
5501 	case BPF_XOR:
5502 	case BPF_XOR | BPF_FETCH:
5503 	case BPF_XCHG:
5504 	case BPF_CMPXCHG:
5505 		break;
5506 	default:
5507 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5508 		return -EINVAL;
5509 	}
5510 
5511 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5512 		verbose(env, "invalid atomic operand size\n");
5513 		return -EINVAL;
5514 	}
5515 
5516 	/* check src1 operand */
5517 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5518 	if (err)
5519 		return err;
5520 
5521 	/* check src2 operand */
5522 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5523 	if (err)
5524 		return err;
5525 
5526 	if (insn->imm == BPF_CMPXCHG) {
5527 		/* Check comparison of R0 with memory location */
5528 		const u32 aux_reg = BPF_REG_0;
5529 
5530 		err = check_reg_arg(env, aux_reg, SRC_OP);
5531 		if (err)
5532 			return err;
5533 
5534 		if (is_pointer_value(env, aux_reg)) {
5535 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5536 			return -EACCES;
5537 		}
5538 	}
5539 
5540 	if (is_pointer_value(env, insn->src_reg)) {
5541 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5542 		return -EACCES;
5543 	}
5544 
5545 	if (is_ctx_reg(env, insn->dst_reg) ||
5546 	    is_pkt_reg(env, insn->dst_reg) ||
5547 	    is_flow_key_reg(env, insn->dst_reg) ||
5548 	    is_sk_reg(env, insn->dst_reg)) {
5549 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5550 			insn->dst_reg,
5551 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5552 		return -EACCES;
5553 	}
5554 
5555 	if (insn->imm & BPF_FETCH) {
5556 		if (insn->imm == BPF_CMPXCHG)
5557 			load_reg = BPF_REG_0;
5558 		else
5559 			load_reg = insn->src_reg;
5560 
5561 		/* check and record load of old value */
5562 		err = check_reg_arg(env, load_reg, DST_OP);
5563 		if (err)
5564 			return err;
5565 	} else {
5566 		/* This instruction accesses a memory location but doesn't
5567 		 * actually load it into a register.
5568 		 */
5569 		load_reg = -1;
5570 	}
5571 
5572 	/* Check whether we can read the memory, with second call for fetch
5573 	 * case to simulate the register fill.
5574 	 */
5575 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5576 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5577 	if (!err && load_reg >= 0)
5578 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5579 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5580 				       true);
5581 	if (err)
5582 		return err;
5583 
5584 	/* Check whether we can write into the same memory. */
5585 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5586 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5587 	if (err)
5588 		return err;
5589 
5590 	return 0;
5591 }
5592 
5593 /* When register 'regno' is used to read the stack (either directly or through
5594  * a helper function) make sure that it's within stack boundary and, depending
5595  * on the access type, that all elements of the stack are initialized.
5596  *
5597  * 'off' includes 'regno->off', but not its dynamic part (if any).
5598  *
5599  * All registers that have been spilled on the stack in the slots within the
5600  * read offsets are marked as read.
5601  */
5602 static int check_stack_range_initialized(
5603 		struct bpf_verifier_env *env, int regno, int off,
5604 		int access_size, bool zero_size_allowed,
5605 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5606 {
5607 	struct bpf_reg_state *reg = reg_state(env, regno);
5608 	struct bpf_func_state *state = func(env, reg);
5609 	int err, min_off, max_off, i, j, slot, spi;
5610 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5611 	enum bpf_access_type bounds_check_type;
5612 	/* Some accesses can write anything into the stack, others are
5613 	 * read-only.
5614 	 */
5615 	bool clobber = false;
5616 
5617 	if (access_size == 0 && !zero_size_allowed) {
5618 		verbose(env, "invalid zero-sized read\n");
5619 		return -EACCES;
5620 	}
5621 
5622 	if (type == ACCESS_HELPER) {
5623 		/* The bounds checks for writes are more permissive than for
5624 		 * reads. However, if raw_mode is not set, we'll do extra
5625 		 * checks below.
5626 		 */
5627 		bounds_check_type = BPF_WRITE;
5628 		clobber = true;
5629 	} else {
5630 		bounds_check_type = BPF_READ;
5631 	}
5632 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5633 					       type, bounds_check_type);
5634 	if (err)
5635 		return err;
5636 
5637 
5638 	if (tnum_is_const(reg->var_off)) {
5639 		min_off = max_off = reg->var_off.value + off;
5640 	} else {
5641 		/* Variable offset is prohibited for unprivileged mode for
5642 		 * simplicity since it requires corresponding support in
5643 		 * Spectre masking for stack ALU.
5644 		 * See also retrieve_ptr_limit().
5645 		 */
5646 		if (!env->bypass_spec_v1) {
5647 			char tn_buf[48];
5648 
5649 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5650 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5651 				regno, err_extra, tn_buf);
5652 			return -EACCES;
5653 		}
5654 		/* Only initialized buffer on stack is allowed to be accessed
5655 		 * with variable offset. With uninitialized buffer it's hard to
5656 		 * guarantee that whole memory is marked as initialized on
5657 		 * helper return since specific bounds are unknown what may
5658 		 * cause uninitialized stack leaking.
5659 		 */
5660 		if (meta && meta->raw_mode)
5661 			meta = NULL;
5662 
5663 		min_off = reg->smin_value + off;
5664 		max_off = reg->smax_value + off;
5665 	}
5666 
5667 	if (meta && meta->raw_mode) {
5668 		/* Ensure we won't be overwriting dynptrs when simulating byte
5669 		 * by byte access in check_helper_call using meta.access_size.
5670 		 * This would be a problem if we have a helper in the future
5671 		 * which takes:
5672 		 *
5673 		 *	helper(uninit_mem, len, dynptr)
5674 		 *
5675 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5676 		 * may end up writing to dynptr itself when touching memory from
5677 		 * arg 1. This can be relaxed on a case by case basis for known
5678 		 * safe cases, but reject due to the possibilitiy of aliasing by
5679 		 * default.
5680 		 */
5681 		for (i = min_off; i < max_off + access_size; i++) {
5682 			int stack_off = -i - 1;
5683 
5684 			spi = __get_spi(i);
5685 			/* raw_mode may write past allocated_stack */
5686 			if (state->allocated_stack <= stack_off)
5687 				continue;
5688 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5689 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5690 				return -EACCES;
5691 			}
5692 		}
5693 		meta->access_size = access_size;
5694 		meta->regno = regno;
5695 		return 0;
5696 	}
5697 
5698 	for (i = min_off; i < max_off + access_size; i++) {
5699 		u8 *stype;
5700 
5701 		slot = -i - 1;
5702 		spi = slot / BPF_REG_SIZE;
5703 		if (state->allocated_stack <= slot)
5704 			goto err;
5705 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5706 		if (*stype == STACK_MISC)
5707 			goto mark;
5708 		if (*stype == STACK_ZERO) {
5709 			if (clobber) {
5710 				/* helper can write anything into the stack */
5711 				*stype = STACK_MISC;
5712 			}
5713 			goto mark;
5714 		}
5715 
5716 		if (is_spilled_reg(&state->stack[spi]) &&
5717 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5718 		     env->allow_ptr_leaks)) {
5719 			if (clobber) {
5720 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5721 				for (j = 0; j < BPF_REG_SIZE; j++)
5722 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5723 			}
5724 			goto mark;
5725 		}
5726 
5727 err:
5728 		if (tnum_is_const(reg->var_off)) {
5729 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5730 				err_extra, regno, min_off, i - min_off, access_size);
5731 		} else {
5732 			char tn_buf[48];
5733 
5734 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5735 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5736 				err_extra, regno, tn_buf, i - min_off, access_size);
5737 		}
5738 		return -EACCES;
5739 mark:
5740 		/* reading any byte out of 8-byte 'spill_slot' will cause
5741 		 * the whole slot to be marked as 'read'
5742 		 */
5743 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5744 			      state->stack[spi].spilled_ptr.parent,
5745 			      REG_LIVE_READ64);
5746 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5747 		 * be sure that whether stack slot is written to or not. Hence,
5748 		 * we must still conservatively propagate reads upwards even if
5749 		 * helper may write to the entire memory range.
5750 		 */
5751 	}
5752 	return update_stack_depth(env, state, min_off);
5753 }
5754 
5755 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5756 				   int access_size, bool zero_size_allowed,
5757 				   struct bpf_call_arg_meta *meta)
5758 {
5759 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5760 	u32 *max_access;
5761 
5762 	switch (base_type(reg->type)) {
5763 	case PTR_TO_PACKET:
5764 	case PTR_TO_PACKET_META:
5765 		return check_packet_access(env, regno, reg->off, access_size,
5766 					   zero_size_allowed);
5767 	case PTR_TO_MAP_KEY:
5768 		if (meta && meta->raw_mode) {
5769 			verbose(env, "R%d cannot write into %s\n", regno,
5770 				reg_type_str(env, reg->type));
5771 			return -EACCES;
5772 		}
5773 		return check_mem_region_access(env, regno, reg->off, access_size,
5774 					       reg->map_ptr->key_size, false);
5775 	case PTR_TO_MAP_VALUE:
5776 		if (check_map_access_type(env, regno, reg->off, access_size,
5777 					  meta && meta->raw_mode ? BPF_WRITE :
5778 					  BPF_READ))
5779 			return -EACCES;
5780 		return check_map_access(env, regno, reg->off, access_size,
5781 					zero_size_allowed, ACCESS_HELPER);
5782 	case PTR_TO_MEM:
5783 		if (type_is_rdonly_mem(reg->type)) {
5784 			if (meta && meta->raw_mode) {
5785 				verbose(env, "R%d cannot write into %s\n", regno,
5786 					reg_type_str(env, reg->type));
5787 				return -EACCES;
5788 			}
5789 		}
5790 		return check_mem_region_access(env, regno, reg->off,
5791 					       access_size, reg->mem_size,
5792 					       zero_size_allowed);
5793 	case PTR_TO_BUF:
5794 		if (type_is_rdonly_mem(reg->type)) {
5795 			if (meta && meta->raw_mode) {
5796 				verbose(env, "R%d cannot write into %s\n", regno,
5797 					reg_type_str(env, reg->type));
5798 				return -EACCES;
5799 			}
5800 
5801 			max_access = &env->prog->aux->max_rdonly_access;
5802 		} else {
5803 			max_access = &env->prog->aux->max_rdwr_access;
5804 		}
5805 		return check_buffer_access(env, reg, regno, reg->off,
5806 					   access_size, zero_size_allowed,
5807 					   max_access);
5808 	case PTR_TO_STACK:
5809 		return check_stack_range_initialized(
5810 				env,
5811 				regno, reg->off, access_size,
5812 				zero_size_allowed, ACCESS_HELPER, meta);
5813 	case PTR_TO_CTX:
5814 		/* in case the function doesn't know how to access the context,
5815 		 * (because we are in a program of type SYSCALL for example), we
5816 		 * can not statically check its size.
5817 		 * Dynamically check it now.
5818 		 */
5819 		if (!env->ops->convert_ctx_access) {
5820 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5821 			int offset = access_size - 1;
5822 
5823 			/* Allow zero-byte read from PTR_TO_CTX */
5824 			if (access_size == 0)
5825 				return zero_size_allowed ? 0 : -EACCES;
5826 
5827 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5828 						atype, -1, false);
5829 		}
5830 
5831 		fallthrough;
5832 	default: /* scalar_value or invalid ptr */
5833 		/* Allow zero-byte read from NULL, regardless of pointer type */
5834 		if (zero_size_allowed && access_size == 0 &&
5835 		    register_is_null(reg))
5836 			return 0;
5837 
5838 		verbose(env, "R%d type=%s ", regno,
5839 			reg_type_str(env, reg->type));
5840 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5841 		return -EACCES;
5842 	}
5843 }
5844 
5845 static int check_mem_size_reg(struct bpf_verifier_env *env,
5846 			      struct bpf_reg_state *reg, u32 regno,
5847 			      bool zero_size_allowed,
5848 			      struct bpf_call_arg_meta *meta)
5849 {
5850 	int err;
5851 
5852 	/* This is used to refine r0 return value bounds for helpers
5853 	 * that enforce this value as an upper bound on return values.
5854 	 * See do_refine_retval_range() for helpers that can refine
5855 	 * the return value. C type of helper is u32 so we pull register
5856 	 * bound from umax_value however, if negative verifier errors
5857 	 * out. Only upper bounds can be learned because retval is an
5858 	 * int type and negative retvals are allowed.
5859 	 */
5860 	meta->msize_max_value = reg->umax_value;
5861 
5862 	/* The register is SCALAR_VALUE; the access check
5863 	 * happens using its boundaries.
5864 	 */
5865 	if (!tnum_is_const(reg->var_off))
5866 		/* For unprivileged variable accesses, disable raw
5867 		 * mode so that the program is required to
5868 		 * initialize all the memory that the helper could
5869 		 * just partially fill up.
5870 		 */
5871 		meta = NULL;
5872 
5873 	if (reg->smin_value < 0) {
5874 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5875 			regno);
5876 		return -EACCES;
5877 	}
5878 
5879 	if (reg->umin_value == 0) {
5880 		err = check_helper_mem_access(env, regno - 1, 0,
5881 					      zero_size_allowed,
5882 					      meta);
5883 		if (err)
5884 			return err;
5885 	}
5886 
5887 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5888 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5889 			regno);
5890 		return -EACCES;
5891 	}
5892 	err = check_helper_mem_access(env, regno - 1,
5893 				      reg->umax_value,
5894 				      zero_size_allowed, meta);
5895 	if (!err)
5896 		err = mark_chain_precision(env, regno);
5897 	return err;
5898 }
5899 
5900 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5901 		   u32 regno, u32 mem_size)
5902 {
5903 	bool may_be_null = type_may_be_null(reg->type);
5904 	struct bpf_reg_state saved_reg;
5905 	struct bpf_call_arg_meta meta;
5906 	int err;
5907 
5908 	if (register_is_null(reg))
5909 		return 0;
5910 
5911 	memset(&meta, 0, sizeof(meta));
5912 	/* Assuming that the register contains a value check if the memory
5913 	 * access is safe. Temporarily save and restore the register's state as
5914 	 * the conversion shouldn't be visible to a caller.
5915 	 */
5916 	if (may_be_null) {
5917 		saved_reg = *reg;
5918 		mark_ptr_not_null_reg(reg);
5919 	}
5920 
5921 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5922 	/* Check access for BPF_WRITE */
5923 	meta.raw_mode = true;
5924 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5925 
5926 	if (may_be_null)
5927 		*reg = saved_reg;
5928 
5929 	return err;
5930 }
5931 
5932 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5933 				    u32 regno)
5934 {
5935 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5936 	bool may_be_null = type_may_be_null(mem_reg->type);
5937 	struct bpf_reg_state saved_reg;
5938 	struct bpf_call_arg_meta meta;
5939 	int err;
5940 
5941 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5942 
5943 	memset(&meta, 0, sizeof(meta));
5944 
5945 	if (may_be_null) {
5946 		saved_reg = *mem_reg;
5947 		mark_ptr_not_null_reg(mem_reg);
5948 	}
5949 
5950 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5951 	/* Check access for BPF_WRITE */
5952 	meta.raw_mode = true;
5953 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5954 
5955 	if (may_be_null)
5956 		*mem_reg = saved_reg;
5957 	return err;
5958 }
5959 
5960 /* Implementation details:
5961  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5962  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5963  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5964  * Two separate bpf_obj_new will also have different reg->id.
5965  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5966  * clears reg->id after value_or_null->value transition, since the verifier only
5967  * cares about the range of access to valid map value pointer and doesn't care
5968  * about actual address of the map element.
5969  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5970  * reg->id > 0 after value_or_null->value transition. By doing so
5971  * two bpf_map_lookups will be considered two different pointers that
5972  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5973  * returned from bpf_obj_new.
5974  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5975  * dead-locks.
5976  * Since only one bpf_spin_lock is allowed the checks are simpler than
5977  * reg_is_refcounted() logic. The verifier needs to remember only
5978  * one spin_lock instead of array of acquired_refs.
5979  * cur_state->active_lock remembers which map value element or allocated
5980  * object got locked and clears it after bpf_spin_unlock.
5981  */
5982 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5983 			     bool is_lock)
5984 {
5985 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5986 	struct bpf_verifier_state *cur = env->cur_state;
5987 	bool is_const = tnum_is_const(reg->var_off);
5988 	u64 val = reg->var_off.value;
5989 	struct bpf_map *map = NULL;
5990 	struct btf *btf = NULL;
5991 	struct btf_record *rec;
5992 
5993 	if (!is_const) {
5994 		verbose(env,
5995 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5996 			regno);
5997 		return -EINVAL;
5998 	}
5999 	if (reg->type == PTR_TO_MAP_VALUE) {
6000 		map = reg->map_ptr;
6001 		if (!map->btf) {
6002 			verbose(env,
6003 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6004 				map->name);
6005 			return -EINVAL;
6006 		}
6007 	} else {
6008 		btf = reg->btf;
6009 	}
6010 
6011 	rec = reg_btf_record(reg);
6012 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6013 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6014 			map ? map->name : "kptr");
6015 		return -EINVAL;
6016 	}
6017 	if (rec->spin_lock_off != val + reg->off) {
6018 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6019 			val + reg->off, rec->spin_lock_off);
6020 		return -EINVAL;
6021 	}
6022 	if (is_lock) {
6023 		if (cur->active_lock.ptr) {
6024 			verbose(env,
6025 				"Locking two bpf_spin_locks are not allowed\n");
6026 			return -EINVAL;
6027 		}
6028 		if (map)
6029 			cur->active_lock.ptr = map;
6030 		else
6031 			cur->active_lock.ptr = btf;
6032 		cur->active_lock.id = reg->id;
6033 	} else {
6034 		struct bpf_func_state *fstate = cur_func(env);
6035 		void *ptr;
6036 		int i;
6037 
6038 		if (map)
6039 			ptr = map;
6040 		else
6041 			ptr = btf;
6042 
6043 		if (!cur->active_lock.ptr) {
6044 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6045 			return -EINVAL;
6046 		}
6047 		if (cur->active_lock.ptr != ptr ||
6048 		    cur->active_lock.id != reg->id) {
6049 			verbose(env, "bpf_spin_unlock of different lock\n");
6050 			return -EINVAL;
6051 		}
6052 		cur->active_lock.ptr = NULL;
6053 		cur->active_lock.id = 0;
6054 
6055 		for (i = fstate->acquired_refs - 1; i >= 0; i--) {
6056 			int err;
6057 
6058 			/* Complain on error because this reference state cannot
6059 			 * be freed before this point, as bpf_spin_lock critical
6060 			 * section does not allow functions that release the
6061 			 * allocated object immediately.
6062 			 */
6063 			if (!fstate->refs[i].release_on_unlock)
6064 				continue;
6065 			err = release_reference(env, fstate->refs[i].id);
6066 			if (err) {
6067 				verbose(env, "failed to release release_on_unlock reference");
6068 				return err;
6069 			}
6070 		}
6071 	}
6072 	return 0;
6073 }
6074 
6075 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6076 			      struct bpf_call_arg_meta *meta)
6077 {
6078 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6079 	bool is_const = tnum_is_const(reg->var_off);
6080 	struct bpf_map *map = reg->map_ptr;
6081 	u64 val = reg->var_off.value;
6082 
6083 	if (!is_const) {
6084 		verbose(env,
6085 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6086 			regno);
6087 		return -EINVAL;
6088 	}
6089 	if (!map->btf) {
6090 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6091 			map->name);
6092 		return -EINVAL;
6093 	}
6094 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6095 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6096 		return -EINVAL;
6097 	}
6098 	if (map->record->timer_off != val + reg->off) {
6099 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6100 			val + reg->off, map->record->timer_off);
6101 		return -EINVAL;
6102 	}
6103 	if (meta->map_ptr) {
6104 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6105 		return -EFAULT;
6106 	}
6107 	meta->map_uid = reg->map_uid;
6108 	meta->map_ptr = map;
6109 	return 0;
6110 }
6111 
6112 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6113 			     struct bpf_call_arg_meta *meta)
6114 {
6115 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6116 	struct bpf_map *map_ptr = reg->map_ptr;
6117 	struct btf_field *kptr_field;
6118 	u32 kptr_off;
6119 
6120 	if (!tnum_is_const(reg->var_off)) {
6121 		verbose(env,
6122 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6123 			regno);
6124 		return -EINVAL;
6125 	}
6126 	if (!map_ptr->btf) {
6127 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6128 			map_ptr->name);
6129 		return -EINVAL;
6130 	}
6131 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6132 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6133 		return -EINVAL;
6134 	}
6135 
6136 	meta->map_ptr = map_ptr;
6137 	kptr_off = reg->off + reg->var_off.value;
6138 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6139 	if (!kptr_field) {
6140 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6141 		return -EACCES;
6142 	}
6143 	if (kptr_field->type != BPF_KPTR_REF) {
6144 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6145 		return -EACCES;
6146 	}
6147 	meta->kptr_field = kptr_field;
6148 	return 0;
6149 }
6150 
6151 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6152  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6153  *
6154  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6155  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6156  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6157  *
6158  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6159  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6160  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6161  * mutate the view of the dynptr and also possibly destroy it. In the latter
6162  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6163  * memory that dynptr points to.
6164  *
6165  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6166  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6167  * readonly dynptr view yet, hence only the first case is tracked and checked.
6168  *
6169  * This is consistent with how C applies the const modifier to a struct object,
6170  * where the pointer itself inside bpf_dynptr becomes const but not what it
6171  * points to.
6172  *
6173  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6174  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6175  */
6176 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
6177 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
6178 {
6179 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6180 	int spi = 0;
6181 
6182 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6183 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6184 	 */
6185 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6186 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6187 		return -EFAULT;
6188 	}
6189 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
6190 	 * check_func_arg_reg_off's logic. We only need to check offset
6191 	 * and its alignment for PTR_TO_STACK.
6192 	 */
6193 	if (reg->type == PTR_TO_STACK) {
6194 		spi = dynptr_get_spi(env, reg);
6195 		if (spi < 0 && spi != -ERANGE)
6196 			return spi;
6197 	}
6198 
6199 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6200 	 *		 constructing a mutable bpf_dynptr object.
6201 	 *
6202 	 *		 Currently, this is only possible with PTR_TO_STACK
6203 	 *		 pointing to a region of at least 16 bytes which doesn't
6204 	 *		 contain an existing bpf_dynptr.
6205 	 *
6206 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6207 	 *		 mutated or destroyed. However, the memory it points to
6208 	 *		 may be mutated.
6209 	 *
6210 	 *  None       - Points to a initialized dynptr that can be mutated and
6211 	 *		 destroyed, including mutation of the memory it points
6212 	 *		 to.
6213 	 */
6214 	if (arg_type & MEM_UNINIT) {
6215 		if (!is_dynptr_reg_valid_uninit(env, reg, spi)) {
6216 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6217 			return -EINVAL;
6218 		}
6219 
6220 		/* We only support one dynptr being uninitialized at the moment,
6221 		 * which is sufficient for the helper functions we have right now.
6222 		 */
6223 		if (meta->uninit_dynptr_regno) {
6224 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6225 			return -EFAULT;
6226 		}
6227 
6228 		meta->uninit_dynptr_regno = regno;
6229 	} else /* MEM_RDONLY and None case from above */ {
6230 		int err;
6231 
6232 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6233 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6234 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6235 			return -EINVAL;
6236 		}
6237 
6238 		if (!is_dynptr_reg_valid_init(env, reg, spi)) {
6239 			verbose(env,
6240 				"Expected an initialized dynptr as arg #%d\n",
6241 				regno);
6242 			return -EINVAL;
6243 		}
6244 
6245 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6246 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6247 			const char *err_extra = "";
6248 
6249 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6250 			case DYNPTR_TYPE_LOCAL:
6251 				err_extra = "local";
6252 				break;
6253 			case DYNPTR_TYPE_RINGBUF:
6254 				err_extra = "ringbuf";
6255 				break;
6256 			default:
6257 				err_extra = "<unknown>";
6258 				break;
6259 			}
6260 			verbose(env,
6261 				"Expected a dynptr of type %s as arg #%d\n",
6262 				err_extra, regno);
6263 			return -EINVAL;
6264 		}
6265 
6266 		err = mark_dynptr_read(env, reg);
6267 		if (err)
6268 			return err;
6269 	}
6270 	return 0;
6271 }
6272 
6273 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6274 {
6275 	return type == ARG_CONST_SIZE ||
6276 	       type == ARG_CONST_SIZE_OR_ZERO;
6277 }
6278 
6279 static bool arg_type_is_release(enum bpf_arg_type type)
6280 {
6281 	return type & OBJ_RELEASE;
6282 }
6283 
6284 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6285 {
6286 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6287 }
6288 
6289 static int int_ptr_type_to_size(enum bpf_arg_type type)
6290 {
6291 	if (type == ARG_PTR_TO_INT)
6292 		return sizeof(u32);
6293 	else if (type == ARG_PTR_TO_LONG)
6294 		return sizeof(u64);
6295 
6296 	return -EINVAL;
6297 }
6298 
6299 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6300 				 const struct bpf_call_arg_meta *meta,
6301 				 enum bpf_arg_type *arg_type)
6302 {
6303 	if (!meta->map_ptr) {
6304 		/* kernel subsystem misconfigured verifier */
6305 		verbose(env, "invalid map_ptr to access map->type\n");
6306 		return -EACCES;
6307 	}
6308 
6309 	switch (meta->map_ptr->map_type) {
6310 	case BPF_MAP_TYPE_SOCKMAP:
6311 	case BPF_MAP_TYPE_SOCKHASH:
6312 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6313 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6314 		} else {
6315 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6316 			return -EINVAL;
6317 		}
6318 		break;
6319 	case BPF_MAP_TYPE_BLOOM_FILTER:
6320 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6321 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6322 		break;
6323 	default:
6324 		break;
6325 	}
6326 	return 0;
6327 }
6328 
6329 struct bpf_reg_types {
6330 	const enum bpf_reg_type types[10];
6331 	u32 *btf_id;
6332 };
6333 
6334 static const struct bpf_reg_types sock_types = {
6335 	.types = {
6336 		PTR_TO_SOCK_COMMON,
6337 		PTR_TO_SOCKET,
6338 		PTR_TO_TCP_SOCK,
6339 		PTR_TO_XDP_SOCK,
6340 	},
6341 };
6342 
6343 #ifdef CONFIG_NET
6344 static const struct bpf_reg_types btf_id_sock_common_types = {
6345 	.types = {
6346 		PTR_TO_SOCK_COMMON,
6347 		PTR_TO_SOCKET,
6348 		PTR_TO_TCP_SOCK,
6349 		PTR_TO_XDP_SOCK,
6350 		PTR_TO_BTF_ID,
6351 		PTR_TO_BTF_ID | PTR_TRUSTED,
6352 	},
6353 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6354 };
6355 #endif
6356 
6357 static const struct bpf_reg_types mem_types = {
6358 	.types = {
6359 		PTR_TO_STACK,
6360 		PTR_TO_PACKET,
6361 		PTR_TO_PACKET_META,
6362 		PTR_TO_MAP_KEY,
6363 		PTR_TO_MAP_VALUE,
6364 		PTR_TO_MEM,
6365 		PTR_TO_MEM | MEM_RINGBUF,
6366 		PTR_TO_BUF,
6367 	},
6368 };
6369 
6370 static const struct bpf_reg_types int_ptr_types = {
6371 	.types = {
6372 		PTR_TO_STACK,
6373 		PTR_TO_PACKET,
6374 		PTR_TO_PACKET_META,
6375 		PTR_TO_MAP_KEY,
6376 		PTR_TO_MAP_VALUE,
6377 	},
6378 };
6379 
6380 static const struct bpf_reg_types spin_lock_types = {
6381 	.types = {
6382 		PTR_TO_MAP_VALUE,
6383 		PTR_TO_BTF_ID | MEM_ALLOC,
6384 	}
6385 };
6386 
6387 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6388 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6389 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6390 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6391 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6392 static const struct bpf_reg_types btf_ptr_types = {
6393 	.types = {
6394 		PTR_TO_BTF_ID,
6395 		PTR_TO_BTF_ID | PTR_TRUSTED,
6396 		PTR_TO_BTF_ID | MEM_RCU,
6397 	},
6398 };
6399 static const struct bpf_reg_types percpu_btf_ptr_types = {
6400 	.types = {
6401 		PTR_TO_BTF_ID | MEM_PERCPU,
6402 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6403 	}
6404 };
6405 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6406 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6407 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6408 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6409 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6410 static const struct bpf_reg_types dynptr_types = {
6411 	.types = {
6412 		PTR_TO_STACK,
6413 		CONST_PTR_TO_DYNPTR,
6414 	}
6415 };
6416 
6417 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6418 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6419 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6420 	[ARG_CONST_SIZE]		= &scalar_types,
6421 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6422 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6423 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6424 	[ARG_PTR_TO_CTX]		= &context_types,
6425 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6426 #ifdef CONFIG_NET
6427 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6428 #endif
6429 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6430 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6431 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6432 	[ARG_PTR_TO_MEM]		= &mem_types,
6433 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6434 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6435 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6436 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6437 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6438 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6439 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6440 	[ARG_PTR_TO_TIMER]		= &timer_types,
6441 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6442 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6443 };
6444 
6445 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6446 			  enum bpf_arg_type arg_type,
6447 			  const u32 *arg_btf_id,
6448 			  struct bpf_call_arg_meta *meta)
6449 {
6450 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6451 	enum bpf_reg_type expected, type = reg->type;
6452 	const struct bpf_reg_types *compatible;
6453 	int i, j;
6454 
6455 	compatible = compatible_reg_types[base_type(arg_type)];
6456 	if (!compatible) {
6457 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6458 		return -EFAULT;
6459 	}
6460 
6461 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6462 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6463 	 *
6464 	 * Same for MAYBE_NULL:
6465 	 *
6466 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6467 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6468 	 *
6469 	 * Therefore we fold these flags depending on the arg_type before comparison.
6470 	 */
6471 	if (arg_type & MEM_RDONLY)
6472 		type &= ~MEM_RDONLY;
6473 	if (arg_type & PTR_MAYBE_NULL)
6474 		type &= ~PTR_MAYBE_NULL;
6475 
6476 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6477 		expected = compatible->types[i];
6478 		if (expected == NOT_INIT)
6479 			break;
6480 
6481 		if (type == expected)
6482 			goto found;
6483 	}
6484 
6485 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6486 	for (j = 0; j + 1 < i; j++)
6487 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6488 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6489 	return -EACCES;
6490 
6491 found:
6492 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6493 		/* For bpf_sk_release, it needs to match against first member
6494 		 * 'struct sock_common', hence make an exception for it. This
6495 		 * allows bpf_sk_release to work for multiple socket types.
6496 		 */
6497 		bool strict_type_match = arg_type_is_release(arg_type) &&
6498 					 meta->func_id != BPF_FUNC_sk_release;
6499 
6500 		if (!arg_btf_id) {
6501 			if (!compatible->btf_id) {
6502 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6503 				return -EFAULT;
6504 			}
6505 			arg_btf_id = compatible->btf_id;
6506 		}
6507 
6508 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6509 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6510 				return -EACCES;
6511 		} else {
6512 			if (arg_btf_id == BPF_PTR_POISON) {
6513 				verbose(env, "verifier internal error:");
6514 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6515 					regno);
6516 				return -EACCES;
6517 			}
6518 
6519 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6520 						  btf_vmlinux, *arg_btf_id,
6521 						  strict_type_match)) {
6522 				verbose(env, "R%d is of type %s but %s is expected\n",
6523 					regno, kernel_type_name(reg->btf, reg->btf_id),
6524 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6525 				return -EACCES;
6526 			}
6527 		}
6528 	} else if (type_is_alloc(reg->type)) {
6529 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6530 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6531 			return -EFAULT;
6532 		}
6533 	}
6534 
6535 	return 0;
6536 }
6537 
6538 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6539 			   const struct bpf_reg_state *reg, int regno,
6540 			   enum bpf_arg_type arg_type)
6541 {
6542 	u32 type = reg->type;
6543 
6544 	/* When referenced register is passed to release function, its fixed
6545 	 * offset must be 0.
6546 	 *
6547 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6548 	 * meta->release_regno.
6549 	 */
6550 	if (arg_type_is_release(arg_type)) {
6551 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6552 		 * may not directly point to the object being released, but to
6553 		 * dynptr pointing to such object, which might be at some offset
6554 		 * on the stack. In that case, we simply to fallback to the
6555 		 * default handling.
6556 		 */
6557 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6558 			return 0;
6559 		/* Doing check_ptr_off_reg check for the offset will catch this
6560 		 * because fixed_off_ok is false, but checking here allows us
6561 		 * to give the user a better error message.
6562 		 */
6563 		if (reg->off) {
6564 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6565 				regno);
6566 			return -EINVAL;
6567 		}
6568 		return __check_ptr_off_reg(env, reg, regno, false);
6569 	}
6570 
6571 	switch (type) {
6572 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6573 	case PTR_TO_STACK:
6574 	case PTR_TO_PACKET:
6575 	case PTR_TO_PACKET_META:
6576 	case PTR_TO_MAP_KEY:
6577 	case PTR_TO_MAP_VALUE:
6578 	case PTR_TO_MEM:
6579 	case PTR_TO_MEM | MEM_RDONLY:
6580 	case PTR_TO_MEM | MEM_RINGBUF:
6581 	case PTR_TO_BUF:
6582 	case PTR_TO_BUF | MEM_RDONLY:
6583 	case SCALAR_VALUE:
6584 		return 0;
6585 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6586 	 * fixed offset.
6587 	 */
6588 	case PTR_TO_BTF_ID:
6589 	case PTR_TO_BTF_ID | MEM_ALLOC:
6590 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6591 	case PTR_TO_BTF_ID | MEM_RCU:
6592 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6593 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6594 		 * its fixed offset must be 0. In the other cases, fixed offset
6595 		 * can be non-zero. This was already checked above. So pass
6596 		 * fixed_off_ok as true to allow fixed offset for all other
6597 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6598 		 * still need to do checks instead of returning.
6599 		 */
6600 		return __check_ptr_off_reg(env, reg, regno, true);
6601 	default:
6602 		return __check_ptr_off_reg(env, reg, regno, false);
6603 	}
6604 }
6605 
6606 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6607 {
6608 	struct bpf_func_state *state = func(env, reg);
6609 	int spi;
6610 
6611 	if (reg->type == CONST_PTR_TO_DYNPTR)
6612 		return reg->id;
6613 	spi = dynptr_get_spi(env, reg);
6614 	if (spi < 0)
6615 		return spi;
6616 	return state->stack[spi].spilled_ptr.id;
6617 }
6618 
6619 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6620 {
6621 	struct bpf_func_state *state = func(env, reg);
6622 	int spi;
6623 
6624 	if (reg->type == CONST_PTR_TO_DYNPTR)
6625 		return reg->ref_obj_id;
6626 	spi = dynptr_get_spi(env, reg);
6627 	if (spi < 0)
6628 		return spi;
6629 	return state->stack[spi].spilled_ptr.ref_obj_id;
6630 }
6631 
6632 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6633 			  struct bpf_call_arg_meta *meta,
6634 			  const struct bpf_func_proto *fn)
6635 {
6636 	u32 regno = BPF_REG_1 + arg;
6637 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6638 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6639 	enum bpf_reg_type type = reg->type;
6640 	u32 *arg_btf_id = NULL;
6641 	int err = 0;
6642 
6643 	if (arg_type == ARG_DONTCARE)
6644 		return 0;
6645 
6646 	err = check_reg_arg(env, regno, SRC_OP);
6647 	if (err)
6648 		return err;
6649 
6650 	if (arg_type == ARG_ANYTHING) {
6651 		if (is_pointer_value(env, regno)) {
6652 			verbose(env, "R%d leaks addr into helper function\n",
6653 				regno);
6654 			return -EACCES;
6655 		}
6656 		return 0;
6657 	}
6658 
6659 	if (type_is_pkt_pointer(type) &&
6660 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6661 		verbose(env, "helper access to the packet is not allowed\n");
6662 		return -EACCES;
6663 	}
6664 
6665 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6666 		err = resolve_map_arg_type(env, meta, &arg_type);
6667 		if (err)
6668 			return err;
6669 	}
6670 
6671 	if (register_is_null(reg) && type_may_be_null(arg_type))
6672 		/* A NULL register has a SCALAR_VALUE type, so skip
6673 		 * type checking.
6674 		 */
6675 		goto skip_type_check;
6676 
6677 	/* arg_btf_id and arg_size are in a union. */
6678 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6679 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6680 		arg_btf_id = fn->arg_btf_id[arg];
6681 
6682 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6683 	if (err)
6684 		return err;
6685 
6686 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6687 	if (err)
6688 		return err;
6689 
6690 skip_type_check:
6691 	if (arg_type_is_release(arg_type)) {
6692 		if (arg_type_is_dynptr(arg_type)) {
6693 			struct bpf_func_state *state = func(env, reg);
6694 			int spi;
6695 
6696 			/* Only dynptr created on stack can be released, thus
6697 			 * the get_spi and stack state checks for spilled_ptr
6698 			 * should only be done before process_dynptr_func for
6699 			 * PTR_TO_STACK.
6700 			 */
6701 			if (reg->type == PTR_TO_STACK) {
6702 				spi = dynptr_get_spi(env, reg);
6703 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
6704 					verbose(env, "arg %d is an unacquired reference\n", regno);
6705 					return -EINVAL;
6706 				}
6707 			} else {
6708 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6709 				return -EINVAL;
6710 			}
6711 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6712 			verbose(env, "R%d must be referenced when passed to release function\n",
6713 				regno);
6714 			return -EINVAL;
6715 		}
6716 		if (meta->release_regno) {
6717 			verbose(env, "verifier internal error: more than one release argument\n");
6718 			return -EFAULT;
6719 		}
6720 		meta->release_regno = regno;
6721 	}
6722 
6723 	if (reg->ref_obj_id) {
6724 		if (meta->ref_obj_id) {
6725 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6726 				regno, reg->ref_obj_id,
6727 				meta->ref_obj_id);
6728 			return -EFAULT;
6729 		}
6730 		meta->ref_obj_id = reg->ref_obj_id;
6731 	}
6732 
6733 	switch (base_type(arg_type)) {
6734 	case ARG_CONST_MAP_PTR:
6735 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6736 		if (meta->map_ptr) {
6737 			/* Use map_uid (which is unique id of inner map) to reject:
6738 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6739 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6740 			 * if (inner_map1 && inner_map2) {
6741 			 *     timer = bpf_map_lookup_elem(inner_map1);
6742 			 *     if (timer)
6743 			 *         // mismatch would have been allowed
6744 			 *         bpf_timer_init(timer, inner_map2);
6745 			 * }
6746 			 *
6747 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6748 			 */
6749 			if (meta->map_ptr != reg->map_ptr ||
6750 			    meta->map_uid != reg->map_uid) {
6751 				verbose(env,
6752 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6753 					meta->map_uid, reg->map_uid);
6754 				return -EINVAL;
6755 			}
6756 		}
6757 		meta->map_ptr = reg->map_ptr;
6758 		meta->map_uid = reg->map_uid;
6759 		break;
6760 	case ARG_PTR_TO_MAP_KEY:
6761 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6762 		 * check that [key, key + map->key_size) are within
6763 		 * stack limits and initialized
6764 		 */
6765 		if (!meta->map_ptr) {
6766 			/* in function declaration map_ptr must come before
6767 			 * map_key, so that it's verified and known before
6768 			 * we have to check map_key here. Otherwise it means
6769 			 * that kernel subsystem misconfigured verifier
6770 			 */
6771 			verbose(env, "invalid map_ptr to access map->key\n");
6772 			return -EACCES;
6773 		}
6774 		err = check_helper_mem_access(env, regno,
6775 					      meta->map_ptr->key_size, false,
6776 					      NULL);
6777 		break;
6778 	case ARG_PTR_TO_MAP_VALUE:
6779 		if (type_may_be_null(arg_type) && register_is_null(reg))
6780 			return 0;
6781 
6782 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6783 		 * check [value, value + map->value_size) validity
6784 		 */
6785 		if (!meta->map_ptr) {
6786 			/* kernel subsystem misconfigured verifier */
6787 			verbose(env, "invalid map_ptr to access map->value\n");
6788 			return -EACCES;
6789 		}
6790 		meta->raw_mode = arg_type & MEM_UNINIT;
6791 		err = check_helper_mem_access(env, regno,
6792 					      meta->map_ptr->value_size, false,
6793 					      meta);
6794 		break;
6795 	case ARG_PTR_TO_PERCPU_BTF_ID:
6796 		if (!reg->btf_id) {
6797 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6798 			return -EACCES;
6799 		}
6800 		meta->ret_btf = reg->btf;
6801 		meta->ret_btf_id = reg->btf_id;
6802 		break;
6803 	case ARG_PTR_TO_SPIN_LOCK:
6804 		if (meta->func_id == BPF_FUNC_spin_lock) {
6805 			err = process_spin_lock(env, regno, true);
6806 			if (err)
6807 				return err;
6808 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6809 			err = process_spin_lock(env, regno, false);
6810 			if (err)
6811 				return err;
6812 		} else {
6813 			verbose(env, "verifier internal error\n");
6814 			return -EFAULT;
6815 		}
6816 		break;
6817 	case ARG_PTR_TO_TIMER:
6818 		err = process_timer_func(env, regno, meta);
6819 		if (err)
6820 			return err;
6821 		break;
6822 	case ARG_PTR_TO_FUNC:
6823 		meta->subprogno = reg->subprogno;
6824 		break;
6825 	case ARG_PTR_TO_MEM:
6826 		/* The access to this pointer is only checked when we hit the
6827 		 * next is_mem_size argument below.
6828 		 */
6829 		meta->raw_mode = arg_type & MEM_UNINIT;
6830 		if (arg_type & MEM_FIXED_SIZE) {
6831 			err = check_helper_mem_access(env, regno,
6832 						      fn->arg_size[arg], false,
6833 						      meta);
6834 		}
6835 		break;
6836 	case ARG_CONST_SIZE:
6837 		err = check_mem_size_reg(env, reg, regno, false, meta);
6838 		break;
6839 	case ARG_CONST_SIZE_OR_ZERO:
6840 		err = check_mem_size_reg(env, reg, regno, true, meta);
6841 		break;
6842 	case ARG_PTR_TO_DYNPTR:
6843 		err = process_dynptr_func(env, regno, arg_type, meta);
6844 		if (err)
6845 			return err;
6846 		break;
6847 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6848 		if (!tnum_is_const(reg->var_off)) {
6849 			verbose(env, "R%d is not a known constant'\n",
6850 				regno);
6851 			return -EACCES;
6852 		}
6853 		meta->mem_size = reg->var_off.value;
6854 		err = mark_chain_precision(env, regno);
6855 		if (err)
6856 			return err;
6857 		break;
6858 	case ARG_PTR_TO_INT:
6859 	case ARG_PTR_TO_LONG:
6860 	{
6861 		int size = int_ptr_type_to_size(arg_type);
6862 
6863 		err = check_helper_mem_access(env, regno, size, false, meta);
6864 		if (err)
6865 			return err;
6866 		err = check_ptr_alignment(env, reg, 0, size, true);
6867 		break;
6868 	}
6869 	case ARG_PTR_TO_CONST_STR:
6870 	{
6871 		struct bpf_map *map = reg->map_ptr;
6872 		int map_off;
6873 		u64 map_addr;
6874 		char *str_ptr;
6875 
6876 		if (!bpf_map_is_rdonly(map)) {
6877 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6878 			return -EACCES;
6879 		}
6880 
6881 		if (!tnum_is_const(reg->var_off)) {
6882 			verbose(env, "R%d is not a constant address'\n", regno);
6883 			return -EACCES;
6884 		}
6885 
6886 		if (!map->ops->map_direct_value_addr) {
6887 			verbose(env, "no direct value access support for this map type\n");
6888 			return -EACCES;
6889 		}
6890 
6891 		err = check_map_access(env, regno, reg->off,
6892 				       map->value_size - reg->off, false,
6893 				       ACCESS_HELPER);
6894 		if (err)
6895 			return err;
6896 
6897 		map_off = reg->off + reg->var_off.value;
6898 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6899 		if (err) {
6900 			verbose(env, "direct value access on string failed\n");
6901 			return err;
6902 		}
6903 
6904 		str_ptr = (char *)(long)(map_addr);
6905 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6906 			verbose(env, "string is not zero-terminated\n");
6907 			return -EINVAL;
6908 		}
6909 		break;
6910 	}
6911 	case ARG_PTR_TO_KPTR:
6912 		err = process_kptr_func(env, regno, meta);
6913 		if (err)
6914 			return err;
6915 		break;
6916 	}
6917 
6918 	return err;
6919 }
6920 
6921 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6922 {
6923 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6924 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6925 
6926 	if (func_id != BPF_FUNC_map_update_elem)
6927 		return false;
6928 
6929 	/* It's not possible to get access to a locked struct sock in these
6930 	 * contexts, so updating is safe.
6931 	 */
6932 	switch (type) {
6933 	case BPF_PROG_TYPE_TRACING:
6934 		if (eatype == BPF_TRACE_ITER)
6935 			return true;
6936 		break;
6937 	case BPF_PROG_TYPE_SOCKET_FILTER:
6938 	case BPF_PROG_TYPE_SCHED_CLS:
6939 	case BPF_PROG_TYPE_SCHED_ACT:
6940 	case BPF_PROG_TYPE_XDP:
6941 	case BPF_PROG_TYPE_SK_REUSEPORT:
6942 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6943 	case BPF_PROG_TYPE_SK_LOOKUP:
6944 		return true;
6945 	default:
6946 		break;
6947 	}
6948 
6949 	verbose(env, "cannot update sockmap in this context\n");
6950 	return false;
6951 }
6952 
6953 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6954 {
6955 	return env->prog->jit_requested &&
6956 	       bpf_jit_supports_subprog_tailcalls();
6957 }
6958 
6959 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6960 					struct bpf_map *map, int func_id)
6961 {
6962 	if (!map)
6963 		return 0;
6964 
6965 	/* We need a two way check, first is from map perspective ... */
6966 	switch (map->map_type) {
6967 	case BPF_MAP_TYPE_PROG_ARRAY:
6968 		if (func_id != BPF_FUNC_tail_call)
6969 			goto error;
6970 		break;
6971 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6972 		if (func_id != BPF_FUNC_perf_event_read &&
6973 		    func_id != BPF_FUNC_perf_event_output &&
6974 		    func_id != BPF_FUNC_skb_output &&
6975 		    func_id != BPF_FUNC_perf_event_read_value &&
6976 		    func_id != BPF_FUNC_xdp_output)
6977 			goto error;
6978 		break;
6979 	case BPF_MAP_TYPE_RINGBUF:
6980 		if (func_id != BPF_FUNC_ringbuf_output &&
6981 		    func_id != BPF_FUNC_ringbuf_reserve &&
6982 		    func_id != BPF_FUNC_ringbuf_query &&
6983 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6984 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6985 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6986 			goto error;
6987 		break;
6988 	case BPF_MAP_TYPE_USER_RINGBUF:
6989 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6990 			goto error;
6991 		break;
6992 	case BPF_MAP_TYPE_STACK_TRACE:
6993 		if (func_id != BPF_FUNC_get_stackid)
6994 			goto error;
6995 		break;
6996 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6997 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6998 		    func_id != BPF_FUNC_current_task_under_cgroup)
6999 			goto error;
7000 		break;
7001 	case BPF_MAP_TYPE_CGROUP_STORAGE:
7002 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7003 		if (func_id != BPF_FUNC_get_local_storage)
7004 			goto error;
7005 		break;
7006 	case BPF_MAP_TYPE_DEVMAP:
7007 	case BPF_MAP_TYPE_DEVMAP_HASH:
7008 		if (func_id != BPF_FUNC_redirect_map &&
7009 		    func_id != BPF_FUNC_map_lookup_elem)
7010 			goto error;
7011 		break;
7012 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
7013 	 * appear.
7014 	 */
7015 	case BPF_MAP_TYPE_CPUMAP:
7016 		if (func_id != BPF_FUNC_redirect_map)
7017 			goto error;
7018 		break;
7019 	case BPF_MAP_TYPE_XSKMAP:
7020 		if (func_id != BPF_FUNC_redirect_map &&
7021 		    func_id != BPF_FUNC_map_lookup_elem)
7022 			goto error;
7023 		break;
7024 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7025 	case BPF_MAP_TYPE_HASH_OF_MAPS:
7026 		if (func_id != BPF_FUNC_map_lookup_elem)
7027 			goto error;
7028 		break;
7029 	case BPF_MAP_TYPE_SOCKMAP:
7030 		if (func_id != BPF_FUNC_sk_redirect_map &&
7031 		    func_id != BPF_FUNC_sock_map_update &&
7032 		    func_id != BPF_FUNC_map_delete_elem &&
7033 		    func_id != BPF_FUNC_msg_redirect_map &&
7034 		    func_id != BPF_FUNC_sk_select_reuseport &&
7035 		    func_id != BPF_FUNC_map_lookup_elem &&
7036 		    !may_update_sockmap(env, func_id))
7037 			goto error;
7038 		break;
7039 	case BPF_MAP_TYPE_SOCKHASH:
7040 		if (func_id != BPF_FUNC_sk_redirect_hash &&
7041 		    func_id != BPF_FUNC_sock_hash_update &&
7042 		    func_id != BPF_FUNC_map_delete_elem &&
7043 		    func_id != BPF_FUNC_msg_redirect_hash &&
7044 		    func_id != BPF_FUNC_sk_select_reuseport &&
7045 		    func_id != BPF_FUNC_map_lookup_elem &&
7046 		    !may_update_sockmap(env, func_id))
7047 			goto error;
7048 		break;
7049 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7050 		if (func_id != BPF_FUNC_sk_select_reuseport)
7051 			goto error;
7052 		break;
7053 	case BPF_MAP_TYPE_QUEUE:
7054 	case BPF_MAP_TYPE_STACK:
7055 		if (func_id != BPF_FUNC_map_peek_elem &&
7056 		    func_id != BPF_FUNC_map_pop_elem &&
7057 		    func_id != BPF_FUNC_map_push_elem)
7058 			goto error;
7059 		break;
7060 	case BPF_MAP_TYPE_SK_STORAGE:
7061 		if (func_id != BPF_FUNC_sk_storage_get &&
7062 		    func_id != BPF_FUNC_sk_storage_delete)
7063 			goto error;
7064 		break;
7065 	case BPF_MAP_TYPE_INODE_STORAGE:
7066 		if (func_id != BPF_FUNC_inode_storage_get &&
7067 		    func_id != BPF_FUNC_inode_storage_delete)
7068 			goto error;
7069 		break;
7070 	case BPF_MAP_TYPE_TASK_STORAGE:
7071 		if (func_id != BPF_FUNC_task_storage_get &&
7072 		    func_id != BPF_FUNC_task_storage_delete)
7073 			goto error;
7074 		break;
7075 	case BPF_MAP_TYPE_CGRP_STORAGE:
7076 		if (func_id != BPF_FUNC_cgrp_storage_get &&
7077 		    func_id != BPF_FUNC_cgrp_storage_delete)
7078 			goto error;
7079 		break;
7080 	case BPF_MAP_TYPE_BLOOM_FILTER:
7081 		if (func_id != BPF_FUNC_map_peek_elem &&
7082 		    func_id != BPF_FUNC_map_push_elem)
7083 			goto error;
7084 		break;
7085 	default:
7086 		break;
7087 	}
7088 
7089 	/* ... and second from the function itself. */
7090 	switch (func_id) {
7091 	case BPF_FUNC_tail_call:
7092 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7093 			goto error;
7094 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7095 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7096 			return -EINVAL;
7097 		}
7098 		break;
7099 	case BPF_FUNC_perf_event_read:
7100 	case BPF_FUNC_perf_event_output:
7101 	case BPF_FUNC_perf_event_read_value:
7102 	case BPF_FUNC_skb_output:
7103 	case BPF_FUNC_xdp_output:
7104 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7105 			goto error;
7106 		break;
7107 	case BPF_FUNC_ringbuf_output:
7108 	case BPF_FUNC_ringbuf_reserve:
7109 	case BPF_FUNC_ringbuf_query:
7110 	case BPF_FUNC_ringbuf_reserve_dynptr:
7111 	case BPF_FUNC_ringbuf_submit_dynptr:
7112 	case BPF_FUNC_ringbuf_discard_dynptr:
7113 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7114 			goto error;
7115 		break;
7116 	case BPF_FUNC_user_ringbuf_drain:
7117 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7118 			goto error;
7119 		break;
7120 	case BPF_FUNC_get_stackid:
7121 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7122 			goto error;
7123 		break;
7124 	case BPF_FUNC_current_task_under_cgroup:
7125 	case BPF_FUNC_skb_under_cgroup:
7126 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7127 			goto error;
7128 		break;
7129 	case BPF_FUNC_redirect_map:
7130 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7131 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7132 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
7133 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
7134 			goto error;
7135 		break;
7136 	case BPF_FUNC_sk_redirect_map:
7137 	case BPF_FUNC_msg_redirect_map:
7138 	case BPF_FUNC_sock_map_update:
7139 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7140 			goto error;
7141 		break;
7142 	case BPF_FUNC_sk_redirect_hash:
7143 	case BPF_FUNC_msg_redirect_hash:
7144 	case BPF_FUNC_sock_hash_update:
7145 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7146 			goto error;
7147 		break;
7148 	case BPF_FUNC_get_local_storage:
7149 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7150 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7151 			goto error;
7152 		break;
7153 	case BPF_FUNC_sk_select_reuseport:
7154 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7155 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7156 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
7157 			goto error;
7158 		break;
7159 	case BPF_FUNC_map_pop_elem:
7160 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7161 		    map->map_type != BPF_MAP_TYPE_STACK)
7162 			goto error;
7163 		break;
7164 	case BPF_FUNC_map_peek_elem:
7165 	case BPF_FUNC_map_push_elem:
7166 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7167 		    map->map_type != BPF_MAP_TYPE_STACK &&
7168 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7169 			goto error;
7170 		break;
7171 	case BPF_FUNC_map_lookup_percpu_elem:
7172 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7173 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7174 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7175 			goto error;
7176 		break;
7177 	case BPF_FUNC_sk_storage_get:
7178 	case BPF_FUNC_sk_storage_delete:
7179 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7180 			goto error;
7181 		break;
7182 	case BPF_FUNC_inode_storage_get:
7183 	case BPF_FUNC_inode_storage_delete:
7184 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7185 			goto error;
7186 		break;
7187 	case BPF_FUNC_task_storage_get:
7188 	case BPF_FUNC_task_storage_delete:
7189 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7190 			goto error;
7191 		break;
7192 	case BPF_FUNC_cgrp_storage_get:
7193 	case BPF_FUNC_cgrp_storage_delete:
7194 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7195 			goto error;
7196 		break;
7197 	default:
7198 		break;
7199 	}
7200 
7201 	return 0;
7202 error:
7203 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
7204 		map->map_type, func_id_name(func_id), func_id);
7205 	return -EINVAL;
7206 }
7207 
7208 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7209 {
7210 	int count = 0;
7211 
7212 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7213 		count++;
7214 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7215 		count++;
7216 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7217 		count++;
7218 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7219 		count++;
7220 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7221 		count++;
7222 
7223 	/* We only support one arg being in raw mode at the moment,
7224 	 * which is sufficient for the helper functions we have
7225 	 * right now.
7226 	 */
7227 	return count <= 1;
7228 }
7229 
7230 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7231 {
7232 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7233 	bool has_size = fn->arg_size[arg] != 0;
7234 	bool is_next_size = false;
7235 
7236 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7237 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7238 
7239 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7240 		return is_next_size;
7241 
7242 	return has_size == is_next_size || is_next_size == is_fixed;
7243 }
7244 
7245 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7246 {
7247 	/* bpf_xxx(..., buf, len) call will access 'len'
7248 	 * bytes from memory 'buf'. Both arg types need
7249 	 * to be paired, so make sure there's no buggy
7250 	 * helper function specification.
7251 	 */
7252 	if (arg_type_is_mem_size(fn->arg1_type) ||
7253 	    check_args_pair_invalid(fn, 0) ||
7254 	    check_args_pair_invalid(fn, 1) ||
7255 	    check_args_pair_invalid(fn, 2) ||
7256 	    check_args_pair_invalid(fn, 3) ||
7257 	    check_args_pair_invalid(fn, 4))
7258 		return false;
7259 
7260 	return true;
7261 }
7262 
7263 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7264 {
7265 	int i;
7266 
7267 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7268 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7269 			return !!fn->arg_btf_id[i];
7270 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7271 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7272 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7273 		    /* arg_btf_id and arg_size are in a union. */
7274 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7275 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7276 			return false;
7277 	}
7278 
7279 	return true;
7280 }
7281 
7282 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7283 {
7284 	return check_raw_mode_ok(fn) &&
7285 	       check_arg_pair_ok(fn) &&
7286 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7287 }
7288 
7289 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7290  * are now invalid, so turn them into unknown SCALAR_VALUE.
7291  */
7292 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7293 {
7294 	struct bpf_func_state *state;
7295 	struct bpf_reg_state *reg;
7296 
7297 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7298 		if (reg_is_pkt_pointer_any(reg))
7299 			__mark_reg_unknown(env, reg);
7300 	}));
7301 }
7302 
7303 enum {
7304 	AT_PKT_END = -1,
7305 	BEYOND_PKT_END = -2,
7306 };
7307 
7308 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7309 {
7310 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7311 	struct bpf_reg_state *reg = &state->regs[regn];
7312 
7313 	if (reg->type != PTR_TO_PACKET)
7314 		/* PTR_TO_PACKET_META is not supported yet */
7315 		return;
7316 
7317 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7318 	 * How far beyond pkt_end it goes is unknown.
7319 	 * if (!range_open) it's the case of pkt >= pkt_end
7320 	 * if (range_open) it's the case of pkt > pkt_end
7321 	 * hence this pointer is at least 1 byte bigger than pkt_end
7322 	 */
7323 	if (range_open)
7324 		reg->range = BEYOND_PKT_END;
7325 	else
7326 		reg->range = AT_PKT_END;
7327 }
7328 
7329 /* The pointer with the specified id has released its reference to kernel
7330  * resources. Identify all copies of the same pointer and clear the reference.
7331  */
7332 static int release_reference(struct bpf_verifier_env *env,
7333 			     int ref_obj_id)
7334 {
7335 	struct bpf_func_state *state;
7336 	struct bpf_reg_state *reg;
7337 	int err;
7338 
7339 	err = release_reference_state(cur_func(env), ref_obj_id);
7340 	if (err)
7341 		return err;
7342 
7343 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7344 		if (reg->ref_obj_id == ref_obj_id) {
7345 			if (!env->allow_ptr_leaks)
7346 				__mark_reg_not_init(env, reg);
7347 			else
7348 				__mark_reg_unknown(env, reg);
7349 		}
7350 	}));
7351 
7352 	return 0;
7353 }
7354 
7355 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7356 				    struct bpf_reg_state *regs)
7357 {
7358 	int i;
7359 
7360 	/* after the call registers r0 - r5 were scratched */
7361 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7362 		mark_reg_not_init(env, regs, caller_saved[i]);
7363 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7364 	}
7365 }
7366 
7367 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7368 				   struct bpf_func_state *caller,
7369 				   struct bpf_func_state *callee,
7370 				   int insn_idx);
7371 
7372 static int set_callee_state(struct bpf_verifier_env *env,
7373 			    struct bpf_func_state *caller,
7374 			    struct bpf_func_state *callee, int insn_idx);
7375 
7376 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7377 			     int *insn_idx, int subprog,
7378 			     set_callee_state_fn set_callee_state_cb)
7379 {
7380 	struct bpf_verifier_state *state = env->cur_state;
7381 	struct bpf_func_info_aux *func_info_aux;
7382 	struct bpf_func_state *caller, *callee;
7383 	int err;
7384 	bool is_global = false;
7385 
7386 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7387 		verbose(env, "the call stack of %d frames is too deep\n",
7388 			state->curframe + 2);
7389 		return -E2BIG;
7390 	}
7391 
7392 	caller = state->frame[state->curframe];
7393 	if (state->frame[state->curframe + 1]) {
7394 		verbose(env, "verifier bug. Frame %d already allocated\n",
7395 			state->curframe + 1);
7396 		return -EFAULT;
7397 	}
7398 
7399 	func_info_aux = env->prog->aux->func_info_aux;
7400 	if (func_info_aux)
7401 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7402 	err = btf_check_subprog_call(env, subprog, caller->regs);
7403 	if (err == -EFAULT)
7404 		return err;
7405 	if (is_global) {
7406 		if (err) {
7407 			verbose(env, "Caller passes invalid args into func#%d\n",
7408 				subprog);
7409 			return err;
7410 		} else {
7411 			if (env->log.level & BPF_LOG_LEVEL)
7412 				verbose(env,
7413 					"Func#%d is global and valid. Skipping.\n",
7414 					subprog);
7415 			clear_caller_saved_regs(env, caller->regs);
7416 
7417 			/* All global functions return a 64-bit SCALAR_VALUE */
7418 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7419 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7420 
7421 			/* continue with next insn after call */
7422 			return 0;
7423 		}
7424 	}
7425 
7426 	/* set_callee_state is used for direct subprog calls, but we are
7427 	 * interested in validating only BPF helpers that can call subprogs as
7428 	 * callbacks
7429 	 */
7430 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7431 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7432 			func_id_name(insn->imm), insn->imm);
7433 		return -EFAULT;
7434 	}
7435 
7436 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7437 	    insn->src_reg == 0 &&
7438 	    insn->imm == BPF_FUNC_timer_set_callback) {
7439 		struct bpf_verifier_state *async_cb;
7440 
7441 		/* there is no real recursion here. timer callbacks are async */
7442 		env->subprog_info[subprog].is_async_cb = true;
7443 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7444 					 *insn_idx, subprog);
7445 		if (!async_cb)
7446 			return -EFAULT;
7447 		callee = async_cb->frame[0];
7448 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7449 
7450 		/* Convert bpf_timer_set_callback() args into timer callback args */
7451 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7452 		if (err)
7453 			return err;
7454 
7455 		clear_caller_saved_regs(env, caller->regs);
7456 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7457 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7458 		/* continue with next insn after call */
7459 		return 0;
7460 	}
7461 
7462 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7463 	if (!callee)
7464 		return -ENOMEM;
7465 	state->frame[state->curframe + 1] = callee;
7466 
7467 	/* callee cannot access r0, r6 - r9 for reading and has to write
7468 	 * into its own stack before reading from it.
7469 	 * callee can read/write into caller's stack
7470 	 */
7471 	init_func_state(env, callee,
7472 			/* remember the callsite, it will be used by bpf_exit */
7473 			*insn_idx /* callsite */,
7474 			state->curframe + 1 /* frameno within this callchain */,
7475 			subprog /* subprog number within this prog */);
7476 
7477 	/* Transfer references to the callee */
7478 	err = copy_reference_state(callee, caller);
7479 	if (err)
7480 		goto err_out;
7481 
7482 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7483 	if (err)
7484 		goto err_out;
7485 
7486 	clear_caller_saved_regs(env, caller->regs);
7487 
7488 	/* only increment it after check_reg_arg() finished */
7489 	state->curframe++;
7490 
7491 	/* and go analyze first insn of the callee */
7492 	*insn_idx = env->subprog_info[subprog].start - 1;
7493 
7494 	if (env->log.level & BPF_LOG_LEVEL) {
7495 		verbose(env, "caller:\n");
7496 		print_verifier_state(env, caller, true);
7497 		verbose(env, "callee:\n");
7498 		print_verifier_state(env, callee, true);
7499 	}
7500 	return 0;
7501 
7502 err_out:
7503 	free_func_state(callee);
7504 	state->frame[state->curframe + 1] = NULL;
7505 	return err;
7506 }
7507 
7508 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7509 				   struct bpf_func_state *caller,
7510 				   struct bpf_func_state *callee)
7511 {
7512 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7513 	 *      void *callback_ctx, u64 flags);
7514 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7515 	 *      void *callback_ctx);
7516 	 */
7517 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7518 
7519 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7520 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7521 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7522 
7523 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7524 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7525 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7526 
7527 	/* pointer to stack or null */
7528 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7529 
7530 	/* unused */
7531 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7532 	return 0;
7533 }
7534 
7535 static int set_callee_state(struct bpf_verifier_env *env,
7536 			    struct bpf_func_state *caller,
7537 			    struct bpf_func_state *callee, int insn_idx)
7538 {
7539 	int i;
7540 
7541 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7542 	 * pointers, which connects us up to the liveness chain
7543 	 */
7544 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7545 		callee->regs[i] = caller->regs[i];
7546 	return 0;
7547 }
7548 
7549 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7550 			   int *insn_idx)
7551 {
7552 	int subprog, target_insn;
7553 
7554 	target_insn = *insn_idx + insn->imm + 1;
7555 	subprog = find_subprog(env, target_insn);
7556 	if (subprog < 0) {
7557 		verbose(env, "verifier bug. No program starts at insn %d\n",
7558 			target_insn);
7559 		return -EFAULT;
7560 	}
7561 
7562 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7563 }
7564 
7565 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7566 				       struct bpf_func_state *caller,
7567 				       struct bpf_func_state *callee,
7568 				       int insn_idx)
7569 {
7570 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7571 	struct bpf_map *map;
7572 	int err;
7573 
7574 	if (bpf_map_ptr_poisoned(insn_aux)) {
7575 		verbose(env, "tail_call abusing map_ptr\n");
7576 		return -EINVAL;
7577 	}
7578 
7579 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7580 	if (!map->ops->map_set_for_each_callback_args ||
7581 	    !map->ops->map_for_each_callback) {
7582 		verbose(env, "callback function not allowed for map\n");
7583 		return -ENOTSUPP;
7584 	}
7585 
7586 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7587 	if (err)
7588 		return err;
7589 
7590 	callee->in_callback_fn = true;
7591 	callee->callback_ret_range = tnum_range(0, 1);
7592 	return 0;
7593 }
7594 
7595 static int set_loop_callback_state(struct bpf_verifier_env *env,
7596 				   struct bpf_func_state *caller,
7597 				   struct bpf_func_state *callee,
7598 				   int insn_idx)
7599 {
7600 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7601 	 *	    u64 flags);
7602 	 * callback_fn(u32 index, void *callback_ctx);
7603 	 */
7604 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7605 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7606 
7607 	/* unused */
7608 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7609 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7610 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7611 
7612 	callee->in_callback_fn = true;
7613 	callee->callback_ret_range = tnum_range(0, 1);
7614 	return 0;
7615 }
7616 
7617 static int set_timer_callback_state(struct bpf_verifier_env *env,
7618 				    struct bpf_func_state *caller,
7619 				    struct bpf_func_state *callee,
7620 				    int insn_idx)
7621 {
7622 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7623 
7624 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7625 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7626 	 */
7627 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7628 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7629 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7630 
7631 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7632 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7633 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7634 
7635 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7636 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7637 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7638 
7639 	/* unused */
7640 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7641 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7642 	callee->in_async_callback_fn = true;
7643 	callee->callback_ret_range = tnum_range(0, 1);
7644 	return 0;
7645 }
7646 
7647 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7648 				       struct bpf_func_state *caller,
7649 				       struct bpf_func_state *callee,
7650 				       int insn_idx)
7651 {
7652 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7653 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7654 	 * (callback_fn)(struct task_struct *task,
7655 	 *               struct vm_area_struct *vma, void *callback_ctx);
7656 	 */
7657 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7658 
7659 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7660 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7661 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7662 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7663 
7664 	/* pointer to stack or null */
7665 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7666 
7667 	/* unused */
7668 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7669 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7670 	callee->in_callback_fn = true;
7671 	callee->callback_ret_range = tnum_range(0, 1);
7672 	return 0;
7673 }
7674 
7675 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7676 					   struct bpf_func_state *caller,
7677 					   struct bpf_func_state *callee,
7678 					   int insn_idx)
7679 {
7680 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7681 	 *			  callback_ctx, u64 flags);
7682 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7683 	 */
7684 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7685 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7686 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7687 
7688 	/* unused */
7689 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7690 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7691 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7692 
7693 	callee->in_callback_fn = true;
7694 	callee->callback_ret_range = tnum_range(0, 1);
7695 	return 0;
7696 }
7697 
7698 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7699 {
7700 	struct bpf_verifier_state *state = env->cur_state;
7701 	struct bpf_func_state *caller, *callee;
7702 	struct bpf_reg_state *r0;
7703 	int err;
7704 
7705 	callee = state->frame[state->curframe];
7706 	r0 = &callee->regs[BPF_REG_0];
7707 	if (r0->type == PTR_TO_STACK) {
7708 		/* technically it's ok to return caller's stack pointer
7709 		 * (or caller's caller's pointer) back to the caller,
7710 		 * since these pointers are valid. Only current stack
7711 		 * pointer will be invalid as soon as function exits,
7712 		 * but let's be conservative
7713 		 */
7714 		verbose(env, "cannot return stack pointer to the caller\n");
7715 		return -EINVAL;
7716 	}
7717 
7718 	caller = state->frame[state->curframe - 1];
7719 	if (callee->in_callback_fn) {
7720 		/* enforce R0 return value range [0, 1]. */
7721 		struct tnum range = callee->callback_ret_range;
7722 
7723 		if (r0->type != SCALAR_VALUE) {
7724 			verbose(env, "R0 not a scalar value\n");
7725 			return -EACCES;
7726 		}
7727 		if (!tnum_in(range, r0->var_off)) {
7728 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7729 			return -EINVAL;
7730 		}
7731 	} else {
7732 		/* return to the caller whatever r0 had in the callee */
7733 		caller->regs[BPF_REG_0] = *r0;
7734 	}
7735 
7736 	/* callback_fn frame should have released its own additions to parent's
7737 	 * reference state at this point, or check_reference_leak would
7738 	 * complain, hence it must be the same as the caller. There is no need
7739 	 * to copy it back.
7740 	 */
7741 	if (!callee->in_callback_fn) {
7742 		/* Transfer references to the caller */
7743 		err = copy_reference_state(caller, callee);
7744 		if (err)
7745 			return err;
7746 	}
7747 
7748 	*insn_idx = callee->callsite + 1;
7749 	if (env->log.level & BPF_LOG_LEVEL) {
7750 		verbose(env, "returning from callee:\n");
7751 		print_verifier_state(env, callee, true);
7752 		verbose(env, "to caller at %d:\n", *insn_idx);
7753 		print_verifier_state(env, caller, true);
7754 	}
7755 	/* clear everything in the callee */
7756 	free_func_state(callee);
7757 	state->frame[state->curframe--] = NULL;
7758 	return 0;
7759 }
7760 
7761 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7762 				   int func_id,
7763 				   struct bpf_call_arg_meta *meta)
7764 {
7765 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7766 
7767 	if (ret_type != RET_INTEGER ||
7768 	    (func_id != BPF_FUNC_get_stack &&
7769 	     func_id != BPF_FUNC_get_task_stack &&
7770 	     func_id != BPF_FUNC_probe_read_str &&
7771 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7772 	     func_id != BPF_FUNC_probe_read_user_str))
7773 		return;
7774 
7775 	ret_reg->smax_value = meta->msize_max_value;
7776 	ret_reg->s32_max_value = meta->msize_max_value;
7777 	ret_reg->smin_value = -MAX_ERRNO;
7778 	ret_reg->s32_min_value = -MAX_ERRNO;
7779 	reg_bounds_sync(ret_reg);
7780 }
7781 
7782 static int
7783 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7784 		int func_id, int insn_idx)
7785 {
7786 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7787 	struct bpf_map *map = meta->map_ptr;
7788 
7789 	if (func_id != BPF_FUNC_tail_call &&
7790 	    func_id != BPF_FUNC_map_lookup_elem &&
7791 	    func_id != BPF_FUNC_map_update_elem &&
7792 	    func_id != BPF_FUNC_map_delete_elem &&
7793 	    func_id != BPF_FUNC_map_push_elem &&
7794 	    func_id != BPF_FUNC_map_pop_elem &&
7795 	    func_id != BPF_FUNC_map_peek_elem &&
7796 	    func_id != BPF_FUNC_for_each_map_elem &&
7797 	    func_id != BPF_FUNC_redirect_map &&
7798 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7799 		return 0;
7800 
7801 	if (map == NULL) {
7802 		verbose(env, "kernel subsystem misconfigured verifier\n");
7803 		return -EINVAL;
7804 	}
7805 
7806 	/* In case of read-only, some additional restrictions
7807 	 * need to be applied in order to prevent altering the
7808 	 * state of the map from program side.
7809 	 */
7810 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7811 	    (func_id == BPF_FUNC_map_delete_elem ||
7812 	     func_id == BPF_FUNC_map_update_elem ||
7813 	     func_id == BPF_FUNC_map_push_elem ||
7814 	     func_id == BPF_FUNC_map_pop_elem)) {
7815 		verbose(env, "write into map forbidden\n");
7816 		return -EACCES;
7817 	}
7818 
7819 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7820 		bpf_map_ptr_store(aux, meta->map_ptr,
7821 				  !meta->map_ptr->bypass_spec_v1);
7822 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7823 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7824 				  !meta->map_ptr->bypass_spec_v1);
7825 	return 0;
7826 }
7827 
7828 static int
7829 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7830 		int func_id, int insn_idx)
7831 {
7832 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7833 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7834 	struct bpf_map *map = meta->map_ptr;
7835 	u64 val, max;
7836 	int err;
7837 
7838 	if (func_id != BPF_FUNC_tail_call)
7839 		return 0;
7840 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7841 		verbose(env, "kernel subsystem misconfigured verifier\n");
7842 		return -EINVAL;
7843 	}
7844 
7845 	reg = &regs[BPF_REG_3];
7846 	val = reg->var_off.value;
7847 	max = map->max_entries;
7848 
7849 	if (!(register_is_const(reg) && val < max)) {
7850 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7851 		return 0;
7852 	}
7853 
7854 	err = mark_chain_precision(env, BPF_REG_3);
7855 	if (err)
7856 		return err;
7857 	if (bpf_map_key_unseen(aux))
7858 		bpf_map_key_store(aux, val);
7859 	else if (!bpf_map_key_poisoned(aux) &&
7860 		  bpf_map_key_immediate(aux) != val)
7861 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7862 	return 0;
7863 }
7864 
7865 static int check_reference_leak(struct bpf_verifier_env *env)
7866 {
7867 	struct bpf_func_state *state = cur_func(env);
7868 	bool refs_lingering = false;
7869 	int i;
7870 
7871 	if (state->frameno && !state->in_callback_fn)
7872 		return 0;
7873 
7874 	for (i = 0; i < state->acquired_refs; i++) {
7875 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7876 			continue;
7877 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7878 			state->refs[i].id, state->refs[i].insn_idx);
7879 		refs_lingering = true;
7880 	}
7881 	return refs_lingering ? -EINVAL : 0;
7882 }
7883 
7884 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7885 				   struct bpf_reg_state *regs)
7886 {
7887 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7888 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7889 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7890 	struct bpf_bprintf_data data = {};
7891 	int err, fmt_map_off, num_args;
7892 	u64 fmt_addr;
7893 	char *fmt;
7894 
7895 	/* data must be an array of u64 */
7896 	if (data_len_reg->var_off.value % 8)
7897 		return -EINVAL;
7898 	num_args = data_len_reg->var_off.value / 8;
7899 
7900 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7901 	 * and map_direct_value_addr is set.
7902 	 */
7903 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7904 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7905 						  fmt_map_off);
7906 	if (err) {
7907 		verbose(env, "verifier bug\n");
7908 		return -EFAULT;
7909 	}
7910 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7911 
7912 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7913 	 * can focus on validating the format specifiers.
7914 	 */
7915 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7916 	if (err < 0)
7917 		verbose(env, "Invalid format string\n");
7918 
7919 	return err;
7920 }
7921 
7922 static int check_get_func_ip(struct bpf_verifier_env *env)
7923 {
7924 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7925 	int func_id = BPF_FUNC_get_func_ip;
7926 
7927 	if (type == BPF_PROG_TYPE_TRACING) {
7928 		if (!bpf_prog_has_trampoline(env->prog)) {
7929 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7930 				func_id_name(func_id), func_id);
7931 			return -ENOTSUPP;
7932 		}
7933 		return 0;
7934 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7935 		return 0;
7936 	}
7937 
7938 	verbose(env, "func %s#%d not supported for program type %d\n",
7939 		func_id_name(func_id), func_id, type);
7940 	return -ENOTSUPP;
7941 }
7942 
7943 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7944 {
7945 	return &env->insn_aux_data[env->insn_idx];
7946 }
7947 
7948 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7949 {
7950 	struct bpf_reg_state *regs = cur_regs(env);
7951 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7952 	bool reg_is_null = register_is_null(reg);
7953 
7954 	if (reg_is_null)
7955 		mark_chain_precision(env, BPF_REG_4);
7956 
7957 	return reg_is_null;
7958 }
7959 
7960 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7961 {
7962 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7963 
7964 	if (!state->initialized) {
7965 		state->initialized = 1;
7966 		state->fit_for_inline = loop_flag_is_zero(env);
7967 		state->callback_subprogno = subprogno;
7968 		return;
7969 	}
7970 
7971 	if (!state->fit_for_inline)
7972 		return;
7973 
7974 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7975 				 state->callback_subprogno == subprogno);
7976 }
7977 
7978 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7979 			     int *insn_idx_p)
7980 {
7981 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7982 	const struct bpf_func_proto *fn = NULL;
7983 	enum bpf_return_type ret_type;
7984 	enum bpf_type_flag ret_flag;
7985 	struct bpf_reg_state *regs;
7986 	struct bpf_call_arg_meta meta;
7987 	int insn_idx = *insn_idx_p;
7988 	bool changes_data;
7989 	int i, err, func_id;
7990 
7991 	/* find function prototype */
7992 	func_id = insn->imm;
7993 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7994 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7995 			func_id);
7996 		return -EINVAL;
7997 	}
7998 
7999 	if (env->ops->get_func_proto)
8000 		fn = env->ops->get_func_proto(func_id, env->prog);
8001 	if (!fn) {
8002 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8003 			func_id);
8004 		return -EINVAL;
8005 	}
8006 
8007 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
8008 	if (!env->prog->gpl_compatible && fn->gpl_only) {
8009 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8010 		return -EINVAL;
8011 	}
8012 
8013 	if (fn->allowed && !fn->allowed(env->prog)) {
8014 		verbose(env, "helper call is not allowed in probe\n");
8015 		return -EINVAL;
8016 	}
8017 
8018 	if (!env->prog->aux->sleepable && fn->might_sleep) {
8019 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
8020 		return -EINVAL;
8021 	}
8022 
8023 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
8024 	changes_data = bpf_helper_changes_pkt_data(fn->func);
8025 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8026 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8027 			func_id_name(func_id), func_id);
8028 		return -EINVAL;
8029 	}
8030 
8031 	memset(&meta, 0, sizeof(meta));
8032 	meta.pkt_access = fn->pkt_access;
8033 
8034 	err = check_func_proto(fn, func_id);
8035 	if (err) {
8036 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8037 			func_id_name(func_id), func_id);
8038 		return err;
8039 	}
8040 
8041 	if (env->cur_state->active_rcu_lock) {
8042 		if (fn->might_sleep) {
8043 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8044 				func_id_name(func_id), func_id);
8045 			return -EINVAL;
8046 		}
8047 
8048 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8049 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8050 	}
8051 
8052 	meta.func_id = func_id;
8053 	/* check args */
8054 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8055 		err = check_func_arg(env, i, &meta, fn);
8056 		if (err)
8057 			return err;
8058 	}
8059 
8060 	err = record_func_map(env, &meta, func_id, insn_idx);
8061 	if (err)
8062 		return err;
8063 
8064 	err = record_func_key(env, &meta, func_id, insn_idx);
8065 	if (err)
8066 		return err;
8067 
8068 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
8069 	 * is inferred from register state.
8070 	 */
8071 	for (i = 0; i < meta.access_size; i++) {
8072 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8073 				       BPF_WRITE, -1, false);
8074 		if (err)
8075 			return err;
8076 	}
8077 
8078 	regs = cur_regs(env);
8079 
8080 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8081 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
8082 	 * is safe to do directly.
8083 	 */
8084 	if (meta.uninit_dynptr_regno) {
8085 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
8086 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
8087 			return -EFAULT;
8088 		}
8089 		/* we write BPF_DW bits (8 bytes) at a time */
8090 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8091 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
8092 					       i, BPF_DW, BPF_WRITE, -1, false);
8093 			if (err)
8094 				return err;
8095 		}
8096 
8097 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
8098 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
8099 					      insn_idx);
8100 		if (err)
8101 			return err;
8102 	}
8103 
8104 	if (meta.release_regno) {
8105 		err = -EINVAL;
8106 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8107 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8108 		 * is safe to do directly.
8109 		 */
8110 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8111 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8112 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8113 				return -EFAULT;
8114 			}
8115 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8116 		} else if (meta.ref_obj_id) {
8117 			err = release_reference(env, meta.ref_obj_id);
8118 		} else if (register_is_null(&regs[meta.release_regno])) {
8119 			/* meta.ref_obj_id can only be 0 if register that is meant to be
8120 			 * released is NULL, which must be > R0.
8121 			 */
8122 			err = 0;
8123 		}
8124 		if (err) {
8125 			verbose(env, "func %s#%d reference has not been acquired before\n",
8126 				func_id_name(func_id), func_id);
8127 			return err;
8128 		}
8129 	}
8130 
8131 	switch (func_id) {
8132 	case BPF_FUNC_tail_call:
8133 		err = check_reference_leak(env);
8134 		if (err) {
8135 			verbose(env, "tail_call would lead to reference leak\n");
8136 			return err;
8137 		}
8138 		break;
8139 	case BPF_FUNC_get_local_storage:
8140 		/* check that flags argument in get_local_storage(map, flags) is 0,
8141 		 * this is required because get_local_storage() can't return an error.
8142 		 */
8143 		if (!register_is_null(&regs[BPF_REG_2])) {
8144 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8145 			return -EINVAL;
8146 		}
8147 		break;
8148 	case BPF_FUNC_for_each_map_elem:
8149 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8150 					set_map_elem_callback_state);
8151 		break;
8152 	case BPF_FUNC_timer_set_callback:
8153 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8154 					set_timer_callback_state);
8155 		break;
8156 	case BPF_FUNC_find_vma:
8157 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8158 					set_find_vma_callback_state);
8159 		break;
8160 	case BPF_FUNC_snprintf:
8161 		err = check_bpf_snprintf_call(env, regs);
8162 		break;
8163 	case BPF_FUNC_loop:
8164 		update_loop_inline_state(env, meta.subprogno);
8165 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8166 					set_loop_callback_state);
8167 		break;
8168 	case BPF_FUNC_dynptr_from_mem:
8169 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8170 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8171 				reg_type_str(env, regs[BPF_REG_1].type));
8172 			return -EACCES;
8173 		}
8174 		break;
8175 	case BPF_FUNC_set_retval:
8176 		if (prog_type == BPF_PROG_TYPE_LSM &&
8177 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8178 			if (!env->prog->aux->attach_func_proto->type) {
8179 				/* Make sure programs that attach to void
8180 				 * hooks don't try to modify return value.
8181 				 */
8182 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8183 				return -EINVAL;
8184 			}
8185 		}
8186 		break;
8187 	case BPF_FUNC_dynptr_data:
8188 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8189 			if (arg_type_is_dynptr(fn->arg_type[i])) {
8190 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
8191 				int id, ref_obj_id;
8192 
8193 				if (meta.dynptr_id) {
8194 					verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8195 					return -EFAULT;
8196 				}
8197 
8198 				if (meta.ref_obj_id) {
8199 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8200 					return -EFAULT;
8201 				}
8202 
8203 				id = dynptr_id(env, reg);
8204 				if (id < 0) {
8205 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8206 					return id;
8207 				}
8208 
8209 				ref_obj_id = dynptr_ref_obj_id(env, reg);
8210 				if (ref_obj_id < 0) {
8211 					verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8212 					return ref_obj_id;
8213 				}
8214 
8215 				meta.dynptr_id = id;
8216 				meta.ref_obj_id = ref_obj_id;
8217 				break;
8218 			}
8219 		}
8220 		if (i == MAX_BPF_FUNC_REG_ARGS) {
8221 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
8222 			return -EFAULT;
8223 		}
8224 		break;
8225 	case BPF_FUNC_user_ringbuf_drain:
8226 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8227 					set_user_ringbuf_callback_state);
8228 		break;
8229 	}
8230 
8231 	if (err)
8232 		return err;
8233 
8234 	/* reset caller saved regs */
8235 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8236 		mark_reg_not_init(env, regs, caller_saved[i]);
8237 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8238 	}
8239 
8240 	/* helper call returns 64-bit value. */
8241 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8242 
8243 	/* update return register (already marked as written above) */
8244 	ret_type = fn->ret_type;
8245 	ret_flag = type_flag(ret_type);
8246 
8247 	switch (base_type(ret_type)) {
8248 	case RET_INTEGER:
8249 		/* sets type to SCALAR_VALUE */
8250 		mark_reg_unknown(env, regs, BPF_REG_0);
8251 		break;
8252 	case RET_VOID:
8253 		regs[BPF_REG_0].type = NOT_INIT;
8254 		break;
8255 	case RET_PTR_TO_MAP_VALUE:
8256 		/* There is no offset yet applied, variable or fixed */
8257 		mark_reg_known_zero(env, regs, BPF_REG_0);
8258 		/* remember map_ptr, so that check_map_access()
8259 		 * can check 'value_size' boundary of memory access
8260 		 * to map element returned from bpf_map_lookup_elem()
8261 		 */
8262 		if (meta.map_ptr == NULL) {
8263 			verbose(env,
8264 				"kernel subsystem misconfigured verifier\n");
8265 			return -EINVAL;
8266 		}
8267 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
8268 		regs[BPF_REG_0].map_uid = meta.map_uid;
8269 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8270 		if (!type_may_be_null(ret_type) &&
8271 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8272 			regs[BPF_REG_0].id = ++env->id_gen;
8273 		}
8274 		break;
8275 	case RET_PTR_TO_SOCKET:
8276 		mark_reg_known_zero(env, regs, BPF_REG_0);
8277 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8278 		break;
8279 	case RET_PTR_TO_SOCK_COMMON:
8280 		mark_reg_known_zero(env, regs, BPF_REG_0);
8281 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8282 		break;
8283 	case RET_PTR_TO_TCP_SOCK:
8284 		mark_reg_known_zero(env, regs, BPF_REG_0);
8285 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8286 		break;
8287 	case RET_PTR_TO_MEM:
8288 		mark_reg_known_zero(env, regs, BPF_REG_0);
8289 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8290 		regs[BPF_REG_0].mem_size = meta.mem_size;
8291 		break;
8292 	case RET_PTR_TO_MEM_OR_BTF_ID:
8293 	{
8294 		const struct btf_type *t;
8295 
8296 		mark_reg_known_zero(env, regs, BPF_REG_0);
8297 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8298 		if (!btf_type_is_struct(t)) {
8299 			u32 tsize;
8300 			const struct btf_type *ret;
8301 			const char *tname;
8302 
8303 			/* resolve the type size of ksym. */
8304 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8305 			if (IS_ERR(ret)) {
8306 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8307 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8308 					tname, PTR_ERR(ret));
8309 				return -EINVAL;
8310 			}
8311 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8312 			regs[BPF_REG_0].mem_size = tsize;
8313 		} else {
8314 			/* MEM_RDONLY may be carried from ret_flag, but it
8315 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8316 			 * it will confuse the check of PTR_TO_BTF_ID in
8317 			 * check_mem_access().
8318 			 */
8319 			ret_flag &= ~MEM_RDONLY;
8320 
8321 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8322 			regs[BPF_REG_0].btf = meta.ret_btf;
8323 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8324 		}
8325 		break;
8326 	}
8327 	case RET_PTR_TO_BTF_ID:
8328 	{
8329 		struct btf *ret_btf;
8330 		int ret_btf_id;
8331 
8332 		mark_reg_known_zero(env, regs, BPF_REG_0);
8333 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8334 		if (func_id == BPF_FUNC_kptr_xchg) {
8335 			ret_btf = meta.kptr_field->kptr.btf;
8336 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8337 		} else {
8338 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8339 				verbose(env, "verifier internal error:");
8340 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8341 					func_id_name(func_id));
8342 				return -EINVAL;
8343 			}
8344 			ret_btf = btf_vmlinux;
8345 			ret_btf_id = *fn->ret_btf_id;
8346 		}
8347 		if (ret_btf_id == 0) {
8348 			verbose(env, "invalid return type %u of func %s#%d\n",
8349 				base_type(ret_type), func_id_name(func_id),
8350 				func_id);
8351 			return -EINVAL;
8352 		}
8353 		regs[BPF_REG_0].btf = ret_btf;
8354 		regs[BPF_REG_0].btf_id = ret_btf_id;
8355 		break;
8356 	}
8357 	default:
8358 		verbose(env, "unknown return type %u of func %s#%d\n",
8359 			base_type(ret_type), func_id_name(func_id), func_id);
8360 		return -EINVAL;
8361 	}
8362 
8363 	if (type_may_be_null(regs[BPF_REG_0].type))
8364 		regs[BPF_REG_0].id = ++env->id_gen;
8365 
8366 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8367 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8368 			func_id_name(func_id), func_id);
8369 		return -EFAULT;
8370 	}
8371 
8372 	if (is_dynptr_ref_function(func_id))
8373 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8374 
8375 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8376 		/* For release_reference() */
8377 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8378 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8379 		int id = acquire_reference_state(env, insn_idx);
8380 
8381 		if (id < 0)
8382 			return id;
8383 		/* For mark_ptr_or_null_reg() */
8384 		regs[BPF_REG_0].id = id;
8385 		/* For release_reference() */
8386 		regs[BPF_REG_0].ref_obj_id = id;
8387 	}
8388 
8389 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8390 
8391 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8392 	if (err)
8393 		return err;
8394 
8395 	if ((func_id == BPF_FUNC_get_stack ||
8396 	     func_id == BPF_FUNC_get_task_stack) &&
8397 	    !env->prog->has_callchain_buf) {
8398 		const char *err_str;
8399 
8400 #ifdef CONFIG_PERF_EVENTS
8401 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8402 		err_str = "cannot get callchain buffer for func %s#%d\n";
8403 #else
8404 		err = -ENOTSUPP;
8405 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8406 #endif
8407 		if (err) {
8408 			verbose(env, err_str, func_id_name(func_id), func_id);
8409 			return err;
8410 		}
8411 
8412 		env->prog->has_callchain_buf = true;
8413 	}
8414 
8415 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8416 		env->prog->call_get_stack = true;
8417 
8418 	if (func_id == BPF_FUNC_get_func_ip) {
8419 		if (check_get_func_ip(env))
8420 			return -ENOTSUPP;
8421 		env->prog->call_get_func_ip = true;
8422 	}
8423 
8424 	if (changes_data)
8425 		clear_all_pkt_pointers(env);
8426 	return 0;
8427 }
8428 
8429 /* mark_btf_func_reg_size() is used when the reg size is determined by
8430  * the BTF func_proto's return value size and argument.
8431  */
8432 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8433 				   size_t reg_size)
8434 {
8435 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8436 
8437 	if (regno == BPF_REG_0) {
8438 		/* Function return value */
8439 		reg->live |= REG_LIVE_WRITTEN;
8440 		reg->subreg_def = reg_size == sizeof(u64) ?
8441 			DEF_NOT_SUBREG : env->insn_idx + 1;
8442 	} else {
8443 		/* Function argument */
8444 		if (reg_size == sizeof(u64)) {
8445 			mark_insn_zext(env, reg);
8446 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8447 		} else {
8448 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8449 		}
8450 	}
8451 }
8452 
8453 struct bpf_kfunc_call_arg_meta {
8454 	/* In parameters */
8455 	struct btf *btf;
8456 	u32 func_id;
8457 	u32 kfunc_flags;
8458 	const struct btf_type *func_proto;
8459 	const char *func_name;
8460 	/* Out parameters */
8461 	u32 ref_obj_id;
8462 	u8 release_regno;
8463 	bool r0_rdonly;
8464 	u32 ret_btf_id;
8465 	u64 r0_size;
8466 	struct {
8467 		u64 value;
8468 		bool found;
8469 	} arg_constant;
8470 	struct {
8471 		struct btf *btf;
8472 		u32 btf_id;
8473 	} arg_obj_drop;
8474 	struct {
8475 		struct btf_field *field;
8476 	} arg_list_head;
8477 };
8478 
8479 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8480 {
8481 	return meta->kfunc_flags & KF_ACQUIRE;
8482 }
8483 
8484 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8485 {
8486 	return meta->kfunc_flags & KF_RET_NULL;
8487 }
8488 
8489 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8490 {
8491 	return meta->kfunc_flags & KF_RELEASE;
8492 }
8493 
8494 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8495 {
8496 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8497 }
8498 
8499 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8500 {
8501 	return meta->kfunc_flags & KF_SLEEPABLE;
8502 }
8503 
8504 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8505 {
8506 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8507 }
8508 
8509 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8510 {
8511 	return meta->kfunc_flags & KF_RCU;
8512 }
8513 
8514 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8515 {
8516 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8517 }
8518 
8519 static bool __kfunc_param_match_suffix(const struct btf *btf,
8520 				       const struct btf_param *arg,
8521 				       const char *suffix)
8522 {
8523 	int suffix_len = strlen(suffix), len;
8524 	const char *param_name;
8525 
8526 	/* In the future, this can be ported to use BTF tagging */
8527 	param_name = btf_name_by_offset(btf, arg->name_off);
8528 	if (str_is_empty(param_name))
8529 		return false;
8530 	len = strlen(param_name);
8531 	if (len < suffix_len)
8532 		return false;
8533 	param_name += len - suffix_len;
8534 	return !strncmp(param_name, suffix, suffix_len);
8535 }
8536 
8537 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8538 				  const struct btf_param *arg,
8539 				  const struct bpf_reg_state *reg)
8540 {
8541 	const struct btf_type *t;
8542 
8543 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8544 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8545 		return false;
8546 
8547 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8548 }
8549 
8550 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8551 {
8552 	return __kfunc_param_match_suffix(btf, arg, "__k");
8553 }
8554 
8555 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8556 {
8557 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8558 }
8559 
8560 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8561 {
8562 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8563 }
8564 
8565 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8566 					  const struct btf_param *arg,
8567 					  const char *name)
8568 {
8569 	int len, target_len = strlen(name);
8570 	const char *param_name;
8571 
8572 	param_name = btf_name_by_offset(btf, arg->name_off);
8573 	if (str_is_empty(param_name))
8574 		return false;
8575 	len = strlen(param_name);
8576 	if (len != target_len)
8577 		return false;
8578 	if (strcmp(param_name, name))
8579 		return false;
8580 
8581 	return true;
8582 }
8583 
8584 enum {
8585 	KF_ARG_DYNPTR_ID,
8586 	KF_ARG_LIST_HEAD_ID,
8587 	KF_ARG_LIST_NODE_ID,
8588 };
8589 
8590 BTF_ID_LIST(kf_arg_btf_ids)
8591 BTF_ID(struct, bpf_dynptr_kern)
8592 BTF_ID(struct, bpf_list_head)
8593 BTF_ID(struct, bpf_list_node)
8594 
8595 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8596 				    const struct btf_param *arg, int type)
8597 {
8598 	const struct btf_type *t;
8599 	u32 res_id;
8600 
8601 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8602 	if (!t)
8603 		return false;
8604 	if (!btf_type_is_ptr(t))
8605 		return false;
8606 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8607 	if (!t)
8608 		return false;
8609 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8610 }
8611 
8612 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8613 {
8614 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8615 }
8616 
8617 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8618 {
8619 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8620 }
8621 
8622 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8623 {
8624 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8625 }
8626 
8627 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8628 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8629 					const struct btf *btf,
8630 					const struct btf_type *t, int rec)
8631 {
8632 	const struct btf_type *member_type;
8633 	const struct btf_member *member;
8634 	u32 i;
8635 
8636 	if (!btf_type_is_struct(t))
8637 		return false;
8638 
8639 	for_each_member(i, t, member) {
8640 		const struct btf_array *array;
8641 
8642 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8643 		if (btf_type_is_struct(member_type)) {
8644 			if (rec >= 3) {
8645 				verbose(env, "max struct nesting depth exceeded\n");
8646 				return false;
8647 			}
8648 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8649 				return false;
8650 			continue;
8651 		}
8652 		if (btf_type_is_array(member_type)) {
8653 			array = btf_array(member_type);
8654 			if (!array->nelems)
8655 				return false;
8656 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8657 			if (!btf_type_is_scalar(member_type))
8658 				return false;
8659 			continue;
8660 		}
8661 		if (!btf_type_is_scalar(member_type))
8662 			return false;
8663 	}
8664 	return true;
8665 }
8666 
8667 
8668 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8669 #ifdef CONFIG_NET
8670 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8671 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8672 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8673 #endif
8674 };
8675 
8676 enum kfunc_ptr_arg_type {
8677 	KF_ARG_PTR_TO_CTX,
8678 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8679 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8680 	KF_ARG_PTR_TO_DYNPTR,
8681 	KF_ARG_PTR_TO_LIST_HEAD,
8682 	KF_ARG_PTR_TO_LIST_NODE,
8683 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8684 	KF_ARG_PTR_TO_MEM,
8685 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8686 };
8687 
8688 enum special_kfunc_type {
8689 	KF_bpf_obj_new_impl,
8690 	KF_bpf_obj_drop_impl,
8691 	KF_bpf_list_push_front,
8692 	KF_bpf_list_push_back,
8693 	KF_bpf_list_pop_front,
8694 	KF_bpf_list_pop_back,
8695 	KF_bpf_cast_to_kern_ctx,
8696 	KF_bpf_rdonly_cast,
8697 	KF_bpf_rcu_read_lock,
8698 	KF_bpf_rcu_read_unlock,
8699 };
8700 
8701 BTF_SET_START(special_kfunc_set)
8702 BTF_ID(func, bpf_obj_new_impl)
8703 BTF_ID(func, bpf_obj_drop_impl)
8704 BTF_ID(func, bpf_list_push_front)
8705 BTF_ID(func, bpf_list_push_back)
8706 BTF_ID(func, bpf_list_pop_front)
8707 BTF_ID(func, bpf_list_pop_back)
8708 BTF_ID(func, bpf_cast_to_kern_ctx)
8709 BTF_ID(func, bpf_rdonly_cast)
8710 BTF_SET_END(special_kfunc_set)
8711 
8712 BTF_ID_LIST(special_kfunc_list)
8713 BTF_ID(func, bpf_obj_new_impl)
8714 BTF_ID(func, bpf_obj_drop_impl)
8715 BTF_ID(func, bpf_list_push_front)
8716 BTF_ID(func, bpf_list_push_back)
8717 BTF_ID(func, bpf_list_pop_front)
8718 BTF_ID(func, bpf_list_pop_back)
8719 BTF_ID(func, bpf_cast_to_kern_ctx)
8720 BTF_ID(func, bpf_rdonly_cast)
8721 BTF_ID(func, bpf_rcu_read_lock)
8722 BTF_ID(func, bpf_rcu_read_unlock)
8723 
8724 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8725 {
8726 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8727 }
8728 
8729 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8730 {
8731 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8732 }
8733 
8734 static enum kfunc_ptr_arg_type
8735 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8736 		       struct bpf_kfunc_call_arg_meta *meta,
8737 		       const struct btf_type *t, const struct btf_type *ref_t,
8738 		       const char *ref_tname, const struct btf_param *args,
8739 		       int argno, int nargs)
8740 {
8741 	u32 regno = argno + 1;
8742 	struct bpf_reg_state *regs = cur_regs(env);
8743 	struct bpf_reg_state *reg = &regs[regno];
8744 	bool arg_mem_size = false;
8745 
8746 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8747 		return KF_ARG_PTR_TO_CTX;
8748 
8749 	/* In this function, we verify the kfunc's BTF as per the argument type,
8750 	 * leaving the rest of the verification with respect to the register
8751 	 * type to our caller. When a set of conditions hold in the BTF type of
8752 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8753 	 */
8754 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8755 		return KF_ARG_PTR_TO_CTX;
8756 
8757 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8758 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8759 
8760 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8761 		if (!btf_type_is_ptr(ref_t)) {
8762 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8763 			return -EINVAL;
8764 		}
8765 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8766 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8767 		if (!btf_type_is_struct(ref_t)) {
8768 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8769 				meta->func_name, btf_type_str(ref_t), ref_tname);
8770 			return -EINVAL;
8771 		}
8772 		return KF_ARG_PTR_TO_KPTR;
8773 	}
8774 
8775 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8776 		return KF_ARG_PTR_TO_DYNPTR;
8777 
8778 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8779 		return KF_ARG_PTR_TO_LIST_HEAD;
8780 
8781 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8782 		return KF_ARG_PTR_TO_LIST_NODE;
8783 
8784 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8785 		if (!btf_type_is_struct(ref_t)) {
8786 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8787 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8788 			return -EINVAL;
8789 		}
8790 		return KF_ARG_PTR_TO_BTF_ID;
8791 	}
8792 
8793 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8794 		arg_mem_size = true;
8795 
8796 	/* This is the catch all argument type of register types supported by
8797 	 * check_helper_mem_access. However, we only allow when argument type is
8798 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8799 	 * arg_mem_size is true, the pointer can be void *.
8800 	 */
8801 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8802 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8803 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8804 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8805 		return -EINVAL;
8806 	}
8807 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8808 }
8809 
8810 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8811 					struct bpf_reg_state *reg,
8812 					const struct btf_type *ref_t,
8813 					const char *ref_tname, u32 ref_id,
8814 					struct bpf_kfunc_call_arg_meta *meta,
8815 					int argno)
8816 {
8817 	const struct btf_type *reg_ref_t;
8818 	bool strict_type_match = false;
8819 	const struct btf *reg_btf;
8820 	const char *reg_ref_tname;
8821 	u32 reg_ref_id;
8822 
8823 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
8824 		reg_btf = reg->btf;
8825 		reg_ref_id = reg->btf_id;
8826 	} else {
8827 		reg_btf = btf_vmlinux;
8828 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8829 	}
8830 
8831 	/* Enforce strict type matching for calls to kfuncs that are acquiring
8832 	 * or releasing a reference, or are no-cast aliases. We do _not_
8833 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
8834 	 * as we want to enable BPF programs to pass types that are bitwise
8835 	 * equivalent without forcing them to explicitly cast with something
8836 	 * like bpf_cast_to_kern_ctx().
8837 	 *
8838 	 * For example, say we had a type like the following:
8839 	 *
8840 	 * struct bpf_cpumask {
8841 	 *	cpumask_t cpumask;
8842 	 *	refcount_t usage;
8843 	 * };
8844 	 *
8845 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
8846 	 * to a struct cpumask, so it would be safe to pass a struct
8847 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
8848 	 *
8849 	 * The philosophy here is similar to how we allow scalars of different
8850 	 * types to be passed to kfuncs as long as the size is the same. The
8851 	 * only difference here is that we're simply allowing
8852 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
8853 	 * resolve types.
8854 	 */
8855 	if (is_kfunc_acquire(meta) ||
8856 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
8857 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
8858 		strict_type_match = true;
8859 
8860 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
8861 
8862 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8863 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8864 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8865 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8866 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8867 			btf_type_str(reg_ref_t), reg_ref_tname);
8868 		return -EINVAL;
8869 	}
8870 	return 0;
8871 }
8872 
8873 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8874 				      struct bpf_reg_state *reg,
8875 				      const struct btf_type *ref_t,
8876 				      const char *ref_tname,
8877 				      struct bpf_kfunc_call_arg_meta *meta,
8878 				      int argno)
8879 {
8880 	struct btf_field *kptr_field;
8881 
8882 	/* check_func_arg_reg_off allows var_off for
8883 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8884 	 * off_desc.
8885 	 */
8886 	if (!tnum_is_const(reg->var_off)) {
8887 		verbose(env, "arg#0 must have constant offset\n");
8888 		return -EINVAL;
8889 	}
8890 
8891 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8892 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8893 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8894 			reg->off + reg->var_off.value);
8895 		return -EINVAL;
8896 	}
8897 
8898 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8899 				  kptr_field->kptr.btf_id, true)) {
8900 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8901 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8902 		return -EINVAL;
8903 	}
8904 	return 0;
8905 }
8906 
8907 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8908 {
8909 	struct bpf_func_state *state = cur_func(env);
8910 	struct bpf_reg_state *reg;
8911 	int i;
8912 
8913 	/* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8914 	 * subprogs, no global functions. This means that the references would
8915 	 * not be released inside the critical section but they may be added to
8916 	 * the reference state, and the acquired_refs are never copied out for a
8917 	 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8918 	 * critical sections.
8919 	 */
8920 	if (!ref_obj_id) {
8921 		verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8922 		return -EFAULT;
8923 	}
8924 	for (i = 0; i < state->acquired_refs; i++) {
8925 		if (state->refs[i].id == ref_obj_id) {
8926 			if (state->refs[i].release_on_unlock) {
8927 				verbose(env, "verifier internal error: expected false release_on_unlock");
8928 				return -EFAULT;
8929 			}
8930 			state->refs[i].release_on_unlock = true;
8931 			/* Now mark everyone sharing same ref_obj_id as untrusted */
8932 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8933 				if (reg->ref_obj_id == ref_obj_id)
8934 					reg->type |= PTR_UNTRUSTED;
8935 			}));
8936 			return 0;
8937 		}
8938 	}
8939 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8940 	return -EFAULT;
8941 }
8942 
8943 /* Implementation details:
8944  *
8945  * Each register points to some region of memory, which we define as an
8946  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8947  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8948  * allocation. The lock and the data it protects are colocated in the same
8949  * memory region.
8950  *
8951  * Hence, everytime a register holds a pointer value pointing to such
8952  * allocation, the verifier preserves a unique reg->id for it.
8953  *
8954  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8955  * bpf_spin_lock is called.
8956  *
8957  * To enable this, lock state in the verifier captures two values:
8958  *	active_lock.ptr = Register's type specific pointer
8959  *	active_lock.id  = A unique ID for each register pointer value
8960  *
8961  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8962  * supported register types.
8963  *
8964  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8965  * allocated objects is the reg->btf pointer.
8966  *
8967  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8968  * can establish the provenance of the map value statically for each distinct
8969  * lookup into such maps. They always contain a single map value hence unique
8970  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8971  *
8972  * So, in case of global variables, they use array maps with max_entries = 1,
8973  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8974  * into the same map value as max_entries is 1, as described above).
8975  *
8976  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8977  * outer map pointer (in verifier context), but each lookup into an inner map
8978  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8979  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8980  * will get different reg->id assigned to each lookup, hence different
8981  * active_lock.id.
8982  *
8983  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8984  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8985  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8986  */
8987 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8988 {
8989 	void *ptr;
8990 	u32 id;
8991 
8992 	switch ((int)reg->type) {
8993 	case PTR_TO_MAP_VALUE:
8994 		ptr = reg->map_ptr;
8995 		break;
8996 	case PTR_TO_BTF_ID | MEM_ALLOC:
8997 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8998 		ptr = reg->btf;
8999 		break;
9000 	default:
9001 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
9002 		return -EFAULT;
9003 	}
9004 	id = reg->id;
9005 
9006 	if (!env->cur_state->active_lock.ptr)
9007 		return -EINVAL;
9008 	if (env->cur_state->active_lock.ptr != ptr ||
9009 	    env->cur_state->active_lock.id != id) {
9010 		verbose(env, "held lock and object are not in the same allocation\n");
9011 		return -EINVAL;
9012 	}
9013 	return 0;
9014 }
9015 
9016 static bool is_bpf_list_api_kfunc(u32 btf_id)
9017 {
9018 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9019 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9020 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9021 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9022 }
9023 
9024 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9025 					   struct bpf_reg_state *reg, u32 regno,
9026 					   struct bpf_kfunc_call_arg_meta *meta)
9027 {
9028 	struct btf_field *field;
9029 	struct btf_record *rec;
9030 	u32 list_head_off;
9031 
9032 	if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
9033 		verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
9034 		return -EFAULT;
9035 	}
9036 
9037 	if (!tnum_is_const(reg->var_off)) {
9038 		verbose(env,
9039 			"R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
9040 			regno);
9041 		return -EINVAL;
9042 	}
9043 
9044 	rec = reg_btf_record(reg);
9045 	list_head_off = reg->off + reg->var_off.value;
9046 	field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
9047 	if (!field) {
9048 		verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
9049 		return -EINVAL;
9050 	}
9051 
9052 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9053 	if (check_reg_allocation_locked(env, reg)) {
9054 		verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
9055 			rec->spin_lock_off);
9056 		return -EINVAL;
9057 	}
9058 
9059 	if (meta->arg_list_head.field) {
9060 		verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
9061 		return -EFAULT;
9062 	}
9063 	meta->arg_list_head.field = field;
9064 	return 0;
9065 }
9066 
9067 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9068 					   struct bpf_reg_state *reg, u32 regno,
9069 					   struct bpf_kfunc_call_arg_meta *meta)
9070 {
9071 	const struct btf_type *et, *t;
9072 	struct btf_field *field;
9073 	struct btf_record *rec;
9074 	u32 list_node_off;
9075 
9076 	if (meta->btf != btf_vmlinux ||
9077 	    (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
9078 	     meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
9079 		verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
9080 		return -EFAULT;
9081 	}
9082 
9083 	if (!tnum_is_const(reg->var_off)) {
9084 		verbose(env,
9085 			"R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
9086 			regno);
9087 		return -EINVAL;
9088 	}
9089 
9090 	rec = reg_btf_record(reg);
9091 	list_node_off = reg->off + reg->var_off.value;
9092 	field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
9093 	if (!field || field->offset != list_node_off) {
9094 		verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
9095 		return -EINVAL;
9096 	}
9097 
9098 	field = meta->arg_list_head.field;
9099 
9100 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9101 	t = btf_type_by_id(reg->btf, reg->btf_id);
9102 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9103 				  field->graph_root.value_btf_id, true)) {
9104 		verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
9105 			"in struct %s, but arg is at offset=%d in struct %s\n",
9106 			field->graph_root.node_offset,
9107 			btf_name_by_offset(field->graph_root.btf, et->name_off),
9108 			list_node_off, btf_name_by_offset(reg->btf, t->name_off));
9109 		return -EINVAL;
9110 	}
9111 
9112 	if (list_node_off != field->graph_root.node_offset) {
9113 		verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
9114 			list_node_off, field->graph_root.node_offset,
9115 			btf_name_by_offset(field->graph_root.btf, et->name_off));
9116 		return -EINVAL;
9117 	}
9118 	/* Set arg#1 for expiration after unlock */
9119 	return ref_set_release_on_unlock(env, reg->ref_obj_id);
9120 }
9121 
9122 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
9123 {
9124 	const char *func_name = meta->func_name, *ref_tname;
9125 	const struct btf *btf = meta->btf;
9126 	const struct btf_param *args;
9127 	u32 i, nargs;
9128 	int ret;
9129 
9130 	args = (const struct btf_param *)(meta->func_proto + 1);
9131 	nargs = btf_type_vlen(meta->func_proto);
9132 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9133 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9134 			MAX_BPF_FUNC_REG_ARGS);
9135 		return -EINVAL;
9136 	}
9137 
9138 	/* Check that BTF function arguments match actual types that the
9139 	 * verifier sees.
9140 	 */
9141 	for (i = 0; i < nargs; i++) {
9142 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9143 		const struct btf_type *t, *ref_t, *resolve_ret;
9144 		enum bpf_arg_type arg_type = ARG_DONTCARE;
9145 		u32 regno = i + 1, ref_id, type_size;
9146 		bool is_ret_buf_sz = false;
9147 		int kf_arg_type;
9148 
9149 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9150 
9151 		if (is_kfunc_arg_ignore(btf, &args[i]))
9152 			continue;
9153 
9154 		if (btf_type_is_scalar(t)) {
9155 			if (reg->type != SCALAR_VALUE) {
9156 				verbose(env, "R%d is not a scalar\n", regno);
9157 				return -EINVAL;
9158 			}
9159 
9160 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9161 				if (meta->arg_constant.found) {
9162 					verbose(env, "verifier internal error: only one constant argument permitted\n");
9163 					return -EFAULT;
9164 				}
9165 				if (!tnum_is_const(reg->var_off)) {
9166 					verbose(env, "R%d must be a known constant\n", regno);
9167 					return -EINVAL;
9168 				}
9169 				ret = mark_chain_precision(env, regno);
9170 				if (ret < 0)
9171 					return ret;
9172 				meta->arg_constant.found = true;
9173 				meta->arg_constant.value = reg->var_off.value;
9174 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9175 				meta->r0_rdonly = true;
9176 				is_ret_buf_sz = true;
9177 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9178 				is_ret_buf_sz = true;
9179 			}
9180 
9181 			if (is_ret_buf_sz) {
9182 				if (meta->r0_size) {
9183 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9184 					return -EINVAL;
9185 				}
9186 
9187 				if (!tnum_is_const(reg->var_off)) {
9188 					verbose(env, "R%d is not a const\n", regno);
9189 					return -EINVAL;
9190 				}
9191 
9192 				meta->r0_size = reg->var_off.value;
9193 				ret = mark_chain_precision(env, regno);
9194 				if (ret)
9195 					return ret;
9196 			}
9197 			continue;
9198 		}
9199 
9200 		if (!btf_type_is_ptr(t)) {
9201 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9202 			return -EINVAL;
9203 		}
9204 
9205 		if (is_kfunc_trusted_args(meta) &&
9206 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
9207 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9208 			return -EACCES;
9209 		}
9210 
9211 		if (reg->ref_obj_id) {
9212 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
9213 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9214 					regno, reg->ref_obj_id,
9215 					meta->ref_obj_id);
9216 				return -EFAULT;
9217 			}
9218 			meta->ref_obj_id = reg->ref_obj_id;
9219 			if (is_kfunc_release(meta))
9220 				meta->release_regno = regno;
9221 		}
9222 
9223 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9224 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9225 
9226 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9227 		if (kf_arg_type < 0)
9228 			return kf_arg_type;
9229 
9230 		switch (kf_arg_type) {
9231 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9232 		case KF_ARG_PTR_TO_BTF_ID:
9233 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9234 				break;
9235 
9236 			if (!is_trusted_reg(reg)) {
9237 				if (!is_kfunc_rcu(meta)) {
9238 					verbose(env, "R%d must be referenced or trusted\n", regno);
9239 					return -EINVAL;
9240 				}
9241 				if (!is_rcu_reg(reg)) {
9242 					verbose(env, "R%d must be a rcu pointer\n", regno);
9243 					return -EINVAL;
9244 				}
9245 			}
9246 
9247 			fallthrough;
9248 		case KF_ARG_PTR_TO_CTX:
9249 			/* Trusted arguments have the same offset checks as release arguments */
9250 			arg_type |= OBJ_RELEASE;
9251 			break;
9252 		case KF_ARG_PTR_TO_KPTR:
9253 		case KF_ARG_PTR_TO_DYNPTR:
9254 		case KF_ARG_PTR_TO_LIST_HEAD:
9255 		case KF_ARG_PTR_TO_LIST_NODE:
9256 		case KF_ARG_PTR_TO_MEM:
9257 		case KF_ARG_PTR_TO_MEM_SIZE:
9258 			/* Trusted by default */
9259 			break;
9260 		default:
9261 			WARN_ON_ONCE(1);
9262 			return -EFAULT;
9263 		}
9264 
9265 		if (is_kfunc_release(meta) && reg->ref_obj_id)
9266 			arg_type |= OBJ_RELEASE;
9267 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9268 		if (ret < 0)
9269 			return ret;
9270 
9271 		switch (kf_arg_type) {
9272 		case KF_ARG_PTR_TO_CTX:
9273 			if (reg->type != PTR_TO_CTX) {
9274 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9275 				return -EINVAL;
9276 			}
9277 
9278 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9279 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9280 				if (ret < 0)
9281 					return -EINVAL;
9282 				meta->ret_btf_id  = ret;
9283 			}
9284 			break;
9285 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9286 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9287 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9288 				return -EINVAL;
9289 			}
9290 			if (!reg->ref_obj_id) {
9291 				verbose(env, "allocated object must be referenced\n");
9292 				return -EINVAL;
9293 			}
9294 			if (meta->btf == btf_vmlinux &&
9295 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9296 				meta->arg_obj_drop.btf = reg->btf;
9297 				meta->arg_obj_drop.btf_id = reg->btf_id;
9298 			}
9299 			break;
9300 		case KF_ARG_PTR_TO_KPTR:
9301 			if (reg->type != PTR_TO_MAP_VALUE) {
9302 				verbose(env, "arg#0 expected pointer to map value\n");
9303 				return -EINVAL;
9304 			}
9305 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9306 			if (ret < 0)
9307 				return ret;
9308 			break;
9309 		case KF_ARG_PTR_TO_DYNPTR:
9310 			if (reg->type != PTR_TO_STACK &&
9311 			    reg->type != CONST_PTR_TO_DYNPTR) {
9312 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9313 				return -EINVAL;
9314 			}
9315 
9316 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
9317 			if (ret < 0)
9318 				return ret;
9319 			break;
9320 		case KF_ARG_PTR_TO_LIST_HEAD:
9321 			if (reg->type != PTR_TO_MAP_VALUE &&
9322 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9323 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9324 				return -EINVAL;
9325 			}
9326 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9327 				verbose(env, "allocated object must be referenced\n");
9328 				return -EINVAL;
9329 			}
9330 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9331 			if (ret < 0)
9332 				return ret;
9333 			break;
9334 		case KF_ARG_PTR_TO_LIST_NODE:
9335 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9336 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9337 				return -EINVAL;
9338 			}
9339 			if (!reg->ref_obj_id) {
9340 				verbose(env, "allocated object must be referenced\n");
9341 				return -EINVAL;
9342 			}
9343 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9344 			if (ret < 0)
9345 				return ret;
9346 			break;
9347 		case KF_ARG_PTR_TO_BTF_ID:
9348 			/* Only base_type is checked, further checks are done here */
9349 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9350 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9351 			    !reg2btf_ids[base_type(reg->type)]) {
9352 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9353 				verbose(env, "expected %s or socket\n",
9354 					reg_type_str(env, base_type(reg->type) |
9355 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9356 				return -EINVAL;
9357 			}
9358 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9359 			if (ret < 0)
9360 				return ret;
9361 			break;
9362 		case KF_ARG_PTR_TO_MEM:
9363 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9364 			if (IS_ERR(resolve_ret)) {
9365 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9366 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9367 				return -EINVAL;
9368 			}
9369 			ret = check_mem_reg(env, reg, regno, type_size);
9370 			if (ret < 0)
9371 				return ret;
9372 			break;
9373 		case KF_ARG_PTR_TO_MEM_SIZE:
9374 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9375 			if (ret < 0) {
9376 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9377 				return ret;
9378 			}
9379 			/* Skip next '__sz' argument */
9380 			i++;
9381 			break;
9382 		}
9383 	}
9384 
9385 	if (is_kfunc_release(meta) && !meta->release_regno) {
9386 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9387 			func_name);
9388 		return -EINVAL;
9389 	}
9390 
9391 	return 0;
9392 }
9393 
9394 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9395 			    int *insn_idx_p)
9396 {
9397 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9398 	struct bpf_reg_state *regs = cur_regs(env);
9399 	const char *func_name, *ptr_type_name;
9400 	bool sleepable, rcu_lock, rcu_unlock;
9401 	struct bpf_kfunc_call_arg_meta meta;
9402 	u32 i, nargs, func_id, ptr_type_id;
9403 	int err, insn_idx = *insn_idx_p;
9404 	const struct btf_param *args;
9405 	const struct btf_type *ret_t;
9406 	struct btf *desc_btf;
9407 	u32 *kfunc_flags;
9408 
9409 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9410 	if (!insn->imm)
9411 		return 0;
9412 
9413 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9414 	if (IS_ERR(desc_btf))
9415 		return PTR_ERR(desc_btf);
9416 
9417 	func_id = insn->imm;
9418 	func = btf_type_by_id(desc_btf, func_id);
9419 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9420 	func_proto = btf_type_by_id(desc_btf, func->type);
9421 
9422 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9423 	if (!kfunc_flags) {
9424 		verbose(env, "calling kernel function %s is not allowed\n",
9425 			func_name);
9426 		return -EACCES;
9427 	}
9428 
9429 	/* Prepare kfunc call metadata */
9430 	memset(&meta, 0, sizeof(meta));
9431 	meta.btf = desc_btf;
9432 	meta.func_id = func_id;
9433 	meta.kfunc_flags = *kfunc_flags;
9434 	meta.func_proto = func_proto;
9435 	meta.func_name = func_name;
9436 
9437 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9438 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9439 		return -EACCES;
9440 	}
9441 
9442 	sleepable = is_kfunc_sleepable(&meta);
9443 	if (sleepable && !env->prog->aux->sleepable) {
9444 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9445 		return -EACCES;
9446 	}
9447 
9448 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9449 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9450 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9451 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9452 		return -EACCES;
9453 	}
9454 
9455 	if (env->cur_state->active_rcu_lock) {
9456 		struct bpf_func_state *state;
9457 		struct bpf_reg_state *reg;
9458 
9459 		if (rcu_lock) {
9460 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9461 			return -EINVAL;
9462 		} else if (rcu_unlock) {
9463 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9464 				if (reg->type & MEM_RCU) {
9465 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9466 					reg->type |= PTR_UNTRUSTED;
9467 				}
9468 			}));
9469 			env->cur_state->active_rcu_lock = false;
9470 		} else if (sleepable) {
9471 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9472 			return -EACCES;
9473 		}
9474 	} else if (rcu_lock) {
9475 		env->cur_state->active_rcu_lock = true;
9476 	} else if (rcu_unlock) {
9477 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9478 		return -EINVAL;
9479 	}
9480 
9481 	/* Check the arguments */
9482 	err = check_kfunc_args(env, &meta);
9483 	if (err < 0)
9484 		return err;
9485 	/* In case of release function, we get register number of refcounted
9486 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9487 	 */
9488 	if (meta.release_regno) {
9489 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9490 		if (err) {
9491 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9492 				func_name, func_id);
9493 			return err;
9494 		}
9495 	}
9496 
9497 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9498 		mark_reg_not_init(env, regs, caller_saved[i]);
9499 
9500 	/* Check return type */
9501 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9502 
9503 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9504 		/* Only exception is bpf_obj_new_impl */
9505 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9506 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9507 			return -EINVAL;
9508 		}
9509 	}
9510 
9511 	if (btf_type_is_scalar(t)) {
9512 		mark_reg_unknown(env, regs, BPF_REG_0);
9513 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9514 	} else if (btf_type_is_ptr(t)) {
9515 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9516 
9517 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9518 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9519 				struct btf *ret_btf;
9520 				u32 ret_btf_id;
9521 
9522 				if (unlikely(!bpf_global_ma_set))
9523 					return -ENOMEM;
9524 
9525 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9526 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9527 					return -EINVAL;
9528 				}
9529 
9530 				ret_btf = env->prog->aux->btf;
9531 				ret_btf_id = meta.arg_constant.value;
9532 
9533 				/* This may be NULL due to user not supplying a BTF */
9534 				if (!ret_btf) {
9535 					verbose(env, "bpf_obj_new requires prog BTF\n");
9536 					return -EINVAL;
9537 				}
9538 
9539 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9540 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9541 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9542 					return -EINVAL;
9543 				}
9544 
9545 				mark_reg_known_zero(env, regs, BPF_REG_0);
9546 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9547 				regs[BPF_REG_0].btf = ret_btf;
9548 				regs[BPF_REG_0].btf_id = ret_btf_id;
9549 
9550 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9551 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9552 					btf_find_struct_meta(ret_btf, ret_btf_id);
9553 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9554 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9555 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9556 							     meta.arg_obj_drop.btf_id);
9557 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9558 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9559 				struct btf_field *field = meta.arg_list_head.field;
9560 
9561 				mark_reg_known_zero(env, regs, BPF_REG_0);
9562 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9563 				regs[BPF_REG_0].btf = field->graph_root.btf;
9564 				regs[BPF_REG_0].btf_id = field->graph_root.value_btf_id;
9565 				regs[BPF_REG_0].off = field->graph_root.node_offset;
9566 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9567 				mark_reg_known_zero(env, regs, BPF_REG_0);
9568 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9569 				regs[BPF_REG_0].btf = desc_btf;
9570 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9571 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9572 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9573 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9574 					verbose(env,
9575 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9576 					return -EINVAL;
9577 				}
9578 
9579 				mark_reg_known_zero(env, regs, BPF_REG_0);
9580 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9581 				regs[BPF_REG_0].btf = desc_btf;
9582 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9583 			} else {
9584 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9585 					meta.func_name);
9586 				return -EFAULT;
9587 			}
9588 		} else if (!__btf_type_is_struct(ptr_type)) {
9589 			if (!meta.r0_size) {
9590 				ptr_type_name = btf_name_by_offset(desc_btf,
9591 								   ptr_type->name_off);
9592 				verbose(env,
9593 					"kernel function %s returns pointer type %s %s is not supported\n",
9594 					func_name,
9595 					btf_type_str(ptr_type),
9596 					ptr_type_name);
9597 				return -EINVAL;
9598 			}
9599 
9600 			mark_reg_known_zero(env, regs, BPF_REG_0);
9601 			regs[BPF_REG_0].type = PTR_TO_MEM;
9602 			regs[BPF_REG_0].mem_size = meta.r0_size;
9603 
9604 			if (meta.r0_rdonly)
9605 				regs[BPF_REG_0].type |= MEM_RDONLY;
9606 
9607 			/* Ensures we don't access the memory after a release_reference() */
9608 			if (meta.ref_obj_id)
9609 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9610 		} else {
9611 			mark_reg_known_zero(env, regs, BPF_REG_0);
9612 			regs[BPF_REG_0].btf = desc_btf;
9613 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9614 			regs[BPF_REG_0].btf_id = ptr_type_id;
9615 		}
9616 
9617 		if (is_kfunc_ret_null(&meta)) {
9618 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9619 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9620 			regs[BPF_REG_0].id = ++env->id_gen;
9621 		}
9622 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9623 		if (is_kfunc_acquire(&meta)) {
9624 			int id = acquire_reference_state(env, insn_idx);
9625 
9626 			if (id < 0)
9627 				return id;
9628 			if (is_kfunc_ret_null(&meta))
9629 				regs[BPF_REG_0].id = id;
9630 			regs[BPF_REG_0].ref_obj_id = id;
9631 		}
9632 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9633 			regs[BPF_REG_0].id = ++env->id_gen;
9634 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9635 
9636 	nargs = btf_type_vlen(func_proto);
9637 	args = (const struct btf_param *)(func_proto + 1);
9638 	for (i = 0; i < nargs; i++) {
9639 		u32 regno = i + 1;
9640 
9641 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9642 		if (btf_type_is_ptr(t))
9643 			mark_btf_func_reg_size(env, regno, sizeof(void *));
9644 		else
9645 			/* scalar. ensured by btf_check_kfunc_arg_match() */
9646 			mark_btf_func_reg_size(env, regno, t->size);
9647 	}
9648 
9649 	return 0;
9650 }
9651 
9652 static bool signed_add_overflows(s64 a, s64 b)
9653 {
9654 	/* Do the add in u64, where overflow is well-defined */
9655 	s64 res = (s64)((u64)a + (u64)b);
9656 
9657 	if (b < 0)
9658 		return res > a;
9659 	return res < a;
9660 }
9661 
9662 static bool signed_add32_overflows(s32 a, s32 b)
9663 {
9664 	/* Do the add in u32, where overflow is well-defined */
9665 	s32 res = (s32)((u32)a + (u32)b);
9666 
9667 	if (b < 0)
9668 		return res > a;
9669 	return res < a;
9670 }
9671 
9672 static bool signed_sub_overflows(s64 a, s64 b)
9673 {
9674 	/* Do the sub in u64, where overflow is well-defined */
9675 	s64 res = (s64)((u64)a - (u64)b);
9676 
9677 	if (b < 0)
9678 		return res < a;
9679 	return res > a;
9680 }
9681 
9682 static bool signed_sub32_overflows(s32 a, s32 b)
9683 {
9684 	/* Do the sub in u32, where overflow is well-defined */
9685 	s32 res = (s32)((u32)a - (u32)b);
9686 
9687 	if (b < 0)
9688 		return res < a;
9689 	return res > a;
9690 }
9691 
9692 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9693 				  const struct bpf_reg_state *reg,
9694 				  enum bpf_reg_type type)
9695 {
9696 	bool known = tnum_is_const(reg->var_off);
9697 	s64 val = reg->var_off.value;
9698 	s64 smin = reg->smin_value;
9699 
9700 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9701 		verbose(env, "math between %s pointer and %lld is not allowed\n",
9702 			reg_type_str(env, type), val);
9703 		return false;
9704 	}
9705 
9706 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9707 		verbose(env, "%s pointer offset %d is not allowed\n",
9708 			reg_type_str(env, type), reg->off);
9709 		return false;
9710 	}
9711 
9712 	if (smin == S64_MIN) {
9713 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9714 			reg_type_str(env, type));
9715 		return false;
9716 	}
9717 
9718 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9719 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
9720 			smin, reg_type_str(env, type));
9721 		return false;
9722 	}
9723 
9724 	return true;
9725 }
9726 
9727 enum {
9728 	REASON_BOUNDS	= -1,
9729 	REASON_TYPE	= -2,
9730 	REASON_PATHS	= -3,
9731 	REASON_LIMIT	= -4,
9732 	REASON_STACK	= -5,
9733 };
9734 
9735 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9736 			      u32 *alu_limit, bool mask_to_left)
9737 {
9738 	u32 max = 0, ptr_limit = 0;
9739 
9740 	switch (ptr_reg->type) {
9741 	case PTR_TO_STACK:
9742 		/* Offset 0 is out-of-bounds, but acceptable start for the
9743 		 * left direction, see BPF_REG_FP. Also, unknown scalar
9744 		 * offset where we would need to deal with min/max bounds is
9745 		 * currently prohibited for unprivileged.
9746 		 */
9747 		max = MAX_BPF_STACK + mask_to_left;
9748 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9749 		break;
9750 	case PTR_TO_MAP_VALUE:
9751 		max = ptr_reg->map_ptr->value_size;
9752 		ptr_limit = (mask_to_left ?
9753 			     ptr_reg->smin_value :
9754 			     ptr_reg->umax_value) + ptr_reg->off;
9755 		break;
9756 	default:
9757 		return REASON_TYPE;
9758 	}
9759 
9760 	if (ptr_limit >= max)
9761 		return REASON_LIMIT;
9762 	*alu_limit = ptr_limit;
9763 	return 0;
9764 }
9765 
9766 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9767 				    const struct bpf_insn *insn)
9768 {
9769 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9770 }
9771 
9772 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9773 				       u32 alu_state, u32 alu_limit)
9774 {
9775 	/* If we arrived here from different branches with different
9776 	 * state or limits to sanitize, then this won't work.
9777 	 */
9778 	if (aux->alu_state &&
9779 	    (aux->alu_state != alu_state ||
9780 	     aux->alu_limit != alu_limit))
9781 		return REASON_PATHS;
9782 
9783 	/* Corresponding fixup done in do_misc_fixups(). */
9784 	aux->alu_state = alu_state;
9785 	aux->alu_limit = alu_limit;
9786 	return 0;
9787 }
9788 
9789 static int sanitize_val_alu(struct bpf_verifier_env *env,
9790 			    struct bpf_insn *insn)
9791 {
9792 	struct bpf_insn_aux_data *aux = cur_aux(env);
9793 
9794 	if (can_skip_alu_sanitation(env, insn))
9795 		return 0;
9796 
9797 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9798 }
9799 
9800 static bool sanitize_needed(u8 opcode)
9801 {
9802 	return opcode == BPF_ADD || opcode == BPF_SUB;
9803 }
9804 
9805 struct bpf_sanitize_info {
9806 	struct bpf_insn_aux_data aux;
9807 	bool mask_to_left;
9808 };
9809 
9810 static struct bpf_verifier_state *
9811 sanitize_speculative_path(struct bpf_verifier_env *env,
9812 			  const struct bpf_insn *insn,
9813 			  u32 next_idx, u32 curr_idx)
9814 {
9815 	struct bpf_verifier_state *branch;
9816 	struct bpf_reg_state *regs;
9817 
9818 	branch = push_stack(env, next_idx, curr_idx, true);
9819 	if (branch && insn) {
9820 		regs = branch->frame[branch->curframe]->regs;
9821 		if (BPF_SRC(insn->code) == BPF_K) {
9822 			mark_reg_unknown(env, regs, insn->dst_reg);
9823 		} else if (BPF_SRC(insn->code) == BPF_X) {
9824 			mark_reg_unknown(env, regs, insn->dst_reg);
9825 			mark_reg_unknown(env, regs, insn->src_reg);
9826 		}
9827 	}
9828 	return branch;
9829 }
9830 
9831 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9832 			    struct bpf_insn *insn,
9833 			    const struct bpf_reg_state *ptr_reg,
9834 			    const struct bpf_reg_state *off_reg,
9835 			    struct bpf_reg_state *dst_reg,
9836 			    struct bpf_sanitize_info *info,
9837 			    const bool commit_window)
9838 {
9839 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9840 	struct bpf_verifier_state *vstate = env->cur_state;
9841 	bool off_is_imm = tnum_is_const(off_reg->var_off);
9842 	bool off_is_neg = off_reg->smin_value < 0;
9843 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
9844 	u8 opcode = BPF_OP(insn->code);
9845 	u32 alu_state, alu_limit;
9846 	struct bpf_reg_state tmp;
9847 	bool ret;
9848 	int err;
9849 
9850 	if (can_skip_alu_sanitation(env, insn))
9851 		return 0;
9852 
9853 	/* We already marked aux for masking from non-speculative
9854 	 * paths, thus we got here in the first place. We only care
9855 	 * to explore bad access from here.
9856 	 */
9857 	if (vstate->speculative)
9858 		goto do_sim;
9859 
9860 	if (!commit_window) {
9861 		if (!tnum_is_const(off_reg->var_off) &&
9862 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9863 			return REASON_BOUNDS;
9864 
9865 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9866 				     (opcode == BPF_SUB && !off_is_neg);
9867 	}
9868 
9869 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9870 	if (err < 0)
9871 		return err;
9872 
9873 	if (commit_window) {
9874 		/* In commit phase we narrow the masking window based on
9875 		 * the observed pointer move after the simulated operation.
9876 		 */
9877 		alu_state = info->aux.alu_state;
9878 		alu_limit = abs(info->aux.alu_limit - alu_limit);
9879 	} else {
9880 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9881 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9882 		alu_state |= ptr_is_dst_reg ?
9883 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9884 
9885 		/* Limit pruning on unknown scalars to enable deep search for
9886 		 * potential masking differences from other program paths.
9887 		 */
9888 		if (!off_is_imm)
9889 			env->explore_alu_limits = true;
9890 	}
9891 
9892 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9893 	if (err < 0)
9894 		return err;
9895 do_sim:
9896 	/* If we're in commit phase, we're done here given we already
9897 	 * pushed the truncated dst_reg into the speculative verification
9898 	 * stack.
9899 	 *
9900 	 * Also, when register is a known constant, we rewrite register-based
9901 	 * operation to immediate-based, and thus do not need masking (and as
9902 	 * a consequence, do not need to simulate the zero-truncation either).
9903 	 */
9904 	if (commit_window || off_is_imm)
9905 		return 0;
9906 
9907 	/* Simulate and find potential out-of-bounds access under
9908 	 * speculative execution from truncation as a result of
9909 	 * masking when off was not within expected range. If off
9910 	 * sits in dst, then we temporarily need to move ptr there
9911 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9912 	 * for cases where we use K-based arithmetic in one direction
9913 	 * and truncated reg-based in the other in order to explore
9914 	 * bad access.
9915 	 */
9916 	if (!ptr_is_dst_reg) {
9917 		tmp = *dst_reg;
9918 		*dst_reg = *ptr_reg;
9919 	}
9920 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9921 					env->insn_idx);
9922 	if (!ptr_is_dst_reg && ret)
9923 		*dst_reg = tmp;
9924 	return !ret ? REASON_STACK : 0;
9925 }
9926 
9927 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9928 {
9929 	struct bpf_verifier_state *vstate = env->cur_state;
9930 
9931 	/* If we simulate paths under speculation, we don't update the
9932 	 * insn as 'seen' such that when we verify unreachable paths in
9933 	 * the non-speculative domain, sanitize_dead_code() can still
9934 	 * rewrite/sanitize them.
9935 	 */
9936 	if (!vstate->speculative)
9937 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9938 }
9939 
9940 static int sanitize_err(struct bpf_verifier_env *env,
9941 			const struct bpf_insn *insn, int reason,
9942 			const struct bpf_reg_state *off_reg,
9943 			const struct bpf_reg_state *dst_reg)
9944 {
9945 	static const char *err = "pointer arithmetic with it prohibited for !root";
9946 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9947 	u32 dst = insn->dst_reg, src = insn->src_reg;
9948 
9949 	switch (reason) {
9950 	case REASON_BOUNDS:
9951 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9952 			off_reg == dst_reg ? dst : src, err);
9953 		break;
9954 	case REASON_TYPE:
9955 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9956 			off_reg == dst_reg ? src : dst, err);
9957 		break;
9958 	case REASON_PATHS:
9959 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9960 			dst, op, err);
9961 		break;
9962 	case REASON_LIMIT:
9963 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9964 			dst, op, err);
9965 		break;
9966 	case REASON_STACK:
9967 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9968 			dst, err);
9969 		break;
9970 	default:
9971 		verbose(env, "verifier internal error: unknown reason (%d)\n",
9972 			reason);
9973 		break;
9974 	}
9975 
9976 	return -EACCES;
9977 }
9978 
9979 /* check that stack access falls within stack limits and that 'reg' doesn't
9980  * have a variable offset.
9981  *
9982  * Variable offset is prohibited for unprivileged mode for simplicity since it
9983  * requires corresponding support in Spectre masking for stack ALU.  See also
9984  * retrieve_ptr_limit().
9985  *
9986  *
9987  * 'off' includes 'reg->off'.
9988  */
9989 static int check_stack_access_for_ptr_arithmetic(
9990 				struct bpf_verifier_env *env,
9991 				int regno,
9992 				const struct bpf_reg_state *reg,
9993 				int off)
9994 {
9995 	if (!tnum_is_const(reg->var_off)) {
9996 		char tn_buf[48];
9997 
9998 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9999 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10000 			regno, tn_buf, off);
10001 		return -EACCES;
10002 	}
10003 
10004 	if (off >= 0 || off < -MAX_BPF_STACK) {
10005 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
10006 			"prohibited for !root; off=%d\n", regno, off);
10007 		return -EACCES;
10008 	}
10009 
10010 	return 0;
10011 }
10012 
10013 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10014 				 const struct bpf_insn *insn,
10015 				 const struct bpf_reg_state *dst_reg)
10016 {
10017 	u32 dst = insn->dst_reg;
10018 
10019 	/* For unprivileged we require that resulting offset must be in bounds
10020 	 * in order to be able to sanitize access later on.
10021 	 */
10022 	if (env->bypass_spec_v1)
10023 		return 0;
10024 
10025 	switch (dst_reg->type) {
10026 	case PTR_TO_STACK:
10027 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10028 					dst_reg->off + dst_reg->var_off.value))
10029 			return -EACCES;
10030 		break;
10031 	case PTR_TO_MAP_VALUE:
10032 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10033 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10034 				"prohibited for !root\n", dst);
10035 			return -EACCES;
10036 		}
10037 		break;
10038 	default:
10039 		break;
10040 	}
10041 
10042 	return 0;
10043 }
10044 
10045 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10046  * Caller should also handle BPF_MOV case separately.
10047  * If we return -EACCES, caller may want to try again treating pointer as a
10048  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10049  */
10050 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10051 				   struct bpf_insn *insn,
10052 				   const struct bpf_reg_state *ptr_reg,
10053 				   const struct bpf_reg_state *off_reg)
10054 {
10055 	struct bpf_verifier_state *vstate = env->cur_state;
10056 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10057 	struct bpf_reg_state *regs = state->regs, *dst_reg;
10058 	bool known = tnum_is_const(off_reg->var_off);
10059 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10060 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10061 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10062 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10063 	struct bpf_sanitize_info info = {};
10064 	u8 opcode = BPF_OP(insn->code);
10065 	u32 dst = insn->dst_reg;
10066 	int ret;
10067 
10068 	dst_reg = &regs[dst];
10069 
10070 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10071 	    smin_val > smax_val || umin_val > umax_val) {
10072 		/* Taint dst register if offset had invalid bounds derived from
10073 		 * e.g. dead branches.
10074 		 */
10075 		__mark_reg_unknown(env, dst_reg);
10076 		return 0;
10077 	}
10078 
10079 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
10080 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
10081 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10082 			__mark_reg_unknown(env, dst_reg);
10083 			return 0;
10084 		}
10085 
10086 		verbose(env,
10087 			"R%d 32-bit pointer arithmetic prohibited\n",
10088 			dst);
10089 		return -EACCES;
10090 	}
10091 
10092 	if (ptr_reg->type & PTR_MAYBE_NULL) {
10093 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10094 			dst, reg_type_str(env, ptr_reg->type));
10095 		return -EACCES;
10096 	}
10097 
10098 	switch (base_type(ptr_reg->type)) {
10099 	case CONST_PTR_TO_MAP:
10100 		/* smin_val represents the known value */
10101 		if (known && smin_val == 0 && opcode == BPF_ADD)
10102 			break;
10103 		fallthrough;
10104 	case PTR_TO_PACKET_END:
10105 	case PTR_TO_SOCKET:
10106 	case PTR_TO_SOCK_COMMON:
10107 	case PTR_TO_TCP_SOCK:
10108 	case PTR_TO_XDP_SOCK:
10109 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10110 			dst, reg_type_str(env, ptr_reg->type));
10111 		return -EACCES;
10112 	default:
10113 		break;
10114 	}
10115 
10116 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10117 	 * The id may be overwritten later if we create a new variable offset.
10118 	 */
10119 	dst_reg->type = ptr_reg->type;
10120 	dst_reg->id = ptr_reg->id;
10121 
10122 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10123 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10124 		return -EINVAL;
10125 
10126 	/* pointer types do not carry 32-bit bounds at the moment. */
10127 	__mark_reg32_unbounded(dst_reg);
10128 
10129 	if (sanitize_needed(opcode)) {
10130 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10131 				       &info, false);
10132 		if (ret < 0)
10133 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10134 	}
10135 
10136 	switch (opcode) {
10137 	case BPF_ADD:
10138 		/* We can take a fixed offset as long as it doesn't overflow
10139 		 * the s32 'off' field
10140 		 */
10141 		if (known && (ptr_reg->off + smin_val ==
10142 			      (s64)(s32)(ptr_reg->off + smin_val))) {
10143 			/* pointer += K.  Accumulate it into fixed offset */
10144 			dst_reg->smin_value = smin_ptr;
10145 			dst_reg->smax_value = smax_ptr;
10146 			dst_reg->umin_value = umin_ptr;
10147 			dst_reg->umax_value = umax_ptr;
10148 			dst_reg->var_off = ptr_reg->var_off;
10149 			dst_reg->off = ptr_reg->off + smin_val;
10150 			dst_reg->raw = ptr_reg->raw;
10151 			break;
10152 		}
10153 		/* A new variable offset is created.  Note that off_reg->off
10154 		 * == 0, since it's a scalar.
10155 		 * dst_reg gets the pointer type and since some positive
10156 		 * integer value was added to the pointer, give it a new 'id'
10157 		 * if it's a PTR_TO_PACKET.
10158 		 * this creates a new 'base' pointer, off_reg (variable) gets
10159 		 * added into the variable offset, and we copy the fixed offset
10160 		 * from ptr_reg.
10161 		 */
10162 		if (signed_add_overflows(smin_ptr, smin_val) ||
10163 		    signed_add_overflows(smax_ptr, smax_val)) {
10164 			dst_reg->smin_value = S64_MIN;
10165 			dst_reg->smax_value = S64_MAX;
10166 		} else {
10167 			dst_reg->smin_value = smin_ptr + smin_val;
10168 			dst_reg->smax_value = smax_ptr + smax_val;
10169 		}
10170 		if (umin_ptr + umin_val < umin_ptr ||
10171 		    umax_ptr + umax_val < umax_ptr) {
10172 			dst_reg->umin_value = 0;
10173 			dst_reg->umax_value = U64_MAX;
10174 		} else {
10175 			dst_reg->umin_value = umin_ptr + umin_val;
10176 			dst_reg->umax_value = umax_ptr + umax_val;
10177 		}
10178 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10179 		dst_reg->off = ptr_reg->off;
10180 		dst_reg->raw = ptr_reg->raw;
10181 		if (reg_is_pkt_pointer(ptr_reg)) {
10182 			dst_reg->id = ++env->id_gen;
10183 			/* something was added to pkt_ptr, set range to zero */
10184 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10185 		}
10186 		break;
10187 	case BPF_SUB:
10188 		if (dst_reg == off_reg) {
10189 			/* scalar -= pointer.  Creates an unknown scalar */
10190 			verbose(env, "R%d tried to subtract pointer from scalar\n",
10191 				dst);
10192 			return -EACCES;
10193 		}
10194 		/* We don't allow subtraction from FP, because (according to
10195 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
10196 		 * be able to deal with it.
10197 		 */
10198 		if (ptr_reg->type == PTR_TO_STACK) {
10199 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
10200 				dst);
10201 			return -EACCES;
10202 		}
10203 		if (known && (ptr_reg->off - smin_val ==
10204 			      (s64)(s32)(ptr_reg->off - smin_val))) {
10205 			/* pointer -= K.  Subtract it from fixed offset */
10206 			dst_reg->smin_value = smin_ptr;
10207 			dst_reg->smax_value = smax_ptr;
10208 			dst_reg->umin_value = umin_ptr;
10209 			dst_reg->umax_value = umax_ptr;
10210 			dst_reg->var_off = ptr_reg->var_off;
10211 			dst_reg->id = ptr_reg->id;
10212 			dst_reg->off = ptr_reg->off - smin_val;
10213 			dst_reg->raw = ptr_reg->raw;
10214 			break;
10215 		}
10216 		/* A new variable offset is created.  If the subtrahend is known
10217 		 * nonnegative, then any reg->range we had before is still good.
10218 		 */
10219 		if (signed_sub_overflows(smin_ptr, smax_val) ||
10220 		    signed_sub_overflows(smax_ptr, smin_val)) {
10221 			/* Overflow possible, we know nothing */
10222 			dst_reg->smin_value = S64_MIN;
10223 			dst_reg->smax_value = S64_MAX;
10224 		} else {
10225 			dst_reg->smin_value = smin_ptr - smax_val;
10226 			dst_reg->smax_value = smax_ptr - smin_val;
10227 		}
10228 		if (umin_ptr < umax_val) {
10229 			/* Overflow possible, we know nothing */
10230 			dst_reg->umin_value = 0;
10231 			dst_reg->umax_value = U64_MAX;
10232 		} else {
10233 			/* Cannot overflow (as long as bounds are consistent) */
10234 			dst_reg->umin_value = umin_ptr - umax_val;
10235 			dst_reg->umax_value = umax_ptr - umin_val;
10236 		}
10237 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10238 		dst_reg->off = ptr_reg->off;
10239 		dst_reg->raw = ptr_reg->raw;
10240 		if (reg_is_pkt_pointer(ptr_reg)) {
10241 			dst_reg->id = ++env->id_gen;
10242 			/* something was added to pkt_ptr, set range to zero */
10243 			if (smin_val < 0)
10244 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10245 		}
10246 		break;
10247 	case BPF_AND:
10248 	case BPF_OR:
10249 	case BPF_XOR:
10250 		/* bitwise ops on pointers are troublesome, prohibit. */
10251 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
10252 			dst, bpf_alu_string[opcode >> 4]);
10253 		return -EACCES;
10254 	default:
10255 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
10256 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
10257 			dst, bpf_alu_string[opcode >> 4]);
10258 		return -EACCES;
10259 	}
10260 
10261 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
10262 		return -EINVAL;
10263 	reg_bounds_sync(dst_reg);
10264 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
10265 		return -EACCES;
10266 	if (sanitize_needed(opcode)) {
10267 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
10268 				       &info, true);
10269 		if (ret < 0)
10270 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10271 	}
10272 
10273 	return 0;
10274 }
10275 
10276 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
10277 				 struct bpf_reg_state *src_reg)
10278 {
10279 	s32 smin_val = src_reg->s32_min_value;
10280 	s32 smax_val = src_reg->s32_max_value;
10281 	u32 umin_val = src_reg->u32_min_value;
10282 	u32 umax_val = src_reg->u32_max_value;
10283 
10284 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
10285 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
10286 		dst_reg->s32_min_value = S32_MIN;
10287 		dst_reg->s32_max_value = S32_MAX;
10288 	} else {
10289 		dst_reg->s32_min_value += smin_val;
10290 		dst_reg->s32_max_value += smax_val;
10291 	}
10292 	if (dst_reg->u32_min_value + umin_val < umin_val ||
10293 	    dst_reg->u32_max_value + umax_val < umax_val) {
10294 		dst_reg->u32_min_value = 0;
10295 		dst_reg->u32_max_value = U32_MAX;
10296 	} else {
10297 		dst_reg->u32_min_value += umin_val;
10298 		dst_reg->u32_max_value += umax_val;
10299 	}
10300 }
10301 
10302 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
10303 			       struct bpf_reg_state *src_reg)
10304 {
10305 	s64 smin_val = src_reg->smin_value;
10306 	s64 smax_val = src_reg->smax_value;
10307 	u64 umin_val = src_reg->umin_value;
10308 	u64 umax_val = src_reg->umax_value;
10309 
10310 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
10311 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
10312 		dst_reg->smin_value = S64_MIN;
10313 		dst_reg->smax_value = S64_MAX;
10314 	} else {
10315 		dst_reg->smin_value += smin_val;
10316 		dst_reg->smax_value += smax_val;
10317 	}
10318 	if (dst_reg->umin_value + umin_val < umin_val ||
10319 	    dst_reg->umax_value + umax_val < umax_val) {
10320 		dst_reg->umin_value = 0;
10321 		dst_reg->umax_value = U64_MAX;
10322 	} else {
10323 		dst_reg->umin_value += umin_val;
10324 		dst_reg->umax_value += umax_val;
10325 	}
10326 }
10327 
10328 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10329 				 struct bpf_reg_state *src_reg)
10330 {
10331 	s32 smin_val = src_reg->s32_min_value;
10332 	s32 smax_val = src_reg->s32_max_value;
10333 	u32 umin_val = src_reg->u32_min_value;
10334 	u32 umax_val = src_reg->u32_max_value;
10335 
10336 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10337 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10338 		/* Overflow possible, we know nothing */
10339 		dst_reg->s32_min_value = S32_MIN;
10340 		dst_reg->s32_max_value = S32_MAX;
10341 	} else {
10342 		dst_reg->s32_min_value -= smax_val;
10343 		dst_reg->s32_max_value -= smin_val;
10344 	}
10345 	if (dst_reg->u32_min_value < umax_val) {
10346 		/* Overflow possible, we know nothing */
10347 		dst_reg->u32_min_value = 0;
10348 		dst_reg->u32_max_value = U32_MAX;
10349 	} else {
10350 		/* Cannot overflow (as long as bounds are consistent) */
10351 		dst_reg->u32_min_value -= umax_val;
10352 		dst_reg->u32_max_value -= umin_val;
10353 	}
10354 }
10355 
10356 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10357 			       struct bpf_reg_state *src_reg)
10358 {
10359 	s64 smin_val = src_reg->smin_value;
10360 	s64 smax_val = src_reg->smax_value;
10361 	u64 umin_val = src_reg->umin_value;
10362 	u64 umax_val = src_reg->umax_value;
10363 
10364 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10365 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10366 		/* Overflow possible, we know nothing */
10367 		dst_reg->smin_value = S64_MIN;
10368 		dst_reg->smax_value = S64_MAX;
10369 	} else {
10370 		dst_reg->smin_value -= smax_val;
10371 		dst_reg->smax_value -= smin_val;
10372 	}
10373 	if (dst_reg->umin_value < umax_val) {
10374 		/* Overflow possible, we know nothing */
10375 		dst_reg->umin_value = 0;
10376 		dst_reg->umax_value = U64_MAX;
10377 	} else {
10378 		/* Cannot overflow (as long as bounds are consistent) */
10379 		dst_reg->umin_value -= umax_val;
10380 		dst_reg->umax_value -= umin_val;
10381 	}
10382 }
10383 
10384 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10385 				 struct bpf_reg_state *src_reg)
10386 {
10387 	s32 smin_val = src_reg->s32_min_value;
10388 	u32 umin_val = src_reg->u32_min_value;
10389 	u32 umax_val = src_reg->u32_max_value;
10390 
10391 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10392 		/* Ain't nobody got time to multiply that sign */
10393 		__mark_reg32_unbounded(dst_reg);
10394 		return;
10395 	}
10396 	/* Both values are positive, so we can work with unsigned and
10397 	 * copy the result to signed (unless it exceeds S32_MAX).
10398 	 */
10399 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10400 		/* Potential overflow, we know nothing */
10401 		__mark_reg32_unbounded(dst_reg);
10402 		return;
10403 	}
10404 	dst_reg->u32_min_value *= umin_val;
10405 	dst_reg->u32_max_value *= umax_val;
10406 	if (dst_reg->u32_max_value > S32_MAX) {
10407 		/* Overflow possible, we know nothing */
10408 		dst_reg->s32_min_value = S32_MIN;
10409 		dst_reg->s32_max_value = S32_MAX;
10410 	} else {
10411 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10412 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10413 	}
10414 }
10415 
10416 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10417 			       struct bpf_reg_state *src_reg)
10418 {
10419 	s64 smin_val = src_reg->smin_value;
10420 	u64 umin_val = src_reg->umin_value;
10421 	u64 umax_val = src_reg->umax_value;
10422 
10423 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10424 		/* Ain't nobody got time to multiply that sign */
10425 		__mark_reg64_unbounded(dst_reg);
10426 		return;
10427 	}
10428 	/* Both values are positive, so we can work with unsigned and
10429 	 * copy the result to signed (unless it exceeds S64_MAX).
10430 	 */
10431 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10432 		/* Potential overflow, we know nothing */
10433 		__mark_reg64_unbounded(dst_reg);
10434 		return;
10435 	}
10436 	dst_reg->umin_value *= umin_val;
10437 	dst_reg->umax_value *= umax_val;
10438 	if (dst_reg->umax_value > S64_MAX) {
10439 		/* Overflow possible, we know nothing */
10440 		dst_reg->smin_value = S64_MIN;
10441 		dst_reg->smax_value = S64_MAX;
10442 	} else {
10443 		dst_reg->smin_value = dst_reg->umin_value;
10444 		dst_reg->smax_value = dst_reg->umax_value;
10445 	}
10446 }
10447 
10448 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10449 				 struct bpf_reg_state *src_reg)
10450 {
10451 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10452 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10453 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10454 	s32 smin_val = src_reg->s32_min_value;
10455 	u32 umax_val = src_reg->u32_max_value;
10456 
10457 	if (src_known && dst_known) {
10458 		__mark_reg32_known(dst_reg, var32_off.value);
10459 		return;
10460 	}
10461 
10462 	/* We get our minimum from the var_off, since that's inherently
10463 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10464 	 */
10465 	dst_reg->u32_min_value = var32_off.value;
10466 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10467 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10468 		/* Lose signed bounds when ANDing negative numbers,
10469 		 * ain't nobody got time for that.
10470 		 */
10471 		dst_reg->s32_min_value = S32_MIN;
10472 		dst_reg->s32_max_value = S32_MAX;
10473 	} else {
10474 		/* ANDing two positives gives a positive, so safe to
10475 		 * cast result into s64.
10476 		 */
10477 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10478 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10479 	}
10480 }
10481 
10482 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10483 			       struct bpf_reg_state *src_reg)
10484 {
10485 	bool src_known = tnum_is_const(src_reg->var_off);
10486 	bool dst_known = tnum_is_const(dst_reg->var_off);
10487 	s64 smin_val = src_reg->smin_value;
10488 	u64 umax_val = src_reg->umax_value;
10489 
10490 	if (src_known && dst_known) {
10491 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10492 		return;
10493 	}
10494 
10495 	/* We get our minimum from the var_off, since that's inherently
10496 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10497 	 */
10498 	dst_reg->umin_value = dst_reg->var_off.value;
10499 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10500 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10501 		/* Lose signed bounds when ANDing negative numbers,
10502 		 * ain't nobody got time for that.
10503 		 */
10504 		dst_reg->smin_value = S64_MIN;
10505 		dst_reg->smax_value = S64_MAX;
10506 	} else {
10507 		/* ANDing two positives gives a positive, so safe to
10508 		 * cast result into s64.
10509 		 */
10510 		dst_reg->smin_value = dst_reg->umin_value;
10511 		dst_reg->smax_value = dst_reg->umax_value;
10512 	}
10513 	/* We may learn something more from the var_off */
10514 	__update_reg_bounds(dst_reg);
10515 }
10516 
10517 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10518 				struct bpf_reg_state *src_reg)
10519 {
10520 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10521 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10522 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10523 	s32 smin_val = src_reg->s32_min_value;
10524 	u32 umin_val = src_reg->u32_min_value;
10525 
10526 	if (src_known && dst_known) {
10527 		__mark_reg32_known(dst_reg, var32_off.value);
10528 		return;
10529 	}
10530 
10531 	/* We get our maximum from the var_off, and our minimum is the
10532 	 * maximum of the operands' minima
10533 	 */
10534 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10535 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10536 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10537 		/* Lose signed bounds when ORing negative numbers,
10538 		 * ain't nobody got time for that.
10539 		 */
10540 		dst_reg->s32_min_value = S32_MIN;
10541 		dst_reg->s32_max_value = S32_MAX;
10542 	} else {
10543 		/* ORing two positives gives a positive, so safe to
10544 		 * cast result into s64.
10545 		 */
10546 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10547 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10548 	}
10549 }
10550 
10551 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10552 			      struct bpf_reg_state *src_reg)
10553 {
10554 	bool src_known = tnum_is_const(src_reg->var_off);
10555 	bool dst_known = tnum_is_const(dst_reg->var_off);
10556 	s64 smin_val = src_reg->smin_value;
10557 	u64 umin_val = src_reg->umin_value;
10558 
10559 	if (src_known && dst_known) {
10560 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10561 		return;
10562 	}
10563 
10564 	/* We get our maximum from the var_off, and our minimum is the
10565 	 * maximum of the operands' minima
10566 	 */
10567 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10568 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10569 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10570 		/* Lose signed bounds when ORing negative numbers,
10571 		 * ain't nobody got time for that.
10572 		 */
10573 		dst_reg->smin_value = S64_MIN;
10574 		dst_reg->smax_value = S64_MAX;
10575 	} else {
10576 		/* ORing two positives gives a positive, so safe to
10577 		 * cast result into s64.
10578 		 */
10579 		dst_reg->smin_value = dst_reg->umin_value;
10580 		dst_reg->smax_value = dst_reg->umax_value;
10581 	}
10582 	/* We may learn something more from the var_off */
10583 	__update_reg_bounds(dst_reg);
10584 }
10585 
10586 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10587 				 struct bpf_reg_state *src_reg)
10588 {
10589 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10590 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10591 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10592 	s32 smin_val = src_reg->s32_min_value;
10593 
10594 	if (src_known && dst_known) {
10595 		__mark_reg32_known(dst_reg, var32_off.value);
10596 		return;
10597 	}
10598 
10599 	/* We get both minimum and maximum from the var32_off. */
10600 	dst_reg->u32_min_value = var32_off.value;
10601 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10602 
10603 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10604 		/* XORing two positive sign numbers gives a positive,
10605 		 * so safe to cast u32 result into s32.
10606 		 */
10607 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10608 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10609 	} else {
10610 		dst_reg->s32_min_value = S32_MIN;
10611 		dst_reg->s32_max_value = S32_MAX;
10612 	}
10613 }
10614 
10615 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10616 			       struct bpf_reg_state *src_reg)
10617 {
10618 	bool src_known = tnum_is_const(src_reg->var_off);
10619 	bool dst_known = tnum_is_const(dst_reg->var_off);
10620 	s64 smin_val = src_reg->smin_value;
10621 
10622 	if (src_known && dst_known) {
10623 		/* dst_reg->var_off.value has been updated earlier */
10624 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10625 		return;
10626 	}
10627 
10628 	/* We get both minimum and maximum from the var_off. */
10629 	dst_reg->umin_value = dst_reg->var_off.value;
10630 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10631 
10632 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10633 		/* XORing two positive sign numbers gives a positive,
10634 		 * so safe to cast u64 result into s64.
10635 		 */
10636 		dst_reg->smin_value = dst_reg->umin_value;
10637 		dst_reg->smax_value = dst_reg->umax_value;
10638 	} else {
10639 		dst_reg->smin_value = S64_MIN;
10640 		dst_reg->smax_value = S64_MAX;
10641 	}
10642 
10643 	__update_reg_bounds(dst_reg);
10644 }
10645 
10646 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10647 				   u64 umin_val, u64 umax_val)
10648 {
10649 	/* We lose all sign bit information (except what we can pick
10650 	 * up from var_off)
10651 	 */
10652 	dst_reg->s32_min_value = S32_MIN;
10653 	dst_reg->s32_max_value = S32_MAX;
10654 	/* If we might shift our top bit out, then we know nothing */
10655 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10656 		dst_reg->u32_min_value = 0;
10657 		dst_reg->u32_max_value = U32_MAX;
10658 	} else {
10659 		dst_reg->u32_min_value <<= umin_val;
10660 		dst_reg->u32_max_value <<= umax_val;
10661 	}
10662 }
10663 
10664 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10665 				 struct bpf_reg_state *src_reg)
10666 {
10667 	u32 umax_val = src_reg->u32_max_value;
10668 	u32 umin_val = src_reg->u32_min_value;
10669 	/* u32 alu operation will zext upper bits */
10670 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10671 
10672 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10673 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10674 	/* Not required but being careful mark reg64 bounds as unknown so
10675 	 * that we are forced to pick them up from tnum and zext later and
10676 	 * if some path skips this step we are still safe.
10677 	 */
10678 	__mark_reg64_unbounded(dst_reg);
10679 	__update_reg32_bounds(dst_reg);
10680 }
10681 
10682 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10683 				   u64 umin_val, u64 umax_val)
10684 {
10685 	/* Special case <<32 because it is a common compiler pattern to sign
10686 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10687 	 * positive we know this shift will also be positive so we can track
10688 	 * bounds correctly. Otherwise we lose all sign bit information except
10689 	 * what we can pick up from var_off. Perhaps we can generalize this
10690 	 * later to shifts of any length.
10691 	 */
10692 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10693 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10694 	else
10695 		dst_reg->smax_value = S64_MAX;
10696 
10697 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10698 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10699 	else
10700 		dst_reg->smin_value = S64_MIN;
10701 
10702 	/* If we might shift our top bit out, then we know nothing */
10703 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10704 		dst_reg->umin_value = 0;
10705 		dst_reg->umax_value = U64_MAX;
10706 	} else {
10707 		dst_reg->umin_value <<= umin_val;
10708 		dst_reg->umax_value <<= umax_val;
10709 	}
10710 }
10711 
10712 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10713 			       struct bpf_reg_state *src_reg)
10714 {
10715 	u64 umax_val = src_reg->umax_value;
10716 	u64 umin_val = src_reg->umin_value;
10717 
10718 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
10719 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10720 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10721 
10722 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10723 	/* We may learn something more from the var_off */
10724 	__update_reg_bounds(dst_reg);
10725 }
10726 
10727 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10728 				 struct bpf_reg_state *src_reg)
10729 {
10730 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10731 	u32 umax_val = src_reg->u32_max_value;
10732 	u32 umin_val = src_reg->u32_min_value;
10733 
10734 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10735 	 * be negative, then either:
10736 	 * 1) src_reg might be zero, so the sign bit of the result is
10737 	 *    unknown, so we lose our signed bounds
10738 	 * 2) it's known negative, thus the unsigned bounds capture the
10739 	 *    signed bounds
10740 	 * 3) the signed bounds cross zero, so they tell us nothing
10741 	 *    about the result
10742 	 * If the value in dst_reg is known nonnegative, then again the
10743 	 * unsigned bounds capture the signed bounds.
10744 	 * Thus, in all cases it suffices to blow away our signed bounds
10745 	 * and rely on inferring new ones from the unsigned bounds and
10746 	 * var_off of the result.
10747 	 */
10748 	dst_reg->s32_min_value = S32_MIN;
10749 	dst_reg->s32_max_value = S32_MAX;
10750 
10751 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
10752 	dst_reg->u32_min_value >>= umax_val;
10753 	dst_reg->u32_max_value >>= umin_val;
10754 
10755 	__mark_reg64_unbounded(dst_reg);
10756 	__update_reg32_bounds(dst_reg);
10757 }
10758 
10759 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10760 			       struct bpf_reg_state *src_reg)
10761 {
10762 	u64 umax_val = src_reg->umax_value;
10763 	u64 umin_val = src_reg->umin_value;
10764 
10765 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10766 	 * be negative, then either:
10767 	 * 1) src_reg might be zero, so the sign bit of the result is
10768 	 *    unknown, so we lose our signed bounds
10769 	 * 2) it's known negative, thus the unsigned bounds capture the
10770 	 *    signed bounds
10771 	 * 3) the signed bounds cross zero, so they tell us nothing
10772 	 *    about the result
10773 	 * If the value in dst_reg is known nonnegative, then again the
10774 	 * unsigned bounds capture the signed bounds.
10775 	 * Thus, in all cases it suffices to blow away our signed bounds
10776 	 * and rely on inferring new ones from the unsigned bounds and
10777 	 * var_off of the result.
10778 	 */
10779 	dst_reg->smin_value = S64_MIN;
10780 	dst_reg->smax_value = S64_MAX;
10781 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10782 	dst_reg->umin_value >>= umax_val;
10783 	dst_reg->umax_value >>= umin_val;
10784 
10785 	/* Its not easy to operate on alu32 bounds here because it depends
10786 	 * on bits being shifted in. Take easy way out and mark unbounded
10787 	 * so we can recalculate later from tnum.
10788 	 */
10789 	__mark_reg32_unbounded(dst_reg);
10790 	__update_reg_bounds(dst_reg);
10791 }
10792 
10793 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10794 				  struct bpf_reg_state *src_reg)
10795 {
10796 	u64 umin_val = src_reg->u32_min_value;
10797 
10798 	/* Upon reaching here, src_known is true and
10799 	 * umax_val is equal to umin_val.
10800 	 */
10801 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10802 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10803 
10804 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10805 
10806 	/* blow away the dst_reg umin_value/umax_value and rely on
10807 	 * dst_reg var_off to refine the result.
10808 	 */
10809 	dst_reg->u32_min_value = 0;
10810 	dst_reg->u32_max_value = U32_MAX;
10811 
10812 	__mark_reg64_unbounded(dst_reg);
10813 	__update_reg32_bounds(dst_reg);
10814 }
10815 
10816 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10817 				struct bpf_reg_state *src_reg)
10818 {
10819 	u64 umin_val = src_reg->umin_value;
10820 
10821 	/* Upon reaching here, src_known is true and umax_val is equal
10822 	 * to umin_val.
10823 	 */
10824 	dst_reg->smin_value >>= umin_val;
10825 	dst_reg->smax_value >>= umin_val;
10826 
10827 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10828 
10829 	/* blow away the dst_reg umin_value/umax_value and rely on
10830 	 * dst_reg var_off to refine the result.
10831 	 */
10832 	dst_reg->umin_value = 0;
10833 	dst_reg->umax_value = U64_MAX;
10834 
10835 	/* Its not easy to operate on alu32 bounds here because it depends
10836 	 * on bits being shifted in from upper 32-bits. Take easy way out
10837 	 * and mark unbounded so we can recalculate later from tnum.
10838 	 */
10839 	__mark_reg32_unbounded(dst_reg);
10840 	__update_reg_bounds(dst_reg);
10841 }
10842 
10843 /* WARNING: This function does calculations on 64-bit values, but the actual
10844  * execution may occur on 32-bit values. Therefore, things like bitshifts
10845  * need extra checks in the 32-bit case.
10846  */
10847 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10848 				      struct bpf_insn *insn,
10849 				      struct bpf_reg_state *dst_reg,
10850 				      struct bpf_reg_state src_reg)
10851 {
10852 	struct bpf_reg_state *regs = cur_regs(env);
10853 	u8 opcode = BPF_OP(insn->code);
10854 	bool src_known;
10855 	s64 smin_val, smax_val;
10856 	u64 umin_val, umax_val;
10857 	s32 s32_min_val, s32_max_val;
10858 	u32 u32_min_val, u32_max_val;
10859 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10860 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10861 	int ret;
10862 
10863 	smin_val = src_reg.smin_value;
10864 	smax_val = src_reg.smax_value;
10865 	umin_val = src_reg.umin_value;
10866 	umax_val = src_reg.umax_value;
10867 
10868 	s32_min_val = src_reg.s32_min_value;
10869 	s32_max_val = src_reg.s32_max_value;
10870 	u32_min_val = src_reg.u32_min_value;
10871 	u32_max_val = src_reg.u32_max_value;
10872 
10873 	if (alu32) {
10874 		src_known = tnum_subreg_is_const(src_reg.var_off);
10875 		if ((src_known &&
10876 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10877 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10878 			/* Taint dst register if offset had invalid bounds
10879 			 * derived from e.g. dead branches.
10880 			 */
10881 			__mark_reg_unknown(env, dst_reg);
10882 			return 0;
10883 		}
10884 	} else {
10885 		src_known = tnum_is_const(src_reg.var_off);
10886 		if ((src_known &&
10887 		     (smin_val != smax_val || umin_val != umax_val)) ||
10888 		    smin_val > smax_val || umin_val > umax_val) {
10889 			/* Taint dst register if offset had invalid bounds
10890 			 * derived from e.g. dead branches.
10891 			 */
10892 			__mark_reg_unknown(env, dst_reg);
10893 			return 0;
10894 		}
10895 	}
10896 
10897 	if (!src_known &&
10898 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10899 		__mark_reg_unknown(env, dst_reg);
10900 		return 0;
10901 	}
10902 
10903 	if (sanitize_needed(opcode)) {
10904 		ret = sanitize_val_alu(env, insn);
10905 		if (ret < 0)
10906 			return sanitize_err(env, insn, ret, NULL, NULL);
10907 	}
10908 
10909 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10910 	 * There are two classes of instructions: The first class we track both
10911 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
10912 	 * greatest amount of precision when alu operations are mixed with jmp32
10913 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10914 	 * and BPF_OR. This is possible because these ops have fairly easy to
10915 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10916 	 * See alu32 verifier tests for examples. The second class of
10917 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10918 	 * with regards to tracking sign/unsigned bounds because the bits may
10919 	 * cross subreg boundaries in the alu64 case. When this happens we mark
10920 	 * the reg unbounded in the subreg bound space and use the resulting
10921 	 * tnum to calculate an approximation of the sign/unsigned bounds.
10922 	 */
10923 	switch (opcode) {
10924 	case BPF_ADD:
10925 		scalar32_min_max_add(dst_reg, &src_reg);
10926 		scalar_min_max_add(dst_reg, &src_reg);
10927 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10928 		break;
10929 	case BPF_SUB:
10930 		scalar32_min_max_sub(dst_reg, &src_reg);
10931 		scalar_min_max_sub(dst_reg, &src_reg);
10932 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10933 		break;
10934 	case BPF_MUL:
10935 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10936 		scalar32_min_max_mul(dst_reg, &src_reg);
10937 		scalar_min_max_mul(dst_reg, &src_reg);
10938 		break;
10939 	case BPF_AND:
10940 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10941 		scalar32_min_max_and(dst_reg, &src_reg);
10942 		scalar_min_max_and(dst_reg, &src_reg);
10943 		break;
10944 	case BPF_OR:
10945 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10946 		scalar32_min_max_or(dst_reg, &src_reg);
10947 		scalar_min_max_or(dst_reg, &src_reg);
10948 		break;
10949 	case BPF_XOR:
10950 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10951 		scalar32_min_max_xor(dst_reg, &src_reg);
10952 		scalar_min_max_xor(dst_reg, &src_reg);
10953 		break;
10954 	case BPF_LSH:
10955 		if (umax_val >= insn_bitness) {
10956 			/* Shifts greater than 31 or 63 are undefined.
10957 			 * This includes shifts by a negative number.
10958 			 */
10959 			mark_reg_unknown(env, regs, insn->dst_reg);
10960 			break;
10961 		}
10962 		if (alu32)
10963 			scalar32_min_max_lsh(dst_reg, &src_reg);
10964 		else
10965 			scalar_min_max_lsh(dst_reg, &src_reg);
10966 		break;
10967 	case BPF_RSH:
10968 		if (umax_val >= insn_bitness) {
10969 			/* Shifts greater than 31 or 63 are undefined.
10970 			 * This includes shifts by a negative number.
10971 			 */
10972 			mark_reg_unknown(env, regs, insn->dst_reg);
10973 			break;
10974 		}
10975 		if (alu32)
10976 			scalar32_min_max_rsh(dst_reg, &src_reg);
10977 		else
10978 			scalar_min_max_rsh(dst_reg, &src_reg);
10979 		break;
10980 	case BPF_ARSH:
10981 		if (umax_val >= insn_bitness) {
10982 			/* Shifts greater than 31 or 63 are undefined.
10983 			 * This includes shifts by a negative number.
10984 			 */
10985 			mark_reg_unknown(env, regs, insn->dst_reg);
10986 			break;
10987 		}
10988 		if (alu32)
10989 			scalar32_min_max_arsh(dst_reg, &src_reg);
10990 		else
10991 			scalar_min_max_arsh(dst_reg, &src_reg);
10992 		break;
10993 	default:
10994 		mark_reg_unknown(env, regs, insn->dst_reg);
10995 		break;
10996 	}
10997 
10998 	/* ALU32 ops are zero extended into 64bit register */
10999 	if (alu32)
11000 		zext_32_to_64(dst_reg);
11001 	reg_bounds_sync(dst_reg);
11002 	return 0;
11003 }
11004 
11005 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11006  * and var_off.
11007  */
11008 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11009 				   struct bpf_insn *insn)
11010 {
11011 	struct bpf_verifier_state *vstate = env->cur_state;
11012 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11013 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11014 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11015 	u8 opcode = BPF_OP(insn->code);
11016 	int err;
11017 
11018 	dst_reg = &regs[insn->dst_reg];
11019 	src_reg = NULL;
11020 	if (dst_reg->type != SCALAR_VALUE)
11021 		ptr_reg = dst_reg;
11022 	else
11023 		/* Make sure ID is cleared otherwise dst_reg min/max could be
11024 		 * incorrectly propagated into other registers by find_equal_scalars()
11025 		 */
11026 		dst_reg->id = 0;
11027 	if (BPF_SRC(insn->code) == BPF_X) {
11028 		src_reg = &regs[insn->src_reg];
11029 		if (src_reg->type != SCALAR_VALUE) {
11030 			if (dst_reg->type != SCALAR_VALUE) {
11031 				/* Combining two pointers by any ALU op yields
11032 				 * an arbitrary scalar. Disallow all math except
11033 				 * pointer subtraction
11034 				 */
11035 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11036 					mark_reg_unknown(env, regs, insn->dst_reg);
11037 					return 0;
11038 				}
11039 				verbose(env, "R%d pointer %s pointer prohibited\n",
11040 					insn->dst_reg,
11041 					bpf_alu_string[opcode >> 4]);
11042 				return -EACCES;
11043 			} else {
11044 				/* scalar += pointer
11045 				 * This is legal, but we have to reverse our
11046 				 * src/dest handling in computing the range
11047 				 */
11048 				err = mark_chain_precision(env, insn->dst_reg);
11049 				if (err)
11050 					return err;
11051 				return adjust_ptr_min_max_vals(env, insn,
11052 							       src_reg, dst_reg);
11053 			}
11054 		} else if (ptr_reg) {
11055 			/* pointer += scalar */
11056 			err = mark_chain_precision(env, insn->src_reg);
11057 			if (err)
11058 				return err;
11059 			return adjust_ptr_min_max_vals(env, insn,
11060 						       dst_reg, src_reg);
11061 		} else if (dst_reg->precise) {
11062 			/* if dst_reg is precise, src_reg should be precise as well */
11063 			err = mark_chain_precision(env, insn->src_reg);
11064 			if (err)
11065 				return err;
11066 		}
11067 	} else {
11068 		/* Pretend the src is a reg with a known value, since we only
11069 		 * need to be able to read from this state.
11070 		 */
11071 		off_reg.type = SCALAR_VALUE;
11072 		__mark_reg_known(&off_reg, insn->imm);
11073 		src_reg = &off_reg;
11074 		if (ptr_reg) /* pointer += K */
11075 			return adjust_ptr_min_max_vals(env, insn,
11076 						       ptr_reg, src_reg);
11077 	}
11078 
11079 	/* Got here implies adding two SCALAR_VALUEs */
11080 	if (WARN_ON_ONCE(ptr_reg)) {
11081 		print_verifier_state(env, state, true);
11082 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
11083 		return -EINVAL;
11084 	}
11085 	if (WARN_ON(!src_reg)) {
11086 		print_verifier_state(env, state, true);
11087 		verbose(env, "verifier internal error: no src_reg\n");
11088 		return -EINVAL;
11089 	}
11090 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11091 }
11092 
11093 /* check validity of 32-bit and 64-bit arithmetic operations */
11094 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11095 {
11096 	struct bpf_reg_state *regs = cur_regs(env);
11097 	u8 opcode = BPF_OP(insn->code);
11098 	int err;
11099 
11100 	if (opcode == BPF_END || opcode == BPF_NEG) {
11101 		if (opcode == BPF_NEG) {
11102 			if (BPF_SRC(insn->code) != BPF_K ||
11103 			    insn->src_reg != BPF_REG_0 ||
11104 			    insn->off != 0 || insn->imm != 0) {
11105 				verbose(env, "BPF_NEG uses reserved fields\n");
11106 				return -EINVAL;
11107 			}
11108 		} else {
11109 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11110 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11111 			    BPF_CLASS(insn->code) == BPF_ALU64) {
11112 				verbose(env, "BPF_END uses reserved fields\n");
11113 				return -EINVAL;
11114 			}
11115 		}
11116 
11117 		/* check src operand */
11118 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11119 		if (err)
11120 			return err;
11121 
11122 		if (is_pointer_value(env, insn->dst_reg)) {
11123 			verbose(env, "R%d pointer arithmetic prohibited\n",
11124 				insn->dst_reg);
11125 			return -EACCES;
11126 		}
11127 
11128 		/* check dest operand */
11129 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
11130 		if (err)
11131 			return err;
11132 
11133 	} else if (opcode == BPF_MOV) {
11134 
11135 		if (BPF_SRC(insn->code) == BPF_X) {
11136 			if (insn->imm != 0 || insn->off != 0) {
11137 				verbose(env, "BPF_MOV uses reserved fields\n");
11138 				return -EINVAL;
11139 			}
11140 
11141 			/* check src operand */
11142 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11143 			if (err)
11144 				return err;
11145 		} else {
11146 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11147 				verbose(env, "BPF_MOV uses reserved fields\n");
11148 				return -EINVAL;
11149 			}
11150 		}
11151 
11152 		/* check dest operand, mark as required later */
11153 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11154 		if (err)
11155 			return err;
11156 
11157 		if (BPF_SRC(insn->code) == BPF_X) {
11158 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
11159 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11160 
11161 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11162 				/* case: R1 = R2
11163 				 * copy register state to dest reg
11164 				 */
11165 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11166 					/* Assign src and dst registers the same ID
11167 					 * that will be used by find_equal_scalars()
11168 					 * to propagate min/max range.
11169 					 */
11170 					src_reg->id = ++env->id_gen;
11171 				*dst_reg = *src_reg;
11172 				dst_reg->live |= REG_LIVE_WRITTEN;
11173 				dst_reg->subreg_def = DEF_NOT_SUBREG;
11174 			} else {
11175 				/* R1 = (u32) R2 */
11176 				if (is_pointer_value(env, insn->src_reg)) {
11177 					verbose(env,
11178 						"R%d partial copy of pointer\n",
11179 						insn->src_reg);
11180 					return -EACCES;
11181 				} else if (src_reg->type == SCALAR_VALUE) {
11182 					*dst_reg = *src_reg;
11183 					/* Make sure ID is cleared otherwise
11184 					 * dst_reg min/max could be incorrectly
11185 					 * propagated into src_reg by find_equal_scalars()
11186 					 */
11187 					dst_reg->id = 0;
11188 					dst_reg->live |= REG_LIVE_WRITTEN;
11189 					dst_reg->subreg_def = env->insn_idx + 1;
11190 				} else {
11191 					mark_reg_unknown(env, regs,
11192 							 insn->dst_reg);
11193 				}
11194 				zext_32_to_64(dst_reg);
11195 				reg_bounds_sync(dst_reg);
11196 			}
11197 		} else {
11198 			/* case: R = imm
11199 			 * remember the value we stored into this reg
11200 			 */
11201 			/* clear any state __mark_reg_known doesn't set */
11202 			mark_reg_unknown(env, regs, insn->dst_reg);
11203 			regs[insn->dst_reg].type = SCALAR_VALUE;
11204 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11205 				__mark_reg_known(regs + insn->dst_reg,
11206 						 insn->imm);
11207 			} else {
11208 				__mark_reg_known(regs + insn->dst_reg,
11209 						 (u32)insn->imm);
11210 			}
11211 		}
11212 
11213 	} else if (opcode > BPF_END) {
11214 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11215 		return -EINVAL;
11216 
11217 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
11218 
11219 		if (BPF_SRC(insn->code) == BPF_X) {
11220 			if (insn->imm != 0 || insn->off != 0) {
11221 				verbose(env, "BPF_ALU uses reserved fields\n");
11222 				return -EINVAL;
11223 			}
11224 			/* check src1 operand */
11225 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11226 			if (err)
11227 				return err;
11228 		} else {
11229 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11230 				verbose(env, "BPF_ALU uses reserved fields\n");
11231 				return -EINVAL;
11232 			}
11233 		}
11234 
11235 		/* check src2 operand */
11236 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11237 		if (err)
11238 			return err;
11239 
11240 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11241 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11242 			verbose(env, "div by zero\n");
11243 			return -EINVAL;
11244 		}
11245 
11246 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11247 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11248 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11249 
11250 			if (insn->imm < 0 || insn->imm >= size) {
11251 				verbose(env, "invalid shift %d\n", insn->imm);
11252 				return -EINVAL;
11253 			}
11254 		}
11255 
11256 		/* check dest operand */
11257 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11258 		if (err)
11259 			return err;
11260 
11261 		return adjust_reg_min_max_vals(env, insn);
11262 	}
11263 
11264 	return 0;
11265 }
11266 
11267 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
11268 				   struct bpf_reg_state *dst_reg,
11269 				   enum bpf_reg_type type,
11270 				   bool range_right_open)
11271 {
11272 	struct bpf_func_state *state;
11273 	struct bpf_reg_state *reg;
11274 	int new_range;
11275 
11276 	if (dst_reg->off < 0 ||
11277 	    (dst_reg->off == 0 && range_right_open))
11278 		/* This doesn't give us any range */
11279 		return;
11280 
11281 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
11282 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
11283 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
11284 		 * than pkt_end, but that's because it's also less than pkt.
11285 		 */
11286 		return;
11287 
11288 	new_range = dst_reg->off;
11289 	if (range_right_open)
11290 		new_range++;
11291 
11292 	/* Examples for register markings:
11293 	 *
11294 	 * pkt_data in dst register:
11295 	 *
11296 	 *   r2 = r3;
11297 	 *   r2 += 8;
11298 	 *   if (r2 > pkt_end) goto <handle exception>
11299 	 *   <access okay>
11300 	 *
11301 	 *   r2 = r3;
11302 	 *   r2 += 8;
11303 	 *   if (r2 < pkt_end) goto <access okay>
11304 	 *   <handle exception>
11305 	 *
11306 	 *   Where:
11307 	 *     r2 == dst_reg, pkt_end == src_reg
11308 	 *     r2=pkt(id=n,off=8,r=0)
11309 	 *     r3=pkt(id=n,off=0,r=0)
11310 	 *
11311 	 * pkt_data in src register:
11312 	 *
11313 	 *   r2 = r3;
11314 	 *   r2 += 8;
11315 	 *   if (pkt_end >= r2) goto <access okay>
11316 	 *   <handle exception>
11317 	 *
11318 	 *   r2 = r3;
11319 	 *   r2 += 8;
11320 	 *   if (pkt_end <= r2) goto <handle exception>
11321 	 *   <access okay>
11322 	 *
11323 	 *   Where:
11324 	 *     pkt_end == dst_reg, r2 == src_reg
11325 	 *     r2=pkt(id=n,off=8,r=0)
11326 	 *     r3=pkt(id=n,off=0,r=0)
11327 	 *
11328 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11329 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11330 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11331 	 * the check.
11332 	 */
11333 
11334 	/* If our ids match, then we must have the same max_value.  And we
11335 	 * don't care about the other reg's fixed offset, since if it's too big
11336 	 * the range won't allow anything.
11337 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11338 	 */
11339 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11340 		if (reg->type == type && reg->id == dst_reg->id)
11341 			/* keep the maximum range already checked */
11342 			reg->range = max(reg->range, new_range);
11343 	}));
11344 }
11345 
11346 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11347 {
11348 	struct tnum subreg = tnum_subreg(reg->var_off);
11349 	s32 sval = (s32)val;
11350 
11351 	switch (opcode) {
11352 	case BPF_JEQ:
11353 		if (tnum_is_const(subreg))
11354 			return !!tnum_equals_const(subreg, val);
11355 		break;
11356 	case BPF_JNE:
11357 		if (tnum_is_const(subreg))
11358 			return !tnum_equals_const(subreg, val);
11359 		break;
11360 	case BPF_JSET:
11361 		if ((~subreg.mask & subreg.value) & val)
11362 			return 1;
11363 		if (!((subreg.mask | subreg.value) & val))
11364 			return 0;
11365 		break;
11366 	case BPF_JGT:
11367 		if (reg->u32_min_value > val)
11368 			return 1;
11369 		else if (reg->u32_max_value <= val)
11370 			return 0;
11371 		break;
11372 	case BPF_JSGT:
11373 		if (reg->s32_min_value > sval)
11374 			return 1;
11375 		else if (reg->s32_max_value <= sval)
11376 			return 0;
11377 		break;
11378 	case BPF_JLT:
11379 		if (reg->u32_max_value < val)
11380 			return 1;
11381 		else if (reg->u32_min_value >= val)
11382 			return 0;
11383 		break;
11384 	case BPF_JSLT:
11385 		if (reg->s32_max_value < sval)
11386 			return 1;
11387 		else if (reg->s32_min_value >= sval)
11388 			return 0;
11389 		break;
11390 	case BPF_JGE:
11391 		if (reg->u32_min_value >= val)
11392 			return 1;
11393 		else if (reg->u32_max_value < val)
11394 			return 0;
11395 		break;
11396 	case BPF_JSGE:
11397 		if (reg->s32_min_value >= sval)
11398 			return 1;
11399 		else if (reg->s32_max_value < sval)
11400 			return 0;
11401 		break;
11402 	case BPF_JLE:
11403 		if (reg->u32_max_value <= val)
11404 			return 1;
11405 		else if (reg->u32_min_value > val)
11406 			return 0;
11407 		break;
11408 	case BPF_JSLE:
11409 		if (reg->s32_max_value <= sval)
11410 			return 1;
11411 		else if (reg->s32_min_value > sval)
11412 			return 0;
11413 		break;
11414 	}
11415 
11416 	return -1;
11417 }
11418 
11419 
11420 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11421 {
11422 	s64 sval = (s64)val;
11423 
11424 	switch (opcode) {
11425 	case BPF_JEQ:
11426 		if (tnum_is_const(reg->var_off))
11427 			return !!tnum_equals_const(reg->var_off, val);
11428 		break;
11429 	case BPF_JNE:
11430 		if (tnum_is_const(reg->var_off))
11431 			return !tnum_equals_const(reg->var_off, val);
11432 		break;
11433 	case BPF_JSET:
11434 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11435 			return 1;
11436 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11437 			return 0;
11438 		break;
11439 	case BPF_JGT:
11440 		if (reg->umin_value > val)
11441 			return 1;
11442 		else if (reg->umax_value <= val)
11443 			return 0;
11444 		break;
11445 	case BPF_JSGT:
11446 		if (reg->smin_value > sval)
11447 			return 1;
11448 		else if (reg->smax_value <= sval)
11449 			return 0;
11450 		break;
11451 	case BPF_JLT:
11452 		if (reg->umax_value < val)
11453 			return 1;
11454 		else if (reg->umin_value >= val)
11455 			return 0;
11456 		break;
11457 	case BPF_JSLT:
11458 		if (reg->smax_value < sval)
11459 			return 1;
11460 		else if (reg->smin_value >= sval)
11461 			return 0;
11462 		break;
11463 	case BPF_JGE:
11464 		if (reg->umin_value >= val)
11465 			return 1;
11466 		else if (reg->umax_value < val)
11467 			return 0;
11468 		break;
11469 	case BPF_JSGE:
11470 		if (reg->smin_value >= sval)
11471 			return 1;
11472 		else if (reg->smax_value < sval)
11473 			return 0;
11474 		break;
11475 	case BPF_JLE:
11476 		if (reg->umax_value <= val)
11477 			return 1;
11478 		else if (reg->umin_value > val)
11479 			return 0;
11480 		break;
11481 	case BPF_JSLE:
11482 		if (reg->smax_value <= sval)
11483 			return 1;
11484 		else if (reg->smin_value > sval)
11485 			return 0;
11486 		break;
11487 	}
11488 
11489 	return -1;
11490 }
11491 
11492 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11493  * and return:
11494  *  1 - branch will be taken and "goto target" will be executed
11495  *  0 - branch will not be taken and fall-through to next insn
11496  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11497  *      range [0,10]
11498  */
11499 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11500 			   bool is_jmp32)
11501 {
11502 	if (__is_pointer_value(false, reg)) {
11503 		if (!reg_type_not_null(reg->type))
11504 			return -1;
11505 
11506 		/* If pointer is valid tests against zero will fail so we can
11507 		 * use this to direct branch taken.
11508 		 */
11509 		if (val != 0)
11510 			return -1;
11511 
11512 		switch (opcode) {
11513 		case BPF_JEQ:
11514 			return 0;
11515 		case BPF_JNE:
11516 			return 1;
11517 		default:
11518 			return -1;
11519 		}
11520 	}
11521 
11522 	if (is_jmp32)
11523 		return is_branch32_taken(reg, val, opcode);
11524 	return is_branch64_taken(reg, val, opcode);
11525 }
11526 
11527 static int flip_opcode(u32 opcode)
11528 {
11529 	/* How can we transform "a <op> b" into "b <op> a"? */
11530 	static const u8 opcode_flip[16] = {
11531 		/* these stay the same */
11532 		[BPF_JEQ  >> 4] = BPF_JEQ,
11533 		[BPF_JNE  >> 4] = BPF_JNE,
11534 		[BPF_JSET >> 4] = BPF_JSET,
11535 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11536 		[BPF_JGE  >> 4] = BPF_JLE,
11537 		[BPF_JGT  >> 4] = BPF_JLT,
11538 		[BPF_JLE  >> 4] = BPF_JGE,
11539 		[BPF_JLT  >> 4] = BPF_JGT,
11540 		[BPF_JSGE >> 4] = BPF_JSLE,
11541 		[BPF_JSGT >> 4] = BPF_JSLT,
11542 		[BPF_JSLE >> 4] = BPF_JSGE,
11543 		[BPF_JSLT >> 4] = BPF_JSGT
11544 	};
11545 	return opcode_flip[opcode >> 4];
11546 }
11547 
11548 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11549 				   struct bpf_reg_state *src_reg,
11550 				   u8 opcode)
11551 {
11552 	struct bpf_reg_state *pkt;
11553 
11554 	if (src_reg->type == PTR_TO_PACKET_END) {
11555 		pkt = dst_reg;
11556 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11557 		pkt = src_reg;
11558 		opcode = flip_opcode(opcode);
11559 	} else {
11560 		return -1;
11561 	}
11562 
11563 	if (pkt->range >= 0)
11564 		return -1;
11565 
11566 	switch (opcode) {
11567 	case BPF_JLE:
11568 		/* pkt <= pkt_end */
11569 		fallthrough;
11570 	case BPF_JGT:
11571 		/* pkt > pkt_end */
11572 		if (pkt->range == BEYOND_PKT_END)
11573 			/* pkt has at last one extra byte beyond pkt_end */
11574 			return opcode == BPF_JGT;
11575 		break;
11576 	case BPF_JLT:
11577 		/* pkt < pkt_end */
11578 		fallthrough;
11579 	case BPF_JGE:
11580 		/* pkt >= pkt_end */
11581 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11582 			return opcode == BPF_JGE;
11583 		break;
11584 	}
11585 	return -1;
11586 }
11587 
11588 /* Adjusts the register min/max values in the case that the dst_reg is the
11589  * variable register that we are working on, and src_reg is a constant or we're
11590  * simply doing a BPF_K check.
11591  * In JEQ/JNE cases we also adjust the var_off values.
11592  */
11593 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11594 			    struct bpf_reg_state *false_reg,
11595 			    u64 val, u32 val32,
11596 			    u8 opcode, bool is_jmp32)
11597 {
11598 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
11599 	struct tnum false_64off = false_reg->var_off;
11600 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
11601 	struct tnum true_64off = true_reg->var_off;
11602 	s64 sval = (s64)val;
11603 	s32 sval32 = (s32)val32;
11604 
11605 	/* If the dst_reg is a pointer, we can't learn anything about its
11606 	 * variable offset from the compare (unless src_reg were a pointer into
11607 	 * the same object, but we don't bother with that.
11608 	 * Since false_reg and true_reg have the same type by construction, we
11609 	 * only need to check one of them for pointerness.
11610 	 */
11611 	if (__is_pointer_value(false, false_reg))
11612 		return;
11613 
11614 	switch (opcode) {
11615 	/* JEQ/JNE comparison doesn't change the register equivalence.
11616 	 *
11617 	 * r1 = r2;
11618 	 * if (r1 == 42) goto label;
11619 	 * ...
11620 	 * label: // here both r1 and r2 are known to be 42.
11621 	 *
11622 	 * Hence when marking register as known preserve it's ID.
11623 	 */
11624 	case BPF_JEQ:
11625 		if (is_jmp32) {
11626 			__mark_reg32_known(true_reg, val32);
11627 			true_32off = tnum_subreg(true_reg->var_off);
11628 		} else {
11629 			___mark_reg_known(true_reg, val);
11630 			true_64off = true_reg->var_off;
11631 		}
11632 		break;
11633 	case BPF_JNE:
11634 		if (is_jmp32) {
11635 			__mark_reg32_known(false_reg, val32);
11636 			false_32off = tnum_subreg(false_reg->var_off);
11637 		} else {
11638 			___mark_reg_known(false_reg, val);
11639 			false_64off = false_reg->var_off;
11640 		}
11641 		break;
11642 	case BPF_JSET:
11643 		if (is_jmp32) {
11644 			false_32off = tnum_and(false_32off, tnum_const(~val32));
11645 			if (is_power_of_2(val32))
11646 				true_32off = tnum_or(true_32off,
11647 						     tnum_const(val32));
11648 		} else {
11649 			false_64off = tnum_and(false_64off, tnum_const(~val));
11650 			if (is_power_of_2(val))
11651 				true_64off = tnum_or(true_64off,
11652 						     tnum_const(val));
11653 		}
11654 		break;
11655 	case BPF_JGE:
11656 	case BPF_JGT:
11657 	{
11658 		if (is_jmp32) {
11659 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11660 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11661 
11662 			false_reg->u32_max_value = min(false_reg->u32_max_value,
11663 						       false_umax);
11664 			true_reg->u32_min_value = max(true_reg->u32_min_value,
11665 						      true_umin);
11666 		} else {
11667 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11668 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11669 
11670 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
11671 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
11672 		}
11673 		break;
11674 	}
11675 	case BPF_JSGE:
11676 	case BPF_JSGT:
11677 	{
11678 		if (is_jmp32) {
11679 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11680 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11681 
11682 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11683 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11684 		} else {
11685 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11686 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11687 
11688 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
11689 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
11690 		}
11691 		break;
11692 	}
11693 	case BPF_JLE:
11694 	case BPF_JLT:
11695 	{
11696 		if (is_jmp32) {
11697 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11698 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11699 
11700 			false_reg->u32_min_value = max(false_reg->u32_min_value,
11701 						       false_umin);
11702 			true_reg->u32_max_value = min(true_reg->u32_max_value,
11703 						      true_umax);
11704 		} else {
11705 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11706 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11707 
11708 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
11709 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
11710 		}
11711 		break;
11712 	}
11713 	case BPF_JSLE:
11714 	case BPF_JSLT:
11715 	{
11716 		if (is_jmp32) {
11717 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11718 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11719 
11720 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11721 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11722 		} else {
11723 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11724 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11725 
11726 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
11727 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
11728 		}
11729 		break;
11730 	}
11731 	default:
11732 		return;
11733 	}
11734 
11735 	if (is_jmp32) {
11736 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11737 					     tnum_subreg(false_32off));
11738 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11739 					    tnum_subreg(true_32off));
11740 		__reg_combine_32_into_64(false_reg);
11741 		__reg_combine_32_into_64(true_reg);
11742 	} else {
11743 		false_reg->var_off = false_64off;
11744 		true_reg->var_off = true_64off;
11745 		__reg_combine_64_into_32(false_reg);
11746 		__reg_combine_64_into_32(true_reg);
11747 	}
11748 }
11749 
11750 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11751  * the variable reg.
11752  */
11753 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11754 				struct bpf_reg_state *false_reg,
11755 				u64 val, u32 val32,
11756 				u8 opcode, bool is_jmp32)
11757 {
11758 	opcode = flip_opcode(opcode);
11759 	/* This uses zero as "not present in table"; luckily the zero opcode,
11760 	 * BPF_JA, can't get here.
11761 	 */
11762 	if (opcode)
11763 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11764 }
11765 
11766 /* Regs are known to be equal, so intersect their min/max/var_off */
11767 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11768 				  struct bpf_reg_state *dst_reg)
11769 {
11770 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11771 							dst_reg->umin_value);
11772 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11773 							dst_reg->umax_value);
11774 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11775 							dst_reg->smin_value);
11776 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11777 							dst_reg->smax_value);
11778 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11779 							     dst_reg->var_off);
11780 	reg_bounds_sync(src_reg);
11781 	reg_bounds_sync(dst_reg);
11782 }
11783 
11784 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11785 				struct bpf_reg_state *true_dst,
11786 				struct bpf_reg_state *false_src,
11787 				struct bpf_reg_state *false_dst,
11788 				u8 opcode)
11789 {
11790 	switch (opcode) {
11791 	case BPF_JEQ:
11792 		__reg_combine_min_max(true_src, true_dst);
11793 		break;
11794 	case BPF_JNE:
11795 		__reg_combine_min_max(false_src, false_dst);
11796 		break;
11797 	}
11798 }
11799 
11800 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11801 				 struct bpf_reg_state *reg, u32 id,
11802 				 bool is_null)
11803 {
11804 	if (type_may_be_null(reg->type) && reg->id == id &&
11805 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11806 		/* Old offset (both fixed and variable parts) should have been
11807 		 * known-zero, because we don't allow pointer arithmetic on
11808 		 * pointers that might be NULL. If we see this happening, don't
11809 		 * convert the register.
11810 		 *
11811 		 * But in some cases, some helpers that return local kptrs
11812 		 * advance offset for the returned pointer. In those cases, it
11813 		 * is fine to expect to see reg->off.
11814 		 */
11815 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11816 			return;
11817 		if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11818 			return;
11819 		if (is_null) {
11820 			reg->type = SCALAR_VALUE;
11821 			/* We don't need id and ref_obj_id from this point
11822 			 * onwards anymore, thus we should better reset it,
11823 			 * so that state pruning has chances to take effect.
11824 			 */
11825 			reg->id = 0;
11826 			reg->ref_obj_id = 0;
11827 
11828 			return;
11829 		}
11830 
11831 		mark_ptr_not_null_reg(reg);
11832 
11833 		if (!reg_may_point_to_spin_lock(reg)) {
11834 			/* For not-NULL ptr, reg->ref_obj_id will be reset
11835 			 * in release_reference().
11836 			 *
11837 			 * reg->id is still used by spin_lock ptr. Other
11838 			 * than spin_lock ptr type, reg->id can be reset.
11839 			 */
11840 			reg->id = 0;
11841 		}
11842 	}
11843 }
11844 
11845 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11846  * be folded together at some point.
11847  */
11848 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11849 				  bool is_null)
11850 {
11851 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11852 	struct bpf_reg_state *regs = state->regs, *reg;
11853 	u32 ref_obj_id = regs[regno].ref_obj_id;
11854 	u32 id = regs[regno].id;
11855 
11856 	if (ref_obj_id && ref_obj_id == id && is_null)
11857 		/* regs[regno] is in the " == NULL" branch.
11858 		 * No one could have freed the reference state before
11859 		 * doing the NULL check.
11860 		 */
11861 		WARN_ON_ONCE(release_reference_state(state, id));
11862 
11863 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11864 		mark_ptr_or_null_reg(state, reg, id, is_null);
11865 	}));
11866 }
11867 
11868 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11869 				   struct bpf_reg_state *dst_reg,
11870 				   struct bpf_reg_state *src_reg,
11871 				   struct bpf_verifier_state *this_branch,
11872 				   struct bpf_verifier_state *other_branch)
11873 {
11874 	if (BPF_SRC(insn->code) != BPF_X)
11875 		return false;
11876 
11877 	/* Pointers are always 64-bit. */
11878 	if (BPF_CLASS(insn->code) == BPF_JMP32)
11879 		return false;
11880 
11881 	switch (BPF_OP(insn->code)) {
11882 	case BPF_JGT:
11883 		if ((dst_reg->type == PTR_TO_PACKET &&
11884 		     src_reg->type == PTR_TO_PACKET_END) ||
11885 		    (dst_reg->type == PTR_TO_PACKET_META &&
11886 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11887 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11888 			find_good_pkt_pointers(this_branch, dst_reg,
11889 					       dst_reg->type, false);
11890 			mark_pkt_end(other_branch, insn->dst_reg, true);
11891 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11892 			    src_reg->type == PTR_TO_PACKET) ||
11893 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11894 			    src_reg->type == PTR_TO_PACKET_META)) {
11895 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
11896 			find_good_pkt_pointers(other_branch, src_reg,
11897 					       src_reg->type, true);
11898 			mark_pkt_end(this_branch, insn->src_reg, false);
11899 		} else {
11900 			return false;
11901 		}
11902 		break;
11903 	case BPF_JLT:
11904 		if ((dst_reg->type == PTR_TO_PACKET &&
11905 		     src_reg->type == PTR_TO_PACKET_END) ||
11906 		    (dst_reg->type == PTR_TO_PACKET_META &&
11907 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11908 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11909 			find_good_pkt_pointers(other_branch, dst_reg,
11910 					       dst_reg->type, true);
11911 			mark_pkt_end(this_branch, insn->dst_reg, false);
11912 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11913 			    src_reg->type == PTR_TO_PACKET) ||
11914 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11915 			    src_reg->type == PTR_TO_PACKET_META)) {
11916 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
11917 			find_good_pkt_pointers(this_branch, src_reg,
11918 					       src_reg->type, false);
11919 			mark_pkt_end(other_branch, insn->src_reg, true);
11920 		} else {
11921 			return false;
11922 		}
11923 		break;
11924 	case BPF_JGE:
11925 		if ((dst_reg->type == PTR_TO_PACKET &&
11926 		     src_reg->type == PTR_TO_PACKET_END) ||
11927 		    (dst_reg->type == PTR_TO_PACKET_META &&
11928 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11929 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11930 			find_good_pkt_pointers(this_branch, dst_reg,
11931 					       dst_reg->type, true);
11932 			mark_pkt_end(other_branch, insn->dst_reg, false);
11933 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11934 			    src_reg->type == PTR_TO_PACKET) ||
11935 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11936 			    src_reg->type == PTR_TO_PACKET_META)) {
11937 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11938 			find_good_pkt_pointers(other_branch, src_reg,
11939 					       src_reg->type, false);
11940 			mark_pkt_end(this_branch, insn->src_reg, true);
11941 		} else {
11942 			return false;
11943 		}
11944 		break;
11945 	case BPF_JLE:
11946 		if ((dst_reg->type == PTR_TO_PACKET &&
11947 		     src_reg->type == PTR_TO_PACKET_END) ||
11948 		    (dst_reg->type == PTR_TO_PACKET_META &&
11949 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11950 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11951 			find_good_pkt_pointers(other_branch, dst_reg,
11952 					       dst_reg->type, false);
11953 			mark_pkt_end(this_branch, insn->dst_reg, true);
11954 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11955 			    src_reg->type == PTR_TO_PACKET) ||
11956 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11957 			    src_reg->type == PTR_TO_PACKET_META)) {
11958 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11959 			find_good_pkt_pointers(this_branch, src_reg,
11960 					       src_reg->type, true);
11961 			mark_pkt_end(other_branch, insn->src_reg, false);
11962 		} else {
11963 			return false;
11964 		}
11965 		break;
11966 	default:
11967 		return false;
11968 	}
11969 
11970 	return true;
11971 }
11972 
11973 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11974 			       struct bpf_reg_state *known_reg)
11975 {
11976 	struct bpf_func_state *state;
11977 	struct bpf_reg_state *reg;
11978 
11979 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11980 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11981 			*reg = *known_reg;
11982 	}));
11983 }
11984 
11985 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11986 			     struct bpf_insn *insn, int *insn_idx)
11987 {
11988 	struct bpf_verifier_state *this_branch = env->cur_state;
11989 	struct bpf_verifier_state *other_branch;
11990 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11991 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11992 	struct bpf_reg_state *eq_branch_regs;
11993 	u8 opcode = BPF_OP(insn->code);
11994 	bool is_jmp32;
11995 	int pred = -1;
11996 	int err;
11997 
11998 	/* Only conditional jumps are expected to reach here. */
11999 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
12000 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12001 		return -EINVAL;
12002 	}
12003 
12004 	if (BPF_SRC(insn->code) == BPF_X) {
12005 		if (insn->imm != 0) {
12006 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12007 			return -EINVAL;
12008 		}
12009 
12010 		/* check src1 operand */
12011 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12012 		if (err)
12013 			return err;
12014 
12015 		if (is_pointer_value(env, insn->src_reg)) {
12016 			verbose(env, "R%d pointer comparison prohibited\n",
12017 				insn->src_reg);
12018 			return -EACCES;
12019 		}
12020 		src_reg = &regs[insn->src_reg];
12021 	} else {
12022 		if (insn->src_reg != BPF_REG_0) {
12023 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12024 			return -EINVAL;
12025 		}
12026 	}
12027 
12028 	/* check src2 operand */
12029 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12030 	if (err)
12031 		return err;
12032 
12033 	dst_reg = &regs[insn->dst_reg];
12034 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12035 
12036 	if (BPF_SRC(insn->code) == BPF_K) {
12037 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12038 	} else if (src_reg->type == SCALAR_VALUE &&
12039 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12040 		pred = is_branch_taken(dst_reg,
12041 				       tnum_subreg(src_reg->var_off).value,
12042 				       opcode,
12043 				       is_jmp32);
12044 	} else if (src_reg->type == SCALAR_VALUE &&
12045 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12046 		pred = is_branch_taken(dst_reg,
12047 				       src_reg->var_off.value,
12048 				       opcode,
12049 				       is_jmp32);
12050 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
12051 		   reg_is_pkt_pointer_any(src_reg) &&
12052 		   !is_jmp32) {
12053 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12054 	}
12055 
12056 	if (pred >= 0) {
12057 		/* If we get here with a dst_reg pointer type it is because
12058 		 * above is_branch_taken() special cased the 0 comparison.
12059 		 */
12060 		if (!__is_pointer_value(false, dst_reg))
12061 			err = mark_chain_precision(env, insn->dst_reg);
12062 		if (BPF_SRC(insn->code) == BPF_X && !err &&
12063 		    !__is_pointer_value(false, src_reg))
12064 			err = mark_chain_precision(env, insn->src_reg);
12065 		if (err)
12066 			return err;
12067 	}
12068 
12069 	if (pred == 1) {
12070 		/* Only follow the goto, ignore fall-through. If needed, push
12071 		 * the fall-through branch for simulation under speculative
12072 		 * execution.
12073 		 */
12074 		if (!env->bypass_spec_v1 &&
12075 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
12076 					       *insn_idx))
12077 			return -EFAULT;
12078 		*insn_idx += insn->off;
12079 		return 0;
12080 	} else if (pred == 0) {
12081 		/* Only follow the fall-through branch, since that's where the
12082 		 * program will go. If needed, push the goto branch for
12083 		 * simulation under speculative execution.
12084 		 */
12085 		if (!env->bypass_spec_v1 &&
12086 		    !sanitize_speculative_path(env, insn,
12087 					       *insn_idx + insn->off + 1,
12088 					       *insn_idx))
12089 			return -EFAULT;
12090 		return 0;
12091 	}
12092 
12093 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12094 				  false);
12095 	if (!other_branch)
12096 		return -EFAULT;
12097 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12098 
12099 	/* detect if we are comparing against a constant value so we can adjust
12100 	 * our min/max values for our dst register.
12101 	 * this is only legit if both are scalars (or pointers to the same
12102 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12103 	 * because otherwise the different base pointers mean the offsets aren't
12104 	 * comparable.
12105 	 */
12106 	if (BPF_SRC(insn->code) == BPF_X) {
12107 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12108 
12109 		if (dst_reg->type == SCALAR_VALUE &&
12110 		    src_reg->type == SCALAR_VALUE) {
12111 			if (tnum_is_const(src_reg->var_off) ||
12112 			    (is_jmp32 &&
12113 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
12114 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
12115 						dst_reg,
12116 						src_reg->var_off.value,
12117 						tnum_subreg(src_reg->var_off).value,
12118 						opcode, is_jmp32);
12119 			else if (tnum_is_const(dst_reg->var_off) ||
12120 				 (is_jmp32 &&
12121 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
12122 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12123 						    src_reg,
12124 						    dst_reg->var_off.value,
12125 						    tnum_subreg(dst_reg->var_off).value,
12126 						    opcode, is_jmp32);
12127 			else if (!is_jmp32 &&
12128 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
12129 				/* Comparing for equality, we can combine knowledge */
12130 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
12131 						    &other_branch_regs[insn->dst_reg],
12132 						    src_reg, dst_reg, opcode);
12133 			if (src_reg->id &&
12134 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12135 				find_equal_scalars(this_branch, src_reg);
12136 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12137 			}
12138 
12139 		}
12140 	} else if (dst_reg->type == SCALAR_VALUE) {
12141 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
12142 					dst_reg, insn->imm, (u32)insn->imm,
12143 					opcode, is_jmp32);
12144 	}
12145 
12146 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12147 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12148 		find_equal_scalars(this_branch, dst_reg);
12149 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12150 	}
12151 
12152 	/* if one pointer register is compared to another pointer
12153 	 * register check if PTR_MAYBE_NULL could be lifted.
12154 	 * E.g. register A - maybe null
12155 	 *      register B - not null
12156 	 * for JNE A, B, ... - A is not null in the false branch;
12157 	 * for JEQ A, B, ... - A is not null in the true branch.
12158 	 *
12159 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
12160 	 * not need to be null checked by the BPF program, i.e.,
12161 	 * could be null even without PTR_MAYBE_NULL marking, so
12162 	 * only propagate nullness when neither reg is that type.
12163 	 */
12164 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12165 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12166 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12167 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
12168 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12169 		eq_branch_regs = NULL;
12170 		switch (opcode) {
12171 		case BPF_JEQ:
12172 			eq_branch_regs = other_branch_regs;
12173 			break;
12174 		case BPF_JNE:
12175 			eq_branch_regs = regs;
12176 			break;
12177 		default:
12178 			/* do nothing */
12179 			break;
12180 		}
12181 		if (eq_branch_regs) {
12182 			if (type_may_be_null(src_reg->type))
12183 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12184 			else
12185 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12186 		}
12187 	}
12188 
12189 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12190 	 * NOTE: these optimizations below are related with pointer comparison
12191 	 *       which will never be JMP32.
12192 	 */
12193 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12194 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12195 	    type_may_be_null(dst_reg->type)) {
12196 		/* Mark all identical registers in each branch as either
12197 		 * safe or unknown depending R == 0 or R != 0 conditional.
12198 		 */
12199 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12200 				      opcode == BPF_JNE);
12201 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12202 				      opcode == BPF_JEQ);
12203 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12204 					   this_branch, other_branch) &&
12205 		   is_pointer_value(env, insn->dst_reg)) {
12206 		verbose(env, "R%d pointer comparison prohibited\n",
12207 			insn->dst_reg);
12208 		return -EACCES;
12209 	}
12210 	if (env->log.level & BPF_LOG_LEVEL)
12211 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
12212 	return 0;
12213 }
12214 
12215 /* verify BPF_LD_IMM64 instruction */
12216 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12217 {
12218 	struct bpf_insn_aux_data *aux = cur_aux(env);
12219 	struct bpf_reg_state *regs = cur_regs(env);
12220 	struct bpf_reg_state *dst_reg;
12221 	struct bpf_map *map;
12222 	int err;
12223 
12224 	if (BPF_SIZE(insn->code) != BPF_DW) {
12225 		verbose(env, "invalid BPF_LD_IMM insn\n");
12226 		return -EINVAL;
12227 	}
12228 	if (insn->off != 0) {
12229 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12230 		return -EINVAL;
12231 	}
12232 
12233 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
12234 	if (err)
12235 		return err;
12236 
12237 	dst_reg = &regs[insn->dst_reg];
12238 	if (insn->src_reg == 0) {
12239 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12240 
12241 		dst_reg->type = SCALAR_VALUE;
12242 		__mark_reg_known(&regs[insn->dst_reg], imm);
12243 		return 0;
12244 	}
12245 
12246 	/* All special src_reg cases are listed below. From this point onwards
12247 	 * we either succeed and assign a corresponding dst_reg->type after
12248 	 * zeroing the offset, or fail and reject the program.
12249 	 */
12250 	mark_reg_known_zero(env, regs, insn->dst_reg);
12251 
12252 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
12253 		dst_reg->type = aux->btf_var.reg_type;
12254 		switch (base_type(dst_reg->type)) {
12255 		case PTR_TO_MEM:
12256 			dst_reg->mem_size = aux->btf_var.mem_size;
12257 			break;
12258 		case PTR_TO_BTF_ID:
12259 			dst_reg->btf = aux->btf_var.btf;
12260 			dst_reg->btf_id = aux->btf_var.btf_id;
12261 			break;
12262 		default:
12263 			verbose(env, "bpf verifier is misconfigured\n");
12264 			return -EFAULT;
12265 		}
12266 		return 0;
12267 	}
12268 
12269 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
12270 		struct bpf_prog_aux *aux = env->prog->aux;
12271 		u32 subprogno = find_subprog(env,
12272 					     env->insn_idx + insn->imm + 1);
12273 
12274 		if (!aux->func_info) {
12275 			verbose(env, "missing btf func_info\n");
12276 			return -EINVAL;
12277 		}
12278 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
12279 			verbose(env, "callback function not static\n");
12280 			return -EINVAL;
12281 		}
12282 
12283 		dst_reg->type = PTR_TO_FUNC;
12284 		dst_reg->subprogno = subprogno;
12285 		return 0;
12286 	}
12287 
12288 	map = env->used_maps[aux->map_index];
12289 	dst_reg->map_ptr = map;
12290 
12291 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
12292 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
12293 		dst_reg->type = PTR_TO_MAP_VALUE;
12294 		dst_reg->off = aux->map_off;
12295 		WARN_ON_ONCE(map->max_entries != 1);
12296 		/* We want reg->id to be same (0) as map_value is not distinct */
12297 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
12298 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
12299 		dst_reg->type = CONST_PTR_TO_MAP;
12300 	} else {
12301 		verbose(env, "bpf verifier is misconfigured\n");
12302 		return -EINVAL;
12303 	}
12304 
12305 	return 0;
12306 }
12307 
12308 static bool may_access_skb(enum bpf_prog_type type)
12309 {
12310 	switch (type) {
12311 	case BPF_PROG_TYPE_SOCKET_FILTER:
12312 	case BPF_PROG_TYPE_SCHED_CLS:
12313 	case BPF_PROG_TYPE_SCHED_ACT:
12314 		return true;
12315 	default:
12316 		return false;
12317 	}
12318 }
12319 
12320 /* verify safety of LD_ABS|LD_IND instructions:
12321  * - they can only appear in the programs where ctx == skb
12322  * - since they are wrappers of function calls, they scratch R1-R5 registers,
12323  *   preserve R6-R9, and store return value into R0
12324  *
12325  * Implicit input:
12326  *   ctx == skb == R6 == CTX
12327  *
12328  * Explicit input:
12329  *   SRC == any register
12330  *   IMM == 32-bit immediate
12331  *
12332  * Output:
12333  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12334  */
12335 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12336 {
12337 	struct bpf_reg_state *regs = cur_regs(env);
12338 	static const int ctx_reg = BPF_REG_6;
12339 	u8 mode = BPF_MODE(insn->code);
12340 	int i, err;
12341 
12342 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12343 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12344 		return -EINVAL;
12345 	}
12346 
12347 	if (!env->ops->gen_ld_abs) {
12348 		verbose(env, "bpf verifier is misconfigured\n");
12349 		return -EINVAL;
12350 	}
12351 
12352 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12353 	    BPF_SIZE(insn->code) == BPF_DW ||
12354 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12355 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12356 		return -EINVAL;
12357 	}
12358 
12359 	/* check whether implicit source operand (register R6) is readable */
12360 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12361 	if (err)
12362 		return err;
12363 
12364 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12365 	 * gen_ld_abs() may terminate the program at runtime, leading to
12366 	 * reference leak.
12367 	 */
12368 	err = check_reference_leak(env);
12369 	if (err) {
12370 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12371 		return err;
12372 	}
12373 
12374 	if (env->cur_state->active_lock.ptr) {
12375 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12376 		return -EINVAL;
12377 	}
12378 
12379 	if (env->cur_state->active_rcu_lock) {
12380 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12381 		return -EINVAL;
12382 	}
12383 
12384 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12385 		verbose(env,
12386 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12387 		return -EINVAL;
12388 	}
12389 
12390 	if (mode == BPF_IND) {
12391 		/* check explicit source operand */
12392 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12393 		if (err)
12394 			return err;
12395 	}
12396 
12397 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12398 	if (err < 0)
12399 		return err;
12400 
12401 	/* reset caller saved regs to unreadable */
12402 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12403 		mark_reg_not_init(env, regs, caller_saved[i]);
12404 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12405 	}
12406 
12407 	/* mark destination R0 register as readable, since it contains
12408 	 * the value fetched from the packet.
12409 	 * Already marked as written above.
12410 	 */
12411 	mark_reg_unknown(env, regs, BPF_REG_0);
12412 	/* ld_abs load up to 32-bit skb data. */
12413 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12414 	return 0;
12415 }
12416 
12417 static int check_return_code(struct bpf_verifier_env *env)
12418 {
12419 	struct tnum enforce_attach_type_range = tnum_unknown;
12420 	const struct bpf_prog *prog = env->prog;
12421 	struct bpf_reg_state *reg;
12422 	struct tnum range = tnum_range(0, 1);
12423 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12424 	int err;
12425 	struct bpf_func_state *frame = env->cur_state->frame[0];
12426 	const bool is_subprog = frame->subprogno;
12427 
12428 	/* LSM and struct_ops func-ptr's return type could be "void" */
12429 	if (!is_subprog) {
12430 		switch (prog_type) {
12431 		case BPF_PROG_TYPE_LSM:
12432 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12433 				/* See below, can be 0 or 0-1 depending on hook. */
12434 				break;
12435 			fallthrough;
12436 		case BPF_PROG_TYPE_STRUCT_OPS:
12437 			if (!prog->aux->attach_func_proto->type)
12438 				return 0;
12439 			break;
12440 		default:
12441 			break;
12442 		}
12443 	}
12444 
12445 	/* eBPF calling convention is such that R0 is used
12446 	 * to return the value from eBPF program.
12447 	 * Make sure that it's readable at this time
12448 	 * of bpf_exit, which means that program wrote
12449 	 * something into it earlier
12450 	 */
12451 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12452 	if (err)
12453 		return err;
12454 
12455 	if (is_pointer_value(env, BPF_REG_0)) {
12456 		verbose(env, "R0 leaks addr as return value\n");
12457 		return -EACCES;
12458 	}
12459 
12460 	reg = cur_regs(env) + BPF_REG_0;
12461 
12462 	if (frame->in_async_callback_fn) {
12463 		/* enforce return zero from async callbacks like timer */
12464 		if (reg->type != SCALAR_VALUE) {
12465 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12466 				reg_type_str(env, reg->type));
12467 			return -EINVAL;
12468 		}
12469 
12470 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12471 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12472 			return -EINVAL;
12473 		}
12474 		return 0;
12475 	}
12476 
12477 	if (is_subprog) {
12478 		if (reg->type != SCALAR_VALUE) {
12479 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12480 				reg_type_str(env, reg->type));
12481 			return -EINVAL;
12482 		}
12483 		return 0;
12484 	}
12485 
12486 	switch (prog_type) {
12487 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12488 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12489 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12490 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12491 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12492 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12493 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12494 			range = tnum_range(1, 1);
12495 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12496 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12497 			range = tnum_range(0, 3);
12498 		break;
12499 	case BPF_PROG_TYPE_CGROUP_SKB:
12500 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12501 			range = tnum_range(0, 3);
12502 			enforce_attach_type_range = tnum_range(2, 3);
12503 		}
12504 		break;
12505 	case BPF_PROG_TYPE_CGROUP_SOCK:
12506 	case BPF_PROG_TYPE_SOCK_OPS:
12507 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12508 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12509 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12510 		break;
12511 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12512 		if (!env->prog->aux->attach_btf_id)
12513 			return 0;
12514 		range = tnum_const(0);
12515 		break;
12516 	case BPF_PROG_TYPE_TRACING:
12517 		switch (env->prog->expected_attach_type) {
12518 		case BPF_TRACE_FENTRY:
12519 		case BPF_TRACE_FEXIT:
12520 			range = tnum_const(0);
12521 			break;
12522 		case BPF_TRACE_RAW_TP:
12523 		case BPF_MODIFY_RETURN:
12524 			return 0;
12525 		case BPF_TRACE_ITER:
12526 			break;
12527 		default:
12528 			return -ENOTSUPP;
12529 		}
12530 		break;
12531 	case BPF_PROG_TYPE_SK_LOOKUP:
12532 		range = tnum_range(SK_DROP, SK_PASS);
12533 		break;
12534 
12535 	case BPF_PROG_TYPE_LSM:
12536 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12537 			/* Regular BPF_PROG_TYPE_LSM programs can return
12538 			 * any value.
12539 			 */
12540 			return 0;
12541 		}
12542 		if (!env->prog->aux->attach_func_proto->type) {
12543 			/* Make sure programs that attach to void
12544 			 * hooks don't try to modify return value.
12545 			 */
12546 			range = tnum_range(1, 1);
12547 		}
12548 		break;
12549 
12550 	case BPF_PROG_TYPE_EXT:
12551 		/* freplace program can return anything as its return value
12552 		 * depends on the to-be-replaced kernel func or bpf program.
12553 		 */
12554 	default:
12555 		return 0;
12556 	}
12557 
12558 	if (reg->type != SCALAR_VALUE) {
12559 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12560 			reg_type_str(env, reg->type));
12561 		return -EINVAL;
12562 	}
12563 
12564 	if (!tnum_in(range, reg->var_off)) {
12565 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12566 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12567 		    prog_type == BPF_PROG_TYPE_LSM &&
12568 		    !prog->aux->attach_func_proto->type)
12569 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12570 		return -EINVAL;
12571 	}
12572 
12573 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12574 	    tnum_in(enforce_attach_type_range, reg->var_off))
12575 		env->prog->enforce_expected_attach_type = 1;
12576 	return 0;
12577 }
12578 
12579 /* non-recursive DFS pseudo code
12580  * 1  procedure DFS-iterative(G,v):
12581  * 2      label v as discovered
12582  * 3      let S be a stack
12583  * 4      S.push(v)
12584  * 5      while S is not empty
12585  * 6            t <- S.peek()
12586  * 7            if t is what we're looking for:
12587  * 8                return t
12588  * 9            for all edges e in G.adjacentEdges(t) do
12589  * 10               if edge e is already labelled
12590  * 11                   continue with the next edge
12591  * 12               w <- G.adjacentVertex(t,e)
12592  * 13               if vertex w is not discovered and not explored
12593  * 14                   label e as tree-edge
12594  * 15                   label w as discovered
12595  * 16                   S.push(w)
12596  * 17                   continue at 5
12597  * 18               else if vertex w is discovered
12598  * 19                   label e as back-edge
12599  * 20               else
12600  * 21                   // vertex w is explored
12601  * 22                   label e as forward- or cross-edge
12602  * 23           label t as explored
12603  * 24           S.pop()
12604  *
12605  * convention:
12606  * 0x10 - discovered
12607  * 0x11 - discovered and fall-through edge labelled
12608  * 0x12 - discovered and fall-through and branch edges labelled
12609  * 0x20 - explored
12610  */
12611 
12612 enum {
12613 	DISCOVERED = 0x10,
12614 	EXPLORED = 0x20,
12615 	FALLTHROUGH = 1,
12616 	BRANCH = 2,
12617 };
12618 
12619 static u32 state_htab_size(struct bpf_verifier_env *env)
12620 {
12621 	return env->prog->len;
12622 }
12623 
12624 static struct bpf_verifier_state_list **explored_state(
12625 					struct bpf_verifier_env *env,
12626 					int idx)
12627 {
12628 	struct bpf_verifier_state *cur = env->cur_state;
12629 	struct bpf_func_state *state = cur->frame[cur->curframe];
12630 
12631 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12632 }
12633 
12634 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
12635 {
12636 	env->insn_aux_data[idx].prune_point = true;
12637 }
12638 
12639 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
12640 {
12641 	return env->insn_aux_data[insn_idx].prune_point;
12642 }
12643 
12644 enum {
12645 	DONE_EXPLORING = 0,
12646 	KEEP_EXPLORING = 1,
12647 };
12648 
12649 /* t, w, e - match pseudo-code above:
12650  * t - index of current instruction
12651  * w - next instruction
12652  * e - edge
12653  */
12654 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12655 		     bool loop_ok)
12656 {
12657 	int *insn_stack = env->cfg.insn_stack;
12658 	int *insn_state = env->cfg.insn_state;
12659 
12660 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12661 		return DONE_EXPLORING;
12662 
12663 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12664 		return DONE_EXPLORING;
12665 
12666 	if (w < 0 || w >= env->prog->len) {
12667 		verbose_linfo(env, t, "%d: ", t);
12668 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
12669 		return -EINVAL;
12670 	}
12671 
12672 	if (e == BRANCH) {
12673 		/* mark branch target for state pruning */
12674 		mark_prune_point(env, w);
12675 		mark_jmp_point(env, w);
12676 	}
12677 
12678 	if (insn_state[w] == 0) {
12679 		/* tree-edge */
12680 		insn_state[t] = DISCOVERED | e;
12681 		insn_state[w] = DISCOVERED;
12682 		if (env->cfg.cur_stack >= env->prog->len)
12683 			return -E2BIG;
12684 		insn_stack[env->cfg.cur_stack++] = w;
12685 		return KEEP_EXPLORING;
12686 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12687 		if (loop_ok && env->bpf_capable)
12688 			return DONE_EXPLORING;
12689 		verbose_linfo(env, t, "%d: ", t);
12690 		verbose_linfo(env, w, "%d: ", w);
12691 		verbose(env, "back-edge from insn %d to %d\n", t, w);
12692 		return -EINVAL;
12693 	} else if (insn_state[w] == EXPLORED) {
12694 		/* forward- or cross-edge */
12695 		insn_state[t] = DISCOVERED | e;
12696 	} else {
12697 		verbose(env, "insn state internal bug\n");
12698 		return -EFAULT;
12699 	}
12700 	return DONE_EXPLORING;
12701 }
12702 
12703 static int visit_func_call_insn(int t, struct bpf_insn *insns,
12704 				struct bpf_verifier_env *env,
12705 				bool visit_callee)
12706 {
12707 	int ret;
12708 
12709 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12710 	if (ret)
12711 		return ret;
12712 
12713 	mark_prune_point(env, t + 1);
12714 	/* when we exit from subprog, we need to record non-linear history */
12715 	mark_jmp_point(env, t + 1);
12716 
12717 	if (visit_callee) {
12718 		mark_prune_point(env, t);
12719 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12720 				/* It's ok to allow recursion from CFG point of
12721 				 * view. __check_func_call() will do the actual
12722 				 * check.
12723 				 */
12724 				bpf_pseudo_func(insns + t));
12725 	}
12726 	return ret;
12727 }
12728 
12729 /* Visits the instruction at index t and returns one of the following:
12730  *  < 0 - an error occurred
12731  *  DONE_EXPLORING - the instruction was fully explored
12732  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12733  */
12734 static int visit_insn(int t, struct bpf_verifier_env *env)
12735 {
12736 	struct bpf_insn *insns = env->prog->insnsi;
12737 	int ret;
12738 
12739 	if (bpf_pseudo_func(insns + t))
12740 		return visit_func_call_insn(t, insns, env, true);
12741 
12742 	/* All non-branch instructions have a single fall-through edge. */
12743 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12744 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
12745 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
12746 
12747 	switch (BPF_OP(insns[t].code)) {
12748 	case BPF_EXIT:
12749 		return DONE_EXPLORING;
12750 
12751 	case BPF_CALL:
12752 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
12753 			/* Mark this call insn as a prune point to trigger
12754 			 * is_state_visited() check before call itself is
12755 			 * processed by __check_func_call(). Otherwise new
12756 			 * async state will be pushed for further exploration.
12757 			 */
12758 			mark_prune_point(env, t);
12759 		return visit_func_call_insn(t, insns, env,
12760 					    insns[t].src_reg == BPF_PSEUDO_CALL);
12761 
12762 	case BPF_JA:
12763 		if (BPF_SRC(insns[t].code) != BPF_K)
12764 			return -EINVAL;
12765 
12766 		/* unconditional jump with single edge */
12767 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12768 				true);
12769 		if (ret)
12770 			return ret;
12771 
12772 		mark_prune_point(env, t + insns[t].off + 1);
12773 		mark_jmp_point(env, t + insns[t].off + 1);
12774 
12775 		return ret;
12776 
12777 	default:
12778 		/* conditional jump with two edges */
12779 		mark_prune_point(env, t);
12780 
12781 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12782 		if (ret)
12783 			return ret;
12784 
12785 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12786 	}
12787 }
12788 
12789 /* non-recursive depth-first-search to detect loops in BPF program
12790  * loop == back-edge in directed graph
12791  */
12792 static int check_cfg(struct bpf_verifier_env *env)
12793 {
12794 	int insn_cnt = env->prog->len;
12795 	int *insn_stack, *insn_state;
12796 	int ret = 0;
12797 	int i;
12798 
12799 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12800 	if (!insn_state)
12801 		return -ENOMEM;
12802 
12803 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12804 	if (!insn_stack) {
12805 		kvfree(insn_state);
12806 		return -ENOMEM;
12807 	}
12808 
12809 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12810 	insn_stack[0] = 0; /* 0 is the first instruction */
12811 	env->cfg.cur_stack = 1;
12812 
12813 	while (env->cfg.cur_stack > 0) {
12814 		int t = insn_stack[env->cfg.cur_stack - 1];
12815 
12816 		ret = visit_insn(t, env);
12817 		switch (ret) {
12818 		case DONE_EXPLORING:
12819 			insn_state[t] = EXPLORED;
12820 			env->cfg.cur_stack--;
12821 			break;
12822 		case KEEP_EXPLORING:
12823 			break;
12824 		default:
12825 			if (ret > 0) {
12826 				verbose(env, "visit_insn internal bug\n");
12827 				ret = -EFAULT;
12828 			}
12829 			goto err_free;
12830 		}
12831 	}
12832 
12833 	if (env->cfg.cur_stack < 0) {
12834 		verbose(env, "pop stack internal bug\n");
12835 		ret = -EFAULT;
12836 		goto err_free;
12837 	}
12838 
12839 	for (i = 0; i < insn_cnt; i++) {
12840 		if (insn_state[i] != EXPLORED) {
12841 			verbose(env, "unreachable insn %d\n", i);
12842 			ret = -EINVAL;
12843 			goto err_free;
12844 		}
12845 	}
12846 	ret = 0; /* cfg looks good */
12847 
12848 err_free:
12849 	kvfree(insn_state);
12850 	kvfree(insn_stack);
12851 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
12852 	return ret;
12853 }
12854 
12855 static int check_abnormal_return(struct bpf_verifier_env *env)
12856 {
12857 	int i;
12858 
12859 	for (i = 1; i < env->subprog_cnt; i++) {
12860 		if (env->subprog_info[i].has_ld_abs) {
12861 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12862 			return -EINVAL;
12863 		}
12864 		if (env->subprog_info[i].has_tail_call) {
12865 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12866 			return -EINVAL;
12867 		}
12868 	}
12869 	return 0;
12870 }
12871 
12872 /* The minimum supported BTF func info size */
12873 #define MIN_BPF_FUNCINFO_SIZE	8
12874 #define MAX_FUNCINFO_REC_SIZE	252
12875 
12876 static int check_btf_func(struct bpf_verifier_env *env,
12877 			  const union bpf_attr *attr,
12878 			  bpfptr_t uattr)
12879 {
12880 	const struct btf_type *type, *func_proto, *ret_type;
12881 	u32 i, nfuncs, urec_size, min_size;
12882 	u32 krec_size = sizeof(struct bpf_func_info);
12883 	struct bpf_func_info *krecord;
12884 	struct bpf_func_info_aux *info_aux = NULL;
12885 	struct bpf_prog *prog;
12886 	const struct btf *btf;
12887 	bpfptr_t urecord;
12888 	u32 prev_offset = 0;
12889 	bool scalar_return;
12890 	int ret = -ENOMEM;
12891 
12892 	nfuncs = attr->func_info_cnt;
12893 	if (!nfuncs) {
12894 		if (check_abnormal_return(env))
12895 			return -EINVAL;
12896 		return 0;
12897 	}
12898 
12899 	if (nfuncs != env->subprog_cnt) {
12900 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12901 		return -EINVAL;
12902 	}
12903 
12904 	urec_size = attr->func_info_rec_size;
12905 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12906 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
12907 	    urec_size % sizeof(u32)) {
12908 		verbose(env, "invalid func info rec size %u\n", urec_size);
12909 		return -EINVAL;
12910 	}
12911 
12912 	prog = env->prog;
12913 	btf = prog->aux->btf;
12914 
12915 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12916 	min_size = min_t(u32, krec_size, urec_size);
12917 
12918 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12919 	if (!krecord)
12920 		return -ENOMEM;
12921 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12922 	if (!info_aux)
12923 		goto err_free;
12924 
12925 	for (i = 0; i < nfuncs; i++) {
12926 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12927 		if (ret) {
12928 			if (ret == -E2BIG) {
12929 				verbose(env, "nonzero tailing record in func info");
12930 				/* set the size kernel expects so loader can zero
12931 				 * out the rest of the record.
12932 				 */
12933 				if (copy_to_bpfptr_offset(uattr,
12934 							  offsetof(union bpf_attr, func_info_rec_size),
12935 							  &min_size, sizeof(min_size)))
12936 					ret = -EFAULT;
12937 			}
12938 			goto err_free;
12939 		}
12940 
12941 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12942 			ret = -EFAULT;
12943 			goto err_free;
12944 		}
12945 
12946 		/* check insn_off */
12947 		ret = -EINVAL;
12948 		if (i == 0) {
12949 			if (krecord[i].insn_off) {
12950 				verbose(env,
12951 					"nonzero insn_off %u for the first func info record",
12952 					krecord[i].insn_off);
12953 				goto err_free;
12954 			}
12955 		} else if (krecord[i].insn_off <= prev_offset) {
12956 			verbose(env,
12957 				"same or smaller insn offset (%u) than previous func info record (%u)",
12958 				krecord[i].insn_off, prev_offset);
12959 			goto err_free;
12960 		}
12961 
12962 		if (env->subprog_info[i].start != krecord[i].insn_off) {
12963 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12964 			goto err_free;
12965 		}
12966 
12967 		/* check type_id */
12968 		type = btf_type_by_id(btf, krecord[i].type_id);
12969 		if (!type || !btf_type_is_func(type)) {
12970 			verbose(env, "invalid type id %d in func info",
12971 				krecord[i].type_id);
12972 			goto err_free;
12973 		}
12974 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12975 
12976 		func_proto = btf_type_by_id(btf, type->type);
12977 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12978 			/* btf_func_check() already verified it during BTF load */
12979 			goto err_free;
12980 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12981 		scalar_return =
12982 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12983 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12984 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12985 			goto err_free;
12986 		}
12987 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12988 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12989 			goto err_free;
12990 		}
12991 
12992 		prev_offset = krecord[i].insn_off;
12993 		bpfptr_add(&urecord, urec_size);
12994 	}
12995 
12996 	prog->aux->func_info = krecord;
12997 	prog->aux->func_info_cnt = nfuncs;
12998 	prog->aux->func_info_aux = info_aux;
12999 	return 0;
13000 
13001 err_free:
13002 	kvfree(krecord);
13003 	kfree(info_aux);
13004 	return ret;
13005 }
13006 
13007 static void adjust_btf_func(struct bpf_verifier_env *env)
13008 {
13009 	struct bpf_prog_aux *aux = env->prog->aux;
13010 	int i;
13011 
13012 	if (!aux->func_info)
13013 		return;
13014 
13015 	for (i = 0; i < env->subprog_cnt; i++)
13016 		aux->func_info[i].insn_off = env->subprog_info[i].start;
13017 }
13018 
13019 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
13020 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
13021 
13022 static int check_btf_line(struct bpf_verifier_env *env,
13023 			  const union bpf_attr *attr,
13024 			  bpfptr_t uattr)
13025 {
13026 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13027 	struct bpf_subprog_info *sub;
13028 	struct bpf_line_info *linfo;
13029 	struct bpf_prog *prog;
13030 	const struct btf *btf;
13031 	bpfptr_t ulinfo;
13032 	int err;
13033 
13034 	nr_linfo = attr->line_info_cnt;
13035 	if (!nr_linfo)
13036 		return 0;
13037 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13038 		return -EINVAL;
13039 
13040 	rec_size = attr->line_info_rec_size;
13041 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13042 	    rec_size > MAX_LINEINFO_REC_SIZE ||
13043 	    rec_size & (sizeof(u32) - 1))
13044 		return -EINVAL;
13045 
13046 	/* Need to zero it in case the userspace may
13047 	 * pass in a smaller bpf_line_info object.
13048 	 */
13049 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13050 			 GFP_KERNEL | __GFP_NOWARN);
13051 	if (!linfo)
13052 		return -ENOMEM;
13053 
13054 	prog = env->prog;
13055 	btf = prog->aux->btf;
13056 
13057 	s = 0;
13058 	sub = env->subprog_info;
13059 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13060 	expected_size = sizeof(struct bpf_line_info);
13061 	ncopy = min_t(u32, expected_size, rec_size);
13062 	for (i = 0; i < nr_linfo; i++) {
13063 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13064 		if (err) {
13065 			if (err == -E2BIG) {
13066 				verbose(env, "nonzero tailing record in line_info");
13067 				if (copy_to_bpfptr_offset(uattr,
13068 							  offsetof(union bpf_attr, line_info_rec_size),
13069 							  &expected_size, sizeof(expected_size)))
13070 					err = -EFAULT;
13071 			}
13072 			goto err_free;
13073 		}
13074 
13075 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13076 			err = -EFAULT;
13077 			goto err_free;
13078 		}
13079 
13080 		/*
13081 		 * Check insn_off to ensure
13082 		 * 1) strictly increasing AND
13083 		 * 2) bounded by prog->len
13084 		 *
13085 		 * The linfo[0].insn_off == 0 check logically falls into
13086 		 * the later "missing bpf_line_info for func..." case
13087 		 * because the first linfo[0].insn_off must be the
13088 		 * first sub also and the first sub must have
13089 		 * subprog_info[0].start == 0.
13090 		 */
13091 		if ((i && linfo[i].insn_off <= prev_offset) ||
13092 		    linfo[i].insn_off >= prog->len) {
13093 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13094 				i, linfo[i].insn_off, prev_offset,
13095 				prog->len);
13096 			err = -EINVAL;
13097 			goto err_free;
13098 		}
13099 
13100 		if (!prog->insnsi[linfo[i].insn_off].code) {
13101 			verbose(env,
13102 				"Invalid insn code at line_info[%u].insn_off\n",
13103 				i);
13104 			err = -EINVAL;
13105 			goto err_free;
13106 		}
13107 
13108 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13109 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13110 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13111 			err = -EINVAL;
13112 			goto err_free;
13113 		}
13114 
13115 		if (s != env->subprog_cnt) {
13116 			if (linfo[i].insn_off == sub[s].start) {
13117 				sub[s].linfo_idx = i;
13118 				s++;
13119 			} else if (sub[s].start < linfo[i].insn_off) {
13120 				verbose(env, "missing bpf_line_info for func#%u\n", s);
13121 				err = -EINVAL;
13122 				goto err_free;
13123 			}
13124 		}
13125 
13126 		prev_offset = linfo[i].insn_off;
13127 		bpfptr_add(&ulinfo, rec_size);
13128 	}
13129 
13130 	if (s != env->subprog_cnt) {
13131 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13132 			env->subprog_cnt - s, s);
13133 		err = -EINVAL;
13134 		goto err_free;
13135 	}
13136 
13137 	prog->aux->linfo = linfo;
13138 	prog->aux->nr_linfo = nr_linfo;
13139 
13140 	return 0;
13141 
13142 err_free:
13143 	kvfree(linfo);
13144 	return err;
13145 }
13146 
13147 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
13148 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
13149 
13150 static int check_core_relo(struct bpf_verifier_env *env,
13151 			   const union bpf_attr *attr,
13152 			   bpfptr_t uattr)
13153 {
13154 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13155 	struct bpf_core_relo core_relo = {};
13156 	struct bpf_prog *prog = env->prog;
13157 	const struct btf *btf = prog->aux->btf;
13158 	struct bpf_core_ctx ctx = {
13159 		.log = &env->log,
13160 		.btf = btf,
13161 	};
13162 	bpfptr_t u_core_relo;
13163 	int err;
13164 
13165 	nr_core_relo = attr->core_relo_cnt;
13166 	if (!nr_core_relo)
13167 		return 0;
13168 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13169 		return -EINVAL;
13170 
13171 	rec_size = attr->core_relo_rec_size;
13172 	if (rec_size < MIN_CORE_RELO_SIZE ||
13173 	    rec_size > MAX_CORE_RELO_SIZE ||
13174 	    rec_size % sizeof(u32))
13175 		return -EINVAL;
13176 
13177 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13178 	expected_size = sizeof(struct bpf_core_relo);
13179 	ncopy = min_t(u32, expected_size, rec_size);
13180 
13181 	/* Unlike func_info and line_info, copy and apply each CO-RE
13182 	 * relocation record one at a time.
13183 	 */
13184 	for (i = 0; i < nr_core_relo; i++) {
13185 		/* future proofing when sizeof(bpf_core_relo) changes */
13186 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13187 		if (err) {
13188 			if (err == -E2BIG) {
13189 				verbose(env, "nonzero tailing record in core_relo");
13190 				if (copy_to_bpfptr_offset(uattr,
13191 							  offsetof(union bpf_attr, core_relo_rec_size),
13192 							  &expected_size, sizeof(expected_size)))
13193 					err = -EFAULT;
13194 			}
13195 			break;
13196 		}
13197 
13198 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13199 			err = -EFAULT;
13200 			break;
13201 		}
13202 
13203 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13204 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13205 				i, core_relo.insn_off, prog->len);
13206 			err = -EINVAL;
13207 			break;
13208 		}
13209 
13210 		err = bpf_core_apply(&ctx, &core_relo, i,
13211 				     &prog->insnsi[core_relo.insn_off / 8]);
13212 		if (err)
13213 			break;
13214 		bpfptr_add(&u_core_relo, rec_size);
13215 	}
13216 	return err;
13217 }
13218 
13219 static int check_btf_info(struct bpf_verifier_env *env,
13220 			  const union bpf_attr *attr,
13221 			  bpfptr_t uattr)
13222 {
13223 	struct btf *btf;
13224 	int err;
13225 
13226 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
13227 		if (check_abnormal_return(env))
13228 			return -EINVAL;
13229 		return 0;
13230 	}
13231 
13232 	btf = btf_get_by_fd(attr->prog_btf_fd);
13233 	if (IS_ERR(btf))
13234 		return PTR_ERR(btf);
13235 	if (btf_is_kernel(btf)) {
13236 		btf_put(btf);
13237 		return -EACCES;
13238 	}
13239 	env->prog->aux->btf = btf;
13240 
13241 	err = check_btf_func(env, attr, uattr);
13242 	if (err)
13243 		return err;
13244 
13245 	err = check_btf_line(env, attr, uattr);
13246 	if (err)
13247 		return err;
13248 
13249 	err = check_core_relo(env, attr, uattr);
13250 	if (err)
13251 		return err;
13252 
13253 	return 0;
13254 }
13255 
13256 /* check %cur's range satisfies %old's */
13257 static bool range_within(struct bpf_reg_state *old,
13258 			 struct bpf_reg_state *cur)
13259 {
13260 	return old->umin_value <= cur->umin_value &&
13261 	       old->umax_value >= cur->umax_value &&
13262 	       old->smin_value <= cur->smin_value &&
13263 	       old->smax_value >= cur->smax_value &&
13264 	       old->u32_min_value <= cur->u32_min_value &&
13265 	       old->u32_max_value >= cur->u32_max_value &&
13266 	       old->s32_min_value <= cur->s32_min_value &&
13267 	       old->s32_max_value >= cur->s32_max_value;
13268 }
13269 
13270 /* If in the old state two registers had the same id, then they need to have
13271  * the same id in the new state as well.  But that id could be different from
13272  * the old state, so we need to track the mapping from old to new ids.
13273  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
13274  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
13275  * regs with a different old id could still have new id 9, we don't care about
13276  * that.
13277  * So we look through our idmap to see if this old id has been seen before.  If
13278  * so, we require the new id to match; otherwise, we add the id pair to the map.
13279  */
13280 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
13281 {
13282 	unsigned int i;
13283 
13284 	/* either both IDs should be set or both should be zero */
13285 	if (!!old_id != !!cur_id)
13286 		return false;
13287 
13288 	if (old_id == 0) /* cur_id == 0 as well */
13289 		return true;
13290 
13291 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
13292 		if (!idmap[i].old) {
13293 			/* Reached an empty slot; haven't seen this id before */
13294 			idmap[i].old = old_id;
13295 			idmap[i].cur = cur_id;
13296 			return true;
13297 		}
13298 		if (idmap[i].old == old_id)
13299 			return idmap[i].cur == cur_id;
13300 	}
13301 	/* We ran out of idmap slots, which should be impossible */
13302 	WARN_ON_ONCE(1);
13303 	return false;
13304 }
13305 
13306 static void clean_func_state(struct bpf_verifier_env *env,
13307 			     struct bpf_func_state *st)
13308 {
13309 	enum bpf_reg_liveness live;
13310 	int i, j;
13311 
13312 	for (i = 0; i < BPF_REG_FP; i++) {
13313 		live = st->regs[i].live;
13314 		/* liveness must not touch this register anymore */
13315 		st->regs[i].live |= REG_LIVE_DONE;
13316 		if (!(live & REG_LIVE_READ))
13317 			/* since the register is unused, clear its state
13318 			 * to make further comparison simpler
13319 			 */
13320 			__mark_reg_not_init(env, &st->regs[i]);
13321 	}
13322 
13323 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
13324 		live = st->stack[i].spilled_ptr.live;
13325 		/* liveness must not touch this stack slot anymore */
13326 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13327 		if (!(live & REG_LIVE_READ)) {
13328 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13329 			for (j = 0; j < BPF_REG_SIZE; j++)
13330 				st->stack[i].slot_type[j] = STACK_INVALID;
13331 		}
13332 	}
13333 }
13334 
13335 static void clean_verifier_state(struct bpf_verifier_env *env,
13336 				 struct bpf_verifier_state *st)
13337 {
13338 	int i;
13339 
13340 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13341 		/* all regs in this state in all frames were already marked */
13342 		return;
13343 
13344 	for (i = 0; i <= st->curframe; i++)
13345 		clean_func_state(env, st->frame[i]);
13346 }
13347 
13348 /* the parentage chains form a tree.
13349  * the verifier states are added to state lists at given insn and
13350  * pushed into state stack for future exploration.
13351  * when the verifier reaches bpf_exit insn some of the verifer states
13352  * stored in the state lists have their final liveness state already,
13353  * but a lot of states will get revised from liveness point of view when
13354  * the verifier explores other branches.
13355  * Example:
13356  * 1: r0 = 1
13357  * 2: if r1 == 100 goto pc+1
13358  * 3: r0 = 2
13359  * 4: exit
13360  * when the verifier reaches exit insn the register r0 in the state list of
13361  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13362  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13363  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13364  *
13365  * Since the verifier pushes the branch states as it sees them while exploring
13366  * the program the condition of walking the branch instruction for the second
13367  * time means that all states below this branch were already explored and
13368  * their final liveness marks are already propagated.
13369  * Hence when the verifier completes the search of state list in is_state_visited()
13370  * we can call this clean_live_states() function to mark all liveness states
13371  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13372  * will not be used.
13373  * This function also clears the registers and stack for states that !READ
13374  * to simplify state merging.
13375  *
13376  * Important note here that walking the same branch instruction in the callee
13377  * doesn't meant that the states are DONE. The verifier has to compare
13378  * the callsites
13379  */
13380 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13381 			      struct bpf_verifier_state *cur)
13382 {
13383 	struct bpf_verifier_state_list *sl;
13384 	int i;
13385 
13386 	sl = *explored_state(env, insn);
13387 	while (sl) {
13388 		if (sl->state.branches)
13389 			goto next;
13390 		if (sl->state.insn_idx != insn ||
13391 		    sl->state.curframe != cur->curframe)
13392 			goto next;
13393 		for (i = 0; i <= cur->curframe; i++)
13394 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13395 				goto next;
13396 		clean_verifier_state(env, &sl->state);
13397 next:
13398 		sl = sl->next;
13399 	}
13400 }
13401 
13402 static bool regs_exact(const struct bpf_reg_state *rold,
13403 		       const struct bpf_reg_state *rcur,
13404 		       struct bpf_id_pair *idmap)
13405 {
13406 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13407 	       check_ids(rold->id, rcur->id, idmap) &&
13408 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13409 }
13410 
13411 /* Returns true if (rold safe implies rcur safe) */
13412 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13413 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13414 {
13415 	if (!(rold->live & REG_LIVE_READ))
13416 		/* explored state didn't use this */
13417 		return true;
13418 	if (rold->type == NOT_INIT)
13419 		/* explored state can't have used this */
13420 		return true;
13421 	if (rcur->type == NOT_INIT)
13422 		return false;
13423 
13424 	/* Enforce that register types have to match exactly, including their
13425 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13426 	 * rule.
13427 	 *
13428 	 * One can make a point that using a pointer register as unbounded
13429 	 * SCALAR would be technically acceptable, but this could lead to
13430 	 * pointer leaks because scalars are allowed to leak while pointers
13431 	 * are not. We could make this safe in special cases if root is
13432 	 * calling us, but it's probably not worth the hassle.
13433 	 *
13434 	 * Also, register types that are *not* MAYBE_NULL could technically be
13435 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13436 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13437 	 * to the same map).
13438 	 * However, if the old MAYBE_NULL register then got NULL checked,
13439 	 * doing so could have affected others with the same id, and we can't
13440 	 * check for that because we lost the id when we converted to
13441 	 * a non-MAYBE_NULL variant.
13442 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13443 	 * non-MAYBE_NULL registers as well.
13444 	 */
13445 	if (rold->type != rcur->type)
13446 		return false;
13447 
13448 	switch (base_type(rold->type)) {
13449 	case SCALAR_VALUE:
13450 		if (regs_exact(rold, rcur, idmap))
13451 			return true;
13452 		if (env->explore_alu_limits)
13453 			return false;
13454 		if (!rold->precise)
13455 			return true;
13456 		/* new val must satisfy old val knowledge */
13457 		return range_within(rold, rcur) &&
13458 		       tnum_in(rold->var_off, rcur->var_off);
13459 	case PTR_TO_MAP_KEY:
13460 	case PTR_TO_MAP_VALUE:
13461 		/* If the new min/max/var_off satisfy the old ones and
13462 		 * everything else matches, we are OK.
13463 		 */
13464 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13465 		       range_within(rold, rcur) &&
13466 		       tnum_in(rold->var_off, rcur->var_off) &&
13467 		       check_ids(rold->id, rcur->id, idmap);
13468 	case PTR_TO_PACKET_META:
13469 	case PTR_TO_PACKET:
13470 		/* We must have at least as much range as the old ptr
13471 		 * did, so that any accesses which were safe before are
13472 		 * still safe.  This is true even if old range < old off,
13473 		 * since someone could have accessed through (ptr - k), or
13474 		 * even done ptr -= k in a register, to get a safe access.
13475 		 */
13476 		if (rold->range > rcur->range)
13477 			return false;
13478 		/* If the offsets don't match, we can't trust our alignment;
13479 		 * nor can we be sure that we won't fall out of range.
13480 		 */
13481 		if (rold->off != rcur->off)
13482 			return false;
13483 		/* id relations must be preserved */
13484 		if (!check_ids(rold->id, rcur->id, idmap))
13485 			return false;
13486 		/* new val must satisfy old val knowledge */
13487 		return range_within(rold, rcur) &&
13488 		       tnum_in(rold->var_off, rcur->var_off);
13489 	case PTR_TO_STACK:
13490 		/* two stack pointers are equal only if they're pointing to
13491 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13492 		 */
13493 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13494 	default:
13495 		return regs_exact(rold, rcur, idmap);
13496 	}
13497 }
13498 
13499 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13500 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13501 {
13502 	int i, spi;
13503 
13504 	/* walk slots of the explored stack and ignore any additional
13505 	 * slots in the current stack, since explored(safe) state
13506 	 * didn't use them
13507 	 */
13508 	for (i = 0; i < old->allocated_stack; i++) {
13509 		spi = i / BPF_REG_SIZE;
13510 
13511 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13512 			i += BPF_REG_SIZE - 1;
13513 			/* explored state didn't use this */
13514 			continue;
13515 		}
13516 
13517 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13518 			continue;
13519 
13520 		/* explored stack has more populated slots than current stack
13521 		 * and these slots were used
13522 		 */
13523 		if (i >= cur->allocated_stack)
13524 			return false;
13525 
13526 		/* if old state was safe with misc data in the stack
13527 		 * it will be safe with zero-initialized stack.
13528 		 * The opposite is not true
13529 		 */
13530 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13531 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13532 			continue;
13533 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13534 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13535 			/* Ex: old explored (safe) state has STACK_SPILL in
13536 			 * this stack slot, but current has STACK_MISC ->
13537 			 * this verifier states are not equivalent,
13538 			 * return false to continue verification of this path
13539 			 */
13540 			return false;
13541 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13542 			continue;
13543 		/* Both old and cur are having same slot_type */
13544 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
13545 		case STACK_SPILL:
13546 			/* when explored and current stack slot are both storing
13547 			 * spilled registers, check that stored pointers types
13548 			 * are the same as well.
13549 			 * Ex: explored safe path could have stored
13550 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13551 			 * but current path has stored:
13552 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13553 			 * such verifier states are not equivalent.
13554 			 * return false to continue verification of this path
13555 			 */
13556 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
13557 				     &cur->stack[spi].spilled_ptr, idmap))
13558 				return false;
13559 			break;
13560 		case STACK_DYNPTR:
13561 		{
13562 			const struct bpf_reg_state *old_reg, *cur_reg;
13563 
13564 			old_reg = &old->stack[spi].spilled_ptr;
13565 			cur_reg = &cur->stack[spi].spilled_ptr;
13566 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
13567 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
13568 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
13569 				return false;
13570 			break;
13571 		}
13572 		case STACK_MISC:
13573 		case STACK_ZERO:
13574 		case STACK_INVALID:
13575 			continue;
13576 		/* Ensure that new unhandled slot types return false by default */
13577 		default:
13578 			return false;
13579 		}
13580 	}
13581 	return true;
13582 }
13583 
13584 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
13585 		    struct bpf_id_pair *idmap)
13586 {
13587 	int i;
13588 
13589 	if (old->acquired_refs != cur->acquired_refs)
13590 		return false;
13591 
13592 	for (i = 0; i < old->acquired_refs; i++) {
13593 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
13594 			return false;
13595 	}
13596 
13597 	return true;
13598 }
13599 
13600 /* compare two verifier states
13601  *
13602  * all states stored in state_list are known to be valid, since
13603  * verifier reached 'bpf_exit' instruction through them
13604  *
13605  * this function is called when verifier exploring different branches of
13606  * execution popped from the state stack. If it sees an old state that has
13607  * more strict register state and more strict stack state then this execution
13608  * branch doesn't need to be explored further, since verifier already
13609  * concluded that more strict state leads to valid finish.
13610  *
13611  * Therefore two states are equivalent if register state is more conservative
13612  * and explored stack state is more conservative than the current one.
13613  * Example:
13614  *       explored                   current
13615  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13616  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13617  *
13618  * In other words if current stack state (one being explored) has more
13619  * valid slots than old one that already passed validation, it means
13620  * the verifier can stop exploring and conclude that current state is valid too
13621  *
13622  * Similarly with registers. If explored state has register type as invalid
13623  * whereas register type in current state is meaningful, it means that
13624  * the current state will reach 'bpf_exit' instruction safely
13625  */
13626 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13627 			      struct bpf_func_state *cur)
13628 {
13629 	int i;
13630 
13631 	for (i = 0; i < MAX_BPF_REG; i++)
13632 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
13633 			     env->idmap_scratch))
13634 			return false;
13635 
13636 	if (!stacksafe(env, old, cur, env->idmap_scratch))
13637 		return false;
13638 
13639 	if (!refsafe(old, cur, env->idmap_scratch))
13640 		return false;
13641 
13642 	return true;
13643 }
13644 
13645 static bool states_equal(struct bpf_verifier_env *env,
13646 			 struct bpf_verifier_state *old,
13647 			 struct bpf_verifier_state *cur)
13648 {
13649 	int i;
13650 
13651 	if (old->curframe != cur->curframe)
13652 		return false;
13653 
13654 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13655 
13656 	/* Verification state from speculative execution simulation
13657 	 * must never prune a non-speculative execution one.
13658 	 */
13659 	if (old->speculative && !cur->speculative)
13660 		return false;
13661 
13662 	if (old->active_lock.ptr != cur->active_lock.ptr)
13663 		return false;
13664 
13665 	/* Old and cur active_lock's have to be either both present
13666 	 * or both absent.
13667 	 */
13668 	if (!!old->active_lock.id != !!cur->active_lock.id)
13669 		return false;
13670 
13671 	if (old->active_lock.id &&
13672 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
13673 		return false;
13674 
13675 	if (old->active_rcu_lock != cur->active_rcu_lock)
13676 		return false;
13677 
13678 	/* for states to be equal callsites have to be the same
13679 	 * and all frame states need to be equivalent
13680 	 */
13681 	for (i = 0; i <= old->curframe; i++) {
13682 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
13683 			return false;
13684 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13685 			return false;
13686 	}
13687 	return true;
13688 }
13689 
13690 /* Return 0 if no propagation happened. Return negative error code if error
13691  * happened. Otherwise, return the propagated bit.
13692  */
13693 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13694 				  struct bpf_reg_state *reg,
13695 				  struct bpf_reg_state *parent_reg)
13696 {
13697 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13698 	u8 flag = reg->live & REG_LIVE_READ;
13699 	int err;
13700 
13701 	/* When comes here, read flags of PARENT_REG or REG could be any of
13702 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13703 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13704 	 */
13705 	if (parent_flag == REG_LIVE_READ64 ||
13706 	    /* Or if there is no read flag from REG. */
13707 	    !flag ||
13708 	    /* Or if the read flag from REG is the same as PARENT_REG. */
13709 	    parent_flag == flag)
13710 		return 0;
13711 
13712 	err = mark_reg_read(env, reg, parent_reg, flag);
13713 	if (err)
13714 		return err;
13715 
13716 	return flag;
13717 }
13718 
13719 /* A write screens off any subsequent reads; but write marks come from the
13720  * straight-line code between a state and its parent.  When we arrive at an
13721  * equivalent state (jump target or such) we didn't arrive by the straight-line
13722  * code, so read marks in the state must propagate to the parent regardless
13723  * of the state's write marks. That's what 'parent == state->parent' comparison
13724  * in mark_reg_read() is for.
13725  */
13726 static int propagate_liveness(struct bpf_verifier_env *env,
13727 			      const struct bpf_verifier_state *vstate,
13728 			      struct bpf_verifier_state *vparent)
13729 {
13730 	struct bpf_reg_state *state_reg, *parent_reg;
13731 	struct bpf_func_state *state, *parent;
13732 	int i, frame, err = 0;
13733 
13734 	if (vparent->curframe != vstate->curframe) {
13735 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
13736 		     vparent->curframe, vstate->curframe);
13737 		return -EFAULT;
13738 	}
13739 	/* Propagate read liveness of registers... */
13740 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13741 	for (frame = 0; frame <= vstate->curframe; frame++) {
13742 		parent = vparent->frame[frame];
13743 		state = vstate->frame[frame];
13744 		parent_reg = parent->regs;
13745 		state_reg = state->regs;
13746 		/* We don't need to worry about FP liveness, it's read-only */
13747 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13748 			err = propagate_liveness_reg(env, &state_reg[i],
13749 						     &parent_reg[i]);
13750 			if (err < 0)
13751 				return err;
13752 			if (err == REG_LIVE_READ64)
13753 				mark_insn_zext(env, &parent_reg[i]);
13754 		}
13755 
13756 		/* Propagate stack slots. */
13757 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13758 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13759 			parent_reg = &parent->stack[i].spilled_ptr;
13760 			state_reg = &state->stack[i].spilled_ptr;
13761 			err = propagate_liveness_reg(env, state_reg,
13762 						     parent_reg);
13763 			if (err < 0)
13764 				return err;
13765 		}
13766 	}
13767 	return 0;
13768 }
13769 
13770 /* find precise scalars in the previous equivalent state and
13771  * propagate them into the current state
13772  */
13773 static int propagate_precision(struct bpf_verifier_env *env,
13774 			       const struct bpf_verifier_state *old)
13775 {
13776 	struct bpf_reg_state *state_reg;
13777 	struct bpf_func_state *state;
13778 	int i, err = 0, fr;
13779 
13780 	for (fr = old->curframe; fr >= 0; fr--) {
13781 		state = old->frame[fr];
13782 		state_reg = state->regs;
13783 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13784 			if (state_reg->type != SCALAR_VALUE ||
13785 			    !state_reg->precise)
13786 				continue;
13787 			if (env->log.level & BPF_LOG_LEVEL2)
13788 				verbose(env, "frame %d: propagating r%d\n", i, fr);
13789 			err = mark_chain_precision_frame(env, fr, i);
13790 			if (err < 0)
13791 				return err;
13792 		}
13793 
13794 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13795 			if (!is_spilled_reg(&state->stack[i]))
13796 				continue;
13797 			state_reg = &state->stack[i].spilled_ptr;
13798 			if (state_reg->type != SCALAR_VALUE ||
13799 			    !state_reg->precise)
13800 				continue;
13801 			if (env->log.level & BPF_LOG_LEVEL2)
13802 				verbose(env, "frame %d: propagating fp%d\n",
13803 					(-i - 1) * BPF_REG_SIZE, fr);
13804 			err = mark_chain_precision_stack_frame(env, fr, i);
13805 			if (err < 0)
13806 				return err;
13807 		}
13808 	}
13809 	return 0;
13810 }
13811 
13812 static bool states_maybe_looping(struct bpf_verifier_state *old,
13813 				 struct bpf_verifier_state *cur)
13814 {
13815 	struct bpf_func_state *fold, *fcur;
13816 	int i, fr = cur->curframe;
13817 
13818 	if (old->curframe != fr)
13819 		return false;
13820 
13821 	fold = old->frame[fr];
13822 	fcur = cur->frame[fr];
13823 	for (i = 0; i < MAX_BPF_REG; i++)
13824 		if (memcmp(&fold->regs[i], &fcur->regs[i],
13825 			   offsetof(struct bpf_reg_state, parent)))
13826 			return false;
13827 	return true;
13828 }
13829 
13830 
13831 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13832 {
13833 	struct bpf_verifier_state_list *new_sl;
13834 	struct bpf_verifier_state_list *sl, **pprev;
13835 	struct bpf_verifier_state *cur = env->cur_state, *new;
13836 	int i, j, err, states_cnt = 0;
13837 	bool add_new_state = env->test_state_freq ? true : false;
13838 
13839 	/* bpf progs typically have pruning point every 4 instructions
13840 	 * http://vger.kernel.org/bpfconf2019.html#session-1
13841 	 * Do not add new state for future pruning if the verifier hasn't seen
13842 	 * at least 2 jumps and at least 8 instructions.
13843 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13844 	 * In tests that amounts to up to 50% reduction into total verifier
13845 	 * memory consumption and 20% verifier time speedup.
13846 	 */
13847 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13848 	    env->insn_processed - env->prev_insn_processed >= 8)
13849 		add_new_state = true;
13850 
13851 	pprev = explored_state(env, insn_idx);
13852 	sl = *pprev;
13853 
13854 	clean_live_states(env, insn_idx, cur);
13855 
13856 	while (sl) {
13857 		states_cnt++;
13858 		if (sl->state.insn_idx != insn_idx)
13859 			goto next;
13860 
13861 		if (sl->state.branches) {
13862 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13863 
13864 			if (frame->in_async_callback_fn &&
13865 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13866 				/* Different async_entry_cnt means that the verifier is
13867 				 * processing another entry into async callback.
13868 				 * Seeing the same state is not an indication of infinite
13869 				 * loop or infinite recursion.
13870 				 * But finding the same state doesn't mean that it's safe
13871 				 * to stop processing the current state. The previous state
13872 				 * hasn't yet reached bpf_exit, since state.branches > 0.
13873 				 * Checking in_async_callback_fn alone is not enough either.
13874 				 * Since the verifier still needs to catch infinite loops
13875 				 * inside async callbacks.
13876 				 */
13877 			} else if (states_maybe_looping(&sl->state, cur) &&
13878 				   states_equal(env, &sl->state, cur)) {
13879 				verbose_linfo(env, insn_idx, "; ");
13880 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13881 				return -EINVAL;
13882 			}
13883 			/* if the verifier is processing a loop, avoid adding new state
13884 			 * too often, since different loop iterations have distinct
13885 			 * states and may not help future pruning.
13886 			 * This threshold shouldn't be too low to make sure that
13887 			 * a loop with large bound will be rejected quickly.
13888 			 * The most abusive loop will be:
13889 			 * r1 += 1
13890 			 * if r1 < 1000000 goto pc-2
13891 			 * 1M insn_procssed limit / 100 == 10k peak states.
13892 			 * This threshold shouldn't be too high either, since states
13893 			 * at the end of the loop are likely to be useful in pruning.
13894 			 */
13895 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13896 			    env->insn_processed - env->prev_insn_processed < 100)
13897 				add_new_state = false;
13898 			goto miss;
13899 		}
13900 		if (states_equal(env, &sl->state, cur)) {
13901 			sl->hit_cnt++;
13902 			/* reached equivalent register/stack state,
13903 			 * prune the search.
13904 			 * Registers read by the continuation are read by us.
13905 			 * If we have any write marks in env->cur_state, they
13906 			 * will prevent corresponding reads in the continuation
13907 			 * from reaching our parent (an explored_state).  Our
13908 			 * own state will get the read marks recorded, but
13909 			 * they'll be immediately forgotten as we're pruning
13910 			 * this state and will pop a new one.
13911 			 */
13912 			err = propagate_liveness(env, &sl->state, cur);
13913 
13914 			/* if previous state reached the exit with precision and
13915 			 * current state is equivalent to it (except precsion marks)
13916 			 * the precision needs to be propagated back in
13917 			 * the current state.
13918 			 */
13919 			err = err ? : push_jmp_history(env, cur);
13920 			err = err ? : propagate_precision(env, &sl->state);
13921 			if (err)
13922 				return err;
13923 			return 1;
13924 		}
13925 miss:
13926 		/* when new state is not going to be added do not increase miss count.
13927 		 * Otherwise several loop iterations will remove the state
13928 		 * recorded earlier. The goal of these heuristics is to have
13929 		 * states from some iterations of the loop (some in the beginning
13930 		 * and some at the end) to help pruning.
13931 		 */
13932 		if (add_new_state)
13933 			sl->miss_cnt++;
13934 		/* heuristic to determine whether this state is beneficial
13935 		 * to keep checking from state equivalence point of view.
13936 		 * Higher numbers increase max_states_per_insn and verification time,
13937 		 * but do not meaningfully decrease insn_processed.
13938 		 */
13939 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13940 			/* the state is unlikely to be useful. Remove it to
13941 			 * speed up verification
13942 			 */
13943 			*pprev = sl->next;
13944 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13945 				u32 br = sl->state.branches;
13946 
13947 				WARN_ONCE(br,
13948 					  "BUG live_done but branches_to_explore %d\n",
13949 					  br);
13950 				free_verifier_state(&sl->state, false);
13951 				kfree(sl);
13952 				env->peak_states--;
13953 			} else {
13954 				/* cannot free this state, since parentage chain may
13955 				 * walk it later. Add it for free_list instead to
13956 				 * be freed at the end of verification
13957 				 */
13958 				sl->next = env->free_list;
13959 				env->free_list = sl;
13960 			}
13961 			sl = *pprev;
13962 			continue;
13963 		}
13964 next:
13965 		pprev = &sl->next;
13966 		sl = *pprev;
13967 	}
13968 
13969 	if (env->max_states_per_insn < states_cnt)
13970 		env->max_states_per_insn = states_cnt;
13971 
13972 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13973 		return 0;
13974 
13975 	if (!add_new_state)
13976 		return 0;
13977 
13978 	/* There were no equivalent states, remember the current one.
13979 	 * Technically the current state is not proven to be safe yet,
13980 	 * but it will either reach outer most bpf_exit (which means it's safe)
13981 	 * or it will be rejected. When there are no loops the verifier won't be
13982 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13983 	 * again on the way to bpf_exit.
13984 	 * When looping the sl->state.branches will be > 0 and this state
13985 	 * will not be considered for equivalence until branches == 0.
13986 	 */
13987 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13988 	if (!new_sl)
13989 		return -ENOMEM;
13990 	env->total_states++;
13991 	env->peak_states++;
13992 	env->prev_jmps_processed = env->jmps_processed;
13993 	env->prev_insn_processed = env->insn_processed;
13994 
13995 	/* forget precise markings we inherited, see __mark_chain_precision */
13996 	if (env->bpf_capable)
13997 		mark_all_scalars_imprecise(env, cur);
13998 
13999 	/* add new state to the head of linked list */
14000 	new = &new_sl->state;
14001 	err = copy_verifier_state(new, cur);
14002 	if (err) {
14003 		free_verifier_state(new, false);
14004 		kfree(new_sl);
14005 		return err;
14006 	}
14007 	new->insn_idx = insn_idx;
14008 	WARN_ONCE(new->branches != 1,
14009 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14010 
14011 	cur->parent = new;
14012 	cur->first_insn_idx = insn_idx;
14013 	clear_jmp_history(cur);
14014 	new_sl->next = *explored_state(env, insn_idx);
14015 	*explored_state(env, insn_idx) = new_sl;
14016 	/* connect new state to parentage chain. Current frame needs all
14017 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
14018 	 * to the stack implicitly by JITs) so in callers' frames connect just
14019 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14020 	 * the state of the call instruction (with WRITTEN set), and r0 comes
14021 	 * from callee with its full parentage chain, anyway.
14022 	 */
14023 	/* clear write marks in current state: the writes we did are not writes
14024 	 * our child did, so they don't screen off its reads from us.
14025 	 * (There are no read marks in current state, because reads always mark
14026 	 * their parent and current state never has children yet.  Only
14027 	 * explored_states can get read marks.)
14028 	 */
14029 	for (j = 0; j <= cur->curframe; j++) {
14030 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14031 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14032 		for (i = 0; i < BPF_REG_FP; i++)
14033 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14034 	}
14035 
14036 	/* all stack frames are accessible from callee, clear them all */
14037 	for (j = 0; j <= cur->curframe; j++) {
14038 		struct bpf_func_state *frame = cur->frame[j];
14039 		struct bpf_func_state *newframe = new->frame[j];
14040 
14041 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14042 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14043 			frame->stack[i].spilled_ptr.parent =
14044 						&newframe->stack[i].spilled_ptr;
14045 		}
14046 	}
14047 	return 0;
14048 }
14049 
14050 /* Return true if it's OK to have the same insn return a different type. */
14051 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14052 {
14053 	switch (base_type(type)) {
14054 	case PTR_TO_CTX:
14055 	case PTR_TO_SOCKET:
14056 	case PTR_TO_SOCK_COMMON:
14057 	case PTR_TO_TCP_SOCK:
14058 	case PTR_TO_XDP_SOCK:
14059 	case PTR_TO_BTF_ID:
14060 		return false;
14061 	default:
14062 		return true;
14063 	}
14064 }
14065 
14066 /* If an instruction was previously used with particular pointer types, then we
14067  * need to be careful to avoid cases such as the below, where it may be ok
14068  * for one branch accessing the pointer, but not ok for the other branch:
14069  *
14070  * R1 = sock_ptr
14071  * goto X;
14072  * ...
14073  * R1 = some_other_valid_ptr;
14074  * goto X;
14075  * ...
14076  * R2 = *(u32 *)(R1 + 0);
14077  */
14078 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14079 {
14080 	return src != prev && (!reg_type_mismatch_ok(src) ||
14081 			       !reg_type_mismatch_ok(prev));
14082 }
14083 
14084 static int do_check(struct bpf_verifier_env *env)
14085 {
14086 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14087 	struct bpf_verifier_state *state = env->cur_state;
14088 	struct bpf_insn *insns = env->prog->insnsi;
14089 	struct bpf_reg_state *regs;
14090 	int insn_cnt = env->prog->len;
14091 	bool do_print_state = false;
14092 	int prev_insn_idx = -1;
14093 
14094 	for (;;) {
14095 		struct bpf_insn *insn;
14096 		u8 class;
14097 		int err;
14098 
14099 		env->prev_insn_idx = prev_insn_idx;
14100 		if (env->insn_idx >= insn_cnt) {
14101 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
14102 				env->insn_idx, insn_cnt);
14103 			return -EFAULT;
14104 		}
14105 
14106 		insn = &insns[env->insn_idx];
14107 		class = BPF_CLASS(insn->code);
14108 
14109 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14110 			verbose(env,
14111 				"BPF program is too large. Processed %d insn\n",
14112 				env->insn_processed);
14113 			return -E2BIG;
14114 		}
14115 
14116 		state->last_insn_idx = env->prev_insn_idx;
14117 
14118 		if (is_prune_point(env, env->insn_idx)) {
14119 			err = is_state_visited(env, env->insn_idx);
14120 			if (err < 0)
14121 				return err;
14122 			if (err == 1) {
14123 				/* found equivalent state, can prune the search */
14124 				if (env->log.level & BPF_LOG_LEVEL) {
14125 					if (do_print_state)
14126 						verbose(env, "\nfrom %d to %d%s: safe\n",
14127 							env->prev_insn_idx, env->insn_idx,
14128 							env->cur_state->speculative ?
14129 							" (speculative execution)" : "");
14130 					else
14131 						verbose(env, "%d: safe\n", env->insn_idx);
14132 				}
14133 				goto process_bpf_exit;
14134 			}
14135 		}
14136 
14137 		if (is_jmp_point(env, env->insn_idx)) {
14138 			err = push_jmp_history(env, state);
14139 			if (err)
14140 				return err;
14141 		}
14142 
14143 		if (signal_pending(current))
14144 			return -EAGAIN;
14145 
14146 		if (need_resched())
14147 			cond_resched();
14148 
14149 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14150 			verbose(env, "\nfrom %d to %d%s:",
14151 				env->prev_insn_idx, env->insn_idx,
14152 				env->cur_state->speculative ?
14153 				" (speculative execution)" : "");
14154 			print_verifier_state(env, state->frame[state->curframe], true);
14155 			do_print_state = false;
14156 		}
14157 
14158 		if (env->log.level & BPF_LOG_LEVEL) {
14159 			const struct bpf_insn_cbs cbs = {
14160 				.cb_call	= disasm_kfunc_name,
14161 				.cb_print	= verbose,
14162 				.private_data	= env,
14163 			};
14164 
14165 			if (verifier_state_scratched(env))
14166 				print_insn_state(env, state->frame[state->curframe]);
14167 
14168 			verbose_linfo(env, env->insn_idx, "; ");
14169 			env->prev_log_len = env->log.len_used;
14170 			verbose(env, "%d: ", env->insn_idx);
14171 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14172 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14173 			env->prev_log_len = env->log.len_used;
14174 		}
14175 
14176 		if (bpf_prog_is_offloaded(env->prog->aux)) {
14177 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14178 							   env->prev_insn_idx);
14179 			if (err)
14180 				return err;
14181 		}
14182 
14183 		regs = cur_regs(env);
14184 		sanitize_mark_insn_seen(env);
14185 		prev_insn_idx = env->insn_idx;
14186 
14187 		if (class == BPF_ALU || class == BPF_ALU64) {
14188 			err = check_alu_op(env, insn);
14189 			if (err)
14190 				return err;
14191 
14192 		} else if (class == BPF_LDX) {
14193 			enum bpf_reg_type *prev_src_type, src_reg_type;
14194 
14195 			/* check for reserved fields is already done */
14196 
14197 			/* check src operand */
14198 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14199 			if (err)
14200 				return err;
14201 
14202 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14203 			if (err)
14204 				return err;
14205 
14206 			src_reg_type = regs[insn->src_reg].type;
14207 
14208 			/* check that memory (src_reg + off) is readable,
14209 			 * the state of dst_reg will be updated by this func
14210 			 */
14211 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
14212 					       insn->off, BPF_SIZE(insn->code),
14213 					       BPF_READ, insn->dst_reg, false);
14214 			if (err)
14215 				return err;
14216 
14217 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14218 
14219 			if (*prev_src_type == NOT_INIT) {
14220 				/* saw a valid insn
14221 				 * dst_reg = *(u32 *)(src_reg + off)
14222 				 * save type to validate intersecting paths
14223 				 */
14224 				*prev_src_type = src_reg_type;
14225 
14226 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
14227 				/* ABuser program is trying to use the same insn
14228 				 * dst_reg = *(u32*) (src_reg + off)
14229 				 * with different pointer types:
14230 				 * src_reg == ctx in one branch and
14231 				 * src_reg == stack|map in some other branch.
14232 				 * Reject it.
14233 				 */
14234 				verbose(env, "same insn cannot be used with different pointers\n");
14235 				return -EINVAL;
14236 			}
14237 
14238 		} else if (class == BPF_STX) {
14239 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
14240 
14241 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
14242 				err = check_atomic(env, env->insn_idx, insn);
14243 				if (err)
14244 					return err;
14245 				env->insn_idx++;
14246 				continue;
14247 			}
14248 
14249 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
14250 				verbose(env, "BPF_STX uses reserved fields\n");
14251 				return -EINVAL;
14252 			}
14253 
14254 			/* check src1 operand */
14255 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14256 			if (err)
14257 				return err;
14258 			/* check src2 operand */
14259 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14260 			if (err)
14261 				return err;
14262 
14263 			dst_reg_type = regs[insn->dst_reg].type;
14264 
14265 			/* check that memory (dst_reg + off) is writeable */
14266 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14267 					       insn->off, BPF_SIZE(insn->code),
14268 					       BPF_WRITE, insn->src_reg, false);
14269 			if (err)
14270 				return err;
14271 
14272 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14273 
14274 			if (*prev_dst_type == NOT_INIT) {
14275 				*prev_dst_type = dst_reg_type;
14276 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
14277 				verbose(env, "same insn cannot be used with different pointers\n");
14278 				return -EINVAL;
14279 			}
14280 
14281 		} else if (class == BPF_ST) {
14282 			if (BPF_MODE(insn->code) != BPF_MEM ||
14283 			    insn->src_reg != BPF_REG_0) {
14284 				verbose(env, "BPF_ST uses reserved fields\n");
14285 				return -EINVAL;
14286 			}
14287 			/* check src operand */
14288 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14289 			if (err)
14290 				return err;
14291 
14292 			if (is_ctx_reg(env, insn->dst_reg)) {
14293 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
14294 					insn->dst_reg,
14295 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
14296 				return -EACCES;
14297 			}
14298 
14299 			/* check that memory (dst_reg + off) is writeable */
14300 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14301 					       insn->off, BPF_SIZE(insn->code),
14302 					       BPF_WRITE, -1, false);
14303 			if (err)
14304 				return err;
14305 
14306 		} else if (class == BPF_JMP || class == BPF_JMP32) {
14307 			u8 opcode = BPF_OP(insn->code);
14308 
14309 			env->jmps_processed++;
14310 			if (opcode == BPF_CALL) {
14311 				if (BPF_SRC(insn->code) != BPF_K ||
14312 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
14313 				     && insn->off != 0) ||
14314 				    (insn->src_reg != BPF_REG_0 &&
14315 				     insn->src_reg != BPF_PSEUDO_CALL &&
14316 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
14317 				    insn->dst_reg != BPF_REG_0 ||
14318 				    class == BPF_JMP32) {
14319 					verbose(env, "BPF_CALL uses reserved fields\n");
14320 					return -EINVAL;
14321 				}
14322 
14323 				if (env->cur_state->active_lock.ptr) {
14324 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
14325 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
14326 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
14327 					     (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
14328 						verbose(env, "function calls are not allowed while holding a lock\n");
14329 						return -EINVAL;
14330 					}
14331 				}
14332 				if (insn->src_reg == BPF_PSEUDO_CALL)
14333 					err = check_func_call(env, insn, &env->insn_idx);
14334 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
14335 					err = check_kfunc_call(env, insn, &env->insn_idx);
14336 				else
14337 					err = check_helper_call(env, insn, &env->insn_idx);
14338 				if (err)
14339 					return err;
14340 			} else if (opcode == BPF_JA) {
14341 				if (BPF_SRC(insn->code) != BPF_K ||
14342 				    insn->imm != 0 ||
14343 				    insn->src_reg != BPF_REG_0 ||
14344 				    insn->dst_reg != BPF_REG_0 ||
14345 				    class == BPF_JMP32) {
14346 					verbose(env, "BPF_JA uses reserved fields\n");
14347 					return -EINVAL;
14348 				}
14349 
14350 				env->insn_idx += insn->off + 1;
14351 				continue;
14352 
14353 			} else if (opcode == BPF_EXIT) {
14354 				if (BPF_SRC(insn->code) != BPF_K ||
14355 				    insn->imm != 0 ||
14356 				    insn->src_reg != BPF_REG_0 ||
14357 				    insn->dst_reg != BPF_REG_0 ||
14358 				    class == BPF_JMP32) {
14359 					verbose(env, "BPF_EXIT uses reserved fields\n");
14360 					return -EINVAL;
14361 				}
14362 
14363 				if (env->cur_state->active_lock.ptr) {
14364 					verbose(env, "bpf_spin_unlock is missing\n");
14365 					return -EINVAL;
14366 				}
14367 
14368 				if (env->cur_state->active_rcu_lock) {
14369 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14370 					return -EINVAL;
14371 				}
14372 
14373 				/* We must do check_reference_leak here before
14374 				 * prepare_func_exit to handle the case when
14375 				 * state->curframe > 0, it may be a callback
14376 				 * function, for which reference_state must
14377 				 * match caller reference state when it exits.
14378 				 */
14379 				err = check_reference_leak(env);
14380 				if (err)
14381 					return err;
14382 
14383 				if (state->curframe) {
14384 					/* exit from nested function */
14385 					err = prepare_func_exit(env, &env->insn_idx);
14386 					if (err)
14387 						return err;
14388 					do_print_state = true;
14389 					continue;
14390 				}
14391 
14392 				err = check_return_code(env);
14393 				if (err)
14394 					return err;
14395 process_bpf_exit:
14396 				mark_verifier_state_scratched(env);
14397 				update_branch_counts(env, env->cur_state);
14398 				err = pop_stack(env, &prev_insn_idx,
14399 						&env->insn_idx, pop_log);
14400 				if (err < 0) {
14401 					if (err != -ENOENT)
14402 						return err;
14403 					break;
14404 				} else {
14405 					do_print_state = true;
14406 					continue;
14407 				}
14408 			} else {
14409 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14410 				if (err)
14411 					return err;
14412 			}
14413 		} else if (class == BPF_LD) {
14414 			u8 mode = BPF_MODE(insn->code);
14415 
14416 			if (mode == BPF_ABS || mode == BPF_IND) {
14417 				err = check_ld_abs(env, insn);
14418 				if (err)
14419 					return err;
14420 
14421 			} else if (mode == BPF_IMM) {
14422 				err = check_ld_imm(env, insn);
14423 				if (err)
14424 					return err;
14425 
14426 				env->insn_idx++;
14427 				sanitize_mark_insn_seen(env);
14428 			} else {
14429 				verbose(env, "invalid BPF_LD mode\n");
14430 				return -EINVAL;
14431 			}
14432 		} else {
14433 			verbose(env, "unknown insn class %d\n", class);
14434 			return -EINVAL;
14435 		}
14436 
14437 		env->insn_idx++;
14438 	}
14439 
14440 	return 0;
14441 }
14442 
14443 static int find_btf_percpu_datasec(struct btf *btf)
14444 {
14445 	const struct btf_type *t;
14446 	const char *tname;
14447 	int i, n;
14448 
14449 	/*
14450 	 * Both vmlinux and module each have their own ".data..percpu"
14451 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14452 	 * types to look at only module's own BTF types.
14453 	 */
14454 	n = btf_nr_types(btf);
14455 	if (btf_is_module(btf))
14456 		i = btf_nr_types(btf_vmlinux);
14457 	else
14458 		i = 1;
14459 
14460 	for(; i < n; i++) {
14461 		t = btf_type_by_id(btf, i);
14462 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14463 			continue;
14464 
14465 		tname = btf_name_by_offset(btf, t->name_off);
14466 		if (!strcmp(tname, ".data..percpu"))
14467 			return i;
14468 	}
14469 
14470 	return -ENOENT;
14471 }
14472 
14473 /* replace pseudo btf_id with kernel symbol address */
14474 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14475 			       struct bpf_insn *insn,
14476 			       struct bpf_insn_aux_data *aux)
14477 {
14478 	const struct btf_var_secinfo *vsi;
14479 	const struct btf_type *datasec;
14480 	struct btf_mod_pair *btf_mod;
14481 	const struct btf_type *t;
14482 	const char *sym_name;
14483 	bool percpu = false;
14484 	u32 type, id = insn->imm;
14485 	struct btf *btf;
14486 	s32 datasec_id;
14487 	u64 addr;
14488 	int i, btf_fd, err;
14489 
14490 	btf_fd = insn[1].imm;
14491 	if (btf_fd) {
14492 		btf = btf_get_by_fd(btf_fd);
14493 		if (IS_ERR(btf)) {
14494 			verbose(env, "invalid module BTF object FD specified.\n");
14495 			return -EINVAL;
14496 		}
14497 	} else {
14498 		if (!btf_vmlinux) {
14499 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14500 			return -EINVAL;
14501 		}
14502 		btf = btf_vmlinux;
14503 		btf_get(btf);
14504 	}
14505 
14506 	t = btf_type_by_id(btf, id);
14507 	if (!t) {
14508 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14509 		err = -ENOENT;
14510 		goto err_put;
14511 	}
14512 
14513 	if (!btf_type_is_var(t)) {
14514 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14515 		err = -EINVAL;
14516 		goto err_put;
14517 	}
14518 
14519 	sym_name = btf_name_by_offset(btf, t->name_off);
14520 	addr = kallsyms_lookup_name(sym_name);
14521 	if (!addr) {
14522 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14523 			sym_name);
14524 		err = -ENOENT;
14525 		goto err_put;
14526 	}
14527 
14528 	datasec_id = find_btf_percpu_datasec(btf);
14529 	if (datasec_id > 0) {
14530 		datasec = btf_type_by_id(btf, datasec_id);
14531 		for_each_vsi(i, datasec, vsi) {
14532 			if (vsi->type == id) {
14533 				percpu = true;
14534 				break;
14535 			}
14536 		}
14537 	}
14538 
14539 	insn[0].imm = (u32)addr;
14540 	insn[1].imm = addr >> 32;
14541 
14542 	type = t->type;
14543 	t = btf_type_skip_modifiers(btf, type, NULL);
14544 	if (percpu) {
14545 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14546 		aux->btf_var.btf = btf;
14547 		aux->btf_var.btf_id = type;
14548 	} else if (!btf_type_is_struct(t)) {
14549 		const struct btf_type *ret;
14550 		const char *tname;
14551 		u32 tsize;
14552 
14553 		/* resolve the type size of ksym. */
14554 		ret = btf_resolve_size(btf, t, &tsize);
14555 		if (IS_ERR(ret)) {
14556 			tname = btf_name_by_offset(btf, t->name_off);
14557 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14558 				tname, PTR_ERR(ret));
14559 			err = -EINVAL;
14560 			goto err_put;
14561 		}
14562 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14563 		aux->btf_var.mem_size = tsize;
14564 	} else {
14565 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14566 		aux->btf_var.btf = btf;
14567 		aux->btf_var.btf_id = type;
14568 	}
14569 
14570 	/* check whether we recorded this BTF (and maybe module) already */
14571 	for (i = 0; i < env->used_btf_cnt; i++) {
14572 		if (env->used_btfs[i].btf == btf) {
14573 			btf_put(btf);
14574 			return 0;
14575 		}
14576 	}
14577 
14578 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14579 		err = -E2BIG;
14580 		goto err_put;
14581 	}
14582 
14583 	btf_mod = &env->used_btfs[env->used_btf_cnt];
14584 	btf_mod->btf = btf;
14585 	btf_mod->module = NULL;
14586 
14587 	/* if we reference variables from kernel module, bump its refcount */
14588 	if (btf_is_module(btf)) {
14589 		btf_mod->module = btf_try_get_module(btf);
14590 		if (!btf_mod->module) {
14591 			err = -ENXIO;
14592 			goto err_put;
14593 		}
14594 	}
14595 
14596 	env->used_btf_cnt++;
14597 
14598 	return 0;
14599 err_put:
14600 	btf_put(btf);
14601 	return err;
14602 }
14603 
14604 static bool is_tracing_prog_type(enum bpf_prog_type type)
14605 {
14606 	switch (type) {
14607 	case BPF_PROG_TYPE_KPROBE:
14608 	case BPF_PROG_TYPE_TRACEPOINT:
14609 	case BPF_PROG_TYPE_PERF_EVENT:
14610 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14611 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14612 		return true;
14613 	default:
14614 		return false;
14615 	}
14616 }
14617 
14618 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14619 					struct bpf_map *map,
14620 					struct bpf_prog *prog)
14621 
14622 {
14623 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14624 
14625 	if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14626 		if (is_tracing_prog_type(prog_type)) {
14627 			verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14628 			return -EINVAL;
14629 		}
14630 	}
14631 
14632 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14633 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14634 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14635 			return -EINVAL;
14636 		}
14637 
14638 		if (is_tracing_prog_type(prog_type)) {
14639 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14640 			return -EINVAL;
14641 		}
14642 
14643 		if (prog->aux->sleepable) {
14644 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14645 			return -EINVAL;
14646 		}
14647 	}
14648 
14649 	if (btf_record_has_field(map->record, BPF_TIMER)) {
14650 		if (is_tracing_prog_type(prog_type)) {
14651 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
14652 			return -EINVAL;
14653 		}
14654 	}
14655 
14656 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
14657 	    !bpf_offload_prog_map_match(prog, map)) {
14658 		verbose(env, "offload device mismatch between prog and map\n");
14659 		return -EINVAL;
14660 	}
14661 
14662 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14663 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14664 		return -EINVAL;
14665 	}
14666 
14667 	if (prog->aux->sleepable)
14668 		switch (map->map_type) {
14669 		case BPF_MAP_TYPE_HASH:
14670 		case BPF_MAP_TYPE_LRU_HASH:
14671 		case BPF_MAP_TYPE_ARRAY:
14672 		case BPF_MAP_TYPE_PERCPU_HASH:
14673 		case BPF_MAP_TYPE_PERCPU_ARRAY:
14674 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14675 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14676 		case BPF_MAP_TYPE_HASH_OF_MAPS:
14677 		case BPF_MAP_TYPE_RINGBUF:
14678 		case BPF_MAP_TYPE_USER_RINGBUF:
14679 		case BPF_MAP_TYPE_INODE_STORAGE:
14680 		case BPF_MAP_TYPE_SK_STORAGE:
14681 		case BPF_MAP_TYPE_TASK_STORAGE:
14682 		case BPF_MAP_TYPE_CGRP_STORAGE:
14683 			break;
14684 		default:
14685 			verbose(env,
14686 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14687 			return -EINVAL;
14688 		}
14689 
14690 	return 0;
14691 }
14692 
14693 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14694 {
14695 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14696 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14697 }
14698 
14699 /* find and rewrite pseudo imm in ld_imm64 instructions:
14700  *
14701  * 1. if it accesses map FD, replace it with actual map pointer.
14702  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14703  *
14704  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14705  */
14706 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14707 {
14708 	struct bpf_insn *insn = env->prog->insnsi;
14709 	int insn_cnt = env->prog->len;
14710 	int i, j, err;
14711 
14712 	err = bpf_prog_calc_tag(env->prog);
14713 	if (err)
14714 		return err;
14715 
14716 	for (i = 0; i < insn_cnt; i++, insn++) {
14717 		if (BPF_CLASS(insn->code) == BPF_LDX &&
14718 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14719 			verbose(env, "BPF_LDX uses reserved fields\n");
14720 			return -EINVAL;
14721 		}
14722 
14723 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14724 			struct bpf_insn_aux_data *aux;
14725 			struct bpf_map *map;
14726 			struct fd f;
14727 			u64 addr;
14728 			u32 fd;
14729 
14730 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
14731 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14732 			    insn[1].off != 0) {
14733 				verbose(env, "invalid bpf_ld_imm64 insn\n");
14734 				return -EINVAL;
14735 			}
14736 
14737 			if (insn[0].src_reg == 0)
14738 				/* valid generic load 64-bit imm */
14739 				goto next_insn;
14740 
14741 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14742 				aux = &env->insn_aux_data[i];
14743 				err = check_pseudo_btf_id(env, insn, aux);
14744 				if (err)
14745 					return err;
14746 				goto next_insn;
14747 			}
14748 
14749 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14750 				aux = &env->insn_aux_data[i];
14751 				aux->ptr_type = PTR_TO_FUNC;
14752 				goto next_insn;
14753 			}
14754 
14755 			/* In final convert_pseudo_ld_imm64() step, this is
14756 			 * converted into regular 64-bit imm load insn.
14757 			 */
14758 			switch (insn[0].src_reg) {
14759 			case BPF_PSEUDO_MAP_VALUE:
14760 			case BPF_PSEUDO_MAP_IDX_VALUE:
14761 				break;
14762 			case BPF_PSEUDO_MAP_FD:
14763 			case BPF_PSEUDO_MAP_IDX:
14764 				if (insn[1].imm == 0)
14765 					break;
14766 				fallthrough;
14767 			default:
14768 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14769 				return -EINVAL;
14770 			}
14771 
14772 			switch (insn[0].src_reg) {
14773 			case BPF_PSEUDO_MAP_IDX_VALUE:
14774 			case BPF_PSEUDO_MAP_IDX:
14775 				if (bpfptr_is_null(env->fd_array)) {
14776 					verbose(env, "fd_idx without fd_array is invalid\n");
14777 					return -EPROTO;
14778 				}
14779 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
14780 							    insn[0].imm * sizeof(fd),
14781 							    sizeof(fd)))
14782 					return -EFAULT;
14783 				break;
14784 			default:
14785 				fd = insn[0].imm;
14786 				break;
14787 			}
14788 
14789 			f = fdget(fd);
14790 			map = __bpf_map_get(f);
14791 			if (IS_ERR(map)) {
14792 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
14793 					insn[0].imm);
14794 				return PTR_ERR(map);
14795 			}
14796 
14797 			err = check_map_prog_compatibility(env, map, env->prog);
14798 			if (err) {
14799 				fdput(f);
14800 				return err;
14801 			}
14802 
14803 			aux = &env->insn_aux_data[i];
14804 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14805 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14806 				addr = (unsigned long)map;
14807 			} else {
14808 				u32 off = insn[1].imm;
14809 
14810 				if (off >= BPF_MAX_VAR_OFF) {
14811 					verbose(env, "direct value offset of %u is not allowed\n", off);
14812 					fdput(f);
14813 					return -EINVAL;
14814 				}
14815 
14816 				if (!map->ops->map_direct_value_addr) {
14817 					verbose(env, "no direct value access support for this map type\n");
14818 					fdput(f);
14819 					return -EINVAL;
14820 				}
14821 
14822 				err = map->ops->map_direct_value_addr(map, &addr, off);
14823 				if (err) {
14824 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14825 						map->value_size, off);
14826 					fdput(f);
14827 					return err;
14828 				}
14829 
14830 				aux->map_off = off;
14831 				addr += off;
14832 			}
14833 
14834 			insn[0].imm = (u32)addr;
14835 			insn[1].imm = addr >> 32;
14836 
14837 			/* check whether we recorded this map already */
14838 			for (j = 0; j < env->used_map_cnt; j++) {
14839 				if (env->used_maps[j] == map) {
14840 					aux->map_index = j;
14841 					fdput(f);
14842 					goto next_insn;
14843 				}
14844 			}
14845 
14846 			if (env->used_map_cnt >= MAX_USED_MAPS) {
14847 				fdput(f);
14848 				return -E2BIG;
14849 			}
14850 
14851 			/* hold the map. If the program is rejected by verifier,
14852 			 * the map will be released by release_maps() or it
14853 			 * will be used by the valid program until it's unloaded
14854 			 * and all maps are released in free_used_maps()
14855 			 */
14856 			bpf_map_inc(map);
14857 
14858 			aux->map_index = env->used_map_cnt;
14859 			env->used_maps[env->used_map_cnt++] = map;
14860 
14861 			if (bpf_map_is_cgroup_storage(map) &&
14862 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
14863 				verbose(env, "only one cgroup storage of each type is allowed\n");
14864 				fdput(f);
14865 				return -EBUSY;
14866 			}
14867 
14868 			fdput(f);
14869 next_insn:
14870 			insn++;
14871 			i++;
14872 			continue;
14873 		}
14874 
14875 		/* Basic sanity check before we invest more work here. */
14876 		if (!bpf_opcode_in_insntable(insn->code)) {
14877 			verbose(env, "unknown opcode %02x\n", insn->code);
14878 			return -EINVAL;
14879 		}
14880 	}
14881 
14882 	/* now all pseudo BPF_LD_IMM64 instructions load valid
14883 	 * 'struct bpf_map *' into a register instead of user map_fd.
14884 	 * These pointers will be used later by verifier to validate map access.
14885 	 */
14886 	return 0;
14887 }
14888 
14889 /* drop refcnt of maps used by the rejected program */
14890 static void release_maps(struct bpf_verifier_env *env)
14891 {
14892 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
14893 			     env->used_map_cnt);
14894 }
14895 
14896 /* drop refcnt of maps used by the rejected program */
14897 static void release_btfs(struct bpf_verifier_env *env)
14898 {
14899 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14900 			     env->used_btf_cnt);
14901 }
14902 
14903 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14904 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14905 {
14906 	struct bpf_insn *insn = env->prog->insnsi;
14907 	int insn_cnt = env->prog->len;
14908 	int i;
14909 
14910 	for (i = 0; i < insn_cnt; i++, insn++) {
14911 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14912 			continue;
14913 		if (insn->src_reg == BPF_PSEUDO_FUNC)
14914 			continue;
14915 		insn->src_reg = 0;
14916 	}
14917 }
14918 
14919 /* single env->prog->insni[off] instruction was replaced with the range
14920  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14921  * [0, off) and [off, end) to new locations, so the patched range stays zero
14922  */
14923 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14924 				 struct bpf_insn_aux_data *new_data,
14925 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
14926 {
14927 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14928 	struct bpf_insn *insn = new_prog->insnsi;
14929 	u32 old_seen = old_data[off].seen;
14930 	u32 prog_len;
14931 	int i;
14932 
14933 	/* aux info at OFF always needs adjustment, no matter fast path
14934 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14935 	 * original insn at old prog.
14936 	 */
14937 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14938 
14939 	if (cnt == 1)
14940 		return;
14941 	prog_len = new_prog->len;
14942 
14943 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14944 	memcpy(new_data + off + cnt - 1, old_data + off,
14945 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14946 	for (i = off; i < off + cnt - 1; i++) {
14947 		/* Expand insni[off]'s seen count to the patched range. */
14948 		new_data[i].seen = old_seen;
14949 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
14950 	}
14951 	env->insn_aux_data = new_data;
14952 	vfree(old_data);
14953 }
14954 
14955 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14956 {
14957 	int i;
14958 
14959 	if (len == 1)
14960 		return;
14961 	/* NOTE: fake 'exit' subprog should be updated as well. */
14962 	for (i = 0; i <= env->subprog_cnt; i++) {
14963 		if (env->subprog_info[i].start <= off)
14964 			continue;
14965 		env->subprog_info[i].start += len - 1;
14966 	}
14967 }
14968 
14969 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14970 {
14971 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14972 	int i, sz = prog->aux->size_poke_tab;
14973 	struct bpf_jit_poke_descriptor *desc;
14974 
14975 	for (i = 0; i < sz; i++) {
14976 		desc = &tab[i];
14977 		if (desc->insn_idx <= off)
14978 			continue;
14979 		desc->insn_idx += len - 1;
14980 	}
14981 }
14982 
14983 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14984 					    const struct bpf_insn *patch, u32 len)
14985 {
14986 	struct bpf_prog *new_prog;
14987 	struct bpf_insn_aux_data *new_data = NULL;
14988 
14989 	if (len > 1) {
14990 		new_data = vzalloc(array_size(env->prog->len + len - 1,
14991 					      sizeof(struct bpf_insn_aux_data)));
14992 		if (!new_data)
14993 			return NULL;
14994 	}
14995 
14996 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14997 	if (IS_ERR(new_prog)) {
14998 		if (PTR_ERR(new_prog) == -ERANGE)
14999 			verbose(env,
15000 				"insn %d cannot be patched due to 16-bit range\n",
15001 				env->insn_aux_data[off].orig_idx);
15002 		vfree(new_data);
15003 		return NULL;
15004 	}
15005 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
15006 	adjust_subprog_starts(env, off, len);
15007 	adjust_poke_descs(new_prog, off, len);
15008 	return new_prog;
15009 }
15010 
15011 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15012 					      u32 off, u32 cnt)
15013 {
15014 	int i, j;
15015 
15016 	/* find first prog starting at or after off (first to remove) */
15017 	for (i = 0; i < env->subprog_cnt; i++)
15018 		if (env->subprog_info[i].start >= off)
15019 			break;
15020 	/* find first prog starting at or after off + cnt (first to stay) */
15021 	for (j = i; j < env->subprog_cnt; j++)
15022 		if (env->subprog_info[j].start >= off + cnt)
15023 			break;
15024 	/* if j doesn't start exactly at off + cnt, we are just removing
15025 	 * the front of previous prog
15026 	 */
15027 	if (env->subprog_info[j].start != off + cnt)
15028 		j--;
15029 
15030 	if (j > i) {
15031 		struct bpf_prog_aux *aux = env->prog->aux;
15032 		int move;
15033 
15034 		/* move fake 'exit' subprog as well */
15035 		move = env->subprog_cnt + 1 - j;
15036 
15037 		memmove(env->subprog_info + i,
15038 			env->subprog_info + j,
15039 			sizeof(*env->subprog_info) * move);
15040 		env->subprog_cnt -= j - i;
15041 
15042 		/* remove func_info */
15043 		if (aux->func_info) {
15044 			move = aux->func_info_cnt - j;
15045 
15046 			memmove(aux->func_info + i,
15047 				aux->func_info + j,
15048 				sizeof(*aux->func_info) * move);
15049 			aux->func_info_cnt -= j - i;
15050 			/* func_info->insn_off is set after all code rewrites,
15051 			 * in adjust_btf_func() - no need to adjust
15052 			 */
15053 		}
15054 	} else {
15055 		/* convert i from "first prog to remove" to "first to adjust" */
15056 		if (env->subprog_info[i].start == off)
15057 			i++;
15058 	}
15059 
15060 	/* update fake 'exit' subprog as well */
15061 	for (; i <= env->subprog_cnt; i++)
15062 		env->subprog_info[i].start -= cnt;
15063 
15064 	return 0;
15065 }
15066 
15067 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15068 				      u32 cnt)
15069 {
15070 	struct bpf_prog *prog = env->prog;
15071 	u32 i, l_off, l_cnt, nr_linfo;
15072 	struct bpf_line_info *linfo;
15073 
15074 	nr_linfo = prog->aux->nr_linfo;
15075 	if (!nr_linfo)
15076 		return 0;
15077 
15078 	linfo = prog->aux->linfo;
15079 
15080 	/* find first line info to remove, count lines to be removed */
15081 	for (i = 0; i < nr_linfo; i++)
15082 		if (linfo[i].insn_off >= off)
15083 			break;
15084 
15085 	l_off = i;
15086 	l_cnt = 0;
15087 	for (; i < nr_linfo; i++)
15088 		if (linfo[i].insn_off < off + cnt)
15089 			l_cnt++;
15090 		else
15091 			break;
15092 
15093 	/* First live insn doesn't match first live linfo, it needs to "inherit"
15094 	 * last removed linfo.  prog is already modified, so prog->len == off
15095 	 * means no live instructions after (tail of the program was removed).
15096 	 */
15097 	if (prog->len != off && l_cnt &&
15098 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15099 		l_cnt--;
15100 		linfo[--i].insn_off = off + cnt;
15101 	}
15102 
15103 	/* remove the line info which refer to the removed instructions */
15104 	if (l_cnt) {
15105 		memmove(linfo + l_off, linfo + i,
15106 			sizeof(*linfo) * (nr_linfo - i));
15107 
15108 		prog->aux->nr_linfo -= l_cnt;
15109 		nr_linfo = prog->aux->nr_linfo;
15110 	}
15111 
15112 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
15113 	for (i = l_off; i < nr_linfo; i++)
15114 		linfo[i].insn_off -= cnt;
15115 
15116 	/* fix up all subprogs (incl. 'exit') which start >= off */
15117 	for (i = 0; i <= env->subprog_cnt; i++)
15118 		if (env->subprog_info[i].linfo_idx > l_off) {
15119 			/* program may have started in the removed region but
15120 			 * may not be fully removed
15121 			 */
15122 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15123 				env->subprog_info[i].linfo_idx -= l_cnt;
15124 			else
15125 				env->subprog_info[i].linfo_idx = l_off;
15126 		}
15127 
15128 	return 0;
15129 }
15130 
15131 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15132 {
15133 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15134 	unsigned int orig_prog_len = env->prog->len;
15135 	int err;
15136 
15137 	if (bpf_prog_is_offloaded(env->prog->aux))
15138 		bpf_prog_offload_remove_insns(env, off, cnt);
15139 
15140 	err = bpf_remove_insns(env->prog, off, cnt);
15141 	if (err)
15142 		return err;
15143 
15144 	err = adjust_subprog_starts_after_remove(env, off, cnt);
15145 	if (err)
15146 		return err;
15147 
15148 	err = bpf_adj_linfo_after_remove(env, off, cnt);
15149 	if (err)
15150 		return err;
15151 
15152 	memmove(aux_data + off,	aux_data + off + cnt,
15153 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
15154 
15155 	return 0;
15156 }
15157 
15158 /* The verifier does more data flow analysis than llvm and will not
15159  * explore branches that are dead at run time. Malicious programs can
15160  * have dead code too. Therefore replace all dead at-run-time code
15161  * with 'ja -1'.
15162  *
15163  * Just nops are not optimal, e.g. if they would sit at the end of the
15164  * program and through another bug we would manage to jump there, then
15165  * we'd execute beyond program memory otherwise. Returning exception
15166  * code also wouldn't work since we can have subprogs where the dead
15167  * code could be located.
15168  */
15169 static void sanitize_dead_code(struct bpf_verifier_env *env)
15170 {
15171 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15172 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15173 	struct bpf_insn *insn = env->prog->insnsi;
15174 	const int insn_cnt = env->prog->len;
15175 	int i;
15176 
15177 	for (i = 0; i < insn_cnt; i++) {
15178 		if (aux_data[i].seen)
15179 			continue;
15180 		memcpy(insn + i, &trap, sizeof(trap));
15181 		aux_data[i].zext_dst = false;
15182 	}
15183 }
15184 
15185 static bool insn_is_cond_jump(u8 code)
15186 {
15187 	u8 op;
15188 
15189 	if (BPF_CLASS(code) == BPF_JMP32)
15190 		return true;
15191 
15192 	if (BPF_CLASS(code) != BPF_JMP)
15193 		return false;
15194 
15195 	op = BPF_OP(code);
15196 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15197 }
15198 
15199 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15200 {
15201 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15202 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15203 	struct bpf_insn *insn = env->prog->insnsi;
15204 	const int insn_cnt = env->prog->len;
15205 	int i;
15206 
15207 	for (i = 0; i < insn_cnt; i++, insn++) {
15208 		if (!insn_is_cond_jump(insn->code))
15209 			continue;
15210 
15211 		if (!aux_data[i + 1].seen)
15212 			ja.off = insn->off;
15213 		else if (!aux_data[i + 1 + insn->off].seen)
15214 			ja.off = 0;
15215 		else
15216 			continue;
15217 
15218 		if (bpf_prog_is_offloaded(env->prog->aux))
15219 			bpf_prog_offload_replace_insn(env, i, &ja);
15220 
15221 		memcpy(insn, &ja, sizeof(ja));
15222 	}
15223 }
15224 
15225 static int opt_remove_dead_code(struct bpf_verifier_env *env)
15226 {
15227 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15228 	int insn_cnt = env->prog->len;
15229 	int i, err;
15230 
15231 	for (i = 0; i < insn_cnt; i++) {
15232 		int j;
15233 
15234 		j = 0;
15235 		while (i + j < insn_cnt && !aux_data[i + j].seen)
15236 			j++;
15237 		if (!j)
15238 			continue;
15239 
15240 		err = verifier_remove_insns(env, i, j);
15241 		if (err)
15242 			return err;
15243 		insn_cnt = env->prog->len;
15244 	}
15245 
15246 	return 0;
15247 }
15248 
15249 static int opt_remove_nops(struct bpf_verifier_env *env)
15250 {
15251 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15252 	struct bpf_insn *insn = env->prog->insnsi;
15253 	int insn_cnt = env->prog->len;
15254 	int i, err;
15255 
15256 	for (i = 0; i < insn_cnt; i++) {
15257 		if (memcmp(&insn[i], &ja, sizeof(ja)))
15258 			continue;
15259 
15260 		err = verifier_remove_insns(env, i, 1);
15261 		if (err)
15262 			return err;
15263 		insn_cnt--;
15264 		i--;
15265 	}
15266 
15267 	return 0;
15268 }
15269 
15270 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
15271 					 const union bpf_attr *attr)
15272 {
15273 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
15274 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15275 	int i, patch_len, delta = 0, len = env->prog->len;
15276 	struct bpf_insn *insns = env->prog->insnsi;
15277 	struct bpf_prog *new_prog;
15278 	bool rnd_hi32;
15279 
15280 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
15281 	zext_patch[1] = BPF_ZEXT_REG(0);
15282 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
15283 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
15284 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
15285 	for (i = 0; i < len; i++) {
15286 		int adj_idx = i + delta;
15287 		struct bpf_insn insn;
15288 		int load_reg;
15289 
15290 		insn = insns[adj_idx];
15291 		load_reg = insn_def_regno(&insn);
15292 		if (!aux[adj_idx].zext_dst) {
15293 			u8 code, class;
15294 			u32 imm_rnd;
15295 
15296 			if (!rnd_hi32)
15297 				continue;
15298 
15299 			code = insn.code;
15300 			class = BPF_CLASS(code);
15301 			if (load_reg == -1)
15302 				continue;
15303 
15304 			/* NOTE: arg "reg" (the fourth one) is only used for
15305 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
15306 			 *       here.
15307 			 */
15308 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
15309 				if (class == BPF_LD &&
15310 				    BPF_MODE(code) == BPF_IMM)
15311 					i++;
15312 				continue;
15313 			}
15314 
15315 			/* ctx load could be transformed into wider load. */
15316 			if (class == BPF_LDX &&
15317 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
15318 				continue;
15319 
15320 			imm_rnd = get_random_u32();
15321 			rnd_hi32_patch[0] = insn;
15322 			rnd_hi32_patch[1].imm = imm_rnd;
15323 			rnd_hi32_patch[3].dst_reg = load_reg;
15324 			patch = rnd_hi32_patch;
15325 			patch_len = 4;
15326 			goto apply_patch_buffer;
15327 		}
15328 
15329 		/* Add in an zero-extend instruction if a) the JIT has requested
15330 		 * it or b) it's a CMPXCHG.
15331 		 *
15332 		 * The latter is because: BPF_CMPXCHG always loads a value into
15333 		 * R0, therefore always zero-extends. However some archs'
15334 		 * equivalent instruction only does this load when the
15335 		 * comparison is successful. This detail of CMPXCHG is
15336 		 * orthogonal to the general zero-extension behaviour of the
15337 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
15338 		 */
15339 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
15340 			continue;
15341 
15342 		/* Zero-extension is done by the caller. */
15343 		if (bpf_pseudo_kfunc_call(&insn))
15344 			continue;
15345 
15346 		if (WARN_ON(load_reg == -1)) {
15347 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15348 			return -EFAULT;
15349 		}
15350 
15351 		zext_patch[0] = insn;
15352 		zext_patch[1].dst_reg = load_reg;
15353 		zext_patch[1].src_reg = load_reg;
15354 		patch = zext_patch;
15355 		patch_len = 2;
15356 apply_patch_buffer:
15357 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15358 		if (!new_prog)
15359 			return -ENOMEM;
15360 		env->prog = new_prog;
15361 		insns = new_prog->insnsi;
15362 		aux = env->insn_aux_data;
15363 		delta += patch_len - 1;
15364 	}
15365 
15366 	return 0;
15367 }
15368 
15369 /* convert load instructions that access fields of a context type into a
15370  * sequence of instructions that access fields of the underlying structure:
15371  *     struct __sk_buff    -> struct sk_buff
15372  *     struct bpf_sock_ops -> struct sock
15373  */
15374 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15375 {
15376 	const struct bpf_verifier_ops *ops = env->ops;
15377 	int i, cnt, size, ctx_field_size, delta = 0;
15378 	const int insn_cnt = env->prog->len;
15379 	struct bpf_insn insn_buf[16], *insn;
15380 	u32 target_size, size_default, off;
15381 	struct bpf_prog *new_prog;
15382 	enum bpf_access_type type;
15383 	bool is_narrower_load;
15384 
15385 	if (ops->gen_prologue || env->seen_direct_write) {
15386 		if (!ops->gen_prologue) {
15387 			verbose(env, "bpf verifier is misconfigured\n");
15388 			return -EINVAL;
15389 		}
15390 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15391 					env->prog);
15392 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15393 			verbose(env, "bpf verifier is misconfigured\n");
15394 			return -EINVAL;
15395 		} else if (cnt) {
15396 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15397 			if (!new_prog)
15398 				return -ENOMEM;
15399 
15400 			env->prog = new_prog;
15401 			delta += cnt - 1;
15402 		}
15403 	}
15404 
15405 	if (bpf_prog_is_offloaded(env->prog->aux))
15406 		return 0;
15407 
15408 	insn = env->prog->insnsi + delta;
15409 
15410 	for (i = 0; i < insn_cnt; i++, insn++) {
15411 		bpf_convert_ctx_access_t convert_ctx_access;
15412 		bool ctx_access;
15413 
15414 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15415 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15416 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15417 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15418 			type = BPF_READ;
15419 			ctx_access = true;
15420 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15421 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15422 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15423 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15424 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15425 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15426 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15427 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15428 			type = BPF_WRITE;
15429 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15430 		} else {
15431 			continue;
15432 		}
15433 
15434 		if (type == BPF_WRITE &&
15435 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15436 			struct bpf_insn patch[] = {
15437 				*insn,
15438 				BPF_ST_NOSPEC(),
15439 			};
15440 
15441 			cnt = ARRAY_SIZE(patch);
15442 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15443 			if (!new_prog)
15444 				return -ENOMEM;
15445 
15446 			delta    += cnt - 1;
15447 			env->prog = new_prog;
15448 			insn      = new_prog->insnsi + i + delta;
15449 			continue;
15450 		}
15451 
15452 		if (!ctx_access)
15453 			continue;
15454 
15455 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15456 		case PTR_TO_CTX:
15457 			if (!ops->convert_ctx_access)
15458 				continue;
15459 			convert_ctx_access = ops->convert_ctx_access;
15460 			break;
15461 		case PTR_TO_SOCKET:
15462 		case PTR_TO_SOCK_COMMON:
15463 			convert_ctx_access = bpf_sock_convert_ctx_access;
15464 			break;
15465 		case PTR_TO_TCP_SOCK:
15466 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15467 			break;
15468 		case PTR_TO_XDP_SOCK:
15469 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15470 			break;
15471 		case PTR_TO_BTF_ID:
15472 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15473 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15474 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15475 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15476 		 * any faults for loads into such types. BPF_WRITE is disallowed
15477 		 * for this case.
15478 		 */
15479 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15480 			if (type == BPF_READ) {
15481 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15482 					BPF_SIZE((insn)->code);
15483 				env->prog->aux->num_exentries++;
15484 			}
15485 			continue;
15486 		default:
15487 			continue;
15488 		}
15489 
15490 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15491 		size = BPF_LDST_BYTES(insn);
15492 
15493 		/* If the read access is a narrower load of the field,
15494 		 * convert to a 4/8-byte load, to minimum program type specific
15495 		 * convert_ctx_access changes. If conversion is successful,
15496 		 * we will apply proper mask to the result.
15497 		 */
15498 		is_narrower_load = size < ctx_field_size;
15499 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15500 		off = insn->off;
15501 		if (is_narrower_load) {
15502 			u8 size_code;
15503 
15504 			if (type == BPF_WRITE) {
15505 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15506 				return -EINVAL;
15507 			}
15508 
15509 			size_code = BPF_H;
15510 			if (ctx_field_size == 4)
15511 				size_code = BPF_W;
15512 			else if (ctx_field_size == 8)
15513 				size_code = BPF_DW;
15514 
15515 			insn->off = off & ~(size_default - 1);
15516 			insn->code = BPF_LDX | BPF_MEM | size_code;
15517 		}
15518 
15519 		target_size = 0;
15520 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15521 					 &target_size);
15522 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15523 		    (ctx_field_size && !target_size)) {
15524 			verbose(env, "bpf verifier is misconfigured\n");
15525 			return -EINVAL;
15526 		}
15527 
15528 		if (is_narrower_load && size < target_size) {
15529 			u8 shift = bpf_ctx_narrow_access_offset(
15530 				off, size, size_default) * 8;
15531 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15532 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15533 				return -EINVAL;
15534 			}
15535 			if (ctx_field_size <= 4) {
15536 				if (shift)
15537 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15538 									insn->dst_reg,
15539 									shift);
15540 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15541 								(1 << size * 8) - 1);
15542 			} else {
15543 				if (shift)
15544 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15545 									insn->dst_reg,
15546 									shift);
15547 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15548 								(1ULL << size * 8) - 1);
15549 			}
15550 		}
15551 
15552 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15553 		if (!new_prog)
15554 			return -ENOMEM;
15555 
15556 		delta += cnt - 1;
15557 
15558 		/* keep walking new program and skip insns we just inserted */
15559 		env->prog = new_prog;
15560 		insn      = new_prog->insnsi + i + delta;
15561 	}
15562 
15563 	return 0;
15564 }
15565 
15566 static int jit_subprogs(struct bpf_verifier_env *env)
15567 {
15568 	struct bpf_prog *prog = env->prog, **func, *tmp;
15569 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15570 	struct bpf_map *map_ptr;
15571 	struct bpf_insn *insn;
15572 	void *old_bpf_func;
15573 	int err, num_exentries;
15574 
15575 	if (env->subprog_cnt <= 1)
15576 		return 0;
15577 
15578 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15579 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15580 			continue;
15581 
15582 		/* Upon error here we cannot fall back to interpreter but
15583 		 * need a hard reject of the program. Thus -EFAULT is
15584 		 * propagated in any case.
15585 		 */
15586 		subprog = find_subprog(env, i + insn->imm + 1);
15587 		if (subprog < 0) {
15588 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15589 				  i + insn->imm + 1);
15590 			return -EFAULT;
15591 		}
15592 		/* temporarily remember subprog id inside insn instead of
15593 		 * aux_data, since next loop will split up all insns into funcs
15594 		 */
15595 		insn->off = subprog;
15596 		/* remember original imm in case JIT fails and fallback
15597 		 * to interpreter will be needed
15598 		 */
15599 		env->insn_aux_data[i].call_imm = insn->imm;
15600 		/* point imm to __bpf_call_base+1 from JITs point of view */
15601 		insn->imm = 1;
15602 		if (bpf_pseudo_func(insn))
15603 			/* jit (e.g. x86_64) may emit fewer instructions
15604 			 * if it learns a u32 imm is the same as a u64 imm.
15605 			 * Force a non zero here.
15606 			 */
15607 			insn[1].imm = 1;
15608 	}
15609 
15610 	err = bpf_prog_alloc_jited_linfo(prog);
15611 	if (err)
15612 		goto out_undo_insn;
15613 
15614 	err = -ENOMEM;
15615 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15616 	if (!func)
15617 		goto out_undo_insn;
15618 
15619 	for (i = 0; i < env->subprog_cnt; i++) {
15620 		subprog_start = subprog_end;
15621 		subprog_end = env->subprog_info[i + 1].start;
15622 
15623 		len = subprog_end - subprog_start;
15624 		/* bpf_prog_run() doesn't call subprogs directly,
15625 		 * hence main prog stats include the runtime of subprogs.
15626 		 * subprogs don't have IDs and not reachable via prog_get_next_id
15627 		 * func[i]->stats will never be accessed and stays NULL
15628 		 */
15629 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15630 		if (!func[i])
15631 			goto out_free;
15632 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15633 		       len * sizeof(struct bpf_insn));
15634 		func[i]->type = prog->type;
15635 		func[i]->len = len;
15636 		if (bpf_prog_calc_tag(func[i]))
15637 			goto out_free;
15638 		func[i]->is_func = 1;
15639 		func[i]->aux->func_idx = i;
15640 		/* Below members will be freed only at prog->aux */
15641 		func[i]->aux->btf = prog->aux->btf;
15642 		func[i]->aux->func_info = prog->aux->func_info;
15643 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15644 		func[i]->aux->poke_tab = prog->aux->poke_tab;
15645 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15646 
15647 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
15648 			struct bpf_jit_poke_descriptor *poke;
15649 
15650 			poke = &prog->aux->poke_tab[j];
15651 			if (poke->insn_idx < subprog_end &&
15652 			    poke->insn_idx >= subprog_start)
15653 				poke->aux = func[i]->aux;
15654 		}
15655 
15656 		func[i]->aux->name[0] = 'F';
15657 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15658 		func[i]->jit_requested = 1;
15659 		func[i]->blinding_requested = prog->blinding_requested;
15660 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15661 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15662 		func[i]->aux->linfo = prog->aux->linfo;
15663 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15664 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15665 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15666 		num_exentries = 0;
15667 		insn = func[i]->insnsi;
15668 		for (j = 0; j < func[i]->len; j++, insn++) {
15669 			if (BPF_CLASS(insn->code) == BPF_LDX &&
15670 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
15671 				num_exentries++;
15672 		}
15673 		func[i]->aux->num_exentries = num_exentries;
15674 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15675 		func[i] = bpf_int_jit_compile(func[i]);
15676 		if (!func[i]->jited) {
15677 			err = -ENOTSUPP;
15678 			goto out_free;
15679 		}
15680 		cond_resched();
15681 	}
15682 
15683 	/* at this point all bpf functions were successfully JITed
15684 	 * now populate all bpf_calls with correct addresses and
15685 	 * run last pass of JIT
15686 	 */
15687 	for (i = 0; i < env->subprog_cnt; i++) {
15688 		insn = func[i]->insnsi;
15689 		for (j = 0; j < func[i]->len; j++, insn++) {
15690 			if (bpf_pseudo_func(insn)) {
15691 				subprog = insn->off;
15692 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15693 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15694 				continue;
15695 			}
15696 			if (!bpf_pseudo_call(insn))
15697 				continue;
15698 			subprog = insn->off;
15699 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15700 		}
15701 
15702 		/* we use the aux data to keep a list of the start addresses
15703 		 * of the JITed images for each function in the program
15704 		 *
15705 		 * for some architectures, such as powerpc64, the imm field
15706 		 * might not be large enough to hold the offset of the start
15707 		 * address of the callee's JITed image from __bpf_call_base
15708 		 *
15709 		 * in such cases, we can lookup the start address of a callee
15710 		 * by using its subprog id, available from the off field of
15711 		 * the call instruction, as an index for this list
15712 		 */
15713 		func[i]->aux->func = func;
15714 		func[i]->aux->func_cnt = env->subprog_cnt;
15715 	}
15716 	for (i = 0; i < env->subprog_cnt; i++) {
15717 		old_bpf_func = func[i]->bpf_func;
15718 		tmp = bpf_int_jit_compile(func[i]);
15719 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15720 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15721 			err = -ENOTSUPP;
15722 			goto out_free;
15723 		}
15724 		cond_resched();
15725 	}
15726 
15727 	/* finally lock prog and jit images for all functions and
15728 	 * populate kallsysm
15729 	 */
15730 	for (i = 0; i < env->subprog_cnt; i++) {
15731 		bpf_prog_lock_ro(func[i]);
15732 		bpf_prog_kallsyms_add(func[i]);
15733 	}
15734 
15735 	/* Last step: make now unused interpreter insns from main
15736 	 * prog consistent for later dump requests, so they can
15737 	 * later look the same as if they were interpreted only.
15738 	 */
15739 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15740 		if (bpf_pseudo_func(insn)) {
15741 			insn[0].imm = env->insn_aux_data[i].call_imm;
15742 			insn[1].imm = insn->off;
15743 			insn->off = 0;
15744 			continue;
15745 		}
15746 		if (!bpf_pseudo_call(insn))
15747 			continue;
15748 		insn->off = env->insn_aux_data[i].call_imm;
15749 		subprog = find_subprog(env, i + insn->off + 1);
15750 		insn->imm = subprog;
15751 	}
15752 
15753 	prog->jited = 1;
15754 	prog->bpf_func = func[0]->bpf_func;
15755 	prog->jited_len = func[0]->jited_len;
15756 	prog->aux->func = func;
15757 	prog->aux->func_cnt = env->subprog_cnt;
15758 	bpf_prog_jit_attempt_done(prog);
15759 	return 0;
15760 out_free:
15761 	/* We failed JIT'ing, so at this point we need to unregister poke
15762 	 * descriptors from subprogs, so that kernel is not attempting to
15763 	 * patch it anymore as we're freeing the subprog JIT memory.
15764 	 */
15765 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15766 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15767 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15768 	}
15769 	/* At this point we're guaranteed that poke descriptors are not
15770 	 * live anymore. We can just unlink its descriptor table as it's
15771 	 * released with the main prog.
15772 	 */
15773 	for (i = 0; i < env->subprog_cnt; i++) {
15774 		if (!func[i])
15775 			continue;
15776 		func[i]->aux->poke_tab = NULL;
15777 		bpf_jit_free(func[i]);
15778 	}
15779 	kfree(func);
15780 out_undo_insn:
15781 	/* cleanup main prog to be interpreted */
15782 	prog->jit_requested = 0;
15783 	prog->blinding_requested = 0;
15784 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15785 		if (!bpf_pseudo_call(insn))
15786 			continue;
15787 		insn->off = 0;
15788 		insn->imm = env->insn_aux_data[i].call_imm;
15789 	}
15790 	bpf_prog_jit_attempt_done(prog);
15791 	return err;
15792 }
15793 
15794 static int fixup_call_args(struct bpf_verifier_env *env)
15795 {
15796 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15797 	struct bpf_prog *prog = env->prog;
15798 	struct bpf_insn *insn = prog->insnsi;
15799 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15800 	int i, depth;
15801 #endif
15802 	int err = 0;
15803 
15804 	if (env->prog->jit_requested &&
15805 	    !bpf_prog_is_offloaded(env->prog->aux)) {
15806 		err = jit_subprogs(env);
15807 		if (err == 0)
15808 			return 0;
15809 		if (err == -EFAULT)
15810 			return err;
15811 	}
15812 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15813 	if (has_kfunc_call) {
15814 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15815 		return -EINVAL;
15816 	}
15817 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15818 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
15819 		 * have to be rejected, since interpreter doesn't support them yet.
15820 		 */
15821 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15822 		return -EINVAL;
15823 	}
15824 	for (i = 0; i < prog->len; i++, insn++) {
15825 		if (bpf_pseudo_func(insn)) {
15826 			/* When JIT fails the progs with callback calls
15827 			 * have to be rejected, since interpreter doesn't support them yet.
15828 			 */
15829 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
15830 			return -EINVAL;
15831 		}
15832 
15833 		if (!bpf_pseudo_call(insn))
15834 			continue;
15835 		depth = get_callee_stack_depth(env, insn, i);
15836 		if (depth < 0)
15837 			return depth;
15838 		bpf_patch_call_args(insn, depth);
15839 	}
15840 	err = 0;
15841 #endif
15842 	return err;
15843 }
15844 
15845 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15846 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15847 {
15848 	const struct bpf_kfunc_desc *desc;
15849 	void *xdp_kfunc;
15850 
15851 	if (!insn->imm) {
15852 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15853 		return -EINVAL;
15854 	}
15855 
15856 	*cnt = 0;
15857 
15858 	if (bpf_dev_bound_kfunc_id(insn->imm)) {
15859 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
15860 		if (xdp_kfunc) {
15861 			insn->imm = BPF_CALL_IMM(xdp_kfunc);
15862 			return 0;
15863 		}
15864 
15865 		/* fallback to default kfunc when not supported by netdev */
15866 	}
15867 
15868 	/* insn->imm has the btf func_id. Replace it with
15869 	 * an address (relative to __bpf_call_base).
15870 	 */
15871 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15872 	if (!desc) {
15873 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15874 			insn->imm);
15875 		return -EFAULT;
15876 	}
15877 
15878 	insn->imm = desc->imm;
15879 	if (insn->off)
15880 		return 0;
15881 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15882 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15883 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15884 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15885 
15886 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15887 		insn_buf[1] = addr[0];
15888 		insn_buf[2] = addr[1];
15889 		insn_buf[3] = *insn;
15890 		*cnt = 4;
15891 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15892 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15893 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15894 
15895 		insn_buf[0] = addr[0];
15896 		insn_buf[1] = addr[1];
15897 		insn_buf[2] = *insn;
15898 		*cnt = 3;
15899 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15900 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15901 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15902 		*cnt = 1;
15903 	}
15904 	return 0;
15905 }
15906 
15907 /* Do various post-verification rewrites in a single program pass.
15908  * These rewrites simplify JIT and interpreter implementations.
15909  */
15910 static int do_misc_fixups(struct bpf_verifier_env *env)
15911 {
15912 	struct bpf_prog *prog = env->prog;
15913 	enum bpf_attach_type eatype = prog->expected_attach_type;
15914 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15915 	struct bpf_insn *insn = prog->insnsi;
15916 	const struct bpf_func_proto *fn;
15917 	const int insn_cnt = prog->len;
15918 	const struct bpf_map_ops *ops;
15919 	struct bpf_insn_aux_data *aux;
15920 	struct bpf_insn insn_buf[16];
15921 	struct bpf_prog *new_prog;
15922 	struct bpf_map *map_ptr;
15923 	int i, ret, cnt, delta = 0;
15924 
15925 	for (i = 0; i < insn_cnt; i++, insn++) {
15926 		/* Make divide-by-zero exceptions impossible. */
15927 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15928 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15929 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15930 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15931 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15932 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15933 			struct bpf_insn *patchlet;
15934 			struct bpf_insn chk_and_div[] = {
15935 				/* [R,W]x div 0 -> 0 */
15936 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15937 					     BPF_JNE | BPF_K, insn->src_reg,
15938 					     0, 2, 0),
15939 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15940 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15941 				*insn,
15942 			};
15943 			struct bpf_insn chk_and_mod[] = {
15944 				/* [R,W]x mod 0 -> [R,W]x */
15945 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15946 					     BPF_JEQ | BPF_K, insn->src_reg,
15947 					     0, 1 + (is64 ? 0 : 1), 0),
15948 				*insn,
15949 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15950 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15951 			};
15952 
15953 			patchlet = isdiv ? chk_and_div : chk_and_mod;
15954 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15955 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15956 
15957 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, 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 LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15968 		if (BPF_CLASS(insn->code) == BPF_LD &&
15969 		    (BPF_MODE(insn->code) == BPF_ABS ||
15970 		     BPF_MODE(insn->code) == BPF_IND)) {
15971 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
15972 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15973 				verbose(env, "bpf verifier is misconfigured\n");
15974 				return -EINVAL;
15975 			}
15976 
15977 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15978 			if (!new_prog)
15979 				return -ENOMEM;
15980 
15981 			delta    += cnt - 1;
15982 			env->prog = prog = new_prog;
15983 			insn      = new_prog->insnsi + i + delta;
15984 			continue;
15985 		}
15986 
15987 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
15988 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15989 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15990 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15991 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15992 			struct bpf_insn *patch = &insn_buf[0];
15993 			bool issrc, isneg, isimm;
15994 			u32 off_reg;
15995 
15996 			aux = &env->insn_aux_data[i + delta];
15997 			if (!aux->alu_state ||
15998 			    aux->alu_state == BPF_ALU_NON_POINTER)
15999 				continue;
16000 
16001 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16002 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16003 				BPF_ALU_SANITIZE_SRC;
16004 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16005 
16006 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
16007 			if (isimm) {
16008 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16009 			} else {
16010 				if (isneg)
16011 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16012 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16013 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16014 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16015 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16016 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16017 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16018 			}
16019 			if (!issrc)
16020 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16021 			insn->src_reg = BPF_REG_AX;
16022 			if (isneg)
16023 				insn->code = insn->code == code_add ?
16024 					     code_sub : code_add;
16025 			*patch++ = *insn;
16026 			if (issrc && isneg && !isimm)
16027 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16028 			cnt = patch - insn_buf;
16029 
16030 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16031 			if (!new_prog)
16032 				return -ENOMEM;
16033 
16034 			delta    += cnt - 1;
16035 			env->prog = prog = new_prog;
16036 			insn      = new_prog->insnsi + i + delta;
16037 			continue;
16038 		}
16039 
16040 		if (insn->code != (BPF_JMP | BPF_CALL))
16041 			continue;
16042 		if (insn->src_reg == BPF_PSEUDO_CALL)
16043 			continue;
16044 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16045 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16046 			if (ret)
16047 				return ret;
16048 			if (cnt == 0)
16049 				continue;
16050 
16051 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16052 			if (!new_prog)
16053 				return -ENOMEM;
16054 
16055 			delta	 += cnt - 1;
16056 			env->prog = prog = new_prog;
16057 			insn	  = new_prog->insnsi + i + delta;
16058 			continue;
16059 		}
16060 
16061 		if (insn->imm == BPF_FUNC_get_route_realm)
16062 			prog->dst_needed = 1;
16063 		if (insn->imm == BPF_FUNC_get_prandom_u32)
16064 			bpf_user_rnd_init_once();
16065 		if (insn->imm == BPF_FUNC_override_return)
16066 			prog->kprobe_override = 1;
16067 		if (insn->imm == BPF_FUNC_tail_call) {
16068 			/* If we tail call into other programs, we
16069 			 * cannot make any assumptions since they can
16070 			 * be replaced dynamically during runtime in
16071 			 * the program array.
16072 			 */
16073 			prog->cb_access = 1;
16074 			if (!allow_tail_call_in_subprogs(env))
16075 				prog->aux->stack_depth = MAX_BPF_STACK;
16076 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16077 
16078 			/* mark bpf_tail_call as different opcode to avoid
16079 			 * conditional branch in the interpreter for every normal
16080 			 * call and to prevent accidental JITing by JIT compiler
16081 			 * that doesn't support bpf_tail_call yet
16082 			 */
16083 			insn->imm = 0;
16084 			insn->code = BPF_JMP | BPF_TAIL_CALL;
16085 
16086 			aux = &env->insn_aux_data[i + delta];
16087 			if (env->bpf_capable && !prog->blinding_requested &&
16088 			    prog->jit_requested &&
16089 			    !bpf_map_key_poisoned(aux) &&
16090 			    !bpf_map_ptr_poisoned(aux) &&
16091 			    !bpf_map_ptr_unpriv(aux)) {
16092 				struct bpf_jit_poke_descriptor desc = {
16093 					.reason = BPF_POKE_REASON_TAIL_CALL,
16094 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16095 					.tail_call.key = bpf_map_key_immediate(aux),
16096 					.insn_idx = i + delta,
16097 				};
16098 
16099 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
16100 				if (ret < 0) {
16101 					verbose(env, "adding tail call poke descriptor failed\n");
16102 					return ret;
16103 				}
16104 
16105 				insn->imm = ret + 1;
16106 				continue;
16107 			}
16108 
16109 			if (!bpf_map_ptr_unpriv(aux))
16110 				continue;
16111 
16112 			/* instead of changing every JIT dealing with tail_call
16113 			 * emit two extra insns:
16114 			 * if (index >= max_entries) goto out;
16115 			 * index &= array->index_mask;
16116 			 * to avoid out-of-bounds cpu speculation
16117 			 */
16118 			if (bpf_map_ptr_poisoned(aux)) {
16119 				verbose(env, "tail_call abusing map_ptr\n");
16120 				return -EINVAL;
16121 			}
16122 
16123 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16124 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16125 						  map_ptr->max_entries, 2);
16126 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16127 						    container_of(map_ptr,
16128 								 struct bpf_array,
16129 								 map)->index_mask);
16130 			insn_buf[2] = *insn;
16131 			cnt = 3;
16132 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16133 			if (!new_prog)
16134 				return -ENOMEM;
16135 
16136 			delta    += cnt - 1;
16137 			env->prog = prog = new_prog;
16138 			insn      = new_prog->insnsi + i + delta;
16139 			continue;
16140 		}
16141 
16142 		if (insn->imm == BPF_FUNC_timer_set_callback) {
16143 			/* The verifier will process callback_fn as many times as necessary
16144 			 * with different maps and the register states prepared by
16145 			 * set_timer_callback_state will be accurate.
16146 			 *
16147 			 * The following use case is valid:
16148 			 *   map1 is shared by prog1, prog2, prog3.
16149 			 *   prog1 calls bpf_timer_init for some map1 elements
16150 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
16151 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
16152 			 *   prog3 calls bpf_timer_start for some map1 elements.
16153 			 *     Those that were not both bpf_timer_init-ed and
16154 			 *     bpf_timer_set_callback-ed will return -EINVAL.
16155 			 */
16156 			struct bpf_insn ld_addrs[2] = {
16157 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16158 			};
16159 
16160 			insn_buf[0] = ld_addrs[0];
16161 			insn_buf[1] = ld_addrs[1];
16162 			insn_buf[2] = *insn;
16163 			cnt = 3;
16164 
16165 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16166 			if (!new_prog)
16167 				return -ENOMEM;
16168 
16169 			delta    += cnt - 1;
16170 			env->prog = prog = new_prog;
16171 			insn      = new_prog->insnsi + i + delta;
16172 			goto patch_call_imm;
16173 		}
16174 
16175 		if (is_storage_get_function(insn->imm)) {
16176 			if (!env->prog->aux->sleepable ||
16177 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
16178 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16179 			else
16180 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16181 			insn_buf[1] = *insn;
16182 			cnt = 2;
16183 
16184 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16185 			if (!new_prog)
16186 				return -ENOMEM;
16187 
16188 			delta += cnt - 1;
16189 			env->prog = prog = new_prog;
16190 			insn = new_prog->insnsi + i + delta;
16191 			goto patch_call_imm;
16192 		}
16193 
16194 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16195 		 * and other inlining handlers are currently limited to 64 bit
16196 		 * only.
16197 		 */
16198 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16199 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
16200 		     insn->imm == BPF_FUNC_map_update_elem ||
16201 		     insn->imm == BPF_FUNC_map_delete_elem ||
16202 		     insn->imm == BPF_FUNC_map_push_elem   ||
16203 		     insn->imm == BPF_FUNC_map_pop_elem    ||
16204 		     insn->imm == BPF_FUNC_map_peek_elem   ||
16205 		     insn->imm == BPF_FUNC_redirect_map    ||
16206 		     insn->imm == BPF_FUNC_for_each_map_elem ||
16207 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16208 			aux = &env->insn_aux_data[i + delta];
16209 			if (bpf_map_ptr_poisoned(aux))
16210 				goto patch_call_imm;
16211 
16212 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16213 			ops = map_ptr->ops;
16214 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
16215 			    ops->map_gen_lookup) {
16216 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16217 				if (cnt == -EOPNOTSUPP)
16218 					goto patch_map_ops_generic;
16219 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16220 					verbose(env, "bpf verifier is misconfigured\n");
16221 					return -EINVAL;
16222 				}
16223 
16224 				new_prog = bpf_patch_insn_data(env, i + delta,
16225 							       insn_buf, cnt);
16226 				if (!new_prog)
16227 					return -ENOMEM;
16228 
16229 				delta    += cnt - 1;
16230 				env->prog = prog = new_prog;
16231 				insn      = new_prog->insnsi + i + delta;
16232 				continue;
16233 			}
16234 
16235 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
16236 				     (void *(*)(struct bpf_map *map, void *key))NULL));
16237 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
16238 				     (int (*)(struct bpf_map *map, void *key))NULL));
16239 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
16240 				     (int (*)(struct bpf_map *map, void *key, void *value,
16241 					      u64 flags))NULL));
16242 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
16243 				     (int (*)(struct bpf_map *map, void *value,
16244 					      u64 flags))NULL));
16245 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
16246 				     (int (*)(struct bpf_map *map, void *value))NULL));
16247 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
16248 				     (int (*)(struct bpf_map *map, void *value))NULL));
16249 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
16250 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
16251 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
16252 				     (int (*)(struct bpf_map *map,
16253 					      bpf_callback_t callback_fn,
16254 					      void *callback_ctx,
16255 					      u64 flags))NULL));
16256 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
16257 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
16258 
16259 patch_map_ops_generic:
16260 			switch (insn->imm) {
16261 			case BPF_FUNC_map_lookup_elem:
16262 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
16263 				continue;
16264 			case BPF_FUNC_map_update_elem:
16265 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
16266 				continue;
16267 			case BPF_FUNC_map_delete_elem:
16268 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
16269 				continue;
16270 			case BPF_FUNC_map_push_elem:
16271 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
16272 				continue;
16273 			case BPF_FUNC_map_pop_elem:
16274 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
16275 				continue;
16276 			case BPF_FUNC_map_peek_elem:
16277 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
16278 				continue;
16279 			case BPF_FUNC_redirect_map:
16280 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
16281 				continue;
16282 			case BPF_FUNC_for_each_map_elem:
16283 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
16284 				continue;
16285 			case BPF_FUNC_map_lookup_percpu_elem:
16286 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
16287 				continue;
16288 			}
16289 
16290 			goto patch_call_imm;
16291 		}
16292 
16293 		/* Implement bpf_jiffies64 inline. */
16294 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16295 		    insn->imm == BPF_FUNC_jiffies64) {
16296 			struct bpf_insn ld_jiffies_addr[2] = {
16297 				BPF_LD_IMM64(BPF_REG_0,
16298 					     (unsigned long)&jiffies),
16299 			};
16300 
16301 			insn_buf[0] = ld_jiffies_addr[0];
16302 			insn_buf[1] = ld_jiffies_addr[1];
16303 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
16304 						  BPF_REG_0, 0);
16305 			cnt = 3;
16306 
16307 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
16308 						       cnt);
16309 			if (!new_prog)
16310 				return -ENOMEM;
16311 
16312 			delta    += cnt - 1;
16313 			env->prog = prog = new_prog;
16314 			insn      = new_prog->insnsi + i + delta;
16315 			continue;
16316 		}
16317 
16318 		/* Implement bpf_get_func_arg inline. */
16319 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16320 		    insn->imm == BPF_FUNC_get_func_arg) {
16321 			/* Load nr_args from ctx - 8 */
16322 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16323 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
16324 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
16325 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
16326 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
16327 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16328 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
16329 			insn_buf[7] = BPF_JMP_A(1);
16330 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
16331 			cnt = 9;
16332 
16333 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16334 			if (!new_prog)
16335 				return -ENOMEM;
16336 
16337 			delta    += cnt - 1;
16338 			env->prog = prog = new_prog;
16339 			insn      = new_prog->insnsi + i + delta;
16340 			continue;
16341 		}
16342 
16343 		/* Implement bpf_get_func_ret inline. */
16344 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16345 		    insn->imm == BPF_FUNC_get_func_ret) {
16346 			if (eatype == BPF_TRACE_FEXIT ||
16347 			    eatype == BPF_MODIFY_RETURN) {
16348 				/* Load nr_args from ctx - 8 */
16349 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16350 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
16351 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
16352 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16353 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
16354 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
16355 				cnt = 6;
16356 			} else {
16357 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
16358 				cnt = 1;
16359 			}
16360 
16361 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16362 			if (!new_prog)
16363 				return -ENOMEM;
16364 
16365 			delta    += cnt - 1;
16366 			env->prog = prog = new_prog;
16367 			insn      = new_prog->insnsi + i + delta;
16368 			continue;
16369 		}
16370 
16371 		/* Implement get_func_arg_cnt inline. */
16372 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16373 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16374 			/* Load nr_args from ctx - 8 */
16375 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16376 
16377 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16378 			if (!new_prog)
16379 				return -ENOMEM;
16380 
16381 			env->prog = prog = new_prog;
16382 			insn      = new_prog->insnsi + i + delta;
16383 			continue;
16384 		}
16385 
16386 		/* Implement bpf_get_func_ip inline. */
16387 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16388 		    insn->imm == BPF_FUNC_get_func_ip) {
16389 			/* Load IP address from ctx - 16 */
16390 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16391 
16392 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16393 			if (!new_prog)
16394 				return -ENOMEM;
16395 
16396 			env->prog = prog = new_prog;
16397 			insn      = new_prog->insnsi + i + delta;
16398 			continue;
16399 		}
16400 
16401 patch_call_imm:
16402 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16403 		/* all functions that have prototype and verifier allowed
16404 		 * programs to call them, must be real in-kernel functions
16405 		 */
16406 		if (!fn->func) {
16407 			verbose(env,
16408 				"kernel subsystem misconfigured func %s#%d\n",
16409 				func_id_name(insn->imm), insn->imm);
16410 			return -EFAULT;
16411 		}
16412 		insn->imm = fn->func - __bpf_call_base;
16413 	}
16414 
16415 	/* Since poke tab is now finalized, publish aux to tracker. */
16416 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16417 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16418 		if (!map_ptr->ops->map_poke_track ||
16419 		    !map_ptr->ops->map_poke_untrack ||
16420 		    !map_ptr->ops->map_poke_run) {
16421 			verbose(env, "bpf verifier is misconfigured\n");
16422 			return -EINVAL;
16423 		}
16424 
16425 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16426 		if (ret < 0) {
16427 			verbose(env, "tracking tail call prog failed\n");
16428 			return ret;
16429 		}
16430 	}
16431 
16432 	sort_kfunc_descs_by_imm(env->prog);
16433 
16434 	return 0;
16435 }
16436 
16437 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16438 					int position,
16439 					s32 stack_base,
16440 					u32 callback_subprogno,
16441 					u32 *cnt)
16442 {
16443 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16444 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16445 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16446 	int reg_loop_max = BPF_REG_6;
16447 	int reg_loop_cnt = BPF_REG_7;
16448 	int reg_loop_ctx = BPF_REG_8;
16449 
16450 	struct bpf_prog *new_prog;
16451 	u32 callback_start;
16452 	u32 call_insn_offset;
16453 	s32 callback_offset;
16454 
16455 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16456 	 * be careful to modify this code in sync.
16457 	 */
16458 	struct bpf_insn insn_buf[] = {
16459 		/* Return error and jump to the end of the patch if
16460 		 * expected number of iterations is too big.
16461 		 */
16462 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16463 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16464 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16465 		/* spill R6, R7, R8 to use these as loop vars */
16466 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16467 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16468 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16469 		/* initialize loop vars */
16470 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16471 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16472 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16473 		/* loop header,
16474 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16475 		 */
16476 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16477 		/* callback call,
16478 		 * correct callback offset would be set after patching
16479 		 */
16480 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16481 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16482 		BPF_CALL_REL(0),
16483 		/* increment loop counter */
16484 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16485 		/* jump to loop header if callback returned 0 */
16486 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16487 		/* return value of bpf_loop,
16488 		 * set R0 to the number of iterations
16489 		 */
16490 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16491 		/* restore original values of R6, R7, R8 */
16492 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16493 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16494 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16495 	};
16496 
16497 	*cnt = ARRAY_SIZE(insn_buf);
16498 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16499 	if (!new_prog)
16500 		return new_prog;
16501 
16502 	/* callback start is known only after patching */
16503 	callback_start = env->subprog_info[callback_subprogno].start;
16504 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16505 	call_insn_offset = position + 12;
16506 	callback_offset = callback_start - call_insn_offset - 1;
16507 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16508 
16509 	return new_prog;
16510 }
16511 
16512 static bool is_bpf_loop_call(struct bpf_insn *insn)
16513 {
16514 	return insn->code == (BPF_JMP | BPF_CALL) &&
16515 		insn->src_reg == 0 &&
16516 		insn->imm == BPF_FUNC_loop;
16517 }
16518 
16519 /* For all sub-programs in the program (including main) check
16520  * insn_aux_data to see if there are bpf_loop calls that require
16521  * inlining. If such calls are found the calls are replaced with a
16522  * sequence of instructions produced by `inline_bpf_loop` function and
16523  * subprog stack_depth is increased by the size of 3 registers.
16524  * This stack space is used to spill values of the R6, R7, R8.  These
16525  * registers are used to store the loop bound, counter and context
16526  * variables.
16527  */
16528 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16529 {
16530 	struct bpf_subprog_info *subprogs = env->subprog_info;
16531 	int i, cur_subprog = 0, cnt, delta = 0;
16532 	struct bpf_insn *insn = env->prog->insnsi;
16533 	int insn_cnt = env->prog->len;
16534 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16535 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16536 	u16 stack_depth_extra = 0;
16537 
16538 	for (i = 0; i < insn_cnt; i++, insn++) {
16539 		struct bpf_loop_inline_state *inline_state =
16540 			&env->insn_aux_data[i + delta].loop_inline_state;
16541 
16542 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16543 			struct bpf_prog *new_prog;
16544 
16545 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16546 			new_prog = inline_bpf_loop(env,
16547 						   i + delta,
16548 						   -(stack_depth + stack_depth_extra),
16549 						   inline_state->callback_subprogno,
16550 						   &cnt);
16551 			if (!new_prog)
16552 				return -ENOMEM;
16553 
16554 			delta     += cnt - 1;
16555 			env->prog  = new_prog;
16556 			insn       = new_prog->insnsi + i + delta;
16557 		}
16558 
16559 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16560 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16561 			cur_subprog++;
16562 			stack_depth = subprogs[cur_subprog].stack_depth;
16563 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16564 			stack_depth_extra = 0;
16565 		}
16566 	}
16567 
16568 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16569 
16570 	return 0;
16571 }
16572 
16573 static void free_states(struct bpf_verifier_env *env)
16574 {
16575 	struct bpf_verifier_state_list *sl, *sln;
16576 	int i;
16577 
16578 	sl = env->free_list;
16579 	while (sl) {
16580 		sln = sl->next;
16581 		free_verifier_state(&sl->state, false);
16582 		kfree(sl);
16583 		sl = sln;
16584 	}
16585 	env->free_list = NULL;
16586 
16587 	if (!env->explored_states)
16588 		return;
16589 
16590 	for (i = 0; i < state_htab_size(env); i++) {
16591 		sl = env->explored_states[i];
16592 
16593 		while (sl) {
16594 			sln = sl->next;
16595 			free_verifier_state(&sl->state, false);
16596 			kfree(sl);
16597 			sl = sln;
16598 		}
16599 		env->explored_states[i] = NULL;
16600 	}
16601 }
16602 
16603 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16604 {
16605 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16606 	struct bpf_verifier_state *state;
16607 	struct bpf_reg_state *regs;
16608 	int ret, i;
16609 
16610 	env->prev_linfo = NULL;
16611 	env->pass_cnt++;
16612 
16613 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16614 	if (!state)
16615 		return -ENOMEM;
16616 	state->curframe = 0;
16617 	state->speculative = false;
16618 	state->branches = 1;
16619 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16620 	if (!state->frame[0]) {
16621 		kfree(state);
16622 		return -ENOMEM;
16623 	}
16624 	env->cur_state = state;
16625 	init_func_state(env, state->frame[0],
16626 			BPF_MAIN_FUNC /* callsite */,
16627 			0 /* frameno */,
16628 			subprog);
16629 	state->first_insn_idx = env->subprog_info[subprog].start;
16630 	state->last_insn_idx = -1;
16631 
16632 	regs = state->frame[state->curframe]->regs;
16633 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16634 		ret = btf_prepare_func_args(env, subprog, regs);
16635 		if (ret)
16636 			goto out;
16637 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16638 			if (regs[i].type == PTR_TO_CTX)
16639 				mark_reg_known_zero(env, regs, i);
16640 			else if (regs[i].type == SCALAR_VALUE)
16641 				mark_reg_unknown(env, regs, i);
16642 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
16643 				const u32 mem_size = regs[i].mem_size;
16644 
16645 				mark_reg_known_zero(env, regs, i);
16646 				regs[i].mem_size = mem_size;
16647 				regs[i].id = ++env->id_gen;
16648 			}
16649 		}
16650 	} else {
16651 		/* 1st arg to a function */
16652 		regs[BPF_REG_1].type = PTR_TO_CTX;
16653 		mark_reg_known_zero(env, regs, BPF_REG_1);
16654 		ret = btf_check_subprog_arg_match(env, subprog, regs);
16655 		if (ret == -EFAULT)
16656 			/* unlikely verifier bug. abort.
16657 			 * ret == 0 and ret < 0 are sadly acceptable for
16658 			 * main() function due to backward compatibility.
16659 			 * Like socket filter program may be written as:
16660 			 * int bpf_prog(struct pt_regs *ctx)
16661 			 * and never dereference that ctx in the program.
16662 			 * 'struct pt_regs' is a type mismatch for socket
16663 			 * filter that should be using 'struct __sk_buff'.
16664 			 */
16665 			goto out;
16666 	}
16667 
16668 	ret = do_check(env);
16669 out:
16670 	/* check for NULL is necessary, since cur_state can be freed inside
16671 	 * do_check() under memory pressure.
16672 	 */
16673 	if (env->cur_state) {
16674 		free_verifier_state(env->cur_state, true);
16675 		env->cur_state = NULL;
16676 	}
16677 	while (!pop_stack(env, NULL, NULL, false));
16678 	if (!ret && pop_log)
16679 		bpf_vlog_reset(&env->log, 0);
16680 	free_states(env);
16681 	return ret;
16682 }
16683 
16684 /* Verify all global functions in a BPF program one by one based on their BTF.
16685  * All global functions must pass verification. Otherwise the whole program is rejected.
16686  * Consider:
16687  * int bar(int);
16688  * int foo(int f)
16689  * {
16690  *    return bar(f);
16691  * }
16692  * int bar(int b)
16693  * {
16694  *    ...
16695  * }
16696  * foo() will be verified first for R1=any_scalar_value. During verification it
16697  * will be assumed that bar() already verified successfully and call to bar()
16698  * from foo() will be checked for type match only. Later bar() will be verified
16699  * independently to check that it's safe for R1=any_scalar_value.
16700  */
16701 static int do_check_subprogs(struct bpf_verifier_env *env)
16702 {
16703 	struct bpf_prog_aux *aux = env->prog->aux;
16704 	int i, ret;
16705 
16706 	if (!aux->func_info)
16707 		return 0;
16708 
16709 	for (i = 1; i < env->subprog_cnt; i++) {
16710 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16711 			continue;
16712 		env->insn_idx = env->subprog_info[i].start;
16713 		WARN_ON_ONCE(env->insn_idx == 0);
16714 		ret = do_check_common(env, i);
16715 		if (ret) {
16716 			return ret;
16717 		} else if (env->log.level & BPF_LOG_LEVEL) {
16718 			verbose(env,
16719 				"Func#%d is safe for any args that match its prototype\n",
16720 				i);
16721 		}
16722 	}
16723 	return 0;
16724 }
16725 
16726 static int do_check_main(struct bpf_verifier_env *env)
16727 {
16728 	int ret;
16729 
16730 	env->insn_idx = 0;
16731 	ret = do_check_common(env, 0);
16732 	if (!ret)
16733 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16734 	return ret;
16735 }
16736 
16737 
16738 static void print_verification_stats(struct bpf_verifier_env *env)
16739 {
16740 	int i;
16741 
16742 	if (env->log.level & BPF_LOG_STATS) {
16743 		verbose(env, "verification time %lld usec\n",
16744 			div_u64(env->verification_time, 1000));
16745 		verbose(env, "stack depth ");
16746 		for (i = 0; i < env->subprog_cnt; i++) {
16747 			u32 depth = env->subprog_info[i].stack_depth;
16748 
16749 			verbose(env, "%d", depth);
16750 			if (i + 1 < env->subprog_cnt)
16751 				verbose(env, "+");
16752 		}
16753 		verbose(env, "\n");
16754 	}
16755 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16756 		"total_states %d peak_states %d mark_read %d\n",
16757 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16758 		env->max_states_per_insn, env->total_states,
16759 		env->peak_states, env->longest_mark_read_walk);
16760 }
16761 
16762 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16763 {
16764 	const struct btf_type *t, *func_proto;
16765 	const struct bpf_struct_ops *st_ops;
16766 	const struct btf_member *member;
16767 	struct bpf_prog *prog = env->prog;
16768 	u32 btf_id, member_idx;
16769 	const char *mname;
16770 
16771 	if (!prog->gpl_compatible) {
16772 		verbose(env, "struct ops programs must have a GPL compatible license\n");
16773 		return -EINVAL;
16774 	}
16775 
16776 	btf_id = prog->aux->attach_btf_id;
16777 	st_ops = bpf_struct_ops_find(btf_id);
16778 	if (!st_ops) {
16779 		verbose(env, "attach_btf_id %u is not a supported struct\n",
16780 			btf_id);
16781 		return -ENOTSUPP;
16782 	}
16783 
16784 	t = st_ops->type;
16785 	member_idx = prog->expected_attach_type;
16786 	if (member_idx >= btf_type_vlen(t)) {
16787 		verbose(env, "attach to invalid member idx %u of struct %s\n",
16788 			member_idx, st_ops->name);
16789 		return -EINVAL;
16790 	}
16791 
16792 	member = &btf_type_member(t)[member_idx];
16793 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16794 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16795 					       NULL);
16796 	if (!func_proto) {
16797 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16798 			mname, member_idx, st_ops->name);
16799 		return -EINVAL;
16800 	}
16801 
16802 	if (st_ops->check_member) {
16803 		int err = st_ops->check_member(t, member, prog);
16804 
16805 		if (err) {
16806 			verbose(env, "attach to unsupported member %s of struct %s\n",
16807 				mname, st_ops->name);
16808 			return err;
16809 		}
16810 	}
16811 
16812 	prog->aux->attach_func_proto = func_proto;
16813 	prog->aux->attach_func_name = mname;
16814 	env->ops = st_ops->verifier_ops;
16815 
16816 	return 0;
16817 }
16818 #define SECURITY_PREFIX "security_"
16819 
16820 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16821 {
16822 	if (within_error_injection_list(addr) ||
16823 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16824 		return 0;
16825 
16826 	return -EINVAL;
16827 }
16828 
16829 /* list of non-sleepable functions that are otherwise on
16830  * ALLOW_ERROR_INJECTION list
16831  */
16832 BTF_SET_START(btf_non_sleepable_error_inject)
16833 /* Three functions below can be called from sleepable and non-sleepable context.
16834  * Assume non-sleepable from bpf safety point of view.
16835  */
16836 BTF_ID(func, __filemap_add_folio)
16837 BTF_ID(func, should_fail_alloc_page)
16838 BTF_ID(func, should_failslab)
16839 BTF_SET_END(btf_non_sleepable_error_inject)
16840 
16841 static int check_non_sleepable_error_inject(u32 btf_id)
16842 {
16843 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16844 }
16845 
16846 int bpf_check_attach_target(struct bpf_verifier_log *log,
16847 			    const struct bpf_prog *prog,
16848 			    const struct bpf_prog *tgt_prog,
16849 			    u32 btf_id,
16850 			    struct bpf_attach_target_info *tgt_info)
16851 {
16852 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16853 	const char prefix[] = "btf_trace_";
16854 	int ret = 0, subprog = -1, i;
16855 	const struct btf_type *t;
16856 	bool conservative = true;
16857 	const char *tname;
16858 	struct btf *btf;
16859 	long addr = 0;
16860 
16861 	if (!btf_id) {
16862 		bpf_log(log, "Tracing programs must provide btf_id\n");
16863 		return -EINVAL;
16864 	}
16865 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16866 	if (!btf) {
16867 		bpf_log(log,
16868 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16869 		return -EINVAL;
16870 	}
16871 	t = btf_type_by_id(btf, btf_id);
16872 	if (!t) {
16873 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16874 		return -EINVAL;
16875 	}
16876 	tname = btf_name_by_offset(btf, t->name_off);
16877 	if (!tname) {
16878 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16879 		return -EINVAL;
16880 	}
16881 	if (tgt_prog) {
16882 		struct bpf_prog_aux *aux = tgt_prog->aux;
16883 
16884 		if (bpf_prog_is_dev_bound(prog->aux) &&
16885 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
16886 			bpf_log(log, "Target program bound device mismatch");
16887 			return -EINVAL;
16888 		}
16889 
16890 		for (i = 0; i < aux->func_info_cnt; i++)
16891 			if (aux->func_info[i].type_id == btf_id) {
16892 				subprog = i;
16893 				break;
16894 			}
16895 		if (subprog == -1) {
16896 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
16897 			return -EINVAL;
16898 		}
16899 		conservative = aux->func_info_aux[subprog].unreliable;
16900 		if (prog_extension) {
16901 			if (conservative) {
16902 				bpf_log(log,
16903 					"Cannot replace static functions\n");
16904 				return -EINVAL;
16905 			}
16906 			if (!prog->jit_requested) {
16907 				bpf_log(log,
16908 					"Extension programs should be JITed\n");
16909 				return -EINVAL;
16910 			}
16911 		}
16912 		if (!tgt_prog->jited) {
16913 			bpf_log(log, "Can attach to only JITed progs\n");
16914 			return -EINVAL;
16915 		}
16916 		if (tgt_prog->type == prog->type) {
16917 			/* Cannot fentry/fexit another fentry/fexit program.
16918 			 * Cannot attach program extension to another extension.
16919 			 * It's ok to attach fentry/fexit to extension program.
16920 			 */
16921 			bpf_log(log, "Cannot recursively attach\n");
16922 			return -EINVAL;
16923 		}
16924 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16925 		    prog_extension &&
16926 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16927 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16928 			/* Program extensions can extend all program types
16929 			 * except fentry/fexit. The reason is the following.
16930 			 * The fentry/fexit programs are used for performance
16931 			 * analysis, stats and can be attached to any program
16932 			 * type except themselves. When extension program is
16933 			 * replacing XDP function it is necessary to allow
16934 			 * performance analysis of all functions. Both original
16935 			 * XDP program and its program extension. Hence
16936 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16937 			 * allowed. If extending of fentry/fexit was allowed it
16938 			 * would be possible to create long call chain
16939 			 * fentry->extension->fentry->extension beyond
16940 			 * reasonable stack size. Hence extending fentry is not
16941 			 * allowed.
16942 			 */
16943 			bpf_log(log, "Cannot extend fentry/fexit\n");
16944 			return -EINVAL;
16945 		}
16946 	} else {
16947 		if (prog_extension) {
16948 			bpf_log(log, "Cannot replace kernel functions\n");
16949 			return -EINVAL;
16950 		}
16951 	}
16952 
16953 	switch (prog->expected_attach_type) {
16954 	case BPF_TRACE_RAW_TP:
16955 		if (tgt_prog) {
16956 			bpf_log(log,
16957 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16958 			return -EINVAL;
16959 		}
16960 		if (!btf_type_is_typedef(t)) {
16961 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
16962 				btf_id);
16963 			return -EINVAL;
16964 		}
16965 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16966 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16967 				btf_id, tname);
16968 			return -EINVAL;
16969 		}
16970 		tname += sizeof(prefix) - 1;
16971 		t = btf_type_by_id(btf, t->type);
16972 		if (!btf_type_is_ptr(t))
16973 			/* should never happen in valid vmlinux build */
16974 			return -EINVAL;
16975 		t = btf_type_by_id(btf, t->type);
16976 		if (!btf_type_is_func_proto(t))
16977 			/* should never happen in valid vmlinux build */
16978 			return -EINVAL;
16979 
16980 		break;
16981 	case BPF_TRACE_ITER:
16982 		if (!btf_type_is_func(t)) {
16983 			bpf_log(log, "attach_btf_id %u is not a function\n",
16984 				btf_id);
16985 			return -EINVAL;
16986 		}
16987 		t = btf_type_by_id(btf, t->type);
16988 		if (!btf_type_is_func_proto(t))
16989 			return -EINVAL;
16990 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16991 		if (ret)
16992 			return ret;
16993 		break;
16994 	default:
16995 		if (!prog_extension)
16996 			return -EINVAL;
16997 		fallthrough;
16998 	case BPF_MODIFY_RETURN:
16999 	case BPF_LSM_MAC:
17000 	case BPF_LSM_CGROUP:
17001 	case BPF_TRACE_FENTRY:
17002 	case BPF_TRACE_FEXIT:
17003 		if (!btf_type_is_func(t)) {
17004 			bpf_log(log, "attach_btf_id %u is not a function\n",
17005 				btf_id);
17006 			return -EINVAL;
17007 		}
17008 		if (prog_extension &&
17009 		    btf_check_type_match(log, prog, btf, t))
17010 			return -EINVAL;
17011 		t = btf_type_by_id(btf, t->type);
17012 		if (!btf_type_is_func_proto(t))
17013 			return -EINVAL;
17014 
17015 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17016 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17017 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17018 			return -EINVAL;
17019 
17020 		if (tgt_prog && conservative)
17021 			t = NULL;
17022 
17023 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17024 		if (ret < 0)
17025 			return ret;
17026 
17027 		if (tgt_prog) {
17028 			if (subprog == 0)
17029 				addr = (long) tgt_prog->bpf_func;
17030 			else
17031 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17032 		} else {
17033 			addr = kallsyms_lookup_name(tname);
17034 			if (!addr) {
17035 				bpf_log(log,
17036 					"The address of function %s cannot be found\n",
17037 					tname);
17038 				return -ENOENT;
17039 			}
17040 		}
17041 
17042 		if (prog->aux->sleepable) {
17043 			ret = -EINVAL;
17044 			switch (prog->type) {
17045 			case BPF_PROG_TYPE_TRACING:
17046 
17047 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
17048 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17049 				 */
17050 				if (!check_non_sleepable_error_inject(btf_id) &&
17051 				    within_error_injection_list(addr))
17052 					ret = 0;
17053 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
17054 				 * in the fmodret id set with the KF_SLEEPABLE flag.
17055 				 */
17056 				else {
17057 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17058 
17059 					if (flags && (*flags & KF_SLEEPABLE))
17060 						ret = 0;
17061 				}
17062 				break;
17063 			case BPF_PROG_TYPE_LSM:
17064 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
17065 				 * Only some of them are sleepable.
17066 				 */
17067 				if (bpf_lsm_is_sleepable_hook(btf_id))
17068 					ret = 0;
17069 				break;
17070 			default:
17071 				break;
17072 			}
17073 			if (ret) {
17074 				bpf_log(log, "%s is not sleepable\n", tname);
17075 				return ret;
17076 			}
17077 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17078 			if (tgt_prog) {
17079 				bpf_log(log, "can't modify return codes of BPF programs\n");
17080 				return -EINVAL;
17081 			}
17082 			ret = -EINVAL;
17083 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
17084 			    !check_attach_modify_return(addr, tname))
17085 				ret = 0;
17086 			if (ret) {
17087 				bpf_log(log, "%s() is not modifiable\n", tname);
17088 				return ret;
17089 			}
17090 		}
17091 
17092 		break;
17093 	}
17094 	tgt_info->tgt_addr = addr;
17095 	tgt_info->tgt_name = tname;
17096 	tgt_info->tgt_type = t;
17097 	return 0;
17098 }
17099 
17100 BTF_SET_START(btf_id_deny)
17101 BTF_ID_UNUSED
17102 #ifdef CONFIG_SMP
17103 BTF_ID(func, migrate_disable)
17104 BTF_ID(func, migrate_enable)
17105 #endif
17106 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17107 BTF_ID(func, rcu_read_unlock_strict)
17108 #endif
17109 BTF_SET_END(btf_id_deny)
17110 
17111 static bool can_be_sleepable(struct bpf_prog *prog)
17112 {
17113 	if (prog->type == BPF_PROG_TYPE_TRACING) {
17114 		switch (prog->expected_attach_type) {
17115 		case BPF_TRACE_FENTRY:
17116 		case BPF_TRACE_FEXIT:
17117 		case BPF_MODIFY_RETURN:
17118 		case BPF_TRACE_ITER:
17119 			return true;
17120 		default:
17121 			return false;
17122 		}
17123 	}
17124 	return prog->type == BPF_PROG_TYPE_LSM ||
17125 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17126 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17127 }
17128 
17129 static int check_attach_btf_id(struct bpf_verifier_env *env)
17130 {
17131 	struct bpf_prog *prog = env->prog;
17132 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17133 	struct bpf_attach_target_info tgt_info = {};
17134 	u32 btf_id = prog->aux->attach_btf_id;
17135 	struct bpf_trampoline *tr;
17136 	int ret;
17137 	u64 key;
17138 
17139 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17140 		if (prog->aux->sleepable)
17141 			/* attach_btf_id checked to be zero already */
17142 			return 0;
17143 		verbose(env, "Syscall programs can only be sleepable\n");
17144 		return -EINVAL;
17145 	}
17146 
17147 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17148 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17149 		return -EINVAL;
17150 	}
17151 
17152 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17153 		return check_struct_ops_btf_id(env);
17154 
17155 	if (prog->type != BPF_PROG_TYPE_TRACING &&
17156 	    prog->type != BPF_PROG_TYPE_LSM &&
17157 	    prog->type != BPF_PROG_TYPE_EXT)
17158 		return 0;
17159 
17160 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17161 	if (ret)
17162 		return ret;
17163 
17164 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17165 		/* to make freplace equivalent to their targets, they need to
17166 		 * inherit env->ops and expected_attach_type for the rest of the
17167 		 * verification
17168 		 */
17169 		env->ops = bpf_verifier_ops[tgt_prog->type];
17170 		prog->expected_attach_type = tgt_prog->expected_attach_type;
17171 	}
17172 
17173 	/* store info about the attachment target that will be used later */
17174 	prog->aux->attach_func_proto = tgt_info.tgt_type;
17175 	prog->aux->attach_func_name = tgt_info.tgt_name;
17176 
17177 	if (tgt_prog) {
17178 		prog->aux->saved_dst_prog_type = tgt_prog->type;
17179 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17180 	}
17181 
17182 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17183 		prog->aux->attach_btf_trace = true;
17184 		return 0;
17185 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17186 		if (!bpf_iter_prog_supported(prog))
17187 			return -EINVAL;
17188 		return 0;
17189 	}
17190 
17191 	if (prog->type == BPF_PROG_TYPE_LSM) {
17192 		ret = bpf_lsm_verify_prog(&env->log, prog);
17193 		if (ret < 0)
17194 			return ret;
17195 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
17196 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
17197 		return -EINVAL;
17198 	}
17199 
17200 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17201 	tr = bpf_trampoline_get(key, &tgt_info);
17202 	if (!tr)
17203 		return -ENOMEM;
17204 
17205 	prog->aux->dst_trampoline = tr;
17206 	return 0;
17207 }
17208 
17209 struct btf *bpf_get_btf_vmlinux(void)
17210 {
17211 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17212 		mutex_lock(&bpf_verifier_lock);
17213 		if (!btf_vmlinux)
17214 			btf_vmlinux = btf_parse_vmlinux();
17215 		mutex_unlock(&bpf_verifier_lock);
17216 	}
17217 	return btf_vmlinux;
17218 }
17219 
17220 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
17221 {
17222 	u64 start_time = ktime_get_ns();
17223 	struct bpf_verifier_env *env;
17224 	struct bpf_verifier_log *log;
17225 	int i, len, ret = -EINVAL;
17226 	bool is_priv;
17227 
17228 	/* no program is valid */
17229 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
17230 		return -EINVAL;
17231 
17232 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
17233 	 * allocate/free it every time bpf_check() is called
17234 	 */
17235 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
17236 	if (!env)
17237 		return -ENOMEM;
17238 	log = &env->log;
17239 
17240 	len = (*prog)->len;
17241 	env->insn_aux_data =
17242 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
17243 	ret = -ENOMEM;
17244 	if (!env->insn_aux_data)
17245 		goto err_free_env;
17246 	for (i = 0; i < len; i++)
17247 		env->insn_aux_data[i].orig_idx = i;
17248 	env->prog = *prog;
17249 	env->ops = bpf_verifier_ops[env->prog->type];
17250 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
17251 	is_priv = bpf_capable();
17252 
17253 	bpf_get_btf_vmlinux();
17254 
17255 	/* grab the mutex to protect few globals used by verifier */
17256 	if (!is_priv)
17257 		mutex_lock(&bpf_verifier_lock);
17258 
17259 	if (attr->log_level || attr->log_buf || attr->log_size) {
17260 		/* user requested verbose verifier output
17261 		 * and supplied buffer to store the verification trace
17262 		 */
17263 		log->level = attr->log_level;
17264 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
17265 		log->len_total = attr->log_size;
17266 
17267 		/* log attributes have to be sane */
17268 		if (!bpf_verifier_log_attr_valid(log)) {
17269 			ret = -EINVAL;
17270 			goto err_unlock;
17271 		}
17272 	}
17273 
17274 	mark_verifier_state_clean(env);
17275 
17276 	if (IS_ERR(btf_vmlinux)) {
17277 		/* Either gcc or pahole or kernel are broken. */
17278 		verbose(env, "in-kernel BTF is malformed\n");
17279 		ret = PTR_ERR(btf_vmlinux);
17280 		goto skip_full_check;
17281 	}
17282 
17283 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
17284 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
17285 		env->strict_alignment = true;
17286 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
17287 		env->strict_alignment = false;
17288 
17289 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
17290 	env->allow_uninit_stack = bpf_allow_uninit_stack();
17291 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
17292 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
17293 	env->bpf_capable = bpf_capable();
17294 	env->rcu_tag_supported = btf_vmlinux &&
17295 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
17296 
17297 	if (is_priv)
17298 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
17299 
17300 	env->explored_states = kvcalloc(state_htab_size(env),
17301 				       sizeof(struct bpf_verifier_state_list *),
17302 				       GFP_USER);
17303 	ret = -ENOMEM;
17304 	if (!env->explored_states)
17305 		goto skip_full_check;
17306 
17307 	ret = add_subprog_and_kfunc(env);
17308 	if (ret < 0)
17309 		goto skip_full_check;
17310 
17311 	ret = check_subprogs(env);
17312 	if (ret < 0)
17313 		goto skip_full_check;
17314 
17315 	ret = check_btf_info(env, attr, uattr);
17316 	if (ret < 0)
17317 		goto skip_full_check;
17318 
17319 	ret = check_attach_btf_id(env);
17320 	if (ret)
17321 		goto skip_full_check;
17322 
17323 	ret = resolve_pseudo_ldimm64(env);
17324 	if (ret < 0)
17325 		goto skip_full_check;
17326 
17327 	if (bpf_prog_is_offloaded(env->prog->aux)) {
17328 		ret = bpf_prog_offload_verifier_prep(env->prog);
17329 		if (ret)
17330 			goto skip_full_check;
17331 	}
17332 
17333 	ret = check_cfg(env);
17334 	if (ret < 0)
17335 		goto skip_full_check;
17336 
17337 	ret = do_check_subprogs(env);
17338 	ret = ret ?: do_check_main(env);
17339 
17340 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
17341 		ret = bpf_prog_offload_finalize(env);
17342 
17343 skip_full_check:
17344 	kvfree(env->explored_states);
17345 
17346 	if (ret == 0)
17347 		ret = check_max_stack_depth(env);
17348 
17349 	/* instruction rewrites happen after this point */
17350 	if (ret == 0)
17351 		ret = optimize_bpf_loop(env);
17352 
17353 	if (is_priv) {
17354 		if (ret == 0)
17355 			opt_hard_wire_dead_code_branches(env);
17356 		if (ret == 0)
17357 			ret = opt_remove_dead_code(env);
17358 		if (ret == 0)
17359 			ret = opt_remove_nops(env);
17360 	} else {
17361 		if (ret == 0)
17362 			sanitize_dead_code(env);
17363 	}
17364 
17365 	if (ret == 0)
17366 		/* program is valid, convert *(u32*)(ctx + off) accesses */
17367 		ret = convert_ctx_accesses(env);
17368 
17369 	if (ret == 0)
17370 		ret = do_misc_fixups(env);
17371 
17372 	/* do 32-bit optimization after insn patching has done so those patched
17373 	 * insns could be handled correctly.
17374 	 */
17375 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
17376 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
17377 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
17378 								     : false;
17379 	}
17380 
17381 	if (ret == 0)
17382 		ret = fixup_call_args(env);
17383 
17384 	env->verification_time = ktime_get_ns() - start_time;
17385 	print_verification_stats(env);
17386 	env->prog->aux->verified_insns = env->insn_processed;
17387 
17388 	if (log->level && bpf_verifier_log_full(log))
17389 		ret = -ENOSPC;
17390 	if (log->level && !log->ubuf) {
17391 		ret = -EFAULT;
17392 		goto err_release_maps;
17393 	}
17394 
17395 	if (ret)
17396 		goto err_release_maps;
17397 
17398 	if (env->used_map_cnt) {
17399 		/* if program passed verifier, update used_maps in bpf_prog_info */
17400 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17401 							  sizeof(env->used_maps[0]),
17402 							  GFP_KERNEL);
17403 
17404 		if (!env->prog->aux->used_maps) {
17405 			ret = -ENOMEM;
17406 			goto err_release_maps;
17407 		}
17408 
17409 		memcpy(env->prog->aux->used_maps, env->used_maps,
17410 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17411 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17412 	}
17413 	if (env->used_btf_cnt) {
17414 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17415 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17416 							  sizeof(env->used_btfs[0]),
17417 							  GFP_KERNEL);
17418 		if (!env->prog->aux->used_btfs) {
17419 			ret = -ENOMEM;
17420 			goto err_release_maps;
17421 		}
17422 
17423 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17424 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17425 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17426 	}
17427 	if (env->used_map_cnt || env->used_btf_cnt) {
17428 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17429 		 * bpf_ld_imm64 instructions
17430 		 */
17431 		convert_pseudo_ld_imm64(env);
17432 	}
17433 
17434 	adjust_btf_func(env);
17435 
17436 err_release_maps:
17437 	if (!env->prog->aux->used_maps)
17438 		/* if we didn't copy map pointers into bpf_prog_info, release
17439 		 * them now. Otherwise free_used_maps() will release them.
17440 		 */
17441 		release_maps(env);
17442 	if (!env->prog->aux->used_btfs)
17443 		release_btfs(env);
17444 
17445 	/* extension progs temporarily inherit the attach_type of their targets
17446 	   for verification purposes, so set it back to zero before returning
17447 	 */
17448 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17449 		env->prog->expected_attach_type = 0;
17450 
17451 	*prog = env->prog;
17452 err_unlock:
17453 	if (!is_priv)
17454 		mutex_unlock(&bpf_verifier_lock);
17455 	vfree(env->insn_aux_data);
17456 err_free_env:
17457 	kfree(env);
17458 	return ret;
17459 }
17460