xref: /linux/kernel/bpf/verifier.c (revision 34b7074d3fba0d3f3ca8c66b6105b7f575e77e98)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198 
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203 
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 			      const struct bpf_map *map, bool unpriv)
206 {
207 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 	unpriv |= bpf_map_ptr_unpriv(aux);
209 	aux->map_ptr_state = (unsigned long)map |
210 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212 
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217 
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222 
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227 
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 	bool poisoned = bpf_map_key_poisoned(aux);
231 
232 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235 
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 	return insn->code == (BPF_JMP | BPF_CALL) &&
239 	       insn->src_reg == BPF_PSEUDO_CALL;
240 }
241 
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 	return insn->code == (BPF_JMP | BPF_CALL) &&
245 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247 
248 struct bpf_call_arg_meta {
249 	struct bpf_map *map_ptr;
250 	bool raw_mode;
251 	bool pkt_access;
252 	u8 release_regno;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 	struct btf_field *kptr_field;
266 	u8 uninit_dynptr_regno;
267 };
268 
269 struct btf *btf_vmlinux;
270 
271 static DEFINE_MUTEX(bpf_verifier_lock);
272 
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 	const struct bpf_line_info *linfo;
277 	const struct bpf_prog *prog;
278 	u32 i, nr_linfo;
279 
280 	prog = env->prog;
281 	nr_linfo = prog->aux->nr_linfo;
282 
283 	if (!nr_linfo || insn_off >= prog->len)
284 		return NULL;
285 
286 	linfo = prog->aux->linfo;
287 	for (i = 1; i < nr_linfo; i++)
288 		if (insn_off < linfo[i].insn_off)
289 			break;
290 
291 	return &linfo[i - 1];
292 }
293 
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 		       va_list args)
296 {
297 	unsigned int n;
298 
299 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 
301 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 		  "verifier log line truncated - local buffer too short\n");
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 
307 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 		return;
309 	}
310 
311 	n = min(log->len_total - log->len_used - 1, n);
312 	log->kbuf[n] = '\0';
313 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 		log->len_used += n;
315 	else
316 		log->ubuf = NULL;
317 }
318 
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 	char zero = 0;
322 
323 	if (!bpf_verifier_log_needed(log))
324 		return;
325 
326 	log->len_used = new_pos;
327 	if (put_user(zero, log->ubuf + new_pos))
328 		log->ubuf = NULL;
329 }
330 
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 					   const char *fmt, ...)
337 {
338 	va_list args;
339 
340 	if (!bpf_verifier_log_needed(&env->log))
341 		return;
342 
343 	va_start(args, fmt);
344 	bpf_verifier_vlog(&env->log, fmt, args);
345 	va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 	struct bpf_verifier_env *env = private_data;
352 	va_list args;
353 
354 	if (!bpf_verifier_log_needed(&env->log))
355 		return;
356 
357 	va_start(args, fmt);
358 	bpf_verifier_vlog(&env->log, fmt, args);
359 	va_end(args);
360 }
361 
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 			    const char *fmt, ...)
364 {
365 	va_list args;
366 
367 	if (!bpf_verifier_log_needed(log))
368 		return;
369 
370 	va_start(args, fmt);
371 	bpf_verifier_vlog(log, fmt, args);
372 	va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375 
376 static const char *ltrim(const char *s)
377 {
378 	while (isspace(*s))
379 		s++;
380 
381 	return s;
382 }
383 
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 					 u32 insn_off,
386 					 const char *prefix_fmt, ...)
387 {
388 	const struct bpf_line_info *linfo;
389 
390 	if (!bpf_verifier_log_needed(&env->log))
391 		return;
392 
393 	linfo = find_linfo(env, insn_off);
394 	if (!linfo || linfo == env->prev_linfo)
395 		return;
396 
397 	if (prefix_fmt) {
398 		va_list args;
399 
400 		va_start(args, prefix_fmt);
401 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 		va_end(args);
403 	}
404 
405 	verbose(env, "%s\n",
406 		ltrim(btf_name_by_offset(env->prog->aux->btf,
407 					 linfo->line_off)));
408 
409 	env->prev_linfo = linfo;
410 }
411 
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 				   struct bpf_reg_state *reg,
414 				   struct tnum *range, const char *ctx,
415 				   const char *reg_name)
416 {
417 	char tn_buf[48];
418 
419 	verbose(env, "At %s the register %s ", ctx, reg_name);
420 	if (!tnum_is_unknown(reg->var_off)) {
421 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 		verbose(env, "has value %s", tn_buf);
423 	} else {
424 		verbose(env, "has unknown scalar value");
425 	}
426 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 	verbose(env, " should have been in %s\n", tn_buf);
428 }
429 
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 	type = base_type(type);
433 	return type == PTR_TO_PACKET ||
434 	       type == PTR_TO_PACKET_META;
435 }
436 
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_SOCK_COMMON ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_XDP_SOCK;
443 }
444 
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 	return type == PTR_TO_SOCKET ||
448 		type == PTR_TO_TCP_SOCK ||
449 		type == PTR_TO_MAP_VALUE ||
450 		type == PTR_TO_MAP_KEY ||
451 		type == PTR_TO_SOCK_COMMON;
452 }
453 
454 static bool type_is_ptr_alloc_obj(u32 type)
455 {
456 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
457 }
458 
459 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
460 {
461 	struct btf_record *rec = NULL;
462 	struct btf_struct_meta *meta;
463 
464 	if (reg->type == PTR_TO_MAP_VALUE) {
465 		rec = reg->map_ptr->record;
466 	} else if (type_is_ptr_alloc_obj(reg->type)) {
467 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
468 		if (meta)
469 			rec = meta->record;
470 	}
471 	return rec;
472 }
473 
474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
475 {
476 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
477 }
478 
479 static bool type_is_rdonly_mem(u32 type)
480 {
481 	return type & MEM_RDONLY;
482 }
483 
484 static bool type_may_be_null(u32 type)
485 {
486 	return type & PTR_MAYBE_NULL;
487 }
488 
489 static bool is_acquire_function(enum bpf_func_id func_id,
490 				const struct bpf_map *map)
491 {
492 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
493 
494 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
495 	    func_id == BPF_FUNC_sk_lookup_udp ||
496 	    func_id == BPF_FUNC_skc_lookup_tcp ||
497 	    func_id == BPF_FUNC_ringbuf_reserve ||
498 	    func_id == BPF_FUNC_kptr_xchg)
499 		return true;
500 
501 	if (func_id == BPF_FUNC_map_lookup_elem &&
502 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
503 	     map_type == BPF_MAP_TYPE_SOCKHASH))
504 		return true;
505 
506 	return false;
507 }
508 
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511 	return func_id == BPF_FUNC_tcp_sock ||
512 		func_id == BPF_FUNC_sk_fullsock ||
513 		func_id == BPF_FUNC_skc_to_tcp_sock ||
514 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
515 		func_id == BPF_FUNC_skc_to_udp6_sock ||
516 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
517 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
519 }
520 
521 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
522 {
523 	return func_id == BPF_FUNC_dynptr_data;
524 }
525 
526 static bool is_callback_calling_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_for_each_map_elem ||
529 	       func_id == BPF_FUNC_timer_set_callback ||
530 	       func_id == BPF_FUNC_find_vma ||
531 	       func_id == BPF_FUNC_loop ||
532 	       func_id == BPF_FUNC_user_ringbuf_drain;
533 }
534 
535 static bool is_storage_get_function(enum bpf_func_id func_id)
536 {
537 	return func_id == BPF_FUNC_sk_storage_get ||
538 	       func_id == BPF_FUNC_inode_storage_get ||
539 	       func_id == BPF_FUNC_task_storage_get ||
540 	       func_id == BPF_FUNC_cgrp_storage_get;
541 }
542 
543 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
544 					const struct bpf_map *map)
545 {
546 	int ref_obj_uses = 0;
547 
548 	if (is_ptr_cast_function(func_id))
549 		ref_obj_uses++;
550 	if (is_acquire_function(func_id, map))
551 		ref_obj_uses++;
552 	if (is_dynptr_ref_function(func_id))
553 		ref_obj_uses++;
554 
555 	return ref_obj_uses > 1;
556 }
557 
558 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
559 {
560 	return BPF_CLASS(insn->code) == BPF_STX &&
561 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
562 	       insn->imm == BPF_CMPXCHG;
563 }
564 
565 /* string representation of 'enum bpf_reg_type'
566  *
567  * Note that reg_type_str() can not appear more than once in a single verbose()
568  * statement.
569  */
570 static const char *reg_type_str(struct bpf_verifier_env *env,
571 				enum bpf_reg_type type)
572 {
573 	char postfix[16] = {0}, prefix[64] = {0};
574 	static const char * const str[] = {
575 		[NOT_INIT]		= "?",
576 		[SCALAR_VALUE]		= "scalar",
577 		[PTR_TO_CTX]		= "ctx",
578 		[CONST_PTR_TO_MAP]	= "map_ptr",
579 		[PTR_TO_MAP_VALUE]	= "map_value",
580 		[PTR_TO_STACK]		= "fp",
581 		[PTR_TO_PACKET]		= "pkt",
582 		[PTR_TO_PACKET_META]	= "pkt_meta",
583 		[PTR_TO_PACKET_END]	= "pkt_end",
584 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
585 		[PTR_TO_SOCKET]		= "sock",
586 		[PTR_TO_SOCK_COMMON]	= "sock_common",
587 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
588 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
589 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
590 		[PTR_TO_BTF_ID]		= "ptr_",
591 		[PTR_TO_MEM]		= "mem",
592 		[PTR_TO_BUF]		= "buf",
593 		[PTR_TO_FUNC]		= "func",
594 		[PTR_TO_MAP_KEY]	= "map_key",
595 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
596 	};
597 
598 	if (type & PTR_MAYBE_NULL) {
599 		if (base_type(type) == PTR_TO_BTF_ID)
600 			strncpy(postfix, "or_null_", 16);
601 		else
602 			strncpy(postfix, "_or_null", 16);
603 	}
604 
605 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
606 		 type & MEM_RDONLY ? "rdonly_" : "",
607 		 type & MEM_RINGBUF ? "ringbuf_" : "",
608 		 type & MEM_USER ? "user_" : "",
609 		 type & MEM_PERCPU ? "percpu_" : "",
610 		 type & MEM_RCU ? "rcu_" : "",
611 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
612 		 type & PTR_TRUSTED ? "trusted_" : ""
613 	);
614 
615 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
616 		 prefix, str[base_type(type)], postfix);
617 	return env->type_str_buf;
618 }
619 
620 static char slot_type_char[] = {
621 	[STACK_INVALID]	= '?',
622 	[STACK_SPILL]	= 'r',
623 	[STACK_MISC]	= 'm',
624 	[STACK_ZERO]	= '0',
625 	[STACK_DYNPTR]	= 'd',
626 };
627 
628 static void print_liveness(struct bpf_verifier_env *env,
629 			   enum bpf_reg_liveness live)
630 {
631 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
632 	    verbose(env, "_");
633 	if (live & REG_LIVE_READ)
634 		verbose(env, "r");
635 	if (live & REG_LIVE_WRITTEN)
636 		verbose(env, "w");
637 	if (live & REG_LIVE_DONE)
638 		verbose(env, "D");
639 }
640 
641 static int get_spi(s32 off)
642 {
643 	return (-off - 1) / BPF_REG_SIZE;
644 }
645 
646 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
647 {
648 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
649 
650 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
651 	 * within [0, allocated_stack).
652 	 *
653 	 * Please note that the spi grows downwards. For example, a dynptr
654 	 * takes the size of two stack slots; the first slot will be at
655 	 * spi and the second slot will be at spi - 1.
656 	 */
657 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
658 }
659 
660 static struct bpf_func_state *func(struct bpf_verifier_env *env,
661 				   const struct bpf_reg_state *reg)
662 {
663 	struct bpf_verifier_state *cur = env->cur_state;
664 
665 	return cur->frame[reg->frameno];
666 }
667 
668 static const char *kernel_type_name(const struct btf* btf, u32 id)
669 {
670 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
671 }
672 
673 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
674 {
675 	env->scratched_regs |= 1U << regno;
676 }
677 
678 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
679 {
680 	env->scratched_stack_slots |= 1ULL << spi;
681 }
682 
683 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
684 {
685 	return (env->scratched_regs >> regno) & 1;
686 }
687 
688 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
689 {
690 	return (env->scratched_stack_slots >> regno) & 1;
691 }
692 
693 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
694 {
695 	return env->scratched_regs || env->scratched_stack_slots;
696 }
697 
698 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
699 {
700 	env->scratched_regs = 0U;
701 	env->scratched_stack_slots = 0ULL;
702 }
703 
704 /* Used for printing the entire verifier state. */
705 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
706 {
707 	env->scratched_regs = ~0U;
708 	env->scratched_stack_slots = ~0ULL;
709 }
710 
711 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
712 {
713 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
714 	case DYNPTR_TYPE_LOCAL:
715 		return BPF_DYNPTR_TYPE_LOCAL;
716 	case DYNPTR_TYPE_RINGBUF:
717 		return BPF_DYNPTR_TYPE_RINGBUF;
718 	default:
719 		return BPF_DYNPTR_TYPE_INVALID;
720 	}
721 }
722 
723 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
724 {
725 	return type == BPF_DYNPTR_TYPE_RINGBUF;
726 }
727 
728 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
729 			      enum bpf_dynptr_type type,
730 			      bool first_slot);
731 
732 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
733 				struct bpf_reg_state *reg);
734 
735 static void mark_dynptr_stack_regs(struct bpf_reg_state *sreg1,
736 				   struct bpf_reg_state *sreg2,
737 				   enum bpf_dynptr_type type)
738 {
739 	__mark_dynptr_reg(sreg1, type, true);
740 	__mark_dynptr_reg(sreg2, type, false);
741 }
742 
743 static void mark_dynptr_cb_reg(struct bpf_reg_state *reg,
744 			       enum bpf_dynptr_type type)
745 {
746 	__mark_dynptr_reg(reg, type, true);
747 }
748 
749 
750 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
751 				   enum bpf_arg_type arg_type, int insn_idx)
752 {
753 	struct bpf_func_state *state = func(env, reg);
754 	enum bpf_dynptr_type type;
755 	int spi, i, id;
756 
757 	spi = get_spi(reg->off);
758 
759 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760 		return -EINVAL;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(&state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		id = acquire_reference_state(env, insn_idx);
777 		if (id < 0)
778 			return id;
779 
780 		state->stack[spi].spilled_ptr.ref_obj_id = id;
781 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
782 	}
783 
784 	return 0;
785 }
786 
787 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
788 {
789 	struct bpf_func_state *state = func(env, reg);
790 	int spi, i;
791 
792 	spi = get_spi(reg->off);
793 
794 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
795 		return -EINVAL;
796 
797 	for (i = 0; i < BPF_REG_SIZE; i++) {
798 		state->stack[spi].slot_type[i] = STACK_INVALID;
799 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
800 	}
801 
802 	/* Invalidate any slices associated with this dynptr */
803 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
804 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
805 
806 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
807 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
808 	return 0;
809 }
810 
811 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
812 {
813 	struct bpf_func_state *state = func(env, reg);
814 	int spi, i;
815 
816 	if (reg->type == CONST_PTR_TO_DYNPTR)
817 		return false;
818 
819 	spi = get_spi(reg->off);
820 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
821 		return true;
822 
823 	for (i = 0; i < BPF_REG_SIZE; i++) {
824 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
825 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
826 			return false;
827 	}
828 
829 	return true;
830 }
831 
832 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
833 {
834 	struct bpf_func_state *state = func(env, reg);
835 	int spi;
836 	int i;
837 
838 	/* This already represents first slot of initialized bpf_dynptr */
839 	if (reg->type == CONST_PTR_TO_DYNPTR)
840 		return true;
841 
842 	spi = get_spi(reg->off);
843 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
844 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
845 		return false;
846 
847 	for (i = 0; i < BPF_REG_SIZE; i++) {
848 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
849 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
850 			return false;
851 	}
852 
853 	return true;
854 }
855 
856 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
857 				    enum bpf_arg_type arg_type)
858 {
859 	struct bpf_func_state *state = func(env, reg);
860 	enum bpf_dynptr_type dynptr_type;
861 	int spi;
862 
863 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
864 	if (arg_type == ARG_PTR_TO_DYNPTR)
865 		return true;
866 
867 	dynptr_type = arg_to_dynptr_type(arg_type);
868 	if (reg->type == CONST_PTR_TO_DYNPTR) {
869 		return reg->dynptr.type == dynptr_type;
870 	} else {
871 		spi = get_spi(reg->off);
872 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
873 	}
874 }
875 
876 /* The reg state of a pointer or a bounded scalar was saved when
877  * it was spilled to the stack.
878  */
879 static bool is_spilled_reg(const struct bpf_stack_state *stack)
880 {
881 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
882 }
883 
884 static void scrub_spilled_slot(u8 *stype)
885 {
886 	if (*stype != STACK_INVALID)
887 		*stype = STACK_MISC;
888 }
889 
890 static void print_verifier_state(struct bpf_verifier_env *env,
891 				 const struct bpf_func_state *state,
892 				 bool print_all)
893 {
894 	const struct bpf_reg_state *reg;
895 	enum bpf_reg_type t;
896 	int i;
897 
898 	if (state->frameno)
899 		verbose(env, " frame%d:", state->frameno);
900 	for (i = 0; i < MAX_BPF_REG; i++) {
901 		reg = &state->regs[i];
902 		t = reg->type;
903 		if (t == NOT_INIT)
904 			continue;
905 		if (!print_all && !reg_scratched(env, i))
906 			continue;
907 		verbose(env, " R%d", i);
908 		print_liveness(env, reg->live);
909 		verbose(env, "=");
910 		if (t == SCALAR_VALUE && reg->precise)
911 			verbose(env, "P");
912 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
913 		    tnum_is_const(reg->var_off)) {
914 			/* reg->off should be 0 for SCALAR_VALUE */
915 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
916 			verbose(env, "%lld", reg->var_off.value + reg->off);
917 		} else {
918 			const char *sep = "";
919 
920 			verbose(env, "%s", reg_type_str(env, t));
921 			if (base_type(t) == PTR_TO_BTF_ID)
922 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
923 			verbose(env, "(");
924 /*
925  * _a stands for append, was shortened to avoid multiline statements below.
926  * This macro is used to output a comma separated list of attributes.
927  */
928 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
929 
930 			if (reg->id)
931 				verbose_a("id=%d", reg->id);
932 			if (reg->ref_obj_id)
933 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
934 			if (t != SCALAR_VALUE)
935 				verbose_a("off=%d", reg->off);
936 			if (type_is_pkt_pointer(t))
937 				verbose_a("r=%d", reg->range);
938 			else if (base_type(t) == CONST_PTR_TO_MAP ||
939 				 base_type(t) == PTR_TO_MAP_KEY ||
940 				 base_type(t) == PTR_TO_MAP_VALUE)
941 				verbose_a("ks=%d,vs=%d",
942 					  reg->map_ptr->key_size,
943 					  reg->map_ptr->value_size);
944 			if (tnum_is_const(reg->var_off)) {
945 				/* Typically an immediate SCALAR_VALUE, but
946 				 * could be a pointer whose offset is too big
947 				 * for reg->off
948 				 */
949 				verbose_a("imm=%llx", reg->var_off.value);
950 			} else {
951 				if (reg->smin_value != reg->umin_value &&
952 				    reg->smin_value != S64_MIN)
953 					verbose_a("smin=%lld", (long long)reg->smin_value);
954 				if (reg->smax_value != reg->umax_value &&
955 				    reg->smax_value != S64_MAX)
956 					verbose_a("smax=%lld", (long long)reg->smax_value);
957 				if (reg->umin_value != 0)
958 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
959 				if (reg->umax_value != U64_MAX)
960 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
961 				if (!tnum_is_unknown(reg->var_off)) {
962 					char tn_buf[48];
963 
964 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
965 					verbose_a("var_off=%s", tn_buf);
966 				}
967 				if (reg->s32_min_value != reg->smin_value &&
968 				    reg->s32_min_value != S32_MIN)
969 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
970 				if (reg->s32_max_value != reg->smax_value &&
971 				    reg->s32_max_value != S32_MAX)
972 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
973 				if (reg->u32_min_value != reg->umin_value &&
974 				    reg->u32_min_value != U32_MIN)
975 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
976 				if (reg->u32_max_value != reg->umax_value &&
977 				    reg->u32_max_value != U32_MAX)
978 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
979 			}
980 #undef verbose_a
981 
982 			verbose(env, ")");
983 		}
984 	}
985 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
986 		char types_buf[BPF_REG_SIZE + 1];
987 		bool valid = false;
988 		int j;
989 
990 		for (j = 0; j < BPF_REG_SIZE; j++) {
991 			if (state->stack[i].slot_type[j] != STACK_INVALID)
992 				valid = true;
993 			types_buf[j] = slot_type_char[
994 					state->stack[i].slot_type[j]];
995 		}
996 		types_buf[BPF_REG_SIZE] = 0;
997 		if (!valid)
998 			continue;
999 		if (!print_all && !stack_slot_scratched(env, i))
1000 			continue;
1001 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1002 		print_liveness(env, state->stack[i].spilled_ptr.live);
1003 		if (is_spilled_reg(&state->stack[i])) {
1004 			reg = &state->stack[i].spilled_ptr;
1005 			t = reg->type;
1006 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1007 			if (t == SCALAR_VALUE && reg->precise)
1008 				verbose(env, "P");
1009 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1010 				verbose(env, "%lld", reg->var_off.value + reg->off);
1011 		} else {
1012 			verbose(env, "=%s", types_buf);
1013 		}
1014 	}
1015 	if (state->acquired_refs && state->refs[0].id) {
1016 		verbose(env, " refs=%d", state->refs[0].id);
1017 		for (i = 1; i < state->acquired_refs; i++)
1018 			if (state->refs[i].id)
1019 				verbose(env, ",%d", state->refs[i].id);
1020 	}
1021 	if (state->in_callback_fn)
1022 		verbose(env, " cb");
1023 	if (state->in_async_callback_fn)
1024 		verbose(env, " async_cb");
1025 	verbose(env, "\n");
1026 	mark_verifier_state_clean(env);
1027 }
1028 
1029 static inline u32 vlog_alignment(u32 pos)
1030 {
1031 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1032 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1033 }
1034 
1035 static void print_insn_state(struct bpf_verifier_env *env,
1036 			     const struct bpf_func_state *state)
1037 {
1038 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1039 		/* remove new line character */
1040 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1041 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1042 	} else {
1043 		verbose(env, "%d:", env->insn_idx);
1044 	}
1045 	print_verifier_state(env, state, false);
1046 }
1047 
1048 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1049  * small to hold src. This is different from krealloc since we don't want to preserve
1050  * the contents of dst.
1051  *
1052  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1053  * not be allocated.
1054  */
1055 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1056 {
1057 	size_t alloc_bytes;
1058 	void *orig = dst;
1059 	size_t bytes;
1060 
1061 	if (ZERO_OR_NULL_PTR(src))
1062 		goto out;
1063 
1064 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1065 		return NULL;
1066 
1067 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1068 	dst = krealloc(orig, alloc_bytes, flags);
1069 	if (!dst) {
1070 		kfree(orig);
1071 		return NULL;
1072 	}
1073 
1074 	memcpy(dst, src, bytes);
1075 out:
1076 	return dst ? dst : ZERO_SIZE_PTR;
1077 }
1078 
1079 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1080  * small to hold new_n items. new items are zeroed out if the array grows.
1081  *
1082  * Contrary to krealloc_array, does not free arr if new_n is zero.
1083  */
1084 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1085 {
1086 	size_t alloc_size;
1087 	void *new_arr;
1088 
1089 	if (!new_n || old_n == new_n)
1090 		goto out;
1091 
1092 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1093 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1094 	if (!new_arr) {
1095 		kfree(arr);
1096 		return NULL;
1097 	}
1098 	arr = new_arr;
1099 
1100 	if (new_n > old_n)
1101 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1102 
1103 out:
1104 	return arr ? arr : ZERO_SIZE_PTR;
1105 }
1106 
1107 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1108 {
1109 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1110 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1111 	if (!dst->refs)
1112 		return -ENOMEM;
1113 
1114 	dst->acquired_refs = src->acquired_refs;
1115 	return 0;
1116 }
1117 
1118 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1119 {
1120 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1121 
1122 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1123 				GFP_KERNEL);
1124 	if (!dst->stack)
1125 		return -ENOMEM;
1126 
1127 	dst->allocated_stack = src->allocated_stack;
1128 	return 0;
1129 }
1130 
1131 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1132 {
1133 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1134 				    sizeof(struct bpf_reference_state));
1135 	if (!state->refs)
1136 		return -ENOMEM;
1137 
1138 	state->acquired_refs = n;
1139 	return 0;
1140 }
1141 
1142 static int grow_stack_state(struct bpf_func_state *state, int size)
1143 {
1144 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1145 
1146 	if (old_n >= n)
1147 		return 0;
1148 
1149 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1150 	if (!state->stack)
1151 		return -ENOMEM;
1152 
1153 	state->allocated_stack = size;
1154 	return 0;
1155 }
1156 
1157 /* Acquire a pointer id from the env and update the state->refs to include
1158  * this new pointer reference.
1159  * On success, returns a valid pointer id to associate with the register
1160  * On failure, returns a negative errno.
1161  */
1162 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1163 {
1164 	struct bpf_func_state *state = cur_func(env);
1165 	int new_ofs = state->acquired_refs;
1166 	int id, err;
1167 
1168 	err = resize_reference_state(state, state->acquired_refs + 1);
1169 	if (err)
1170 		return err;
1171 	id = ++env->id_gen;
1172 	state->refs[new_ofs].id = id;
1173 	state->refs[new_ofs].insn_idx = insn_idx;
1174 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1175 
1176 	return id;
1177 }
1178 
1179 /* release function corresponding to acquire_reference_state(). Idempotent. */
1180 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1181 {
1182 	int i, last_idx;
1183 
1184 	last_idx = state->acquired_refs - 1;
1185 	for (i = 0; i < state->acquired_refs; i++) {
1186 		if (state->refs[i].id == ptr_id) {
1187 			/* Cannot release caller references in callbacks */
1188 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1189 				return -EINVAL;
1190 			if (last_idx && i != last_idx)
1191 				memcpy(&state->refs[i], &state->refs[last_idx],
1192 				       sizeof(*state->refs));
1193 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1194 			state->acquired_refs--;
1195 			return 0;
1196 		}
1197 	}
1198 	return -EINVAL;
1199 }
1200 
1201 static void free_func_state(struct bpf_func_state *state)
1202 {
1203 	if (!state)
1204 		return;
1205 	kfree(state->refs);
1206 	kfree(state->stack);
1207 	kfree(state);
1208 }
1209 
1210 static void clear_jmp_history(struct bpf_verifier_state *state)
1211 {
1212 	kfree(state->jmp_history);
1213 	state->jmp_history = NULL;
1214 	state->jmp_history_cnt = 0;
1215 }
1216 
1217 static void free_verifier_state(struct bpf_verifier_state *state,
1218 				bool free_self)
1219 {
1220 	int i;
1221 
1222 	for (i = 0; i <= state->curframe; i++) {
1223 		free_func_state(state->frame[i]);
1224 		state->frame[i] = NULL;
1225 	}
1226 	clear_jmp_history(state);
1227 	if (free_self)
1228 		kfree(state);
1229 }
1230 
1231 /* copy verifier state from src to dst growing dst stack space
1232  * when necessary to accommodate larger src stack
1233  */
1234 static int copy_func_state(struct bpf_func_state *dst,
1235 			   const struct bpf_func_state *src)
1236 {
1237 	int err;
1238 
1239 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1240 	err = copy_reference_state(dst, src);
1241 	if (err)
1242 		return err;
1243 	return copy_stack_state(dst, src);
1244 }
1245 
1246 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1247 			       const struct bpf_verifier_state *src)
1248 {
1249 	struct bpf_func_state *dst;
1250 	int i, err;
1251 
1252 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1253 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1254 					    GFP_USER);
1255 	if (!dst_state->jmp_history)
1256 		return -ENOMEM;
1257 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1258 
1259 	/* if dst has more stack frames then src frame, free them */
1260 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1261 		free_func_state(dst_state->frame[i]);
1262 		dst_state->frame[i] = NULL;
1263 	}
1264 	dst_state->speculative = src->speculative;
1265 	dst_state->active_rcu_lock = src->active_rcu_lock;
1266 	dst_state->curframe = src->curframe;
1267 	dst_state->active_lock.ptr = src->active_lock.ptr;
1268 	dst_state->active_lock.id = src->active_lock.id;
1269 	dst_state->branches = src->branches;
1270 	dst_state->parent = src->parent;
1271 	dst_state->first_insn_idx = src->first_insn_idx;
1272 	dst_state->last_insn_idx = src->last_insn_idx;
1273 	for (i = 0; i <= src->curframe; i++) {
1274 		dst = dst_state->frame[i];
1275 		if (!dst) {
1276 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1277 			if (!dst)
1278 				return -ENOMEM;
1279 			dst_state->frame[i] = dst;
1280 		}
1281 		err = copy_func_state(dst, src->frame[i]);
1282 		if (err)
1283 			return err;
1284 	}
1285 	return 0;
1286 }
1287 
1288 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1289 {
1290 	while (st) {
1291 		u32 br = --st->branches;
1292 
1293 		/* WARN_ON(br > 1) technically makes sense here,
1294 		 * but see comment in push_stack(), hence:
1295 		 */
1296 		WARN_ONCE((int)br < 0,
1297 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1298 			  br);
1299 		if (br)
1300 			break;
1301 		st = st->parent;
1302 	}
1303 }
1304 
1305 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1306 		     int *insn_idx, bool pop_log)
1307 {
1308 	struct bpf_verifier_state *cur = env->cur_state;
1309 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1310 	int err;
1311 
1312 	if (env->head == NULL)
1313 		return -ENOENT;
1314 
1315 	if (cur) {
1316 		err = copy_verifier_state(cur, &head->st);
1317 		if (err)
1318 			return err;
1319 	}
1320 	if (pop_log)
1321 		bpf_vlog_reset(&env->log, head->log_pos);
1322 	if (insn_idx)
1323 		*insn_idx = head->insn_idx;
1324 	if (prev_insn_idx)
1325 		*prev_insn_idx = head->prev_insn_idx;
1326 	elem = head->next;
1327 	free_verifier_state(&head->st, false);
1328 	kfree(head);
1329 	env->head = elem;
1330 	env->stack_size--;
1331 	return 0;
1332 }
1333 
1334 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1335 					     int insn_idx, int prev_insn_idx,
1336 					     bool speculative)
1337 {
1338 	struct bpf_verifier_state *cur = env->cur_state;
1339 	struct bpf_verifier_stack_elem *elem;
1340 	int err;
1341 
1342 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1343 	if (!elem)
1344 		goto err;
1345 
1346 	elem->insn_idx = insn_idx;
1347 	elem->prev_insn_idx = prev_insn_idx;
1348 	elem->next = env->head;
1349 	elem->log_pos = env->log.len_used;
1350 	env->head = elem;
1351 	env->stack_size++;
1352 	err = copy_verifier_state(&elem->st, cur);
1353 	if (err)
1354 		goto err;
1355 	elem->st.speculative |= speculative;
1356 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1357 		verbose(env, "The sequence of %d jumps is too complex.\n",
1358 			env->stack_size);
1359 		goto err;
1360 	}
1361 	if (elem->st.parent) {
1362 		++elem->st.parent->branches;
1363 		/* WARN_ON(branches > 2) technically makes sense here,
1364 		 * but
1365 		 * 1. speculative states will bump 'branches' for non-branch
1366 		 * instructions
1367 		 * 2. is_state_visited() heuristics may decide not to create
1368 		 * a new state for a sequence of branches and all such current
1369 		 * and cloned states will be pointing to a single parent state
1370 		 * which might have large 'branches' count.
1371 		 */
1372 	}
1373 	return &elem->st;
1374 err:
1375 	free_verifier_state(env->cur_state, true);
1376 	env->cur_state = NULL;
1377 	/* pop all elements and return */
1378 	while (!pop_stack(env, NULL, NULL, false));
1379 	return NULL;
1380 }
1381 
1382 #define CALLER_SAVED_REGS 6
1383 static const int caller_saved[CALLER_SAVED_REGS] = {
1384 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1385 };
1386 
1387 /* This helper doesn't clear reg->id */
1388 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1389 {
1390 	reg->var_off = tnum_const(imm);
1391 	reg->smin_value = (s64)imm;
1392 	reg->smax_value = (s64)imm;
1393 	reg->umin_value = imm;
1394 	reg->umax_value = imm;
1395 
1396 	reg->s32_min_value = (s32)imm;
1397 	reg->s32_max_value = (s32)imm;
1398 	reg->u32_min_value = (u32)imm;
1399 	reg->u32_max_value = (u32)imm;
1400 }
1401 
1402 /* Mark the unknown part of a register (variable offset or scalar value) as
1403  * known to have the value @imm.
1404  */
1405 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1406 {
1407 	/* Clear off and union(map_ptr, range) */
1408 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1409 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1410 	reg->id = 0;
1411 	reg->ref_obj_id = 0;
1412 	___mark_reg_known(reg, imm);
1413 }
1414 
1415 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1416 {
1417 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1418 	reg->s32_min_value = (s32)imm;
1419 	reg->s32_max_value = (s32)imm;
1420 	reg->u32_min_value = (u32)imm;
1421 	reg->u32_max_value = (u32)imm;
1422 }
1423 
1424 /* Mark the 'variable offset' part of a register as zero.  This should be
1425  * used only on registers holding a pointer type.
1426  */
1427 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1428 {
1429 	__mark_reg_known(reg, 0);
1430 }
1431 
1432 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1433 {
1434 	__mark_reg_known(reg, 0);
1435 	reg->type = SCALAR_VALUE;
1436 }
1437 
1438 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1439 				struct bpf_reg_state *regs, u32 regno)
1440 {
1441 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1442 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1443 		/* Something bad happened, let's kill all regs */
1444 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1445 			__mark_reg_not_init(env, regs + regno);
1446 		return;
1447 	}
1448 	__mark_reg_known_zero(regs + regno);
1449 }
1450 
1451 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1452 			      bool first_slot)
1453 {
1454 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1455 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1456 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1457 	 */
1458 	__mark_reg_known_zero(reg);
1459 	reg->type = CONST_PTR_TO_DYNPTR;
1460 	reg->dynptr.type = type;
1461 	reg->dynptr.first_slot = first_slot;
1462 }
1463 
1464 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1465 {
1466 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1467 		const struct bpf_map *map = reg->map_ptr;
1468 
1469 		if (map->inner_map_meta) {
1470 			reg->type = CONST_PTR_TO_MAP;
1471 			reg->map_ptr = map->inner_map_meta;
1472 			/* transfer reg's id which is unique for every map_lookup_elem
1473 			 * as UID of the inner map.
1474 			 */
1475 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1476 				reg->map_uid = reg->id;
1477 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1478 			reg->type = PTR_TO_XDP_SOCK;
1479 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1480 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1481 			reg->type = PTR_TO_SOCKET;
1482 		} else {
1483 			reg->type = PTR_TO_MAP_VALUE;
1484 		}
1485 		return;
1486 	}
1487 
1488 	reg->type &= ~PTR_MAYBE_NULL;
1489 }
1490 
1491 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1492 {
1493 	return type_is_pkt_pointer(reg->type);
1494 }
1495 
1496 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1497 {
1498 	return reg_is_pkt_pointer(reg) ||
1499 	       reg->type == PTR_TO_PACKET_END;
1500 }
1501 
1502 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1503 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1504 				    enum bpf_reg_type which)
1505 {
1506 	/* The register can already have a range from prior markings.
1507 	 * This is fine as long as it hasn't been advanced from its
1508 	 * origin.
1509 	 */
1510 	return reg->type == which &&
1511 	       reg->id == 0 &&
1512 	       reg->off == 0 &&
1513 	       tnum_equals_const(reg->var_off, 0);
1514 }
1515 
1516 /* Reset the min/max bounds of a register */
1517 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1518 {
1519 	reg->smin_value = S64_MIN;
1520 	reg->smax_value = S64_MAX;
1521 	reg->umin_value = 0;
1522 	reg->umax_value = U64_MAX;
1523 
1524 	reg->s32_min_value = S32_MIN;
1525 	reg->s32_max_value = S32_MAX;
1526 	reg->u32_min_value = 0;
1527 	reg->u32_max_value = U32_MAX;
1528 }
1529 
1530 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1531 {
1532 	reg->smin_value = S64_MIN;
1533 	reg->smax_value = S64_MAX;
1534 	reg->umin_value = 0;
1535 	reg->umax_value = U64_MAX;
1536 }
1537 
1538 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1539 {
1540 	reg->s32_min_value = S32_MIN;
1541 	reg->s32_max_value = S32_MAX;
1542 	reg->u32_min_value = 0;
1543 	reg->u32_max_value = U32_MAX;
1544 }
1545 
1546 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1547 {
1548 	struct tnum var32_off = tnum_subreg(reg->var_off);
1549 
1550 	/* min signed is max(sign bit) | min(other bits) */
1551 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1552 			var32_off.value | (var32_off.mask & S32_MIN));
1553 	/* max signed is min(sign bit) | max(other bits) */
1554 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1555 			var32_off.value | (var32_off.mask & S32_MAX));
1556 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1557 	reg->u32_max_value = min(reg->u32_max_value,
1558 				 (u32)(var32_off.value | var32_off.mask));
1559 }
1560 
1561 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1562 {
1563 	/* min signed is max(sign bit) | min(other bits) */
1564 	reg->smin_value = max_t(s64, reg->smin_value,
1565 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1566 	/* max signed is min(sign bit) | max(other bits) */
1567 	reg->smax_value = min_t(s64, reg->smax_value,
1568 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1569 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1570 	reg->umax_value = min(reg->umax_value,
1571 			      reg->var_off.value | reg->var_off.mask);
1572 }
1573 
1574 static void __update_reg_bounds(struct bpf_reg_state *reg)
1575 {
1576 	__update_reg32_bounds(reg);
1577 	__update_reg64_bounds(reg);
1578 }
1579 
1580 /* Uses signed min/max values to inform unsigned, and vice-versa */
1581 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583 	/* Learn sign from signed bounds.
1584 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1585 	 * are the same, so combine.  This works even in the negative case, e.g.
1586 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1587 	 */
1588 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1589 		reg->s32_min_value = reg->u32_min_value =
1590 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1591 		reg->s32_max_value = reg->u32_max_value =
1592 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1593 		return;
1594 	}
1595 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1596 	 * boundary, so we must be careful.
1597 	 */
1598 	if ((s32)reg->u32_max_value >= 0) {
1599 		/* Positive.  We can't learn anything from the smin, but smax
1600 		 * is positive, hence safe.
1601 		 */
1602 		reg->s32_min_value = reg->u32_min_value;
1603 		reg->s32_max_value = reg->u32_max_value =
1604 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1605 	} else if ((s32)reg->u32_min_value < 0) {
1606 		/* Negative.  We can't learn anything from the smax, but smin
1607 		 * is negative, hence safe.
1608 		 */
1609 		reg->s32_min_value = reg->u32_min_value =
1610 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1611 		reg->s32_max_value = reg->u32_max_value;
1612 	}
1613 }
1614 
1615 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1616 {
1617 	/* Learn sign from signed bounds.
1618 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1619 	 * are the same, so combine.  This works even in the negative case, e.g.
1620 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1621 	 */
1622 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1623 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1624 							  reg->umin_value);
1625 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1626 							  reg->umax_value);
1627 		return;
1628 	}
1629 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1630 	 * boundary, so we must be careful.
1631 	 */
1632 	if ((s64)reg->umax_value >= 0) {
1633 		/* Positive.  We can't learn anything from the smin, but smax
1634 		 * is positive, hence safe.
1635 		 */
1636 		reg->smin_value = reg->umin_value;
1637 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1638 							  reg->umax_value);
1639 	} else if ((s64)reg->umin_value < 0) {
1640 		/* Negative.  We can't learn anything from the smax, but smin
1641 		 * is negative, hence safe.
1642 		 */
1643 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1644 							  reg->umin_value);
1645 		reg->smax_value = reg->umax_value;
1646 	}
1647 }
1648 
1649 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1650 {
1651 	__reg32_deduce_bounds(reg);
1652 	__reg64_deduce_bounds(reg);
1653 }
1654 
1655 /* Attempts to improve var_off based on unsigned min/max information */
1656 static void __reg_bound_offset(struct bpf_reg_state *reg)
1657 {
1658 	struct tnum var64_off = tnum_intersect(reg->var_off,
1659 					       tnum_range(reg->umin_value,
1660 							  reg->umax_value));
1661 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1662 						tnum_range(reg->u32_min_value,
1663 							   reg->u32_max_value));
1664 
1665 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1666 }
1667 
1668 static void reg_bounds_sync(struct bpf_reg_state *reg)
1669 {
1670 	/* We might have learned new bounds from the var_off. */
1671 	__update_reg_bounds(reg);
1672 	/* We might have learned something about the sign bit. */
1673 	__reg_deduce_bounds(reg);
1674 	/* We might have learned some bits from the bounds. */
1675 	__reg_bound_offset(reg);
1676 	/* Intersecting with the old var_off might have improved our bounds
1677 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1678 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1679 	 */
1680 	__update_reg_bounds(reg);
1681 }
1682 
1683 static bool __reg32_bound_s64(s32 a)
1684 {
1685 	return a >= 0 && a <= S32_MAX;
1686 }
1687 
1688 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1689 {
1690 	reg->umin_value = reg->u32_min_value;
1691 	reg->umax_value = reg->u32_max_value;
1692 
1693 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1694 	 * be positive otherwise set to worse case bounds and refine later
1695 	 * from tnum.
1696 	 */
1697 	if (__reg32_bound_s64(reg->s32_min_value) &&
1698 	    __reg32_bound_s64(reg->s32_max_value)) {
1699 		reg->smin_value = reg->s32_min_value;
1700 		reg->smax_value = reg->s32_max_value;
1701 	} else {
1702 		reg->smin_value = 0;
1703 		reg->smax_value = U32_MAX;
1704 	}
1705 }
1706 
1707 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1708 {
1709 	/* special case when 64-bit register has upper 32-bit register
1710 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1711 	 * allowing us to use 32-bit bounds directly,
1712 	 */
1713 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1714 		__reg_assign_32_into_64(reg);
1715 	} else {
1716 		/* Otherwise the best we can do is push lower 32bit known and
1717 		 * unknown bits into register (var_off set from jmp logic)
1718 		 * then learn as much as possible from the 64-bit tnum
1719 		 * known and unknown bits. The previous smin/smax bounds are
1720 		 * invalid here because of jmp32 compare so mark them unknown
1721 		 * so they do not impact tnum bounds calculation.
1722 		 */
1723 		__mark_reg64_unbounded(reg);
1724 	}
1725 	reg_bounds_sync(reg);
1726 }
1727 
1728 static bool __reg64_bound_s32(s64 a)
1729 {
1730 	return a >= S32_MIN && a <= S32_MAX;
1731 }
1732 
1733 static bool __reg64_bound_u32(u64 a)
1734 {
1735 	return a >= U32_MIN && a <= U32_MAX;
1736 }
1737 
1738 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1739 {
1740 	__mark_reg32_unbounded(reg);
1741 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1742 		reg->s32_min_value = (s32)reg->smin_value;
1743 		reg->s32_max_value = (s32)reg->smax_value;
1744 	}
1745 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1746 		reg->u32_min_value = (u32)reg->umin_value;
1747 		reg->u32_max_value = (u32)reg->umax_value;
1748 	}
1749 	reg_bounds_sync(reg);
1750 }
1751 
1752 /* Mark a register as having a completely unknown (scalar) value. */
1753 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1754 			       struct bpf_reg_state *reg)
1755 {
1756 	/*
1757 	 * Clear type, off, and union(map_ptr, range) and
1758 	 * padding between 'type' and union
1759 	 */
1760 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1761 	reg->type = SCALAR_VALUE;
1762 	reg->id = 0;
1763 	reg->ref_obj_id = 0;
1764 	reg->var_off = tnum_unknown;
1765 	reg->frameno = 0;
1766 	reg->precise = !env->bpf_capable;
1767 	__mark_reg_unbounded(reg);
1768 }
1769 
1770 static void mark_reg_unknown(struct bpf_verifier_env *env,
1771 			     struct bpf_reg_state *regs, u32 regno)
1772 {
1773 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1774 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1775 		/* Something bad happened, let's kill all regs except FP */
1776 		for (regno = 0; regno < BPF_REG_FP; regno++)
1777 			__mark_reg_not_init(env, regs + regno);
1778 		return;
1779 	}
1780 	__mark_reg_unknown(env, regs + regno);
1781 }
1782 
1783 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1784 				struct bpf_reg_state *reg)
1785 {
1786 	__mark_reg_unknown(env, reg);
1787 	reg->type = NOT_INIT;
1788 }
1789 
1790 static void mark_reg_not_init(struct bpf_verifier_env *env,
1791 			      struct bpf_reg_state *regs, u32 regno)
1792 {
1793 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1794 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1795 		/* Something bad happened, let's kill all regs except FP */
1796 		for (regno = 0; regno < BPF_REG_FP; regno++)
1797 			__mark_reg_not_init(env, regs + regno);
1798 		return;
1799 	}
1800 	__mark_reg_not_init(env, regs + regno);
1801 }
1802 
1803 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1804 			    struct bpf_reg_state *regs, u32 regno,
1805 			    enum bpf_reg_type reg_type,
1806 			    struct btf *btf, u32 btf_id,
1807 			    enum bpf_type_flag flag)
1808 {
1809 	if (reg_type == SCALAR_VALUE) {
1810 		mark_reg_unknown(env, regs, regno);
1811 		return;
1812 	}
1813 	mark_reg_known_zero(env, regs, regno);
1814 	regs[regno].type = PTR_TO_BTF_ID | flag;
1815 	regs[regno].btf = btf;
1816 	regs[regno].btf_id = btf_id;
1817 }
1818 
1819 #define DEF_NOT_SUBREG	(0)
1820 static void init_reg_state(struct bpf_verifier_env *env,
1821 			   struct bpf_func_state *state)
1822 {
1823 	struct bpf_reg_state *regs = state->regs;
1824 	int i;
1825 
1826 	for (i = 0; i < MAX_BPF_REG; i++) {
1827 		mark_reg_not_init(env, regs, i);
1828 		regs[i].live = REG_LIVE_NONE;
1829 		regs[i].parent = NULL;
1830 		regs[i].subreg_def = DEF_NOT_SUBREG;
1831 	}
1832 
1833 	/* frame pointer */
1834 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1835 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1836 	regs[BPF_REG_FP].frameno = state->frameno;
1837 }
1838 
1839 #define BPF_MAIN_FUNC (-1)
1840 static void init_func_state(struct bpf_verifier_env *env,
1841 			    struct bpf_func_state *state,
1842 			    int callsite, int frameno, int subprogno)
1843 {
1844 	state->callsite = callsite;
1845 	state->frameno = frameno;
1846 	state->subprogno = subprogno;
1847 	state->callback_ret_range = tnum_range(0, 0);
1848 	init_reg_state(env, state);
1849 	mark_verifier_state_scratched(env);
1850 }
1851 
1852 /* Similar to push_stack(), but for async callbacks */
1853 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1854 						int insn_idx, int prev_insn_idx,
1855 						int subprog)
1856 {
1857 	struct bpf_verifier_stack_elem *elem;
1858 	struct bpf_func_state *frame;
1859 
1860 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1861 	if (!elem)
1862 		goto err;
1863 
1864 	elem->insn_idx = insn_idx;
1865 	elem->prev_insn_idx = prev_insn_idx;
1866 	elem->next = env->head;
1867 	elem->log_pos = env->log.len_used;
1868 	env->head = elem;
1869 	env->stack_size++;
1870 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1871 		verbose(env,
1872 			"The sequence of %d jumps is too complex for async cb.\n",
1873 			env->stack_size);
1874 		goto err;
1875 	}
1876 	/* Unlike push_stack() do not copy_verifier_state().
1877 	 * The caller state doesn't matter.
1878 	 * This is async callback. It starts in a fresh stack.
1879 	 * Initialize it similar to do_check_common().
1880 	 */
1881 	elem->st.branches = 1;
1882 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1883 	if (!frame)
1884 		goto err;
1885 	init_func_state(env, frame,
1886 			BPF_MAIN_FUNC /* callsite */,
1887 			0 /* frameno within this callchain */,
1888 			subprog /* subprog number within this prog */);
1889 	elem->st.frame[0] = frame;
1890 	return &elem->st;
1891 err:
1892 	free_verifier_state(env->cur_state, true);
1893 	env->cur_state = NULL;
1894 	/* pop all elements and return */
1895 	while (!pop_stack(env, NULL, NULL, false));
1896 	return NULL;
1897 }
1898 
1899 
1900 enum reg_arg_type {
1901 	SRC_OP,		/* register is used as source operand */
1902 	DST_OP,		/* register is used as destination operand */
1903 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1904 };
1905 
1906 static int cmp_subprogs(const void *a, const void *b)
1907 {
1908 	return ((struct bpf_subprog_info *)a)->start -
1909 	       ((struct bpf_subprog_info *)b)->start;
1910 }
1911 
1912 static int find_subprog(struct bpf_verifier_env *env, int off)
1913 {
1914 	struct bpf_subprog_info *p;
1915 
1916 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1917 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1918 	if (!p)
1919 		return -ENOENT;
1920 	return p - env->subprog_info;
1921 
1922 }
1923 
1924 static int add_subprog(struct bpf_verifier_env *env, int off)
1925 {
1926 	int insn_cnt = env->prog->len;
1927 	int ret;
1928 
1929 	if (off >= insn_cnt || off < 0) {
1930 		verbose(env, "call to invalid destination\n");
1931 		return -EINVAL;
1932 	}
1933 	ret = find_subprog(env, off);
1934 	if (ret >= 0)
1935 		return ret;
1936 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1937 		verbose(env, "too many subprograms\n");
1938 		return -E2BIG;
1939 	}
1940 	/* determine subprog starts. The end is one before the next starts */
1941 	env->subprog_info[env->subprog_cnt++].start = off;
1942 	sort(env->subprog_info, env->subprog_cnt,
1943 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1944 	return env->subprog_cnt - 1;
1945 }
1946 
1947 #define MAX_KFUNC_DESCS 256
1948 #define MAX_KFUNC_BTFS	256
1949 
1950 struct bpf_kfunc_desc {
1951 	struct btf_func_model func_model;
1952 	u32 func_id;
1953 	s32 imm;
1954 	u16 offset;
1955 };
1956 
1957 struct bpf_kfunc_btf {
1958 	struct btf *btf;
1959 	struct module *module;
1960 	u16 offset;
1961 };
1962 
1963 struct bpf_kfunc_desc_tab {
1964 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1965 	u32 nr_descs;
1966 };
1967 
1968 struct bpf_kfunc_btf_tab {
1969 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1970 	u32 nr_descs;
1971 };
1972 
1973 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1974 {
1975 	const struct bpf_kfunc_desc *d0 = a;
1976 	const struct bpf_kfunc_desc *d1 = b;
1977 
1978 	/* func_id is not greater than BTF_MAX_TYPE */
1979 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1980 }
1981 
1982 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1983 {
1984 	const struct bpf_kfunc_btf *d0 = a;
1985 	const struct bpf_kfunc_btf *d1 = b;
1986 
1987 	return d0->offset - d1->offset;
1988 }
1989 
1990 static const struct bpf_kfunc_desc *
1991 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1992 {
1993 	struct bpf_kfunc_desc desc = {
1994 		.func_id = func_id,
1995 		.offset = offset,
1996 	};
1997 	struct bpf_kfunc_desc_tab *tab;
1998 
1999 	tab = prog->aux->kfunc_tab;
2000 	return bsearch(&desc, tab->descs, tab->nr_descs,
2001 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2002 }
2003 
2004 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2005 					 s16 offset)
2006 {
2007 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2008 	struct bpf_kfunc_btf_tab *tab;
2009 	struct bpf_kfunc_btf *b;
2010 	struct module *mod;
2011 	struct btf *btf;
2012 	int btf_fd;
2013 
2014 	tab = env->prog->aux->kfunc_btf_tab;
2015 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2016 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2017 	if (!b) {
2018 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2019 			verbose(env, "too many different module BTFs\n");
2020 			return ERR_PTR(-E2BIG);
2021 		}
2022 
2023 		if (bpfptr_is_null(env->fd_array)) {
2024 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2025 			return ERR_PTR(-EPROTO);
2026 		}
2027 
2028 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2029 					    offset * sizeof(btf_fd),
2030 					    sizeof(btf_fd)))
2031 			return ERR_PTR(-EFAULT);
2032 
2033 		btf = btf_get_by_fd(btf_fd);
2034 		if (IS_ERR(btf)) {
2035 			verbose(env, "invalid module BTF fd specified\n");
2036 			return btf;
2037 		}
2038 
2039 		if (!btf_is_module(btf)) {
2040 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2041 			btf_put(btf);
2042 			return ERR_PTR(-EINVAL);
2043 		}
2044 
2045 		mod = btf_try_get_module(btf);
2046 		if (!mod) {
2047 			btf_put(btf);
2048 			return ERR_PTR(-ENXIO);
2049 		}
2050 
2051 		b = &tab->descs[tab->nr_descs++];
2052 		b->btf = btf;
2053 		b->module = mod;
2054 		b->offset = offset;
2055 
2056 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2057 		     kfunc_btf_cmp_by_off, NULL);
2058 	}
2059 	return b->btf;
2060 }
2061 
2062 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2063 {
2064 	if (!tab)
2065 		return;
2066 
2067 	while (tab->nr_descs--) {
2068 		module_put(tab->descs[tab->nr_descs].module);
2069 		btf_put(tab->descs[tab->nr_descs].btf);
2070 	}
2071 	kfree(tab);
2072 }
2073 
2074 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2075 {
2076 	if (offset) {
2077 		if (offset < 0) {
2078 			/* In the future, this can be allowed to increase limit
2079 			 * of fd index into fd_array, interpreted as u16.
2080 			 */
2081 			verbose(env, "negative offset disallowed for kernel module function call\n");
2082 			return ERR_PTR(-EINVAL);
2083 		}
2084 
2085 		return __find_kfunc_desc_btf(env, offset);
2086 	}
2087 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2088 }
2089 
2090 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2091 {
2092 	const struct btf_type *func, *func_proto;
2093 	struct bpf_kfunc_btf_tab *btf_tab;
2094 	struct bpf_kfunc_desc_tab *tab;
2095 	struct bpf_prog_aux *prog_aux;
2096 	struct bpf_kfunc_desc *desc;
2097 	const char *func_name;
2098 	struct btf *desc_btf;
2099 	unsigned long call_imm;
2100 	unsigned long addr;
2101 	int err;
2102 
2103 	prog_aux = env->prog->aux;
2104 	tab = prog_aux->kfunc_tab;
2105 	btf_tab = prog_aux->kfunc_btf_tab;
2106 	if (!tab) {
2107 		if (!btf_vmlinux) {
2108 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2109 			return -ENOTSUPP;
2110 		}
2111 
2112 		if (!env->prog->jit_requested) {
2113 			verbose(env, "JIT is required for calling kernel function\n");
2114 			return -ENOTSUPP;
2115 		}
2116 
2117 		if (!bpf_jit_supports_kfunc_call()) {
2118 			verbose(env, "JIT does not support calling kernel function\n");
2119 			return -ENOTSUPP;
2120 		}
2121 
2122 		if (!env->prog->gpl_compatible) {
2123 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2124 			return -EINVAL;
2125 		}
2126 
2127 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2128 		if (!tab)
2129 			return -ENOMEM;
2130 		prog_aux->kfunc_tab = tab;
2131 	}
2132 
2133 	/* func_id == 0 is always invalid, but instead of returning an error, be
2134 	 * conservative and wait until the code elimination pass before returning
2135 	 * error, so that invalid calls that get pruned out can be in BPF programs
2136 	 * loaded from userspace.  It is also required that offset be untouched
2137 	 * for such calls.
2138 	 */
2139 	if (!func_id && !offset)
2140 		return 0;
2141 
2142 	if (!btf_tab && offset) {
2143 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2144 		if (!btf_tab)
2145 			return -ENOMEM;
2146 		prog_aux->kfunc_btf_tab = btf_tab;
2147 	}
2148 
2149 	desc_btf = find_kfunc_desc_btf(env, offset);
2150 	if (IS_ERR(desc_btf)) {
2151 		verbose(env, "failed to find BTF for kernel function\n");
2152 		return PTR_ERR(desc_btf);
2153 	}
2154 
2155 	if (find_kfunc_desc(env->prog, func_id, offset))
2156 		return 0;
2157 
2158 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2159 		verbose(env, "too many different kernel function calls\n");
2160 		return -E2BIG;
2161 	}
2162 
2163 	func = btf_type_by_id(desc_btf, func_id);
2164 	if (!func || !btf_type_is_func(func)) {
2165 		verbose(env, "kernel btf_id %u is not a function\n",
2166 			func_id);
2167 		return -EINVAL;
2168 	}
2169 	func_proto = btf_type_by_id(desc_btf, func->type);
2170 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2171 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2172 			func_id);
2173 		return -EINVAL;
2174 	}
2175 
2176 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2177 	addr = kallsyms_lookup_name(func_name);
2178 	if (!addr) {
2179 		verbose(env, "cannot find address for kernel function %s\n",
2180 			func_name);
2181 		return -EINVAL;
2182 	}
2183 
2184 	call_imm = BPF_CALL_IMM(addr);
2185 	/* Check whether or not the relative offset overflows desc->imm */
2186 	if ((unsigned long)(s32)call_imm != call_imm) {
2187 		verbose(env, "address of kernel function %s is out of range\n",
2188 			func_name);
2189 		return -EINVAL;
2190 	}
2191 
2192 	desc = &tab->descs[tab->nr_descs++];
2193 	desc->func_id = func_id;
2194 	desc->imm = call_imm;
2195 	desc->offset = offset;
2196 	err = btf_distill_func_proto(&env->log, desc_btf,
2197 				     func_proto, func_name,
2198 				     &desc->func_model);
2199 	if (!err)
2200 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2201 		     kfunc_desc_cmp_by_id_off, NULL);
2202 	return err;
2203 }
2204 
2205 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2206 {
2207 	const struct bpf_kfunc_desc *d0 = a;
2208 	const struct bpf_kfunc_desc *d1 = b;
2209 
2210 	if (d0->imm > d1->imm)
2211 		return 1;
2212 	else if (d0->imm < d1->imm)
2213 		return -1;
2214 	return 0;
2215 }
2216 
2217 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2218 {
2219 	struct bpf_kfunc_desc_tab *tab;
2220 
2221 	tab = prog->aux->kfunc_tab;
2222 	if (!tab)
2223 		return;
2224 
2225 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2226 	     kfunc_desc_cmp_by_imm, NULL);
2227 }
2228 
2229 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2230 {
2231 	return !!prog->aux->kfunc_tab;
2232 }
2233 
2234 const struct btf_func_model *
2235 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2236 			 const struct bpf_insn *insn)
2237 {
2238 	const struct bpf_kfunc_desc desc = {
2239 		.imm = insn->imm,
2240 	};
2241 	const struct bpf_kfunc_desc *res;
2242 	struct bpf_kfunc_desc_tab *tab;
2243 
2244 	tab = prog->aux->kfunc_tab;
2245 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2246 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2247 
2248 	return res ? &res->func_model : NULL;
2249 }
2250 
2251 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2252 {
2253 	struct bpf_subprog_info *subprog = env->subprog_info;
2254 	struct bpf_insn *insn = env->prog->insnsi;
2255 	int i, ret, insn_cnt = env->prog->len;
2256 
2257 	/* Add entry function. */
2258 	ret = add_subprog(env, 0);
2259 	if (ret)
2260 		return ret;
2261 
2262 	for (i = 0; i < insn_cnt; i++, insn++) {
2263 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2264 		    !bpf_pseudo_kfunc_call(insn))
2265 			continue;
2266 
2267 		if (!env->bpf_capable) {
2268 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2269 			return -EPERM;
2270 		}
2271 
2272 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2273 			ret = add_subprog(env, i + insn->imm + 1);
2274 		else
2275 			ret = add_kfunc_call(env, insn->imm, insn->off);
2276 
2277 		if (ret < 0)
2278 			return ret;
2279 	}
2280 
2281 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2282 	 * logic. 'subprog_cnt' should not be increased.
2283 	 */
2284 	subprog[env->subprog_cnt].start = insn_cnt;
2285 
2286 	if (env->log.level & BPF_LOG_LEVEL2)
2287 		for (i = 0; i < env->subprog_cnt; i++)
2288 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2289 
2290 	return 0;
2291 }
2292 
2293 static int check_subprogs(struct bpf_verifier_env *env)
2294 {
2295 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2296 	struct bpf_subprog_info *subprog = env->subprog_info;
2297 	struct bpf_insn *insn = env->prog->insnsi;
2298 	int insn_cnt = env->prog->len;
2299 
2300 	/* now check that all jumps are within the same subprog */
2301 	subprog_start = subprog[cur_subprog].start;
2302 	subprog_end = subprog[cur_subprog + 1].start;
2303 	for (i = 0; i < insn_cnt; i++) {
2304 		u8 code = insn[i].code;
2305 
2306 		if (code == (BPF_JMP | BPF_CALL) &&
2307 		    insn[i].imm == BPF_FUNC_tail_call &&
2308 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2309 			subprog[cur_subprog].has_tail_call = true;
2310 		if (BPF_CLASS(code) == BPF_LD &&
2311 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2312 			subprog[cur_subprog].has_ld_abs = true;
2313 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2314 			goto next;
2315 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2316 			goto next;
2317 		off = i + insn[i].off + 1;
2318 		if (off < subprog_start || off >= subprog_end) {
2319 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2320 			return -EINVAL;
2321 		}
2322 next:
2323 		if (i == subprog_end - 1) {
2324 			/* to avoid fall-through from one subprog into another
2325 			 * the last insn of the subprog should be either exit
2326 			 * or unconditional jump back
2327 			 */
2328 			if (code != (BPF_JMP | BPF_EXIT) &&
2329 			    code != (BPF_JMP | BPF_JA)) {
2330 				verbose(env, "last insn is not an exit or jmp\n");
2331 				return -EINVAL;
2332 			}
2333 			subprog_start = subprog_end;
2334 			cur_subprog++;
2335 			if (cur_subprog < env->subprog_cnt)
2336 				subprog_end = subprog[cur_subprog + 1].start;
2337 		}
2338 	}
2339 	return 0;
2340 }
2341 
2342 /* Parentage chain of this register (or stack slot) should take care of all
2343  * issues like callee-saved registers, stack slot allocation time, etc.
2344  */
2345 static int mark_reg_read(struct bpf_verifier_env *env,
2346 			 const struct bpf_reg_state *state,
2347 			 struct bpf_reg_state *parent, u8 flag)
2348 {
2349 	bool writes = parent == state->parent; /* Observe write marks */
2350 	int cnt = 0;
2351 
2352 	while (parent) {
2353 		/* if read wasn't screened by an earlier write ... */
2354 		if (writes && state->live & REG_LIVE_WRITTEN)
2355 			break;
2356 		if (parent->live & REG_LIVE_DONE) {
2357 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2358 				reg_type_str(env, parent->type),
2359 				parent->var_off.value, parent->off);
2360 			return -EFAULT;
2361 		}
2362 		/* The first condition is more likely to be true than the
2363 		 * second, checked it first.
2364 		 */
2365 		if ((parent->live & REG_LIVE_READ) == flag ||
2366 		    parent->live & REG_LIVE_READ64)
2367 			/* The parentage chain never changes and
2368 			 * this parent was already marked as LIVE_READ.
2369 			 * There is no need to keep walking the chain again and
2370 			 * keep re-marking all parents as LIVE_READ.
2371 			 * This case happens when the same register is read
2372 			 * multiple times without writes into it in-between.
2373 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2374 			 * then no need to set the weak REG_LIVE_READ32.
2375 			 */
2376 			break;
2377 		/* ... then we depend on parent's value */
2378 		parent->live |= flag;
2379 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2380 		if (flag == REG_LIVE_READ64)
2381 			parent->live &= ~REG_LIVE_READ32;
2382 		state = parent;
2383 		parent = state->parent;
2384 		writes = true;
2385 		cnt++;
2386 	}
2387 
2388 	if (env->longest_mark_read_walk < cnt)
2389 		env->longest_mark_read_walk = cnt;
2390 	return 0;
2391 }
2392 
2393 /* This function is supposed to be used by the following 32-bit optimization
2394  * code only. It returns TRUE if the source or destination register operates
2395  * on 64-bit, otherwise return FALSE.
2396  */
2397 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2398 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2399 {
2400 	u8 code, class, op;
2401 
2402 	code = insn->code;
2403 	class = BPF_CLASS(code);
2404 	op = BPF_OP(code);
2405 	if (class == BPF_JMP) {
2406 		/* BPF_EXIT for "main" will reach here. Return TRUE
2407 		 * conservatively.
2408 		 */
2409 		if (op == BPF_EXIT)
2410 			return true;
2411 		if (op == BPF_CALL) {
2412 			/* BPF to BPF call will reach here because of marking
2413 			 * caller saved clobber with DST_OP_NO_MARK for which we
2414 			 * don't care the register def because they are anyway
2415 			 * marked as NOT_INIT already.
2416 			 */
2417 			if (insn->src_reg == BPF_PSEUDO_CALL)
2418 				return false;
2419 			/* Helper call will reach here because of arg type
2420 			 * check, conservatively return TRUE.
2421 			 */
2422 			if (t == SRC_OP)
2423 				return true;
2424 
2425 			return false;
2426 		}
2427 	}
2428 
2429 	if (class == BPF_ALU64 || class == BPF_JMP ||
2430 	    /* BPF_END always use BPF_ALU class. */
2431 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2432 		return true;
2433 
2434 	if (class == BPF_ALU || class == BPF_JMP32)
2435 		return false;
2436 
2437 	if (class == BPF_LDX) {
2438 		if (t != SRC_OP)
2439 			return BPF_SIZE(code) == BPF_DW;
2440 		/* LDX source must be ptr. */
2441 		return true;
2442 	}
2443 
2444 	if (class == BPF_STX) {
2445 		/* BPF_STX (including atomic variants) has multiple source
2446 		 * operands, one of which is a ptr. Check whether the caller is
2447 		 * asking about it.
2448 		 */
2449 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2450 			return true;
2451 		return BPF_SIZE(code) == BPF_DW;
2452 	}
2453 
2454 	if (class == BPF_LD) {
2455 		u8 mode = BPF_MODE(code);
2456 
2457 		/* LD_IMM64 */
2458 		if (mode == BPF_IMM)
2459 			return true;
2460 
2461 		/* Both LD_IND and LD_ABS return 32-bit data. */
2462 		if (t != SRC_OP)
2463 			return  false;
2464 
2465 		/* Implicit ctx ptr. */
2466 		if (regno == BPF_REG_6)
2467 			return true;
2468 
2469 		/* Explicit source could be any width. */
2470 		return true;
2471 	}
2472 
2473 	if (class == BPF_ST)
2474 		/* The only source register for BPF_ST is a ptr. */
2475 		return true;
2476 
2477 	/* Conservatively return true at default. */
2478 	return true;
2479 }
2480 
2481 /* Return the regno defined by the insn, or -1. */
2482 static int insn_def_regno(const struct bpf_insn *insn)
2483 {
2484 	switch (BPF_CLASS(insn->code)) {
2485 	case BPF_JMP:
2486 	case BPF_JMP32:
2487 	case BPF_ST:
2488 		return -1;
2489 	case BPF_STX:
2490 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2491 		    (insn->imm & BPF_FETCH)) {
2492 			if (insn->imm == BPF_CMPXCHG)
2493 				return BPF_REG_0;
2494 			else
2495 				return insn->src_reg;
2496 		} else {
2497 			return -1;
2498 		}
2499 	default:
2500 		return insn->dst_reg;
2501 	}
2502 }
2503 
2504 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2505 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2506 {
2507 	int dst_reg = insn_def_regno(insn);
2508 
2509 	if (dst_reg == -1)
2510 		return false;
2511 
2512 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2513 }
2514 
2515 static void mark_insn_zext(struct bpf_verifier_env *env,
2516 			   struct bpf_reg_state *reg)
2517 {
2518 	s32 def_idx = reg->subreg_def;
2519 
2520 	if (def_idx == DEF_NOT_SUBREG)
2521 		return;
2522 
2523 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2524 	/* The dst will be zero extended, so won't be sub-register anymore. */
2525 	reg->subreg_def = DEF_NOT_SUBREG;
2526 }
2527 
2528 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2529 			 enum reg_arg_type t)
2530 {
2531 	struct bpf_verifier_state *vstate = env->cur_state;
2532 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2533 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2534 	struct bpf_reg_state *reg, *regs = state->regs;
2535 	bool rw64;
2536 
2537 	if (regno >= MAX_BPF_REG) {
2538 		verbose(env, "R%d is invalid\n", regno);
2539 		return -EINVAL;
2540 	}
2541 
2542 	mark_reg_scratched(env, regno);
2543 
2544 	reg = &regs[regno];
2545 	rw64 = is_reg64(env, insn, regno, reg, t);
2546 	if (t == SRC_OP) {
2547 		/* check whether register used as source operand can be read */
2548 		if (reg->type == NOT_INIT) {
2549 			verbose(env, "R%d !read_ok\n", regno);
2550 			return -EACCES;
2551 		}
2552 		/* We don't need to worry about FP liveness because it's read-only */
2553 		if (regno == BPF_REG_FP)
2554 			return 0;
2555 
2556 		if (rw64)
2557 			mark_insn_zext(env, reg);
2558 
2559 		return mark_reg_read(env, reg, reg->parent,
2560 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2561 	} else {
2562 		/* check whether register used as dest operand can be written to */
2563 		if (regno == BPF_REG_FP) {
2564 			verbose(env, "frame pointer is read only\n");
2565 			return -EACCES;
2566 		}
2567 		reg->live |= REG_LIVE_WRITTEN;
2568 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2569 		if (t == DST_OP)
2570 			mark_reg_unknown(env, regs, regno);
2571 	}
2572 	return 0;
2573 }
2574 
2575 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2576 {
2577 	env->insn_aux_data[idx].jmp_point = true;
2578 }
2579 
2580 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2581 {
2582 	return env->insn_aux_data[insn_idx].jmp_point;
2583 }
2584 
2585 /* for any branch, call, exit record the history of jmps in the given state */
2586 static int push_jmp_history(struct bpf_verifier_env *env,
2587 			    struct bpf_verifier_state *cur)
2588 {
2589 	u32 cnt = cur->jmp_history_cnt;
2590 	struct bpf_idx_pair *p;
2591 	size_t alloc_size;
2592 
2593 	if (!is_jmp_point(env, env->insn_idx))
2594 		return 0;
2595 
2596 	cnt++;
2597 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2598 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2599 	if (!p)
2600 		return -ENOMEM;
2601 	p[cnt - 1].idx = env->insn_idx;
2602 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2603 	cur->jmp_history = p;
2604 	cur->jmp_history_cnt = cnt;
2605 	return 0;
2606 }
2607 
2608 /* Backtrack one insn at a time. If idx is not at the top of recorded
2609  * history then previous instruction came from straight line execution.
2610  */
2611 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2612 			     u32 *history)
2613 {
2614 	u32 cnt = *history;
2615 
2616 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2617 		i = st->jmp_history[cnt - 1].prev_idx;
2618 		(*history)--;
2619 	} else {
2620 		i--;
2621 	}
2622 	return i;
2623 }
2624 
2625 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2626 {
2627 	const struct btf_type *func;
2628 	struct btf *desc_btf;
2629 
2630 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2631 		return NULL;
2632 
2633 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2634 	if (IS_ERR(desc_btf))
2635 		return "<error>";
2636 
2637 	func = btf_type_by_id(desc_btf, insn->imm);
2638 	return btf_name_by_offset(desc_btf, func->name_off);
2639 }
2640 
2641 /* For given verifier state backtrack_insn() is called from the last insn to
2642  * the first insn. Its purpose is to compute a bitmask of registers and
2643  * stack slots that needs precision in the parent verifier state.
2644  */
2645 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2646 			  u32 *reg_mask, u64 *stack_mask)
2647 {
2648 	const struct bpf_insn_cbs cbs = {
2649 		.cb_call	= disasm_kfunc_name,
2650 		.cb_print	= verbose,
2651 		.private_data	= env,
2652 	};
2653 	struct bpf_insn *insn = env->prog->insnsi + idx;
2654 	u8 class = BPF_CLASS(insn->code);
2655 	u8 opcode = BPF_OP(insn->code);
2656 	u8 mode = BPF_MODE(insn->code);
2657 	u32 dreg = 1u << insn->dst_reg;
2658 	u32 sreg = 1u << insn->src_reg;
2659 	u32 spi;
2660 
2661 	if (insn->code == 0)
2662 		return 0;
2663 	if (env->log.level & BPF_LOG_LEVEL2) {
2664 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2665 		verbose(env, "%d: ", idx);
2666 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2667 	}
2668 
2669 	if (class == BPF_ALU || class == BPF_ALU64) {
2670 		if (!(*reg_mask & dreg))
2671 			return 0;
2672 		if (opcode == BPF_MOV) {
2673 			if (BPF_SRC(insn->code) == BPF_X) {
2674 				/* dreg = sreg
2675 				 * dreg needs precision after this insn
2676 				 * sreg needs precision before this insn
2677 				 */
2678 				*reg_mask &= ~dreg;
2679 				*reg_mask |= sreg;
2680 			} else {
2681 				/* dreg = K
2682 				 * dreg needs precision after this insn.
2683 				 * Corresponding register is already marked
2684 				 * as precise=true in this verifier state.
2685 				 * No further markings in parent are necessary
2686 				 */
2687 				*reg_mask &= ~dreg;
2688 			}
2689 		} else {
2690 			if (BPF_SRC(insn->code) == BPF_X) {
2691 				/* dreg += sreg
2692 				 * both dreg and sreg need precision
2693 				 * before this insn
2694 				 */
2695 				*reg_mask |= sreg;
2696 			} /* else dreg += K
2697 			   * dreg still needs precision before this insn
2698 			   */
2699 		}
2700 	} else if (class == BPF_LDX) {
2701 		if (!(*reg_mask & dreg))
2702 			return 0;
2703 		*reg_mask &= ~dreg;
2704 
2705 		/* scalars can only be spilled into stack w/o losing precision.
2706 		 * Load from any other memory can be zero extended.
2707 		 * The desire to keep that precision is already indicated
2708 		 * by 'precise' mark in corresponding register of this state.
2709 		 * No further tracking necessary.
2710 		 */
2711 		if (insn->src_reg != BPF_REG_FP)
2712 			return 0;
2713 
2714 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2715 		 * that [fp - off] slot contains scalar that needs to be
2716 		 * tracked with precision
2717 		 */
2718 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2719 		if (spi >= 64) {
2720 			verbose(env, "BUG spi %d\n", spi);
2721 			WARN_ONCE(1, "verifier backtracking bug");
2722 			return -EFAULT;
2723 		}
2724 		*stack_mask |= 1ull << spi;
2725 	} else if (class == BPF_STX || class == BPF_ST) {
2726 		if (*reg_mask & dreg)
2727 			/* stx & st shouldn't be using _scalar_ dst_reg
2728 			 * to access memory. It means backtracking
2729 			 * encountered a case of pointer subtraction.
2730 			 */
2731 			return -ENOTSUPP;
2732 		/* scalars can only be spilled into stack */
2733 		if (insn->dst_reg != BPF_REG_FP)
2734 			return 0;
2735 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2736 		if (spi >= 64) {
2737 			verbose(env, "BUG spi %d\n", spi);
2738 			WARN_ONCE(1, "verifier backtracking bug");
2739 			return -EFAULT;
2740 		}
2741 		if (!(*stack_mask & (1ull << spi)))
2742 			return 0;
2743 		*stack_mask &= ~(1ull << spi);
2744 		if (class == BPF_STX)
2745 			*reg_mask |= sreg;
2746 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2747 		if (opcode == BPF_CALL) {
2748 			if (insn->src_reg == BPF_PSEUDO_CALL)
2749 				return -ENOTSUPP;
2750 			/* BPF helpers that invoke callback subprogs are
2751 			 * equivalent to BPF_PSEUDO_CALL above
2752 			 */
2753 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2754 				return -ENOTSUPP;
2755 			/* regular helper call sets R0 */
2756 			*reg_mask &= ~1;
2757 			if (*reg_mask & 0x3f) {
2758 				/* if backtracing was looking for registers R1-R5
2759 				 * they should have been found already.
2760 				 */
2761 				verbose(env, "BUG regs %x\n", *reg_mask);
2762 				WARN_ONCE(1, "verifier backtracking bug");
2763 				return -EFAULT;
2764 			}
2765 		} else if (opcode == BPF_EXIT) {
2766 			return -ENOTSUPP;
2767 		}
2768 	} else if (class == BPF_LD) {
2769 		if (!(*reg_mask & dreg))
2770 			return 0;
2771 		*reg_mask &= ~dreg;
2772 		/* It's ld_imm64 or ld_abs or ld_ind.
2773 		 * For ld_imm64 no further tracking of precision
2774 		 * into parent is necessary
2775 		 */
2776 		if (mode == BPF_IND || mode == BPF_ABS)
2777 			/* to be analyzed */
2778 			return -ENOTSUPP;
2779 	}
2780 	return 0;
2781 }
2782 
2783 /* the scalar precision tracking algorithm:
2784  * . at the start all registers have precise=false.
2785  * . scalar ranges are tracked as normal through alu and jmp insns.
2786  * . once precise value of the scalar register is used in:
2787  *   .  ptr + scalar alu
2788  *   . if (scalar cond K|scalar)
2789  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2790  *   backtrack through the verifier states and mark all registers and
2791  *   stack slots with spilled constants that these scalar regisers
2792  *   should be precise.
2793  * . during state pruning two registers (or spilled stack slots)
2794  *   are equivalent if both are not precise.
2795  *
2796  * Note the verifier cannot simply walk register parentage chain,
2797  * since many different registers and stack slots could have been
2798  * used to compute single precise scalar.
2799  *
2800  * The approach of starting with precise=true for all registers and then
2801  * backtrack to mark a register as not precise when the verifier detects
2802  * that program doesn't care about specific value (e.g., when helper
2803  * takes register as ARG_ANYTHING parameter) is not safe.
2804  *
2805  * It's ok to walk single parentage chain of the verifier states.
2806  * It's possible that this backtracking will go all the way till 1st insn.
2807  * All other branches will be explored for needing precision later.
2808  *
2809  * The backtracking needs to deal with cases like:
2810  *   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)
2811  * r9 -= r8
2812  * r5 = r9
2813  * if r5 > 0x79f goto pc+7
2814  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2815  * r5 += 1
2816  * ...
2817  * call bpf_perf_event_output#25
2818  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2819  *
2820  * and this case:
2821  * r6 = 1
2822  * call foo // uses callee's r6 inside to compute r0
2823  * r0 += r6
2824  * if r0 == 0 goto
2825  *
2826  * to track above reg_mask/stack_mask needs to be independent for each frame.
2827  *
2828  * Also if parent's curframe > frame where backtracking started,
2829  * the verifier need to mark registers in both frames, otherwise callees
2830  * may incorrectly prune callers. This is similar to
2831  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2832  *
2833  * For now backtracking falls back into conservative marking.
2834  */
2835 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2836 				     struct bpf_verifier_state *st)
2837 {
2838 	struct bpf_func_state *func;
2839 	struct bpf_reg_state *reg;
2840 	int i, j;
2841 
2842 	/* big hammer: mark all scalars precise in this path.
2843 	 * pop_stack may still get !precise scalars.
2844 	 * We also skip current state and go straight to first parent state,
2845 	 * because precision markings in current non-checkpointed state are
2846 	 * not needed. See why in the comment in __mark_chain_precision below.
2847 	 */
2848 	for (st = st->parent; st; st = st->parent) {
2849 		for (i = 0; i <= st->curframe; i++) {
2850 			func = st->frame[i];
2851 			for (j = 0; j < BPF_REG_FP; j++) {
2852 				reg = &func->regs[j];
2853 				if (reg->type != SCALAR_VALUE)
2854 					continue;
2855 				reg->precise = true;
2856 			}
2857 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2858 				if (!is_spilled_reg(&func->stack[j]))
2859 					continue;
2860 				reg = &func->stack[j].spilled_ptr;
2861 				if (reg->type != SCALAR_VALUE)
2862 					continue;
2863 				reg->precise = true;
2864 			}
2865 		}
2866 	}
2867 }
2868 
2869 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2870 {
2871 	struct bpf_func_state *func;
2872 	struct bpf_reg_state *reg;
2873 	int i, j;
2874 
2875 	for (i = 0; i <= st->curframe; i++) {
2876 		func = st->frame[i];
2877 		for (j = 0; j < BPF_REG_FP; j++) {
2878 			reg = &func->regs[j];
2879 			if (reg->type != SCALAR_VALUE)
2880 				continue;
2881 			reg->precise = false;
2882 		}
2883 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2884 			if (!is_spilled_reg(&func->stack[j]))
2885 				continue;
2886 			reg = &func->stack[j].spilled_ptr;
2887 			if (reg->type != SCALAR_VALUE)
2888 				continue;
2889 			reg->precise = false;
2890 		}
2891 	}
2892 }
2893 
2894 /*
2895  * __mark_chain_precision() backtracks BPF program instruction sequence and
2896  * chain of verifier states making sure that register *regno* (if regno >= 0)
2897  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2898  * SCALARS, as well as any other registers and slots that contribute to
2899  * a tracked state of given registers/stack slots, depending on specific BPF
2900  * assembly instructions (see backtrack_insns() for exact instruction handling
2901  * logic). This backtracking relies on recorded jmp_history and is able to
2902  * traverse entire chain of parent states. This process ends only when all the
2903  * necessary registers/slots and their transitive dependencies are marked as
2904  * precise.
2905  *
2906  * One important and subtle aspect is that precise marks *do not matter* in
2907  * the currently verified state (current state). It is important to understand
2908  * why this is the case.
2909  *
2910  * First, note that current state is the state that is not yet "checkpointed",
2911  * i.e., it is not yet put into env->explored_states, and it has no children
2912  * states as well. It's ephemeral, and can end up either a) being discarded if
2913  * compatible explored state is found at some point or BPF_EXIT instruction is
2914  * reached or b) checkpointed and put into env->explored_states, branching out
2915  * into one or more children states.
2916  *
2917  * In the former case, precise markings in current state are completely
2918  * ignored by state comparison code (see regsafe() for details). Only
2919  * checkpointed ("old") state precise markings are important, and if old
2920  * state's register/slot is precise, regsafe() assumes current state's
2921  * register/slot as precise and checks value ranges exactly and precisely. If
2922  * states turn out to be compatible, current state's necessary precise
2923  * markings and any required parent states' precise markings are enforced
2924  * after the fact with propagate_precision() logic, after the fact. But it's
2925  * important to realize that in this case, even after marking current state
2926  * registers/slots as precise, we immediately discard current state. So what
2927  * actually matters is any of the precise markings propagated into current
2928  * state's parent states, which are always checkpointed (due to b) case above).
2929  * As such, for scenario a) it doesn't matter if current state has precise
2930  * markings set or not.
2931  *
2932  * Now, for the scenario b), checkpointing and forking into child(ren)
2933  * state(s). Note that before current state gets to checkpointing step, any
2934  * processed instruction always assumes precise SCALAR register/slot
2935  * knowledge: if precise value or range is useful to prune jump branch, BPF
2936  * verifier takes this opportunity enthusiastically. Similarly, when
2937  * register's value is used to calculate offset or memory address, exact
2938  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2939  * what we mentioned above about state comparison ignoring precise markings
2940  * during state comparison, BPF verifier ignores and also assumes precise
2941  * markings *at will* during instruction verification process. But as verifier
2942  * assumes precision, it also propagates any precision dependencies across
2943  * parent states, which are not yet finalized, so can be further restricted
2944  * based on new knowledge gained from restrictions enforced by their children
2945  * states. This is so that once those parent states are finalized, i.e., when
2946  * they have no more active children state, state comparison logic in
2947  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2948  * required for correctness.
2949  *
2950  * To build a bit more intuition, note also that once a state is checkpointed,
2951  * the path we took to get to that state is not important. This is crucial
2952  * property for state pruning. When state is checkpointed and finalized at
2953  * some instruction index, it can be correctly and safely used to "short
2954  * circuit" any *compatible* state that reaches exactly the same instruction
2955  * index. I.e., if we jumped to that instruction from a completely different
2956  * code path than original finalized state was derived from, it doesn't
2957  * matter, current state can be discarded because from that instruction
2958  * forward having a compatible state will ensure we will safely reach the
2959  * exit. States describe preconditions for further exploration, but completely
2960  * forget the history of how we got here.
2961  *
2962  * This also means that even if we needed precise SCALAR range to get to
2963  * finalized state, but from that point forward *that same* SCALAR register is
2964  * never used in a precise context (i.e., it's precise value is not needed for
2965  * correctness), it's correct and safe to mark such register as "imprecise"
2966  * (i.e., precise marking set to false). This is what we rely on when we do
2967  * not set precise marking in current state. If no child state requires
2968  * precision for any given SCALAR register, it's safe to dictate that it can
2969  * be imprecise. If any child state does require this register to be precise,
2970  * we'll mark it precise later retroactively during precise markings
2971  * propagation from child state to parent states.
2972  *
2973  * Skipping precise marking setting in current state is a mild version of
2974  * relying on the above observation. But we can utilize this property even
2975  * more aggressively by proactively forgetting any precise marking in the
2976  * current state (which we inherited from the parent state), right before we
2977  * checkpoint it and branch off into new child state. This is done by
2978  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2979  * finalized states which help in short circuiting more future states.
2980  */
2981 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2982 				  int spi)
2983 {
2984 	struct bpf_verifier_state *st = env->cur_state;
2985 	int first_idx = st->first_insn_idx;
2986 	int last_idx = env->insn_idx;
2987 	struct bpf_func_state *func;
2988 	struct bpf_reg_state *reg;
2989 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2990 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2991 	bool skip_first = true;
2992 	bool new_marks = false;
2993 	int i, err;
2994 
2995 	if (!env->bpf_capable)
2996 		return 0;
2997 
2998 	/* Do sanity checks against current state of register and/or stack
2999 	 * slot, but don't set precise flag in current state, as precision
3000 	 * tracking in the current state is unnecessary.
3001 	 */
3002 	func = st->frame[frame];
3003 	if (regno >= 0) {
3004 		reg = &func->regs[regno];
3005 		if (reg->type != SCALAR_VALUE) {
3006 			WARN_ONCE(1, "backtracing misuse");
3007 			return -EFAULT;
3008 		}
3009 		new_marks = true;
3010 	}
3011 
3012 	while (spi >= 0) {
3013 		if (!is_spilled_reg(&func->stack[spi])) {
3014 			stack_mask = 0;
3015 			break;
3016 		}
3017 		reg = &func->stack[spi].spilled_ptr;
3018 		if (reg->type != SCALAR_VALUE) {
3019 			stack_mask = 0;
3020 			break;
3021 		}
3022 		new_marks = true;
3023 		break;
3024 	}
3025 
3026 	if (!new_marks)
3027 		return 0;
3028 	if (!reg_mask && !stack_mask)
3029 		return 0;
3030 
3031 	for (;;) {
3032 		DECLARE_BITMAP(mask, 64);
3033 		u32 history = st->jmp_history_cnt;
3034 
3035 		if (env->log.level & BPF_LOG_LEVEL2)
3036 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3037 
3038 		if (last_idx < 0) {
3039 			/* we are at the entry into subprog, which
3040 			 * is expected for global funcs, but only if
3041 			 * requested precise registers are R1-R5
3042 			 * (which are global func's input arguments)
3043 			 */
3044 			if (st->curframe == 0 &&
3045 			    st->frame[0]->subprogno > 0 &&
3046 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3047 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3048 				bitmap_from_u64(mask, reg_mask);
3049 				for_each_set_bit(i, mask, 32) {
3050 					reg = &st->frame[0]->regs[i];
3051 					if (reg->type != SCALAR_VALUE) {
3052 						reg_mask &= ~(1u << i);
3053 						continue;
3054 					}
3055 					reg->precise = true;
3056 				}
3057 				return 0;
3058 			}
3059 
3060 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3061 				st->frame[0]->subprogno, reg_mask, stack_mask);
3062 			WARN_ONCE(1, "verifier backtracking bug");
3063 			return -EFAULT;
3064 		}
3065 
3066 		for (i = last_idx;;) {
3067 			if (skip_first) {
3068 				err = 0;
3069 				skip_first = false;
3070 			} else {
3071 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3072 			}
3073 			if (err == -ENOTSUPP) {
3074 				mark_all_scalars_precise(env, st);
3075 				return 0;
3076 			} else if (err) {
3077 				return err;
3078 			}
3079 			if (!reg_mask && !stack_mask)
3080 				/* Found assignment(s) into tracked register in this state.
3081 				 * Since this state is already marked, just return.
3082 				 * Nothing to be tracked further in the parent state.
3083 				 */
3084 				return 0;
3085 			if (i == first_idx)
3086 				break;
3087 			i = get_prev_insn_idx(st, i, &history);
3088 			if (i >= env->prog->len) {
3089 				/* This can happen if backtracking reached insn 0
3090 				 * and there are still reg_mask or stack_mask
3091 				 * to backtrack.
3092 				 * It means the backtracking missed the spot where
3093 				 * particular register was initialized with a constant.
3094 				 */
3095 				verbose(env, "BUG backtracking idx %d\n", i);
3096 				WARN_ONCE(1, "verifier backtracking bug");
3097 				return -EFAULT;
3098 			}
3099 		}
3100 		st = st->parent;
3101 		if (!st)
3102 			break;
3103 
3104 		new_marks = false;
3105 		func = st->frame[frame];
3106 		bitmap_from_u64(mask, reg_mask);
3107 		for_each_set_bit(i, mask, 32) {
3108 			reg = &func->regs[i];
3109 			if (reg->type != SCALAR_VALUE) {
3110 				reg_mask &= ~(1u << i);
3111 				continue;
3112 			}
3113 			if (!reg->precise)
3114 				new_marks = true;
3115 			reg->precise = true;
3116 		}
3117 
3118 		bitmap_from_u64(mask, stack_mask);
3119 		for_each_set_bit(i, mask, 64) {
3120 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3121 				/* the sequence of instructions:
3122 				 * 2: (bf) r3 = r10
3123 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3124 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3125 				 * doesn't contain jmps. It's backtracked
3126 				 * as a single block.
3127 				 * During backtracking insn 3 is not recognized as
3128 				 * stack access, so at the end of backtracking
3129 				 * stack slot fp-8 is still marked in stack_mask.
3130 				 * However the parent state may not have accessed
3131 				 * fp-8 and it's "unallocated" stack space.
3132 				 * In such case fallback to conservative.
3133 				 */
3134 				mark_all_scalars_precise(env, st);
3135 				return 0;
3136 			}
3137 
3138 			if (!is_spilled_reg(&func->stack[i])) {
3139 				stack_mask &= ~(1ull << i);
3140 				continue;
3141 			}
3142 			reg = &func->stack[i].spilled_ptr;
3143 			if (reg->type != SCALAR_VALUE) {
3144 				stack_mask &= ~(1ull << i);
3145 				continue;
3146 			}
3147 			if (!reg->precise)
3148 				new_marks = true;
3149 			reg->precise = true;
3150 		}
3151 		if (env->log.level & BPF_LOG_LEVEL2) {
3152 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3153 				new_marks ? "didn't have" : "already had",
3154 				reg_mask, stack_mask);
3155 			print_verifier_state(env, func, true);
3156 		}
3157 
3158 		if (!reg_mask && !stack_mask)
3159 			break;
3160 		if (!new_marks)
3161 			break;
3162 
3163 		last_idx = st->last_insn_idx;
3164 		first_idx = st->first_insn_idx;
3165 	}
3166 	return 0;
3167 }
3168 
3169 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3170 {
3171 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3172 }
3173 
3174 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3175 {
3176 	return __mark_chain_precision(env, frame, regno, -1);
3177 }
3178 
3179 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3180 {
3181 	return __mark_chain_precision(env, frame, -1, spi);
3182 }
3183 
3184 static bool is_spillable_regtype(enum bpf_reg_type type)
3185 {
3186 	switch (base_type(type)) {
3187 	case PTR_TO_MAP_VALUE:
3188 	case PTR_TO_STACK:
3189 	case PTR_TO_CTX:
3190 	case PTR_TO_PACKET:
3191 	case PTR_TO_PACKET_META:
3192 	case PTR_TO_PACKET_END:
3193 	case PTR_TO_FLOW_KEYS:
3194 	case CONST_PTR_TO_MAP:
3195 	case PTR_TO_SOCKET:
3196 	case PTR_TO_SOCK_COMMON:
3197 	case PTR_TO_TCP_SOCK:
3198 	case PTR_TO_XDP_SOCK:
3199 	case PTR_TO_BTF_ID:
3200 	case PTR_TO_BUF:
3201 	case PTR_TO_MEM:
3202 	case PTR_TO_FUNC:
3203 	case PTR_TO_MAP_KEY:
3204 		return true;
3205 	default:
3206 		return false;
3207 	}
3208 }
3209 
3210 /* Does this register contain a constant zero? */
3211 static bool register_is_null(struct bpf_reg_state *reg)
3212 {
3213 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3214 }
3215 
3216 static bool register_is_const(struct bpf_reg_state *reg)
3217 {
3218 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3219 }
3220 
3221 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3222 {
3223 	return tnum_is_unknown(reg->var_off) &&
3224 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3225 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3226 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3227 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3228 }
3229 
3230 static bool register_is_bounded(struct bpf_reg_state *reg)
3231 {
3232 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3233 }
3234 
3235 static bool __is_pointer_value(bool allow_ptr_leaks,
3236 			       const struct bpf_reg_state *reg)
3237 {
3238 	if (allow_ptr_leaks)
3239 		return false;
3240 
3241 	return reg->type != SCALAR_VALUE;
3242 }
3243 
3244 static void save_register_state(struct bpf_func_state *state,
3245 				int spi, struct bpf_reg_state *reg,
3246 				int size)
3247 {
3248 	int i;
3249 
3250 	state->stack[spi].spilled_ptr = *reg;
3251 	if (size == BPF_REG_SIZE)
3252 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3253 
3254 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3255 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3256 
3257 	/* size < 8 bytes spill */
3258 	for (; i; i--)
3259 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3260 }
3261 
3262 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3263  * stack boundary and alignment are checked in check_mem_access()
3264  */
3265 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3266 				       /* stack frame we're writing to */
3267 				       struct bpf_func_state *state,
3268 				       int off, int size, int value_regno,
3269 				       int insn_idx)
3270 {
3271 	struct bpf_func_state *cur; /* state of the current function */
3272 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3273 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3274 	struct bpf_reg_state *reg = NULL;
3275 
3276 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3277 	if (err)
3278 		return err;
3279 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3280 	 * so it's aligned access and [off, off + size) are within stack limits
3281 	 */
3282 	if (!env->allow_ptr_leaks &&
3283 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3284 	    size != BPF_REG_SIZE) {
3285 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3286 		return -EACCES;
3287 	}
3288 
3289 	cur = env->cur_state->frame[env->cur_state->curframe];
3290 	if (value_regno >= 0)
3291 		reg = &cur->regs[value_regno];
3292 	if (!env->bypass_spec_v4) {
3293 		bool sanitize = reg && is_spillable_regtype(reg->type);
3294 
3295 		for (i = 0; i < size; i++) {
3296 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3297 				sanitize = true;
3298 				break;
3299 			}
3300 		}
3301 
3302 		if (sanitize)
3303 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3304 	}
3305 
3306 	mark_stack_slot_scratched(env, spi);
3307 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3308 	    !register_is_null(reg) && env->bpf_capable) {
3309 		if (dst_reg != BPF_REG_FP) {
3310 			/* The backtracking logic can only recognize explicit
3311 			 * stack slot address like [fp - 8]. Other spill of
3312 			 * scalar via different register has to be conservative.
3313 			 * Backtrack from here and mark all registers as precise
3314 			 * that contributed into 'reg' being a constant.
3315 			 */
3316 			err = mark_chain_precision(env, value_regno);
3317 			if (err)
3318 				return err;
3319 		}
3320 		save_register_state(state, spi, reg, size);
3321 	} else if (reg && is_spillable_regtype(reg->type)) {
3322 		/* register containing pointer is being spilled into stack */
3323 		if (size != BPF_REG_SIZE) {
3324 			verbose_linfo(env, insn_idx, "; ");
3325 			verbose(env, "invalid size of register spill\n");
3326 			return -EACCES;
3327 		}
3328 		if (state != cur && reg->type == PTR_TO_STACK) {
3329 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3330 			return -EINVAL;
3331 		}
3332 		save_register_state(state, spi, reg, size);
3333 	} else {
3334 		u8 type = STACK_MISC;
3335 
3336 		/* regular write of data into stack destroys any spilled ptr */
3337 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3338 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3339 		if (is_spilled_reg(&state->stack[spi]))
3340 			for (i = 0; i < BPF_REG_SIZE; i++)
3341 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3342 
3343 		/* only mark the slot as written if all 8 bytes were written
3344 		 * otherwise read propagation may incorrectly stop too soon
3345 		 * when stack slots are partially written.
3346 		 * This heuristic means that read propagation will be
3347 		 * conservative, since it will add reg_live_read marks
3348 		 * to stack slots all the way to first state when programs
3349 		 * writes+reads less than 8 bytes
3350 		 */
3351 		if (size == BPF_REG_SIZE)
3352 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3353 
3354 		/* when we zero initialize stack slots mark them as such */
3355 		if (reg && register_is_null(reg)) {
3356 			/* backtracking doesn't work for STACK_ZERO yet. */
3357 			err = mark_chain_precision(env, value_regno);
3358 			if (err)
3359 				return err;
3360 			type = STACK_ZERO;
3361 		}
3362 
3363 		/* Mark slots affected by this stack write. */
3364 		for (i = 0; i < size; i++)
3365 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3366 				type;
3367 	}
3368 	return 0;
3369 }
3370 
3371 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3372  * known to contain a variable offset.
3373  * This function checks whether the write is permitted and conservatively
3374  * tracks the effects of the write, considering that each stack slot in the
3375  * dynamic range is potentially written to.
3376  *
3377  * 'off' includes 'regno->off'.
3378  * 'value_regno' can be -1, meaning that an unknown value is being written to
3379  * the stack.
3380  *
3381  * Spilled pointers in range are not marked as written because we don't know
3382  * what's going to be actually written. This means that read propagation for
3383  * future reads cannot be terminated by this write.
3384  *
3385  * For privileged programs, uninitialized stack slots are considered
3386  * initialized by this write (even though we don't know exactly what offsets
3387  * are going to be written to). The idea is that we don't want the verifier to
3388  * reject future reads that access slots written to through variable offsets.
3389  */
3390 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3391 				     /* func where register points to */
3392 				     struct bpf_func_state *state,
3393 				     int ptr_regno, int off, int size,
3394 				     int value_regno, int insn_idx)
3395 {
3396 	struct bpf_func_state *cur; /* state of the current function */
3397 	int min_off, max_off;
3398 	int i, err;
3399 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3400 	bool writing_zero = false;
3401 	/* set if the fact that we're writing a zero is used to let any
3402 	 * stack slots remain STACK_ZERO
3403 	 */
3404 	bool zero_used = false;
3405 
3406 	cur = env->cur_state->frame[env->cur_state->curframe];
3407 	ptr_reg = &cur->regs[ptr_regno];
3408 	min_off = ptr_reg->smin_value + off;
3409 	max_off = ptr_reg->smax_value + off + size;
3410 	if (value_regno >= 0)
3411 		value_reg = &cur->regs[value_regno];
3412 	if (value_reg && register_is_null(value_reg))
3413 		writing_zero = true;
3414 
3415 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3416 	if (err)
3417 		return err;
3418 
3419 
3420 	/* Variable offset writes destroy any spilled pointers in range. */
3421 	for (i = min_off; i < max_off; i++) {
3422 		u8 new_type, *stype;
3423 		int slot, spi;
3424 
3425 		slot = -i - 1;
3426 		spi = slot / BPF_REG_SIZE;
3427 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3428 		mark_stack_slot_scratched(env, spi);
3429 
3430 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3431 			/* Reject the write if range we may write to has not
3432 			 * been initialized beforehand. If we didn't reject
3433 			 * here, the ptr status would be erased below (even
3434 			 * though not all slots are actually overwritten),
3435 			 * possibly opening the door to leaks.
3436 			 *
3437 			 * We do however catch STACK_INVALID case below, and
3438 			 * only allow reading possibly uninitialized memory
3439 			 * later for CAP_PERFMON, as the write may not happen to
3440 			 * that slot.
3441 			 */
3442 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3443 				insn_idx, i);
3444 			return -EINVAL;
3445 		}
3446 
3447 		/* Erase all spilled pointers. */
3448 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3449 
3450 		/* Update the slot type. */
3451 		new_type = STACK_MISC;
3452 		if (writing_zero && *stype == STACK_ZERO) {
3453 			new_type = STACK_ZERO;
3454 			zero_used = true;
3455 		}
3456 		/* If the slot is STACK_INVALID, we check whether it's OK to
3457 		 * pretend that it will be initialized by this write. The slot
3458 		 * might not actually be written to, and so if we mark it as
3459 		 * initialized future reads might leak uninitialized memory.
3460 		 * For privileged programs, we will accept such reads to slots
3461 		 * that may or may not be written because, if we're reject
3462 		 * them, the error would be too confusing.
3463 		 */
3464 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3465 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3466 					insn_idx, i);
3467 			return -EINVAL;
3468 		}
3469 		*stype = new_type;
3470 	}
3471 	if (zero_used) {
3472 		/* backtracking doesn't work for STACK_ZERO yet. */
3473 		err = mark_chain_precision(env, value_regno);
3474 		if (err)
3475 			return err;
3476 	}
3477 	return 0;
3478 }
3479 
3480 /* When register 'dst_regno' is assigned some values from stack[min_off,
3481  * max_off), we set the register's type according to the types of the
3482  * respective stack slots. If all the stack values are known to be zeros, then
3483  * so is the destination reg. Otherwise, the register is considered to be
3484  * SCALAR. This function does not deal with register filling; the caller must
3485  * ensure that all spilled registers in the stack range have been marked as
3486  * read.
3487  */
3488 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3489 				/* func where src register points to */
3490 				struct bpf_func_state *ptr_state,
3491 				int min_off, int max_off, int dst_regno)
3492 {
3493 	struct bpf_verifier_state *vstate = env->cur_state;
3494 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3495 	int i, slot, spi;
3496 	u8 *stype;
3497 	int zeros = 0;
3498 
3499 	for (i = min_off; i < max_off; i++) {
3500 		slot = -i - 1;
3501 		spi = slot / BPF_REG_SIZE;
3502 		stype = ptr_state->stack[spi].slot_type;
3503 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3504 			break;
3505 		zeros++;
3506 	}
3507 	if (zeros == max_off - min_off) {
3508 		/* any access_size read into register is zero extended,
3509 		 * so the whole register == const_zero
3510 		 */
3511 		__mark_reg_const_zero(&state->regs[dst_regno]);
3512 		/* backtracking doesn't support STACK_ZERO yet,
3513 		 * so mark it precise here, so that later
3514 		 * backtracking can stop here.
3515 		 * Backtracking may not need this if this register
3516 		 * doesn't participate in pointer adjustment.
3517 		 * Forward propagation of precise flag is not
3518 		 * necessary either. This mark is only to stop
3519 		 * backtracking. Any register that contributed
3520 		 * to const 0 was marked precise before spill.
3521 		 */
3522 		state->regs[dst_regno].precise = true;
3523 	} else {
3524 		/* have read misc data from the stack */
3525 		mark_reg_unknown(env, state->regs, dst_regno);
3526 	}
3527 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3528 }
3529 
3530 /* Read the stack at 'off' and put the results into the register indicated by
3531  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3532  * spilled reg.
3533  *
3534  * 'dst_regno' can be -1, meaning that the read value is not going to a
3535  * register.
3536  *
3537  * The access is assumed to be within the current stack bounds.
3538  */
3539 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3540 				      /* func where src register points to */
3541 				      struct bpf_func_state *reg_state,
3542 				      int off, int size, int dst_regno)
3543 {
3544 	struct bpf_verifier_state *vstate = env->cur_state;
3545 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3546 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3547 	struct bpf_reg_state *reg;
3548 	u8 *stype, type;
3549 
3550 	stype = reg_state->stack[spi].slot_type;
3551 	reg = &reg_state->stack[spi].spilled_ptr;
3552 
3553 	if (is_spilled_reg(&reg_state->stack[spi])) {
3554 		u8 spill_size = 1;
3555 
3556 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3557 			spill_size++;
3558 
3559 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3560 			if (reg->type != SCALAR_VALUE) {
3561 				verbose_linfo(env, env->insn_idx, "; ");
3562 				verbose(env, "invalid size of register fill\n");
3563 				return -EACCES;
3564 			}
3565 
3566 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3567 			if (dst_regno < 0)
3568 				return 0;
3569 
3570 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3571 				/* The earlier check_reg_arg() has decided the
3572 				 * subreg_def for this insn.  Save it first.
3573 				 */
3574 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3575 
3576 				state->regs[dst_regno] = *reg;
3577 				state->regs[dst_regno].subreg_def = subreg_def;
3578 			} else {
3579 				for (i = 0; i < size; i++) {
3580 					type = stype[(slot - i) % BPF_REG_SIZE];
3581 					if (type == STACK_SPILL)
3582 						continue;
3583 					if (type == STACK_MISC)
3584 						continue;
3585 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3586 						off, i, size);
3587 					return -EACCES;
3588 				}
3589 				mark_reg_unknown(env, state->regs, dst_regno);
3590 			}
3591 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3592 			return 0;
3593 		}
3594 
3595 		if (dst_regno >= 0) {
3596 			/* restore register state from stack */
3597 			state->regs[dst_regno] = *reg;
3598 			/* mark reg as written since spilled pointer state likely
3599 			 * has its liveness marks cleared by is_state_visited()
3600 			 * which resets stack/reg liveness for state transitions
3601 			 */
3602 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3603 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3604 			/* If dst_regno==-1, the caller is asking us whether
3605 			 * it is acceptable to use this value as a SCALAR_VALUE
3606 			 * (e.g. for XADD).
3607 			 * We must not allow unprivileged callers to do that
3608 			 * with spilled pointers.
3609 			 */
3610 			verbose(env, "leaking pointer from stack off %d\n",
3611 				off);
3612 			return -EACCES;
3613 		}
3614 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3615 	} else {
3616 		for (i = 0; i < size; i++) {
3617 			type = stype[(slot - i) % BPF_REG_SIZE];
3618 			if (type == STACK_MISC)
3619 				continue;
3620 			if (type == STACK_ZERO)
3621 				continue;
3622 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3623 				off, i, size);
3624 			return -EACCES;
3625 		}
3626 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3627 		if (dst_regno >= 0)
3628 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3629 	}
3630 	return 0;
3631 }
3632 
3633 enum bpf_access_src {
3634 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3635 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3636 };
3637 
3638 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3639 					 int regno, int off, int access_size,
3640 					 bool zero_size_allowed,
3641 					 enum bpf_access_src type,
3642 					 struct bpf_call_arg_meta *meta);
3643 
3644 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3645 {
3646 	return cur_regs(env) + regno;
3647 }
3648 
3649 /* Read the stack at 'ptr_regno + off' and put the result into the register
3650  * 'dst_regno'.
3651  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3652  * but not its variable offset.
3653  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3654  *
3655  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3656  * filling registers (i.e. reads of spilled register cannot be detected when
3657  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3658  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3659  * offset; for a fixed offset check_stack_read_fixed_off should be used
3660  * instead.
3661  */
3662 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3663 				    int ptr_regno, int off, int size, int dst_regno)
3664 {
3665 	/* The state of the source register. */
3666 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3667 	struct bpf_func_state *ptr_state = func(env, reg);
3668 	int err;
3669 	int min_off, max_off;
3670 
3671 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3672 	 */
3673 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3674 					    false, ACCESS_DIRECT, NULL);
3675 	if (err)
3676 		return err;
3677 
3678 	min_off = reg->smin_value + off;
3679 	max_off = reg->smax_value + off;
3680 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3681 	return 0;
3682 }
3683 
3684 /* check_stack_read dispatches to check_stack_read_fixed_off or
3685  * check_stack_read_var_off.
3686  *
3687  * The caller must ensure that the offset falls within the allocated stack
3688  * bounds.
3689  *
3690  * 'dst_regno' is a register which will receive the value from the stack. It
3691  * can be -1, meaning that the read value is not going to a register.
3692  */
3693 static int check_stack_read(struct bpf_verifier_env *env,
3694 			    int ptr_regno, int off, int size,
3695 			    int dst_regno)
3696 {
3697 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3698 	struct bpf_func_state *state = func(env, reg);
3699 	int err;
3700 	/* Some accesses are only permitted with a static offset. */
3701 	bool var_off = !tnum_is_const(reg->var_off);
3702 
3703 	/* The offset is required to be static when reads don't go to a
3704 	 * register, in order to not leak pointers (see
3705 	 * check_stack_read_fixed_off).
3706 	 */
3707 	if (dst_regno < 0 && var_off) {
3708 		char tn_buf[48];
3709 
3710 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3711 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3712 			tn_buf, off, size);
3713 		return -EACCES;
3714 	}
3715 	/* Variable offset is prohibited for unprivileged mode for simplicity
3716 	 * since it requires corresponding support in Spectre masking for stack
3717 	 * ALU. See also retrieve_ptr_limit().
3718 	 */
3719 	if (!env->bypass_spec_v1 && var_off) {
3720 		char tn_buf[48];
3721 
3722 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3723 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3724 				ptr_regno, tn_buf);
3725 		return -EACCES;
3726 	}
3727 
3728 	if (!var_off) {
3729 		off += reg->var_off.value;
3730 		err = check_stack_read_fixed_off(env, state, off, size,
3731 						 dst_regno);
3732 	} else {
3733 		/* Variable offset stack reads need more conservative handling
3734 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3735 		 * branch.
3736 		 */
3737 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3738 					       dst_regno);
3739 	}
3740 	return err;
3741 }
3742 
3743 
3744 /* check_stack_write dispatches to check_stack_write_fixed_off or
3745  * check_stack_write_var_off.
3746  *
3747  * 'ptr_regno' is the register used as a pointer into the stack.
3748  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3749  * 'value_regno' is the register whose value we're writing to the stack. It can
3750  * be -1, meaning that we're not writing from a register.
3751  *
3752  * The caller must ensure that the offset falls within the maximum stack size.
3753  */
3754 static int check_stack_write(struct bpf_verifier_env *env,
3755 			     int ptr_regno, int off, int size,
3756 			     int value_regno, int insn_idx)
3757 {
3758 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3759 	struct bpf_func_state *state = func(env, reg);
3760 	int err;
3761 
3762 	if (tnum_is_const(reg->var_off)) {
3763 		off += reg->var_off.value;
3764 		err = check_stack_write_fixed_off(env, state, off, size,
3765 						  value_regno, insn_idx);
3766 	} else {
3767 		/* Variable offset stack reads need more conservative handling
3768 		 * than fixed offset ones.
3769 		 */
3770 		err = check_stack_write_var_off(env, state,
3771 						ptr_regno, off, size,
3772 						value_regno, insn_idx);
3773 	}
3774 	return err;
3775 }
3776 
3777 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3778 				 int off, int size, enum bpf_access_type type)
3779 {
3780 	struct bpf_reg_state *regs = cur_regs(env);
3781 	struct bpf_map *map = regs[regno].map_ptr;
3782 	u32 cap = bpf_map_flags_to_cap(map);
3783 
3784 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3785 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3786 			map->value_size, off, size);
3787 		return -EACCES;
3788 	}
3789 
3790 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3791 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3792 			map->value_size, off, size);
3793 		return -EACCES;
3794 	}
3795 
3796 	return 0;
3797 }
3798 
3799 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3800 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3801 			      int off, int size, u32 mem_size,
3802 			      bool zero_size_allowed)
3803 {
3804 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3805 	struct bpf_reg_state *reg;
3806 
3807 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3808 		return 0;
3809 
3810 	reg = &cur_regs(env)[regno];
3811 	switch (reg->type) {
3812 	case PTR_TO_MAP_KEY:
3813 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3814 			mem_size, off, size);
3815 		break;
3816 	case PTR_TO_MAP_VALUE:
3817 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3818 			mem_size, off, size);
3819 		break;
3820 	case PTR_TO_PACKET:
3821 	case PTR_TO_PACKET_META:
3822 	case PTR_TO_PACKET_END:
3823 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3824 			off, size, regno, reg->id, off, mem_size);
3825 		break;
3826 	case PTR_TO_MEM:
3827 	default:
3828 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3829 			mem_size, off, size);
3830 	}
3831 
3832 	return -EACCES;
3833 }
3834 
3835 /* check read/write into a memory region with possible variable offset */
3836 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3837 				   int off, int size, u32 mem_size,
3838 				   bool zero_size_allowed)
3839 {
3840 	struct bpf_verifier_state *vstate = env->cur_state;
3841 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3842 	struct bpf_reg_state *reg = &state->regs[regno];
3843 	int err;
3844 
3845 	/* We may have adjusted the register pointing to memory region, so we
3846 	 * need to try adding each of min_value and max_value to off
3847 	 * to make sure our theoretical access will be safe.
3848 	 *
3849 	 * The minimum value is only important with signed
3850 	 * comparisons where we can't assume the floor of a
3851 	 * value is 0.  If we are using signed variables for our
3852 	 * index'es we need to make sure that whatever we use
3853 	 * will have a set floor within our range.
3854 	 */
3855 	if (reg->smin_value < 0 &&
3856 	    (reg->smin_value == S64_MIN ||
3857 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3858 	      reg->smin_value + off < 0)) {
3859 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3860 			regno);
3861 		return -EACCES;
3862 	}
3863 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3864 				 mem_size, zero_size_allowed);
3865 	if (err) {
3866 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3867 			regno);
3868 		return err;
3869 	}
3870 
3871 	/* If we haven't set a max value then we need to bail since we can't be
3872 	 * sure we won't do bad things.
3873 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3874 	 */
3875 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3876 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3877 			regno);
3878 		return -EACCES;
3879 	}
3880 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3881 				 mem_size, zero_size_allowed);
3882 	if (err) {
3883 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3884 			regno);
3885 		return err;
3886 	}
3887 
3888 	return 0;
3889 }
3890 
3891 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3892 			       const struct bpf_reg_state *reg, int regno,
3893 			       bool fixed_off_ok)
3894 {
3895 	/* Access to this pointer-typed register or passing it to a helper
3896 	 * is only allowed in its original, unmodified form.
3897 	 */
3898 
3899 	if (reg->off < 0) {
3900 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3901 			reg_type_str(env, reg->type), regno, reg->off);
3902 		return -EACCES;
3903 	}
3904 
3905 	if (!fixed_off_ok && reg->off) {
3906 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3907 			reg_type_str(env, reg->type), regno, reg->off);
3908 		return -EACCES;
3909 	}
3910 
3911 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3912 		char tn_buf[48];
3913 
3914 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3915 		verbose(env, "variable %s access var_off=%s disallowed\n",
3916 			reg_type_str(env, reg->type), tn_buf);
3917 		return -EACCES;
3918 	}
3919 
3920 	return 0;
3921 }
3922 
3923 int check_ptr_off_reg(struct bpf_verifier_env *env,
3924 		      const struct bpf_reg_state *reg, int regno)
3925 {
3926 	return __check_ptr_off_reg(env, reg, regno, false);
3927 }
3928 
3929 static int map_kptr_match_type(struct bpf_verifier_env *env,
3930 			       struct btf_field *kptr_field,
3931 			       struct bpf_reg_state *reg, u32 regno)
3932 {
3933 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3934 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3935 	const char *reg_name = "";
3936 
3937 	/* Only unreferenced case accepts untrusted pointers */
3938 	if (kptr_field->type == BPF_KPTR_UNREF)
3939 		perm_flags |= PTR_UNTRUSTED;
3940 
3941 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3942 		goto bad_type;
3943 
3944 	if (!btf_is_kernel(reg->btf)) {
3945 		verbose(env, "R%d must point to kernel BTF\n", regno);
3946 		return -EINVAL;
3947 	}
3948 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3949 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3950 
3951 	/* For ref_ptr case, release function check should ensure we get one
3952 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3953 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3954 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3955 	 * reg->off and reg->ref_obj_id are not needed here.
3956 	 */
3957 	if (__check_ptr_off_reg(env, reg, regno, true))
3958 		return -EACCES;
3959 
3960 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3961 	 * we also need to take into account the reg->off.
3962 	 *
3963 	 * We want to support cases like:
3964 	 *
3965 	 * struct foo {
3966 	 *         struct bar br;
3967 	 *         struct baz bz;
3968 	 * };
3969 	 *
3970 	 * struct foo *v;
3971 	 * v = func();	      // PTR_TO_BTF_ID
3972 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3973 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3974 	 *                    // first member type of struct after comparison fails
3975 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3976 	 *                    // to match type
3977 	 *
3978 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3979 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3980 	 * the struct to match type against first member of struct, i.e. reject
3981 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3982 	 * strict mode to true for type match.
3983 	 */
3984 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3985 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3986 				  kptr_field->type == BPF_KPTR_REF))
3987 		goto bad_type;
3988 	return 0;
3989 bad_type:
3990 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3991 		reg_type_str(env, reg->type), reg_name);
3992 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3993 	if (kptr_field->type == BPF_KPTR_UNREF)
3994 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3995 			targ_name);
3996 	else
3997 		verbose(env, "\n");
3998 	return -EINVAL;
3999 }
4000 
4001 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4002 				 int value_regno, int insn_idx,
4003 				 struct btf_field *kptr_field)
4004 {
4005 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4006 	int class = BPF_CLASS(insn->code);
4007 	struct bpf_reg_state *val_reg;
4008 
4009 	/* Things we already checked for in check_map_access and caller:
4010 	 *  - Reject cases where variable offset may touch kptr
4011 	 *  - size of access (must be BPF_DW)
4012 	 *  - tnum_is_const(reg->var_off)
4013 	 *  - kptr_field->offset == off + reg->var_off.value
4014 	 */
4015 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4016 	if (BPF_MODE(insn->code) != BPF_MEM) {
4017 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4018 		return -EACCES;
4019 	}
4020 
4021 	/* We only allow loading referenced kptr, since it will be marked as
4022 	 * untrusted, similar to unreferenced kptr.
4023 	 */
4024 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4025 		verbose(env, "store to referenced kptr disallowed\n");
4026 		return -EACCES;
4027 	}
4028 
4029 	if (class == BPF_LDX) {
4030 		val_reg = reg_state(env, value_regno);
4031 		/* We can simply mark the value_regno receiving the pointer
4032 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4033 		 */
4034 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4035 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4036 		/* For mark_ptr_or_null_reg */
4037 		val_reg->id = ++env->id_gen;
4038 	} else if (class == BPF_STX) {
4039 		val_reg = reg_state(env, value_regno);
4040 		if (!register_is_null(val_reg) &&
4041 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4042 			return -EACCES;
4043 	} else if (class == BPF_ST) {
4044 		if (insn->imm) {
4045 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4046 				kptr_field->offset);
4047 			return -EACCES;
4048 		}
4049 	} else {
4050 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4051 		return -EACCES;
4052 	}
4053 	return 0;
4054 }
4055 
4056 /* check read/write into a map element with possible variable offset */
4057 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4058 			    int off, int size, bool zero_size_allowed,
4059 			    enum bpf_access_src src)
4060 {
4061 	struct bpf_verifier_state *vstate = env->cur_state;
4062 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4063 	struct bpf_reg_state *reg = &state->regs[regno];
4064 	struct bpf_map *map = reg->map_ptr;
4065 	struct btf_record *rec;
4066 	int err, i;
4067 
4068 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4069 				      zero_size_allowed);
4070 	if (err)
4071 		return err;
4072 
4073 	if (IS_ERR_OR_NULL(map->record))
4074 		return 0;
4075 	rec = map->record;
4076 	for (i = 0; i < rec->cnt; i++) {
4077 		struct btf_field *field = &rec->fields[i];
4078 		u32 p = field->offset;
4079 
4080 		/* If any part of a field  can be touched by load/store, reject
4081 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4082 		 * it is sufficient to check x1 < y2 && y1 < x2.
4083 		 */
4084 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4085 		    p < reg->umax_value + off + size) {
4086 			switch (field->type) {
4087 			case BPF_KPTR_UNREF:
4088 			case BPF_KPTR_REF:
4089 				if (src != ACCESS_DIRECT) {
4090 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4091 					return -EACCES;
4092 				}
4093 				if (!tnum_is_const(reg->var_off)) {
4094 					verbose(env, "kptr access cannot have variable offset\n");
4095 					return -EACCES;
4096 				}
4097 				if (p != off + reg->var_off.value) {
4098 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4099 						p, off + reg->var_off.value);
4100 					return -EACCES;
4101 				}
4102 				if (size != bpf_size_to_bytes(BPF_DW)) {
4103 					verbose(env, "kptr access size must be BPF_DW\n");
4104 					return -EACCES;
4105 				}
4106 				break;
4107 			default:
4108 				verbose(env, "%s cannot be accessed directly by load/store\n",
4109 					btf_field_type_name(field->type));
4110 				return -EACCES;
4111 			}
4112 		}
4113 	}
4114 	return 0;
4115 }
4116 
4117 #define MAX_PACKET_OFF 0xffff
4118 
4119 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4120 				       const struct bpf_call_arg_meta *meta,
4121 				       enum bpf_access_type t)
4122 {
4123 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4124 
4125 	switch (prog_type) {
4126 	/* Program types only with direct read access go here! */
4127 	case BPF_PROG_TYPE_LWT_IN:
4128 	case BPF_PROG_TYPE_LWT_OUT:
4129 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4130 	case BPF_PROG_TYPE_SK_REUSEPORT:
4131 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4132 	case BPF_PROG_TYPE_CGROUP_SKB:
4133 		if (t == BPF_WRITE)
4134 			return false;
4135 		fallthrough;
4136 
4137 	/* Program types with direct read + write access go here! */
4138 	case BPF_PROG_TYPE_SCHED_CLS:
4139 	case BPF_PROG_TYPE_SCHED_ACT:
4140 	case BPF_PROG_TYPE_XDP:
4141 	case BPF_PROG_TYPE_LWT_XMIT:
4142 	case BPF_PROG_TYPE_SK_SKB:
4143 	case BPF_PROG_TYPE_SK_MSG:
4144 		if (meta)
4145 			return meta->pkt_access;
4146 
4147 		env->seen_direct_write = true;
4148 		return true;
4149 
4150 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4151 		if (t == BPF_WRITE)
4152 			env->seen_direct_write = true;
4153 
4154 		return true;
4155 
4156 	default:
4157 		return false;
4158 	}
4159 }
4160 
4161 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4162 			       int size, bool zero_size_allowed)
4163 {
4164 	struct bpf_reg_state *regs = cur_regs(env);
4165 	struct bpf_reg_state *reg = &regs[regno];
4166 	int err;
4167 
4168 	/* We may have added a variable offset to the packet pointer; but any
4169 	 * reg->range we have comes after that.  We are only checking the fixed
4170 	 * offset.
4171 	 */
4172 
4173 	/* We don't allow negative numbers, because we aren't tracking enough
4174 	 * detail to prove they're safe.
4175 	 */
4176 	if (reg->smin_value < 0) {
4177 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4178 			regno);
4179 		return -EACCES;
4180 	}
4181 
4182 	err = reg->range < 0 ? -EINVAL :
4183 	      __check_mem_access(env, regno, off, size, reg->range,
4184 				 zero_size_allowed);
4185 	if (err) {
4186 		verbose(env, "R%d offset is outside of the packet\n", regno);
4187 		return err;
4188 	}
4189 
4190 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4191 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4192 	 * otherwise find_good_pkt_pointers would have refused to set range info
4193 	 * that __check_mem_access would have rejected this pkt access.
4194 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4195 	 */
4196 	env->prog->aux->max_pkt_offset =
4197 		max_t(u32, env->prog->aux->max_pkt_offset,
4198 		      off + reg->umax_value + size - 1);
4199 
4200 	return err;
4201 }
4202 
4203 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4204 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4205 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4206 			    struct btf **btf, u32 *btf_id)
4207 {
4208 	struct bpf_insn_access_aux info = {
4209 		.reg_type = *reg_type,
4210 		.log = &env->log,
4211 	};
4212 
4213 	if (env->ops->is_valid_access &&
4214 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4215 		/* A non zero info.ctx_field_size indicates that this field is a
4216 		 * candidate for later verifier transformation to load the whole
4217 		 * field and then apply a mask when accessed with a narrower
4218 		 * access than actual ctx access size. A zero info.ctx_field_size
4219 		 * will only allow for whole field access and rejects any other
4220 		 * type of narrower access.
4221 		 */
4222 		*reg_type = info.reg_type;
4223 
4224 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4225 			*btf = info.btf;
4226 			*btf_id = info.btf_id;
4227 		} else {
4228 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4229 		}
4230 		/* remember the offset of last byte accessed in ctx */
4231 		if (env->prog->aux->max_ctx_offset < off + size)
4232 			env->prog->aux->max_ctx_offset = off + size;
4233 		return 0;
4234 	}
4235 
4236 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4237 	return -EACCES;
4238 }
4239 
4240 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4241 				  int size)
4242 {
4243 	if (size < 0 || off < 0 ||
4244 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4245 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4246 			off, size);
4247 		return -EACCES;
4248 	}
4249 	return 0;
4250 }
4251 
4252 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4253 			     u32 regno, int off, int size,
4254 			     enum bpf_access_type t)
4255 {
4256 	struct bpf_reg_state *regs = cur_regs(env);
4257 	struct bpf_reg_state *reg = &regs[regno];
4258 	struct bpf_insn_access_aux info = {};
4259 	bool valid;
4260 
4261 	if (reg->smin_value < 0) {
4262 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4263 			regno);
4264 		return -EACCES;
4265 	}
4266 
4267 	switch (reg->type) {
4268 	case PTR_TO_SOCK_COMMON:
4269 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4270 		break;
4271 	case PTR_TO_SOCKET:
4272 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4273 		break;
4274 	case PTR_TO_TCP_SOCK:
4275 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4276 		break;
4277 	case PTR_TO_XDP_SOCK:
4278 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4279 		break;
4280 	default:
4281 		valid = false;
4282 	}
4283 
4284 
4285 	if (valid) {
4286 		env->insn_aux_data[insn_idx].ctx_field_size =
4287 			info.ctx_field_size;
4288 		return 0;
4289 	}
4290 
4291 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4292 		regno, reg_type_str(env, reg->type), off, size);
4293 
4294 	return -EACCES;
4295 }
4296 
4297 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4298 {
4299 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4300 }
4301 
4302 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4303 {
4304 	const struct bpf_reg_state *reg = reg_state(env, regno);
4305 
4306 	return reg->type == PTR_TO_CTX;
4307 }
4308 
4309 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4310 {
4311 	const struct bpf_reg_state *reg = reg_state(env, regno);
4312 
4313 	return type_is_sk_pointer(reg->type);
4314 }
4315 
4316 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4317 {
4318 	const struct bpf_reg_state *reg = reg_state(env, regno);
4319 
4320 	return type_is_pkt_pointer(reg->type);
4321 }
4322 
4323 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4324 {
4325 	const struct bpf_reg_state *reg = reg_state(env, regno);
4326 
4327 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4328 	return reg->type == PTR_TO_FLOW_KEYS;
4329 }
4330 
4331 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4332 {
4333 	/* A referenced register is always trusted. */
4334 	if (reg->ref_obj_id)
4335 		return true;
4336 
4337 	/* If a register is not referenced, it is trusted if it has the
4338 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4339 	 * other type modifiers may be safe, but we elect to take an opt-in
4340 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4341 	 * not.
4342 	 *
4343 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4344 	 * for whether a register is trusted.
4345 	 */
4346 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4347 	       !bpf_type_has_unsafe_modifiers(reg->type);
4348 }
4349 
4350 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4351 {
4352 	return reg->type & MEM_RCU;
4353 }
4354 
4355 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4356 				   const struct bpf_reg_state *reg,
4357 				   int off, int size, bool strict)
4358 {
4359 	struct tnum reg_off;
4360 	int ip_align;
4361 
4362 	/* Byte size accesses are always allowed. */
4363 	if (!strict || size == 1)
4364 		return 0;
4365 
4366 	/* For platforms that do not have a Kconfig enabling
4367 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4368 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4369 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4370 	 * to this code only in strict mode where we want to emulate
4371 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4372 	 * unconditional IP align value of '2'.
4373 	 */
4374 	ip_align = 2;
4375 
4376 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4377 	if (!tnum_is_aligned(reg_off, size)) {
4378 		char tn_buf[48];
4379 
4380 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4381 		verbose(env,
4382 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4383 			ip_align, tn_buf, reg->off, off, size);
4384 		return -EACCES;
4385 	}
4386 
4387 	return 0;
4388 }
4389 
4390 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4391 				       const struct bpf_reg_state *reg,
4392 				       const char *pointer_desc,
4393 				       int off, int size, bool strict)
4394 {
4395 	struct tnum reg_off;
4396 
4397 	/* Byte size accesses are always allowed. */
4398 	if (!strict || size == 1)
4399 		return 0;
4400 
4401 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4402 	if (!tnum_is_aligned(reg_off, size)) {
4403 		char tn_buf[48];
4404 
4405 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4406 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4407 			pointer_desc, tn_buf, reg->off, off, size);
4408 		return -EACCES;
4409 	}
4410 
4411 	return 0;
4412 }
4413 
4414 static int check_ptr_alignment(struct bpf_verifier_env *env,
4415 			       const struct bpf_reg_state *reg, int off,
4416 			       int size, bool strict_alignment_once)
4417 {
4418 	bool strict = env->strict_alignment || strict_alignment_once;
4419 	const char *pointer_desc = "";
4420 
4421 	switch (reg->type) {
4422 	case PTR_TO_PACKET:
4423 	case PTR_TO_PACKET_META:
4424 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4425 		 * right in front, treat it the very same way.
4426 		 */
4427 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4428 	case PTR_TO_FLOW_KEYS:
4429 		pointer_desc = "flow keys ";
4430 		break;
4431 	case PTR_TO_MAP_KEY:
4432 		pointer_desc = "key ";
4433 		break;
4434 	case PTR_TO_MAP_VALUE:
4435 		pointer_desc = "value ";
4436 		break;
4437 	case PTR_TO_CTX:
4438 		pointer_desc = "context ";
4439 		break;
4440 	case PTR_TO_STACK:
4441 		pointer_desc = "stack ";
4442 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4443 		 * and check_stack_read_fixed_off() relies on stack accesses being
4444 		 * aligned.
4445 		 */
4446 		strict = true;
4447 		break;
4448 	case PTR_TO_SOCKET:
4449 		pointer_desc = "sock ";
4450 		break;
4451 	case PTR_TO_SOCK_COMMON:
4452 		pointer_desc = "sock_common ";
4453 		break;
4454 	case PTR_TO_TCP_SOCK:
4455 		pointer_desc = "tcp_sock ";
4456 		break;
4457 	case PTR_TO_XDP_SOCK:
4458 		pointer_desc = "xdp_sock ";
4459 		break;
4460 	default:
4461 		break;
4462 	}
4463 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4464 					   strict);
4465 }
4466 
4467 static int update_stack_depth(struct bpf_verifier_env *env,
4468 			      const struct bpf_func_state *func,
4469 			      int off)
4470 {
4471 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4472 
4473 	if (stack >= -off)
4474 		return 0;
4475 
4476 	/* update known max for given subprogram */
4477 	env->subprog_info[func->subprogno].stack_depth = -off;
4478 	return 0;
4479 }
4480 
4481 /* starting from main bpf function walk all instructions of the function
4482  * and recursively walk all callees that given function can call.
4483  * Ignore jump and exit insns.
4484  * Since recursion is prevented by check_cfg() this algorithm
4485  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4486  */
4487 static int check_max_stack_depth(struct bpf_verifier_env *env)
4488 {
4489 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4490 	struct bpf_subprog_info *subprog = env->subprog_info;
4491 	struct bpf_insn *insn = env->prog->insnsi;
4492 	bool tail_call_reachable = false;
4493 	int ret_insn[MAX_CALL_FRAMES];
4494 	int ret_prog[MAX_CALL_FRAMES];
4495 	int j;
4496 
4497 process_func:
4498 	/* protect against potential stack overflow that might happen when
4499 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4500 	 * depth for such case down to 256 so that the worst case scenario
4501 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4502 	 * 8k).
4503 	 *
4504 	 * To get the idea what might happen, see an example:
4505 	 * func1 -> sub rsp, 128
4506 	 *  subfunc1 -> sub rsp, 256
4507 	 *  tailcall1 -> add rsp, 256
4508 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4509 	 *   subfunc2 -> sub rsp, 64
4510 	 *   subfunc22 -> sub rsp, 128
4511 	 *   tailcall2 -> add rsp, 128
4512 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4513 	 *
4514 	 * tailcall will unwind the current stack frame but it will not get rid
4515 	 * of caller's stack as shown on the example above.
4516 	 */
4517 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4518 		verbose(env,
4519 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4520 			depth);
4521 		return -EACCES;
4522 	}
4523 	/* round up to 32-bytes, since this is granularity
4524 	 * of interpreter stack size
4525 	 */
4526 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4527 	if (depth > MAX_BPF_STACK) {
4528 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4529 			frame + 1, depth);
4530 		return -EACCES;
4531 	}
4532 continue_func:
4533 	subprog_end = subprog[idx + 1].start;
4534 	for (; i < subprog_end; i++) {
4535 		int next_insn;
4536 
4537 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4538 			continue;
4539 		/* remember insn and function to return to */
4540 		ret_insn[frame] = i + 1;
4541 		ret_prog[frame] = idx;
4542 
4543 		/* find the callee */
4544 		next_insn = i + insn[i].imm + 1;
4545 		idx = find_subprog(env, next_insn);
4546 		if (idx < 0) {
4547 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4548 				  next_insn);
4549 			return -EFAULT;
4550 		}
4551 		if (subprog[idx].is_async_cb) {
4552 			if (subprog[idx].has_tail_call) {
4553 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4554 				return -EFAULT;
4555 			}
4556 			 /* async callbacks don't increase bpf prog stack size */
4557 			continue;
4558 		}
4559 		i = next_insn;
4560 
4561 		if (subprog[idx].has_tail_call)
4562 			tail_call_reachable = true;
4563 
4564 		frame++;
4565 		if (frame >= MAX_CALL_FRAMES) {
4566 			verbose(env, "the call stack of %d frames is too deep !\n",
4567 				frame);
4568 			return -E2BIG;
4569 		}
4570 		goto process_func;
4571 	}
4572 	/* if tail call got detected across bpf2bpf calls then mark each of the
4573 	 * currently present subprog frames as tail call reachable subprogs;
4574 	 * this info will be utilized by JIT so that we will be preserving the
4575 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4576 	 */
4577 	if (tail_call_reachable)
4578 		for (j = 0; j < frame; j++)
4579 			subprog[ret_prog[j]].tail_call_reachable = true;
4580 	if (subprog[0].tail_call_reachable)
4581 		env->prog->aux->tail_call_reachable = true;
4582 
4583 	/* end of for() loop means the last insn of the 'subprog'
4584 	 * was reached. Doesn't matter whether it was JA or EXIT
4585 	 */
4586 	if (frame == 0)
4587 		return 0;
4588 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4589 	frame--;
4590 	i = ret_insn[frame];
4591 	idx = ret_prog[frame];
4592 	goto continue_func;
4593 }
4594 
4595 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4596 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4597 				  const struct bpf_insn *insn, int idx)
4598 {
4599 	int start = idx + insn->imm + 1, subprog;
4600 
4601 	subprog = find_subprog(env, start);
4602 	if (subprog < 0) {
4603 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4604 			  start);
4605 		return -EFAULT;
4606 	}
4607 	return env->subprog_info[subprog].stack_depth;
4608 }
4609 #endif
4610 
4611 static int __check_buffer_access(struct bpf_verifier_env *env,
4612 				 const char *buf_info,
4613 				 const struct bpf_reg_state *reg,
4614 				 int regno, int off, int size)
4615 {
4616 	if (off < 0) {
4617 		verbose(env,
4618 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4619 			regno, buf_info, off, size);
4620 		return -EACCES;
4621 	}
4622 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4623 		char tn_buf[48];
4624 
4625 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4626 		verbose(env,
4627 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4628 			regno, off, tn_buf);
4629 		return -EACCES;
4630 	}
4631 
4632 	return 0;
4633 }
4634 
4635 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4636 				  const struct bpf_reg_state *reg,
4637 				  int regno, int off, int size)
4638 {
4639 	int err;
4640 
4641 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4642 	if (err)
4643 		return err;
4644 
4645 	if (off + size > env->prog->aux->max_tp_access)
4646 		env->prog->aux->max_tp_access = off + size;
4647 
4648 	return 0;
4649 }
4650 
4651 static int check_buffer_access(struct bpf_verifier_env *env,
4652 			       const struct bpf_reg_state *reg,
4653 			       int regno, int off, int size,
4654 			       bool zero_size_allowed,
4655 			       u32 *max_access)
4656 {
4657 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4658 	int err;
4659 
4660 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4661 	if (err)
4662 		return err;
4663 
4664 	if (off + size > *max_access)
4665 		*max_access = off + size;
4666 
4667 	return 0;
4668 }
4669 
4670 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4671 static void zext_32_to_64(struct bpf_reg_state *reg)
4672 {
4673 	reg->var_off = tnum_subreg(reg->var_off);
4674 	__reg_assign_32_into_64(reg);
4675 }
4676 
4677 /* truncate register to smaller size (in bytes)
4678  * must be called with size < BPF_REG_SIZE
4679  */
4680 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4681 {
4682 	u64 mask;
4683 
4684 	/* clear high bits in bit representation */
4685 	reg->var_off = tnum_cast(reg->var_off, size);
4686 
4687 	/* fix arithmetic bounds */
4688 	mask = ((u64)1 << (size * 8)) - 1;
4689 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4690 		reg->umin_value &= mask;
4691 		reg->umax_value &= mask;
4692 	} else {
4693 		reg->umin_value = 0;
4694 		reg->umax_value = mask;
4695 	}
4696 	reg->smin_value = reg->umin_value;
4697 	reg->smax_value = reg->umax_value;
4698 
4699 	/* If size is smaller than 32bit register the 32bit register
4700 	 * values are also truncated so we push 64-bit bounds into
4701 	 * 32-bit bounds. Above were truncated < 32-bits already.
4702 	 */
4703 	if (size >= 4)
4704 		return;
4705 	__reg_combine_64_into_32(reg);
4706 }
4707 
4708 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4709 {
4710 	/* A map is considered read-only if the following condition are true:
4711 	 *
4712 	 * 1) BPF program side cannot change any of the map content. The
4713 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4714 	 *    and was set at map creation time.
4715 	 * 2) The map value(s) have been initialized from user space by a
4716 	 *    loader and then "frozen", such that no new map update/delete
4717 	 *    operations from syscall side are possible for the rest of
4718 	 *    the map's lifetime from that point onwards.
4719 	 * 3) Any parallel/pending map update/delete operations from syscall
4720 	 *    side have been completed. Only after that point, it's safe to
4721 	 *    assume that map value(s) are immutable.
4722 	 */
4723 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4724 	       READ_ONCE(map->frozen) &&
4725 	       !bpf_map_write_active(map);
4726 }
4727 
4728 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4729 {
4730 	void *ptr;
4731 	u64 addr;
4732 	int err;
4733 
4734 	err = map->ops->map_direct_value_addr(map, &addr, off);
4735 	if (err)
4736 		return err;
4737 	ptr = (void *)(long)addr + off;
4738 
4739 	switch (size) {
4740 	case sizeof(u8):
4741 		*val = (u64)*(u8 *)ptr;
4742 		break;
4743 	case sizeof(u16):
4744 		*val = (u64)*(u16 *)ptr;
4745 		break;
4746 	case sizeof(u32):
4747 		*val = (u64)*(u32 *)ptr;
4748 		break;
4749 	case sizeof(u64):
4750 		*val = *(u64 *)ptr;
4751 		break;
4752 	default:
4753 		return -EINVAL;
4754 	}
4755 	return 0;
4756 }
4757 
4758 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4759 				   struct bpf_reg_state *regs,
4760 				   int regno, int off, int size,
4761 				   enum bpf_access_type atype,
4762 				   int value_regno)
4763 {
4764 	struct bpf_reg_state *reg = regs + regno;
4765 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4766 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4767 	enum bpf_type_flag flag = 0;
4768 	u32 btf_id;
4769 	int ret;
4770 
4771 	if (!env->allow_ptr_leaks) {
4772 		verbose(env,
4773 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4774 			tname);
4775 		return -EPERM;
4776 	}
4777 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4778 		verbose(env,
4779 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4780 			tname);
4781 		return -EINVAL;
4782 	}
4783 	if (off < 0) {
4784 		verbose(env,
4785 			"R%d is ptr_%s invalid negative access: off=%d\n",
4786 			regno, tname, off);
4787 		return -EACCES;
4788 	}
4789 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4790 		char tn_buf[48];
4791 
4792 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4793 		verbose(env,
4794 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4795 			regno, tname, off, tn_buf);
4796 		return -EACCES;
4797 	}
4798 
4799 	if (reg->type & MEM_USER) {
4800 		verbose(env,
4801 			"R%d is ptr_%s access user memory: off=%d\n",
4802 			regno, tname, off);
4803 		return -EACCES;
4804 	}
4805 
4806 	if (reg->type & MEM_PERCPU) {
4807 		verbose(env,
4808 			"R%d is ptr_%s access percpu memory: off=%d\n",
4809 			regno, tname, off);
4810 		return -EACCES;
4811 	}
4812 
4813 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4814 		if (!btf_is_kernel(reg->btf)) {
4815 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4816 			return -EFAULT;
4817 		}
4818 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4819 	} else {
4820 		/* Writes are permitted with default btf_struct_access for
4821 		 * program allocated objects (which always have ref_obj_id > 0),
4822 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4823 		 */
4824 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4825 			verbose(env, "only read is supported\n");
4826 			return -EACCES;
4827 		}
4828 
4829 		if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4830 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4831 			return -EFAULT;
4832 		}
4833 
4834 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4835 	}
4836 
4837 	if (ret < 0)
4838 		return ret;
4839 
4840 	/* If this is an untrusted pointer, all pointers formed by walking it
4841 	 * also inherit the untrusted flag.
4842 	 */
4843 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4844 		flag |= PTR_UNTRUSTED;
4845 
4846 	/* By default any pointer obtained from walking a trusted pointer is
4847 	 * no longer trusted except the rcu case below.
4848 	 */
4849 	flag &= ~PTR_TRUSTED;
4850 
4851 	if (flag & MEM_RCU) {
4852 		/* Mark value register as MEM_RCU only if it is protected by
4853 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
4854 		 * itself can already indicate trustedness inside the rcu
4855 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
4856 		 * it could be null in some cases.
4857 		 */
4858 		if (!env->cur_state->active_rcu_lock ||
4859 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
4860 			flag &= ~MEM_RCU;
4861 		else
4862 			flag |= PTR_MAYBE_NULL;
4863 	} else if (reg->type & MEM_RCU) {
4864 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
4865 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
4866 		 */
4867 		flag |= PTR_UNTRUSTED;
4868 	}
4869 
4870 	if (atype == BPF_READ && value_regno >= 0)
4871 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4872 
4873 	return 0;
4874 }
4875 
4876 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4877 				   struct bpf_reg_state *regs,
4878 				   int regno, int off, int size,
4879 				   enum bpf_access_type atype,
4880 				   int value_regno)
4881 {
4882 	struct bpf_reg_state *reg = regs + regno;
4883 	struct bpf_map *map = reg->map_ptr;
4884 	struct bpf_reg_state map_reg;
4885 	enum bpf_type_flag flag = 0;
4886 	const struct btf_type *t;
4887 	const char *tname;
4888 	u32 btf_id;
4889 	int ret;
4890 
4891 	if (!btf_vmlinux) {
4892 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4893 		return -ENOTSUPP;
4894 	}
4895 
4896 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4897 		verbose(env, "map_ptr access not supported for map type %d\n",
4898 			map->map_type);
4899 		return -ENOTSUPP;
4900 	}
4901 
4902 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4903 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4904 
4905 	if (!env->allow_ptr_leaks) {
4906 		verbose(env,
4907 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4908 			tname);
4909 		return -EPERM;
4910 	}
4911 
4912 	if (off < 0) {
4913 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4914 			regno, tname, off);
4915 		return -EACCES;
4916 	}
4917 
4918 	if (atype != BPF_READ) {
4919 		verbose(env, "only read from %s is supported\n", tname);
4920 		return -EACCES;
4921 	}
4922 
4923 	/* Simulate access to a PTR_TO_BTF_ID */
4924 	memset(&map_reg, 0, sizeof(map_reg));
4925 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4926 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4927 	if (ret < 0)
4928 		return ret;
4929 
4930 	if (value_regno >= 0)
4931 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4932 
4933 	return 0;
4934 }
4935 
4936 /* Check that the stack access at the given offset is within bounds. The
4937  * maximum valid offset is -1.
4938  *
4939  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4940  * -state->allocated_stack for reads.
4941  */
4942 static int check_stack_slot_within_bounds(int off,
4943 					  struct bpf_func_state *state,
4944 					  enum bpf_access_type t)
4945 {
4946 	int min_valid_off;
4947 
4948 	if (t == BPF_WRITE)
4949 		min_valid_off = -MAX_BPF_STACK;
4950 	else
4951 		min_valid_off = -state->allocated_stack;
4952 
4953 	if (off < min_valid_off || off > -1)
4954 		return -EACCES;
4955 	return 0;
4956 }
4957 
4958 /* Check that the stack access at 'regno + off' falls within the maximum stack
4959  * bounds.
4960  *
4961  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4962  */
4963 static int check_stack_access_within_bounds(
4964 		struct bpf_verifier_env *env,
4965 		int regno, int off, int access_size,
4966 		enum bpf_access_src src, enum bpf_access_type type)
4967 {
4968 	struct bpf_reg_state *regs = cur_regs(env);
4969 	struct bpf_reg_state *reg = regs + regno;
4970 	struct bpf_func_state *state = func(env, reg);
4971 	int min_off, max_off;
4972 	int err;
4973 	char *err_extra;
4974 
4975 	if (src == ACCESS_HELPER)
4976 		/* We don't know if helpers are reading or writing (or both). */
4977 		err_extra = " indirect access to";
4978 	else if (type == BPF_READ)
4979 		err_extra = " read from";
4980 	else
4981 		err_extra = " write to";
4982 
4983 	if (tnum_is_const(reg->var_off)) {
4984 		min_off = reg->var_off.value + off;
4985 		if (access_size > 0)
4986 			max_off = min_off + access_size - 1;
4987 		else
4988 			max_off = min_off;
4989 	} else {
4990 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4991 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4992 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4993 				err_extra, regno);
4994 			return -EACCES;
4995 		}
4996 		min_off = reg->smin_value + off;
4997 		if (access_size > 0)
4998 			max_off = reg->smax_value + off + access_size - 1;
4999 		else
5000 			max_off = min_off;
5001 	}
5002 
5003 	err = check_stack_slot_within_bounds(min_off, state, type);
5004 	if (!err)
5005 		err = check_stack_slot_within_bounds(max_off, state, type);
5006 
5007 	if (err) {
5008 		if (tnum_is_const(reg->var_off)) {
5009 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5010 				err_extra, regno, off, access_size);
5011 		} else {
5012 			char tn_buf[48];
5013 
5014 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5015 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5016 				err_extra, regno, tn_buf, access_size);
5017 		}
5018 	}
5019 	return err;
5020 }
5021 
5022 /* check whether memory at (regno + off) is accessible for t = (read | write)
5023  * if t==write, value_regno is a register which value is stored into memory
5024  * if t==read, value_regno is a register which will receive the value from memory
5025  * if t==write && value_regno==-1, some unknown value is stored into memory
5026  * if t==read && value_regno==-1, don't care what we read from memory
5027  */
5028 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5029 			    int off, int bpf_size, enum bpf_access_type t,
5030 			    int value_regno, bool strict_alignment_once)
5031 {
5032 	struct bpf_reg_state *regs = cur_regs(env);
5033 	struct bpf_reg_state *reg = regs + regno;
5034 	struct bpf_func_state *state;
5035 	int size, err = 0;
5036 
5037 	size = bpf_size_to_bytes(bpf_size);
5038 	if (size < 0)
5039 		return size;
5040 
5041 	/* alignment checks will add in reg->off themselves */
5042 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5043 	if (err)
5044 		return err;
5045 
5046 	/* for access checks, reg->off is just part of off */
5047 	off += reg->off;
5048 
5049 	if (reg->type == PTR_TO_MAP_KEY) {
5050 		if (t == BPF_WRITE) {
5051 			verbose(env, "write to change key R%d not allowed\n", regno);
5052 			return -EACCES;
5053 		}
5054 
5055 		err = check_mem_region_access(env, regno, off, size,
5056 					      reg->map_ptr->key_size, false);
5057 		if (err)
5058 			return err;
5059 		if (value_regno >= 0)
5060 			mark_reg_unknown(env, regs, value_regno);
5061 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5062 		struct btf_field *kptr_field = NULL;
5063 
5064 		if (t == BPF_WRITE && value_regno >= 0 &&
5065 		    is_pointer_value(env, value_regno)) {
5066 			verbose(env, "R%d leaks addr into map\n", value_regno);
5067 			return -EACCES;
5068 		}
5069 		err = check_map_access_type(env, regno, off, size, t);
5070 		if (err)
5071 			return err;
5072 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5073 		if (err)
5074 			return err;
5075 		if (tnum_is_const(reg->var_off))
5076 			kptr_field = btf_record_find(reg->map_ptr->record,
5077 						     off + reg->var_off.value, BPF_KPTR);
5078 		if (kptr_field) {
5079 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5080 		} else if (t == BPF_READ && value_regno >= 0) {
5081 			struct bpf_map *map = reg->map_ptr;
5082 
5083 			/* if map is read-only, track its contents as scalars */
5084 			if (tnum_is_const(reg->var_off) &&
5085 			    bpf_map_is_rdonly(map) &&
5086 			    map->ops->map_direct_value_addr) {
5087 				int map_off = off + reg->var_off.value;
5088 				u64 val = 0;
5089 
5090 				err = bpf_map_direct_read(map, map_off, size,
5091 							  &val);
5092 				if (err)
5093 					return err;
5094 
5095 				regs[value_regno].type = SCALAR_VALUE;
5096 				__mark_reg_known(&regs[value_regno], val);
5097 			} else {
5098 				mark_reg_unknown(env, regs, value_regno);
5099 			}
5100 		}
5101 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5102 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5103 
5104 		if (type_may_be_null(reg->type)) {
5105 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5106 				reg_type_str(env, reg->type));
5107 			return -EACCES;
5108 		}
5109 
5110 		if (t == BPF_WRITE && rdonly_mem) {
5111 			verbose(env, "R%d cannot write into %s\n",
5112 				regno, reg_type_str(env, reg->type));
5113 			return -EACCES;
5114 		}
5115 
5116 		if (t == BPF_WRITE && value_regno >= 0 &&
5117 		    is_pointer_value(env, value_regno)) {
5118 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5119 			return -EACCES;
5120 		}
5121 
5122 		err = check_mem_region_access(env, regno, off, size,
5123 					      reg->mem_size, false);
5124 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5125 			mark_reg_unknown(env, regs, value_regno);
5126 	} else if (reg->type == PTR_TO_CTX) {
5127 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5128 		struct btf *btf = NULL;
5129 		u32 btf_id = 0;
5130 
5131 		if (t == BPF_WRITE && value_regno >= 0 &&
5132 		    is_pointer_value(env, value_regno)) {
5133 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5134 			return -EACCES;
5135 		}
5136 
5137 		err = check_ptr_off_reg(env, reg, regno);
5138 		if (err < 0)
5139 			return err;
5140 
5141 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5142 				       &btf_id);
5143 		if (err)
5144 			verbose_linfo(env, insn_idx, "; ");
5145 		if (!err && t == BPF_READ && value_regno >= 0) {
5146 			/* ctx access returns either a scalar, or a
5147 			 * PTR_TO_PACKET[_META,_END]. In the latter
5148 			 * case, we know the offset is zero.
5149 			 */
5150 			if (reg_type == SCALAR_VALUE) {
5151 				mark_reg_unknown(env, regs, value_regno);
5152 			} else {
5153 				mark_reg_known_zero(env, regs,
5154 						    value_regno);
5155 				if (type_may_be_null(reg_type))
5156 					regs[value_regno].id = ++env->id_gen;
5157 				/* A load of ctx field could have different
5158 				 * actual load size with the one encoded in the
5159 				 * insn. When the dst is PTR, it is for sure not
5160 				 * a sub-register.
5161 				 */
5162 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5163 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5164 					regs[value_regno].btf = btf;
5165 					regs[value_regno].btf_id = btf_id;
5166 				}
5167 			}
5168 			regs[value_regno].type = reg_type;
5169 		}
5170 
5171 	} else if (reg->type == PTR_TO_STACK) {
5172 		/* Basic bounds checks. */
5173 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5174 		if (err)
5175 			return err;
5176 
5177 		state = func(env, reg);
5178 		err = update_stack_depth(env, state, off);
5179 		if (err)
5180 			return err;
5181 
5182 		if (t == BPF_READ)
5183 			err = check_stack_read(env, regno, off, size,
5184 					       value_regno);
5185 		else
5186 			err = check_stack_write(env, regno, off, size,
5187 						value_regno, insn_idx);
5188 	} else if (reg_is_pkt_pointer(reg)) {
5189 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5190 			verbose(env, "cannot write into packet\n");
5191 			return -EACCES;
5192 		}
5193 		if (t == BPF_WRITE && value_regno >= 0 &&
5194 		    is_pointer_value(env, value_regno)) {
5195 			verbose(env, "R%d leaks addr into packet\n",
5196 				value_regno);
5197 			return -EACCES;
5198 		}
5199 		err = check_packet_access(env, regno, off, size, false);
5200 		if (!err && t == BPF_READ && value_regno >= 0)
5201 			mark_reg_unknown(env, regs, value_regno);
5202 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5203 		if (t == BPF_WRITE && value_regno >= 0 &&
5204 		    is_pointer_value(env, value_regno)) {
5205 			verbose(env, "R%d leaks addr into flow keys\n",
5206 				value_regno);
5207 			return -EACCES;
5208 		}
5209 
5210 		err = check_flow_keys_access(env, off, size);
5211 		if (!err && t == BPF_READ && value_regno >= 0)
5212 			mark_reg_unknown(env, regs, value_regno);
5213 	} else if (type_is_sk_pointer(reg->type)) {
5214 		if (t == BPF_WRITE) {
5215 			verbose(env, "R%d cannot write into %s\n",
5216 				regno, reg_type_str(env, reg->type));
5217 			return -EACCES;
5218 		}
5219 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5220 		if (!err && value_regno >= 0)
5221 			mark_reg_unknown(env, regs, value_regno);
5222 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5223 		err = check_tp_buffer_access(env, reg, regno, off, size);
5224 		if (!err && t == BPF_READ && value_regno >= 0)
5225 			mark_reg_unknown(env, regs, value_regno);
5226 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5227 		   !type_may_be_null(reg->type)) {
5228 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5229 					      value_regno);
5230 	} else if (reg->type == CONST_PTR_TO_MAP) {
5231 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5232 					      value_regno);
5233 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5234 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5235 		u32 *max_access;
5236 
5237 		if (rdonly_mem) {
5238 			if (t == BPF_WRITE) {
5239 				verbose(env, "R%d cannot write into %s\n",
5240 					regno, reg_type_str(env, reg->type));
5241 				return -EACCES;
5242 			}
5243 			max_access = &env->prog->aux->max_rdonly_access;
5244 		} else {
5245 			max_access = &env->prog->aux->max_rdwr_access;
5246 		}
5247 
5248 		err = check_buffer_access(env, reg, regno, off, size, false,
5249 					  max_access);
5250 
5251 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5252 			mark_reg_unknown(env, regs, value_regno);
5253 	} else {
5254 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5255 			reg_type_str(env, reg->type));
5256 		return -EACCES;
5257 	}
5258 
5259 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5260 	    regs[value_regno].type == SCALAR_VALUE) {
5261 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5262 		coerce_reg_to_size(&regs[value_regno], size);
5263 	}
5264 	return err;
5265 }
5266 
5267 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5268 {
5269 	int load_reg;
5270 	int err;
5271 
5272 	switch (insn->imm) {
5273 	case BPF_ADD:
5274 	case BPF_ADD | BPF_FETCH:
5275 	case BPF_AND:
5276 	case BPF_AND | BPF_FETCH:
5277 	case BPF_OR:
5278 	case BPF_OR | BPF_FETCH:
5279 	case BPF_XOR:
5280 	case BPF_XOR | BPF_FETCH:
5281 	case BPF_XCHG:
5282 	case BPF_CMPXCHG:
5283 		break;
5284 	default:
5285 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5286 		return -EINVAL;
5287 	}
5288 
5289 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5290 		verbose(env, "invalid atomic operand size\n");
5291 		return -EINVAL;
5292 	}
5293 
5294 	/* check src1 operand */
5295 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5296 	if (err)
5297 		return err;
5298 
5299 	/* check src2 operand */
5300 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5301 	if (err)
5302 		return err;
5303 
5304 	if (insn->imm == BPF_CMPXCHG) {
5305 		/* Check comparison of R0 with memory location */
5306 		const u32 aux_reg = BPF_REG_0;
5307 
5308 		err = check_reg_arg(env, aux_reg, SRC_OP);
5309 		if (err)
5310 			return err;
5311 
5312 		if (is_pointer_value(env, aux_reg)) {
5313 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5314 			return -EACCES;
5315 		}
5316 	}
5317 
5318 	if (is_pointer_value(env, insn->src_reg)) {
5319 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5320 		return -EACCES;
5321 	}
5322 
5323 	if (is_ctx_reg(env, insn->dst_reg) ||
5324 	    is_pkt_reg(env, insn->dst_reg) ||
5325 	    is_flow_key_reg(env, insn->dst_reg) ||
5326 	    is_sk_reg(env, insn->dst_reg)) {
5327 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5328 			insn->dst_reg,
5329 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5330 		return -EACCES;
5331 	}
5332 
5333 	if (insn->imm & BPF_FETCH) {
5334 		if (insn->imm == BPF_CMPXCHG)
5335 			load_reg = BPF_REG_0;
5336 		else
5337 			load_reg = insn->src_reg;
5338 
5339 		/* check and record load of old value */
5340 		err = check_reg_arg(env, load_reg, DST_OP);
5341 		if (err)
5342 			return err;
5343 	} else {
5344 		/* This instruction accesses a memory location but doesn't
5345 		 * actually load it into a register.
5346 		 */
5347 		load_reg = -1;
5348 	}
5349 
5350 	/* Check whether we can read the memory, with second call for fetch
5351 	 * case to simulate the register fill.
5352 	 */
5353 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5354 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5355 	if (!err && load_reg >= 0)
5356 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5357 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5358 				       true);
5359 	if (err)
5360 		return err;
5361 
5362 	/* Check whether we can write into the same memory. */
5363 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5364 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5365 	if (err)
5366 		return err;
5367 
5368 	return 0;
5369 }
5370 
5371 /* When register 'regno' is used to read the stack (either directly or through
5372  * a helper function) make sure that it's within stack boundary and, depending
5373  * on the access type, that all elements of the stack are initialized.
5374  *
5375  * 'off' includes 'regno->off', but not its dynamic part (if any).
5376  *
5377  * All registers that have been spilled on the stack in the slots within the
5378  * read offsets are marked as read.
5379  */
5380 static int check_stack_range_initialized(
5381 		struct bpf_verifier_env *env, int regno, int off,
5382 		int access_size, bool zero_size_allowed,
5383 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5384 {
5385 	struct bpf_reg_state *reg = reg_state(env, regno);
5386 	struct bpf_func_state *state = func(env, reg);
5387 	int err, min_off, max_off, i, j, slot, spi;
5388 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5389 	enum bpf_access_type bounds_check_type;
5390 	/* Some accesses can write anything into the stack, others are
5391 	 * read-only.
5392 	 */
5393 	bool clobber = false;
5394 
5395 	if (access_size == 0 && !zero_size_allowed) {
5396 		verbose(env, "invalid zero-sized read\n");
5397 		return -EACCES;
5398 	}
5399 
5400 	if (type == ACCESS_HELPER) {
5401 		/* The bounds checks for writes are more permissive than for
5402 		 * reads. However, if raw_mode is not set, we'll do extra
5403 		 * checks below.
5404 		 */
5405 		bounds_check_type = BPF_WRITE;
5406 		clobber = true;
5407 	} else {
5408 		bounds_check_type = BPF_READ;
5409 	}
5410 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5411 					       type, bounds_check_type);
5412 	if (err)
5413 		return err;
5414 
5415 
5416 	if (tnum_is_const(reg->var_off)) {
5417 		min_off = max_off = reg->var_off.value + off;
5418 	} else {
5419 		/* Variable offset is prohibited for unprivileged mode for
5420 		 * simplicity since it requires corresponding support in
5421 		 * Spectre masking for stack ALU.
5422 		 * See also retrieve_ptr_limit().
5423 		 */
5424 		if (!env->bypass_spec_v1) {
5425 			char tn_buf[48];
5426 
5427 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5428 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5429 				regno, err_extra, tn_buf);
5430 			return -EACCES;
5431 		}
5432 		/* Only initialized buffer on stack is allowed to be accessed
5433 		 * with variable offset. With uninitialized buffer it's hard to
5434 		 * guarantee that whole memory is marked as initialized on
5435 		 * helper return since specific bounds are unknown what may
5436 		 * cause uninitialized stack leaking.
5437 		 */
5438 		if (meta && meta->raw_mode)
5439 			meta = NULL;
5440 
5441 		min_off = reg->smin_value + off;
5442 		max_off = reg->smax_value + off;
5443 	}
5444 
5445 	if (meta && meta->raw_mode) {
5446 		meta->access_size = access_size;
5447 		meta->regno = regno;
5448 		return 0;
5449 	}
5450 
5451 	for (i = min_off; i < max_off + access_size; i++) {
5452 		u8 *stype;
5453 
5454 		slot = -i - 1;
5455 		spi = slot / BPF_REG_SIZE;
5456 		if (state->allocated_stack <= slot)
5457 			goto err;
5458 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5459 		if (*stype == STACK_MISC)
5460 			goto mark;
5461 		if (*stype == STACK_ZERO) {
5462 			if (clobber) {
5463 				/* helper can write anything into the stack */
5464 				*stype = STACK_MISC;
5465 			}
5466 			goto mark;
5467 		}
5468 
5469 		if (is_spilled_reg(&state->stack[spi]) &&
5470 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5471 		     env->allow_ptr_leaks)) {
5472 			if (clobber) {
5473 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5474 				for (j = 0; j < BPF_REG_SIZE; j++)
5475 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5476 			}
5477 			goto mark;
5478 		}
5479 
5480 err:
5481 		if (tnum_is_const(reg->var_off)) {
5482 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5483 				err_extra, regno, min_off, i - min_off, access_size);
5484 		} else {
5485 			char tn_buf[48];
5486 
5487 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5488 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5489 				err_extra, regno, tn_buf, i - min_off, access_size);
5490 		}
5491 		return -EACCES;
5492 mark:
5493 		/* reading any byte out of 8-byte 'spill_slot' will cause
5494 		 * the whole slot to be marked as 'read'
5495 		 */
5496 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5497 			      state->stack[spi].spilled_ptr.parent,
5498 			      REG_LIVE_READ64);
5499 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5500 		 * be sure that whether stack slot is written to or not. Hence,
5501 		 * we must still conservatively propagate reads upwards even if
5502 		 * helper may write to the entire memory range.
5503 		 */
5504 	}
5505 	return update_stack_depth(env, state, min_off);
5506 }
5507 
5508 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5509 				   int access_size, bool zero_size_allowed,
5510 				   struct bpf_call_arg_meta *meta)
5511 {
5512 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5513 	u32 *max_access;
5514 
5515 	switch (base_type(reg->type)) {
5516 	case PTR_TO_PACKET:
5517 	case PTR_TO_PACKET_META:
5518 		return check_packet_access(env, regno, reg->off, access_size,
5519 					   zero_size_allowed);
5520 	case PTR_TO_MAP_KEY:
5521 		if (meta && meta->raw_mode) {
5522 			verbose(env, "R%d cannot write into %s\n", regno,
5523 				reg_type_str(env, reg->type));
5524 			return -EACCES;
5525 		}
5526 		return check_mem_region_access(env, regno, reg->off, access_size,
5527 					       reg->map_ptr->key_size, false);
5528 	case PTR_TO_MAP_VALUE:
5529 		if (check_map_access_type(env, regno, reg->off, access_size,
5530 					  meta && meta->raw_mode ? BPF_WRITE :
5531 					  BPF_READ))
5532 			return -EACCES;
5533 		return check_map_access(env, regno, reg->off, access_size,
5534 					zero_size_allowed, ACCESS_HELPER);
5535 	case PTR_TO_MEM:
5536 		if (type_is_rdonly_mem(reg->type)) {
5537 			if (meta && meta->raw_mode) {
5538 				verbose(env, "R%d cannot write into %s\n", regno,
5539 					reg_type_str(env, reg->type));
5540 				return -EACCES;
5541 			}
5542 		}
5543 		return check_mem_region_access(env, regno, reg->off,
5544 					       access_size, reg->mem_size,
5545 					       zero_size_allowed);
5546 	case PTR_TO_BUF:
5547 		if (type_is_rdonly_mem(reg->type)) {
5548 			if (meta && meta->raw_mode) {
5549 				verbose(env, "R%d cannot write into %s\n", regno,
5550 					reg_type_str(env, reg->type));
5551 				return -EACCES;
5552 			}
5553 
5554 			max_access = &env->prog->aux->max_rdonly_access;
5555 		} else {
5556 			max_access = &env->prog->aux->max_rdwr_access;
5557 		}
5558 		return check_buffer_access(env, reg, regno, reg->off,
5559 					   access_size, zero_size_allowed,
5560 					   max_access);
5561 	case PTR_TO_STACK:
5562 		return check_stack_range_initialized(
5563 				env,
5564 				regno, reg->off, access_size,
5565 				zero_size_allowed, ACCESS_HELPER, meta);
5566 	case PTR_TO_CTX:
5567 		/* in case the function doesn't know how to access the context,
5568 		 * (because we are in a program of type SYSCALL for example), we
5569 		 * can not statically check its size.
5570 		 * Dynamically check it now.
5571 		 */
5572 		if (!env->ops->convert_ctx_access) {
5573 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5574 			int offset = access_size - 1;
5575 
5576 			/* Allow zero-byte read from PTR_TO_CTX */
5577 			if (access_size == 0)
5578 				return zero_size_allowed ? 0 : -EACCES;
5579 
5580 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5581 						atype, -1, false);
5582 		}
5583 
5584 		fallthrough;
5585 	default: /* scalar_value or invalid ptr */
5586 		/* Allow zero-byte read from NULL, regardless of pointer type */
5587 		if (zero_size_allowed && access_size == 0 &&
5588 		    register_is_null(reg))
5589 			return 0;
5590 
5591 		verbose(env, "R%d type=%s ", regno,
5592 			reg_type_str(env, reg->type));
5593 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5594 		return -EACCES;
5595 	}
5596 }
5597 
5598 static int check_mem_size_reg(struct bpf_verifier_env *env,
5599 			      struct bpf_reg_state *reg, u32 regno,
5600 			      bool zero_size_allowed,
5601 			      struct bpf_call_arg_meta *meta)
5602 {
5603 	int err;
5604 
5605 	/* This is used to refine r0 return value bounds for helpers
5606 	 * that enforce this value as an upper bound on return values.
5607 	 * See do_refine_retval_range() for helpers that can refine
5608 	 * the return value. C type of helper is u32 so we pull register
5609 	 * bound from umax_value however, if negative verifier errors
5610 	 * out. Only upper bounds can be learned because retval is an
5611 	 * int type and negative retvals are allowed.
5612 	 */
5613 	meta->msize_max_value = reg->umax_value;
5614 
5615 	/* The register is SCALAR_VALUE; the access check
5616 	 * happens using its boundaries.
5617 	 */
5618 	if (!tnum_is_const(reg->var_off))
5619 		/* For unprivileged variable accesses, disable raw
5620 		 * mode so that the program is required to
5621 		 * initialize all the memory that the helper could
5622 		 * just partially fill up.
5623 		 */
5624 		meta = NULL;
5625 
5626 	if (reg->smin_value < 0) {
5627 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5628 			regno);
5629 		return -EACCES;
5630 	}
5631 
5632 	if (reg->umin_value == 0) {
5633 		err = check_helper_mem_access(env, regno - 1, 0,
5634 					      zero_size_allowed,
5635 					      meta);
5636 		if (err)
5637 			return err;
5638 	}
5639 
5640 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5641 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5642 			regno);
5643 		return -EACCES;
5644 	}
5645 	err = check_helper_mem_access(env, regno - 1,
5646 				      reg->umax_value,
5647 				      zero_size_allowed, meta);
5648 	if (!err)
5649 		err = mark_chain_precision(env, regno);
5650 	return err;
5651 }
5652 
5653 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5654 		   u32 regno, u32 mem_size)
5655 {
5656 	bool may_be_null = type_may_be_null(reg->type);
5657 	struct bpf_reg_state saved_reg;
5658 	struct bpf_call_arg_meta meta;
5659 	int err;
5660 
5661 	if (register_is_null(reg))
5662 		return 0;
5663 
5664 	memset(&meta, 0, sizeof(meta));
5665 	/* Assuming that the register contains a value check if the memory
5666 	 * access is safe. Temporarily save and restore the register's state as
5667 	 * the conversion shouldn't be visible to a caller.
5668 	 */
5669 	if (may_be_null) {
5670 		saved_reg = *reg;
5671 		mark_ptr_not_null_reg(reg);
5672 	}
5673 
5674 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5675 	/* Check access for BPF_WRITE */
5676 	meta.raw_mode = true;
5677 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5678 
5679 	if (may_be_null)
5680 		*reg = saved_reg;
5681 
5682 	return err;
5683 }
5684 
5685 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5686 				    u32 regno)
5687 {
5688 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5689 	bool may_be_null = type_may_be_null(mem_reg->type);
5690 	struct bpf_reg_state saved_reg;
5691 	struct bpf_call_arg_meta meta;
5692 	int err;
5693 
5694 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5695 
5696 	memset(&meta, 0, sizeof(meta));
5697 
5698 	if (may_be_null) {
5699 		saved_reg = *mem_reg;
5700 		mark_ptr_not_null_reg(mem_reg);
5701 	}
5702 
5703 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5704 	/* Check access for BPF_WRITE */
5705 	meta.raw_mode = true;
5706 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5707 
5708 	if (may_be_null)
5709 		*mem_reg = saved_reg;
5710 	return err;
5711 }
5712 
5713 /* Implementation details:
5714  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5715  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5716  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5717  * Two separate bpf_obj_new will also have different reg->id.
5718  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5719  * clears reg->id after value_or_null->value transition, since the verifier only
5720  * cares about the range of access to valid map value pointer and doesn't care
5721  * about actual address of the map element.
5722  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5723  * reg->id > 0 after value_or_null->value transition. By doing so
5724  * two bpf_map_lookups will be considered two different pointers that
5725  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5726  * returned from bpf_obj_new.
5727  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5728  * dead-locks.
5729  * Since only one bpf_spin_lock is allowed the checks are simpler than
5730  * reg_is_refcounted() logic. The verifier needs to remember only
5731  * one spin_lock instead of array of acquired_refs.
5732  * cur_state->active_lock remembers which map value element or allocated
5733  * object got locked and clears it after bpf_spin_unlock.
5734  */
5735 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5736 			     bool is_lock)
5737 {
5738 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5739 	struct bpf_verifier_state *cur = env->cur_state;
5740 	bool is_const = tnum_is_const(reg->var_off);
5741 	u64 val = reg->var_off.value;
5742 	struct bpf_map *map = NULL;
5743 	struct btf *btf = NULL;
5744 	struct btf_record *rec;
5745 
5746 	if (!is_const) {
5747 		verbose(env,
5748 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5749 			regno);
5750 		return -EINVAL;
5751 	}
5752 	if (reg->type == PTR_TO_MAP_VALUE) {
5753 		map = reg->map_ptr;
5754 		if (!map->btf) {
5755 			verbose(env,
5756 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5757 				map->name);
5758 			return -EINVAL;
5759 		}
5760 	} else {
5761 		btf = reg->btf;
5762 	}
5763 
5764 	rec = reg_btf_record(reg);
5765 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5766 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5767 			map ? map->name : "kptr");
5768 		return -EINVAL;
5769 	}
5770 	if (rec->spin_lock_off != val + reg->off) {
5771 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5772 			val + reg->off, rec->spin_lock_off);
5773 		return -EINVAL;
5774 	}
5775 	if (is_lock) {
5776 		if (cur->active_lock.ptr) {
5777 			verbose(env,
5778 				"Locking two bpf_spin_locks are not allowed\n");
5779 			return -EINVAL;
5780 		}
5781 		if (map)
5782 			cur->active_lock.ptr = map;
5783 		else
5784 			cur->active_lock.ptr = btf;
5785 		cur->active_lock.id = reg->id;
5786 	} else {
5787 		struct bpf_func_state *fstate = cur_func(env);
5788 		void *ptr;
5789 		int i;
5790 
5791 		if (map)
5792 			ptr = map;
5793 		else
5794 			ptr = btf;
5795 
5796 		if (!cur->active_lock.ptr) {
5797 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5798 			return -EINVAL;
5799 		}
5800 		if (cur->active_lock.ptr != ptr ||
5801 		    cur->active_lock.id != reg->id) {
5802 			verbose(env, "bpf_spin_unlock of different lock\n");
5803 			return -EINVAL;
5804 		}
5805 		cur->active_lock.ptr = NULL;
5806 		cur->active_lock.id = 0;
5807 
5808 		for (i = fstate->acquired_refs - 1; i >= 0; i--) {
5809 			int err;
5810 
5811 			/* Complain on error because this reference state cannot
5812 			 * be freed before this point, as bpf_spin_lock critical
5813 			 * section does not allow functions that release the
5814 			 * allocated object immediately.
5815 			 */
5816 			if (!fstate->refs[i].release_on_unlock)
5817 				continue;
5818 			err = release_reference(env, fstate->refs[i].id);
5819 			if (err) {
5820 				verbose(env, "failed to release release_on_unlock reference");
5821 				return err;
5822 			}
5823 		}
5824 	}
5825 	return 0;
5826 }
5827 
5828 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5829 			      struct bpf_call_arg_meta *meta)
5830 {
5831 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5832 	bool is_const = tnum_is_const(reg->var_off);
5833 	struct bpf_map *map = reg->map_ptr;
5834 	u64 val = reg->var_off.value;
5835 
5836 	if (!is_const) {
5837 		verbose(env,
5838 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5839 			regno);
5840 		return -EINVAL;
5841 	}
5842 	if (!map->btf) {
5843 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5844 			map->name);
5845 		return -EINVAL;
5846 	}
5847 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
5848 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5849 		return -EINVAL;
5850 	}
5851 	if (map->record->timer_off != val + reg->off) {
5852 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5853 			val + reg->off, map->record->timer_off);
5854 		return -EINVAL;
5855 	}
5856 	if (meta->map_ptr) {
5857 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5858 		return -EFAULT;
5859 	}
5860 	meta->map_uid = reg->map_uid;
5861 	meta->map_ptr = map;
5862 	return 0;
5863 }
5864 
5865 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5866 			     struct bpf_call_arg_meta *meta)
5867 {
5868 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5869 	struct bpf_map *map_ptr = reg->map_ptr;
5870 	struct btf_field *kptr_field;
5871 	u32 kptr_off;
5872 
5873 	if (!tnum_is_const(reg->var_off)) {
5874 		verbose(env,
5875 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5876 			regno);
5877 		return -EINVAL;
5878 	}
5879 	if (!map_ptr->btf) {
5880 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5881 			map_ptr->name);
5882 		return -EINVAL;
5883 	}
5884 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5885 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5886 		return -EINVAL;
5887 	}
5888 
5889 	meta->map_ptr = map_ptr;
5890 	kptr_off = reg->off + reg->var_off.value;
5891 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5892 	if (!kptr_field) {
5893 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5894 		return -EACCES;
5895 	}
5896 	if (kptr_field->type != BPF_KPTR_REF) {
5897 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5898 		return -EACCES;
5899 	}
5900 	meta->kptr_field = kptr_field;
5901 	return 0;
5902 }
5903 
5904 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
5905  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
5906  *
5907  * In both cases we deal with the first 8 bytes, but need to mark the next 8
5908  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
5909  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
5910  *
5911  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
5912  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
5913  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
5914  * mutate the view of the dynptr and also possibly destroy it. In the latter
5915  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
5916  * memory that dynptr points to.
5917  *
5918  * The verifier will keep track both levels of mutation (bpf_dynptr's in
5919  * reg->type and the memory's in reg->dynptr.type), but there is no support for
5920  * readonly dynptr view yet, hence only the first case is tracked and checked.
5921  *
5922  * This is consistent with how C applies the const modifier to a struct object,
5923  * where the pointer itself inside bpf_dynptr becomes const but not what it
5924  * points to.
5925  *
5926  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
5927  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
5928  */
5929 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
5930 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
5931 {
5932 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5933 
5934 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
5935 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
5936 	 */
5937 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
5938 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
5939 		return -EFAULT;
5940 	}
5941 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
5942 	 * check_func_arg_reg_off's logic. We only need to check offset
5943 	 * alignment for PTR_TO_STACK.
5944 	 */
5945 	if (reg->type == PTR_TO_STACK && (reg->off % BPF_REG_SIZE)) {
5946 		verbose(env, "cannot pass in dynptr at an offset=%d\n", reg->off);
5947 		return -EINVAL;
5948 	}
5949 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
5950 	 *		 constructing a mutable bpf_dynptr object.
5951 	 *
5952 	 *		 Currently, this is only possible with PTR_TO_STACK
5953 	 *		 pointing to a region of at least 16 bytes which doesn't
5954 	 *		 contain an existing bpf_dynptr.
5955 	 *
5956 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
5957 	 *		 mutated or destroyed. However, the memory it points to
5958 	 *		 may be mutated.
5959 	 *
5960 	 *  None       - Points to a initialized dynptr that can be mutated and
5961 	 *		 destroyed, including mutation of the memory it points
5962 	 *		 to.
5963 	 */
5964 	if (arg_type & MEM_UNINIT) {
5965 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
5966 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
5967 			return -EINVAL;
5968 		}
5969 
5970 		/* We only support one dynptr being uninitialized at the moment,
5971 		 * which is sufficient for the helper functions we have right now.
5972 		 */
5973 		if (meta->uninit_dynptr_regno) {
5974 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
5975 			return -EFAULT;
5976 		}
5977 
5978 		meta->uninit_dynptr_regno = regno;
5979 	} else /* MEM_RDONLY and None case from above */ {
5980 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
5981 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
5982 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
5983 			return -EINVAL;
5984 		}
5985 
5986 		if (!is_dynptr_reg_valid_init(env, reg)) {
5987 			verbose(env,
5988 				"Expected an initialized dynptr as arg #%d\n",
5989 				regno);
5990 			return -EINVAL;
5991 		}
5992 
5993 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
5994 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
5995 			const char *err_extra = "";
5996 
5997 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
5998 			case DYNPTR_TYPE_LOCAL:
5999 				err_extra = "local";
6000 				break;
6001 			case DYNPTR_TYPE_RINGBUF:
6002 				err_extra = "ringbuf";
6003 				break;
6004 			default:
6005 				err_extra = "<unknown>";
6006 				break;
6007 			}
6008 			verbose(env,
6009 				"Expected a dynptr of type %s as arg #%d\n",
6010 				err_extra, regno);
6011 			return -EINVAL;
6012 		}
6013 	}
6014 	return 0;
6015 }
6016 
6017 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6018 {
6019 	return type == ARG_CONST_SIZE ||
6020 	       type == ARG_CONST_SIZE_OR_ZERO;
6021 }
6022 
6023 static bool arg_type_is_release(enum bpf_arg_type type)
6024 {
6025 	return type & OBJ_RELEASE;
6026 }
6027 
6028 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6029 {
6030 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6031 }
6032 
6033 static int int_ptr_type_to_size(enum bpf_arg_type type)
6034 {
6035 	if (type == ARG_PTR_TO_INT)
6036 		return sizeof(u32);
6037 	else if (type == ARG_PTR_TO_LONG)
6038 		return sizeof(u64);
6039 
6040 	return -EINVAL;
6041 }
6042 
6043 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6044 				 const struct bpf_call_arg_meta *meta,
6045 				 enum bpf_arg_type *arg_type)
6046 {
6047 	if (!meta->map_ptr) {
6048 		/* kernel subsystem misconfigured verifier */
6049 		verbose(env, "invalid map_ptr to access map->type\n");
6050 		return -EACCES;
6051 	}
6052 
6053 	switch (meta->map_ptr->map_type) {
6054 	case BPF_MAP_TYPE_SOCKMAP:
6055 	case BPF_MAP_TYPE_SOCKHASH:
6056 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6057 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6058 		} else {
6059 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6060 			return -EINVAL;
6061 		}
6062 		break;
6063 	case BPF_MAP_TYPE_BLOOM_FILTER:
6064 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6065 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6066 		break;
6067 	default:
6068 		break;
6069 	}
6070 	return 0;
6071 }
6072 
6073 struct bpf_reg_types {
6074 	const enum bpf_reg_type types[10];
6075 	u32 *btf_id;
6076 };
6077 
6078 static const struct bpf_reg_types sock_types = {
6079 	.types = {
6080 		PTR_TO_SOCK_COMMON,
6081 		PTR_TO_SOCKET,
6082 		PTR_TO_TCP_SOCK,
6083 		PTR_TO_XDP_SOCK,
6084 	},
6085 };
6086 
6087 #ifdef CONFIG_NET
6088 static const struct bpf_reg_types btf_id_sock_common_types = {
6089 	.types = {
6090 		PTR_TO_SOCK_COMMON,
6091 		PTR_TO_SOCKET,
6092 		PTR_TO_TCP_SOCK,
6093 		PTR_TO_XDP_SOCK,
6094 		PTR_TO_BTF_ID,
6095 		PTR_TO_BTF_ID | PTR_TRUSTED,
6096 	},
6097 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6098 };
6099 #endif
6100 
6101 static const struct bpf_reg_types mem_types = {
6102 	.types = {
6103 		PTR_TO_STACK,
6104 		PTR_TO_PACKET,
6105 		PTR_TO_PACKET_META,
6106 		PTR_TO_MAP_KEY,
6107 		PTR_TO_MAP_VALUE,
6108 		PTR_TO_MEM,
6109 		PTR_TO_MEM | MEM_RINGBUF,
6110 		PTR_TO_BUF,
6111 	},
6112 };
6113 
6114 static const struct bpf_reg_types int_ptr_types = {
6115 	.types = {
6116 		PTR_TO_STACK,
6117 		PTR_TO_PACKET,
6118 		PTR_TO_PACKET_META,
6119 		PTR_TO_MAP_KEY,
6120 		PTR_TO_MAP_VALUE,
6121 	},
6122 };
6123 
6124 static const struct bpf_reg_types spin_lock_types = {
6125 	.types = {
6126 		PTR_TO_MAP_VALUE,
6127 		PTR_TO_BTF_ID | MEM_ALLOC,
6128 	}
6129 };
6130 
6131 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6132 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6133 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6134 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6135 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6136 static const struct bpf_reg_types btf_ptr_types = {
6137 	.types = {
6138 		PTR_TO_BTF_ID,
6139 		PTR_TO_BTF_ID | PTR_TRUSTED,
6140 		PTR_TO_BTF_ID | MEM_RCU,
6141 	},
6142 };
6143 static const struct bpf_reg_types percpu_btf_ptr_types = {
6144 	.types = {
6145 		PTR_TO_BTF_ID | MEM_PERCPU,
6146 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6147 	}
6148 };
6149 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6150 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6151 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6152 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6153 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6154 static const struct bpf_reg_types dynptr_types = {
6155 	.types = {
6156 		PTR_TO_STACK,
6157 		CONST_PTR_TO_DYNPTR,
6158 	}
6159 };
6160 
6161 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6162 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6163 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6164 	[ARG_CONST_SIZE]		= &scalar_types,
6165 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6166 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6167 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6168 	[ARG_PTR_TO_CTX]		= &context_types,
6169 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6170 #ifdef CONFIG_NET
6171 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6172 #endif
6173 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6174 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6175 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6176 	[ARG_PTR_TO_MEM]		= &mem_types,
6177 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6178 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6179 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6180 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6181 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6182 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6183 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6184 	[ARG_PTR_TO_TIMER]		= &timer_types,
6185 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6186 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6187 };
6188 
6189 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6190 			  enum bpf_arg_type arg_type,
6191 			  const u32 *arg_btf_id,
6192 			  struct bpf_call_arg_meta *meta)
6193 {
6194 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6195 	enum bpf_reg_type expected, type = reg->type;
6196 	const struct bpf_reg_types *compatible;
6197 	int i, j;
6198 
6199 	compatible = compatible_reg_types[base_type(arg_type)];
6200 	if (!compatible) {
6201 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6202 		return -EFAULT;
6203 	}
6204 
6205 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6206 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6207 	 *
6208 	 * Same for MAYBE_NULL:
6209 	 *
6210 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6211 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6212 	 *
6213 	 * Therefore we fold these flags depending on the arg_type before comparison.
6214 	 */
6215 	if (arg_type & MEM_RDONLY)
6216 		type &= ~MEM_RDONLY;
6217 	if (arg_type & PTR_MAYBE_NULL)
6218 		type &= ~PTR_MAYBE_NULL;
6219 
6220 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6221 		expected = compatible->types[i];
6222 		if (expected == NOT_INIT)
6223 			break;
6224 
6225 		if (type == expected)
6226 			goto found;
6227 	}
6228 
6229 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6230 	for (j = 0; j + 1 < i; j++)
6231 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6232 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6233 	return -EACCES;
6234 
6235 found:
6236 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6237 		/* For bpf_sk_release, it needs to match against first member
6238 		 * 'struct sock_common', hence make an exception for it. This
6239 		 * allows bpf_sk_release to work for multiple socket types.
6240 		 */
6241 		bool strict_type_match = arg_type_is_release(arg_type) &&
6242 					 meta->func_id != BPF_FUNC_sk_release;
6243 
6244 		if (!arg_btf_id) {
6245 			if (!compatible->btf_id) {
6246 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6247 				return -EFAULT;
6248 			}
6249 			arg_btf_id = compatible->btf_id;
6250 		}
6251 
6252 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6253 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6254 				return -EACCES;
6255 		} else {
6256 			if (arg_btf_id == BPF_PTR_POISON) {
6257 				verbose(env, "verifier internal error:");
6258 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6259 					regno);
6260 				return -EACCES;
6261 			}
6262 
6263 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6264 						  btf_vmlinux, *arg_btf_id,
6265 						  strict_type_match)) {
6266 				verbose(env, "R%d is of type %s but %s is expected\n",
6267 					regno, kernel_type_name(reg->btf, reg->btf_id),
6268 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6269 				return -EACCES;
6270 			}
6271 		}
6272 	} else if (type_is_alloc(reg->type)) {
6273 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6274 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6275 			return -EFAULT;
6276 		}
6277 	}
6278 
6279 	return 0;
6280 }
6281 
6282 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6283 			   const struct bpf_reg_state *reg, int regno,
6284 			   enum bpf_arg_type arg_type)
6285 {
6286 	u32 type = reg->type;
6287 
6288 	/* When referenced register is passed to release function, its fixed
6289 	 * offset must be 0.
6290 	 *
6291 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6292 	 * meta->release_regno.
6293 	 */
6294 	if (arg_type_is_release(arg_type)) {
6295 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6296 		 * may not directly point to the object being released, but to
6297 		 * dynptr pointing to such object, which might be at some offset
6298 		 * on the stack. In that case, we simply to fallback to the
6299 		 * default handling.
6300 		 */
6301 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6302 			return 0;
6303 		/* Doing check_ptr_off_reg check for the offset will catch this
6304 		 * because fixed_off_ok is false, but checking here allows us
6305 		 * to give the user a better error message.
6306 		 */
6307 		if (reg->off) {
6308 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6309 				regno);
6310 			return -EINVAL;
6311 		}
6312 		return __check_ptr_off_reg(env, reg, regno, false);
6313 	}
6314 
6315 	switch (type) {
6316 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6317 	case PTR_TO_STACK:
6318 	case PTR_TO_PACKET:
6319 	case PTR_TO_PACKET_META:
6320 	case PTR_TO_MAP_KEY:
6321 	case PTR_TO_MAP_VALUE:
6322 	case PTR_TO_MEM:
6323 	case PTR_TO_MEM | MEM_RDONLY:
6324 	case PTR_TO_MEM | MEM_RINGBUF:
6325 	case PTR_TO_BUF:
6326 	case PTR_TO_BUF | MEM_RDONLY:
6327 	case SCALAR_VALUE:
6328 		return 0;
6329 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6330 	 * fixed offset.
6331 	 */
6332 	case PTR_TO_BTF_ID:
6333 	case PTR_TO_BTF_ID | MEM_ALLOC:
6334 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6335 	case PTR_TO_BTF_ID | MEM_RCU:
6336 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6337 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6338 		 * its fixed offset must be 0. In the other cases, fixed offset
6339 		 * can be non-zero. This was already checked above. So pass
6340 		 * fixed_off_ok as true to allow fixed offset for all other
6341 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6342 		 * still need to do checks instead of returning.
6343 		 */
6344 		return __check_ptr_off_reg(env, reg, regno, true);
6345 	default:
6346 		return __check_ptr_off_reg(env, reg, regno, false);
6347 	}
6348 }
6349 
6350 static u32 dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6351 {
6352 	struct bpf_func_state *state = func(env, reg);
6353 	int spi;
6354 
6355 	if (reg->type == CONST_PTR_TO_DYNPTR)
6356 		return reg->ref_obj_id;
6357 
6358 	spi = get_spi(reg->off);
6359 	return state->stack[spi].spilled_ptr.ref_obj_id;
6360 }
6361 
6362 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6363 			  struct bpf_call_arg_meta *meta,
6364 			  const struct bpf_func_proto *fn)
6365 {
6366 	u32 regno = BPF_REG_1 + arg;
6367 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6368 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6369 	enum bpf_reg_type type = reg->type;
6370 	u32 *arg_btf_id = NULL;
6371 	int err = 0;
6372 
6373 	if (arg_type == ARG_DONTCARE)
6374 		return 0;
6375 
6376 	err = check_reg_arg(env, regno, SRC_OP);
6377 	if (err)
6378 		return err;
6379 
6380 	if (arg_type == ARG_ANYTHING) {
6381 		if (is_pointer_value(env, regno)) {
6382 			verbose(env, "R%d leaks addr into helper function\n",
6383 				regno);
6384 			return -EACCES;
6385 		}
6386 		return 0;
6387 	}
6388 
6389 	if (type_is_pkt_pointer(type) &&
6390 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6391 		verbose(env, "helper access to the packet is not allowed\n");
6392 		return -EACCES;
6393 	}
6394 
6395 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6396 		err = resolve_map_arg_type(env, meta, &arg_type);
6397 		if (err)
6398 			return err;
6399 	}
6400 
6401 	if (register_is_null(reg) && type_may_be_null(arg_type))
6402 		/* A NULL register has a SCALAR_VALUE type, so skip
6403 		 * type checking.
6404 		 */
6405 		goto skip_type_check;
6406 
6407 	/* arg_btf_id and arg_size are in a union. */
6408 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6409 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6410 		arg_btf_id = fn->arg_btf_id[arg];
6411 
6412 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6413 	if (err)
6414 		return err;
6415 
6416 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6417 	if (err)
6418 		return err;
6419 
6420 skip_type_check:
6421 	if (arg_type_is_release(arg_type)) {
6422 		if (arg_type_is_dynptr(arg_type)) {
6423 			struct bpf_func_state *state = func(env, reg);
6424 			int spi;
6425 
6426 			/* Only dynptr created on stack can be released, thus
6427 			 * the get_spi and stack state checks for spilled_ptr
6428 			 * should only be done before process_dynptr_func for
6429 			 * PTR_TO_STACK.
6430 			 */
6431 			if (reg->type == PTR_TO_STACK) {
6432 				spi = get_spi(reg->off);
6433 				if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6434 				    !state->stack[spi].spilled_ptr.ref_obj_id) {
6435 					verbose(env, "arg %d is an unacquired reference\n", regno);
6436 					return -EINVAL;
6437 				}
6438 			} else {
6439 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6440 				return -EINVAL;
6441 			}
6442 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6443 			verbose(env, "R%d must be referenced when passed to release function\n",
6444 				regno);
6445 			return -EINVAL;
6446 		}
6447 		if (meta->release_regno) {
6448 			verbose(env, "verifier internal error: more than one release argument\n");
6449 			return -EFAULT;
6450 		}
6451 		meta->release_regno = regno;
6452 	}
6453 
6454 	if (reg->ref_obj_id) {
6455 		if (meta->ref_obj_id) {
6456 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6457 				regno, reg->ref_obj_id,
6458 				meta->ref_obj_id);
6459 			return -EFAULT;
6460 		}
6461 		meta->ref_obj_id = reg->ref_obj_id;
6462 	}
6463 
6464 	switch (base_type(arg_type)) {
6465 	case ARG_CONST_MAP_PTR:
6466 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6467 		if (meta->map_ptr) {
6468 			/* Use map_uid (which is unique id of inner map) to reject:
6469 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6470 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6471 			 * if (inner_map1 && inner_map2) {
6472 			 *     timer = bpf_map_lookup_elem(inner_map1);
6473 			 *     if (timer)
6474 			 *         // mismatch would have been allowed
6475 			 *         bpf_timer_init(timer, inner_map2);
6476 			 * }
6477 			 *
6478 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6479 			 */
6480 			if (meta->map_ptr != reg->map_ptr ||
6481 			    meta->map_uid != reg->map_uid) {
6482 				verbose(env,
6483 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6484 					meta->map_uid, reg->map_uid);
6485 				return -EINVAL;
6486 			}
6487 		}
6488 		meta->map_ptr = reg->map_ptr;
6489 		meta->map_uid = reg->map_uid;
6490 		break;
6491 	case ARG_PTR_TO_MAP_KEY:
6492 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6493 		 * check that [key, key + map->key_size) are within
6494 		 * stack limits and initialized
6495 		 */
6496 		if (!meta->map_ptr) {
6497 			/* in function declaration map_ptr must come before
6498 			 * map_key, so that it's verified and known before
6499 			 * we have to check map_key here. Otherwise it means
6500 			 * that kernel subsystem misconfigured verifier
6501 			 */
6502 			verbose(env, "invalid map_ptr to access map->key\n");
6503 			return -EACCES;
6504 		}
6505 		err = check_helper_mem_access(env, regno,
6506 					      meta->map_ptr->key_size, false,
6507 					      NULL);
6508 		break;
6509 	case ARG_PTR_TO_MAP_VALUE:
6510 		if (type_may_be_null(arg_type) && register_is_null(reg))
6511 			return 0;
6512 
6513 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6514 		 * check [value, value + map->value_size) validity
6515 		 */
6516 		if (!meta->map_ptr) {
6517 			/* kernel subsystem misconfigured verifier */
6518 			verbose(env, "invalid map_ptr to access map->value\n");
6519 			return -EACCES;
6520 		}
6521 		meta->raw_mode = arg_type & MEM_UNINIT;
6522 		err = check_helper_mem_access(env, regno,
6523 					      meta->map_ptr->value_size, false,
6524 					      meta);
6525 		break;
6526 	case ARG_PTR_TO_PERCPU_BTF_ID:
6527 		if (!reg->btf_id) {
6528 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6529 			return -EACCES;
6530 		}
6531 		meta->ret_btf = reg->btf;
6532 		meta->ret_btf_id = reg->btf_id;
6533 		break;
6534 	case ARG_PTR_TO_SPIN_LOCK:
6535 		if (meta->func_id == BPF_FUNC_spin_lock) {
6536 			err = process_spin_lock(env, regno, true);
6537 			if (err)
6538 				return err;
6539 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6540 			err = process_spin_lock(env, regno, false);
6541 			if (err)
6542 				return err;
6543 		} else {
6544 			verbose(env, "verifier internal error\n");
6545 			return -EFAULT;
6546 		}
6547 		break;
6548 	case ARG_PTR_TO_TIMER:
6549 		err = process_timer_func(env, regno, meta);
6550 		if (err)
6551 			return err;
6552 		break;
6553 	case ARG_PTR_TO_FUNC:
6554 		meta->subprogno = reg->subprogno;
6555 		break;
6556 	case ARG_PTR_TO_MEM:
6557 		/* The access to this pointer is only checked when we hit the
6558 		 * next is_mem_size argument below.
6559 		 */
6560 		meta->raw_mode = arg_type & MEM_UNINIT;
6561 		if (arg_type & MEM_FIXED_SIZE) {
6562 			err = check_helper_mem_access(env, regno,
6563 						      fn->arg_size[arg], false,
6564 						      meta);
6565 		}
6566 		break;
6567 	case ARG_CONST_SIZE:
6568 		err = check_mem_size_reg(env, reg, regno, false, meta);
6569 		break;
6570 	case ARG_CONST_SIZE_OR_ZERO:
6571 		err = check_mem_size_reg(env, reg, regno, true, meta);
6572 		break;
6573 	case ARG_PTR_TO_DYNPTR:
6574 		err = process_dynptr_func(env, regno, arg_type, meta);
6575 		if (err)
6576 			return err;
6577 		break;
6578 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6579 		if (!tnum_is_const(reg->var_off)) {
6580 			verbose(env, "R%d is not a known constant'\n",
6581 				regno);
6582 			return -EACCES;
6583 		}
6584 		meta->mem_size = reg->var_off.value;
6585 		err = mark_chain_precision(env, regno);
6586 		if (err)
6587 			return err;
6588 		break;
6589 	case ARG_PTR_TO_INT:
6590 	case ARG_PTR_TO_LONG:
6591 	{
6592 		int size = int_ptr_type_to_size(arg_type);
6593 
6594 		err = check_helper_mem_access(env, regno, size, false, meta);
6595 		if (err)
6596 			return err;
6597 		err = check_ptr_alignment(env, reg, 0, size, true);
6598 		break;
6599 	}
6600 	case ARG_PTR_TO_CONST_STR:
6601 	{
6602 		struct bpf_map *map = reg->map_ptr;
6603 		int map_off;
6604 		u64 map_addr;
6605 		char *str_ptr;
6606 
6607 		if (!bpf_map_is_rdonly(map)) {
6608 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6609 			return -EACCES;
6610 		}
6611 
6612 		if (!tnum_is_const(reg->var_off)) {
6613 			verbose(env, "R%d is not a constant address'\n", regno);
6614 			return -EACCES;
6615 		}
6616 
6617 		if (!map->ops->map_direct_value_addr) {
6618 			verbose(env, "no direct value access support for this map type\n");
6619 			return -EACCES;
6620 		}
6621 
6622 		err = check_map_access(env, regno, reg->off,
6623 				       map->value_size - reg->off, false,
6624 				       ACCESS_HELPER);
6625 		if (err)
6626 			return err;
6627 
6628 		map_off = reg->off + reg->var_off.value;
6629 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6630 		if (err) {
6631 			verbose(env, "direct value access on string failed\n");
6632 			return err;
6633 		}
6634 
6635 		str_ptr = (char *)(long)(map_addr);
6636 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6637 			verbose(env, "string is not zero-terminated\n");
6638 			return -EINVAL;
6639 		}
6640 		break;
6641 	}
6642 	case ARG_PTR_TO_KPTR:
6643 		err = process_kptr_func(env, regno, meta);
6644 		if (err)
6645 			return err;
6646 		break;
6647 	}
6648 
6649 	return err;
6650 }
6651 
6652 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6653 {
6654 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6655 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6656 
6657 	if (func_id != BPF_FUNC_map_update_elem)
6658 		return false;
6659 
6660 	/* It's not possible to get access to a locked struct sock in these
6661 	 * contexts, so updating is safe.
6662 	 */
6663 	switch (type) {
6664 	case BPF_PROG_TYPE_TRACING:
6665 		if (eatype == BPF_TRACE_ITER)
6666 			return true;
6667 		break;
6668 	case BPF_PROG_TYPE_SOCKET_FILTER:
6669 	case BPF_PROG_TYPE_SCHED_CLS:
6670 	case BPF_PROG_TYPE_SCHED_ACT:
6671 	case BPF_PROG_TYPE_XDP:
6672 	case BPF_PROG_TYPE_SK_REUSEPORT:
6673 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6674 	case BPF_PROG_TYPE_SK_LOOKUP:
6675 		return true;
6676 	default:
6677 		break;
6678 	}
6679 
6680 	verbose(env, "cannot update sockmap in this context\n");
6681 	return false;
6682 }
6683 
6684 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6685 {
6686 	return env->prog->jit_requested &&
6687 	       bpf_jit_supports_subprog_tailcalls();
6688 }
6689 
6690 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6691 					struct bpf_map *map, int func_id)
6692 {
6693 	if (!map)
6694 		return 0;
6695 
6696 	/* We need a two way check, first is from map perspective ... */
6697 	switch (map->map_type) {
6698 	case BPF_MAP_TYPE_PROG_ARRAY:
6699 		if (func_id != BPF_FUNC_tail_call)
6700 			goto error;
6701 		break;
6702 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6703 		if (func_id != BPF_FUNC_perf_event_read &&
6704 		    func_id != BPF_FUNC_perf_event_output &&
6705 		    func_id != BPF_FUNC_skb_output &&
6706 		    func_id != BPF_FUNC_perf_event_read_value &&
6707 		    func_id != BPF_FUNC_xdp_output)
6708 			goto error;
6709 		break;
6710 	case BPF_MAP_TYPE_RINGBUF:
6711 		if (func_id != BPF_FUNC_ringbuf_output &&
6712 		    func_id != BPF_FUNC_ringbuf_reserve &&
6713 		    func_id != BPF_FUNC_ringbuf_query &&
6714 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6715 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6716 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6717 			goto error;
6718 		break;
6719 	case BPF_MAP_TYPE_USER_RINGBUF:
6720 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6721 			goto error;
6722 		break;
6723 	case BPF_MAP_TYPE_STACK_TRACE:
6724 		if (func_id != BPF_FUNC_get_stackid)
6725 			goto error;
6726 		break;
6727 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6728 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6729 		    func_id != BPF_FUNC_current_task_under_cgroup)
6730 			goto error;
6731 		break;
6732 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6733 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6734 		if (func_id != BPF_FUNC_get_local_storage)
6735 			goto error;
6736 		break;
6737 	case BPF_MAP_TYPE_DEVMAP:
6738 	case BPF_MAP_TYPE_DEVMAP_HASH:
6739 		if (func_id != BPF_FUNC_redirect_map &&
6740 		    func_id != BPF_FUNC_map_lookup_elem)
6741 			goto error;
6742 		break;
6743 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6744 	 * appear.
6745 	 */
6746 	case BPF_MAP_TYPE_CPUMAP:
6747 		if (func_id != BPF_FUNC_redirect_map)
6748 			goto error;
6749 		break;
6750 	case BPF_MAP_TYPE_XSKMAP:
6751 		if (func_id != BPF_FUNC_redirect_map &&
6752 		    func_id != BPF_FUNC_map_lookup_elem)
6753 			goto error;
6754 		break;
6755 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6756 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6757 		if (func_id != BPF_FUNC_map_lookup_elem)
6758 			goto error;
6759 		break;
6760 	case BPF_MAP_TYPE_SOCKMAP:
6761 		if (func_id != BPF_FUNC_sk_redirect_map &&
6762 		    func_id != BPF_FUNC_sock_map_update &&
6763 		    func_id != BPF_FUNC_map_delete_elem &&
6764 		    func_id != BPF_FUNC_msg_redirect_map &&
6765 		    func_id != BPF_FUNC_sk_select_reuseport &&
6766 		    func_id != BPF_FUNC_map_lookup_elem &&
6767 		    !may_update_sockmap(env, func_id))
6768 			goto error;
6769 		break;
6770 	case BPF_MAP_TYPE_SOCKHASH:
6771 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6772 		    func_id != BPF_FUNC_sock_hash_update &&
6773 		    func_id != BPF_FUNC_map_delete_elem &&
6774 		    func_id != BPF_FUNC_msg_redirect_hash &&
6775 		    func_id != BPF_FUNC_sk_select_reuseport &&
6776 		    func_id != BPF_FUNC_map_lookup_elem &&
6777 		    !may_update_sockmap(env, func_id))
6778 			goto error;
6779 		break;
6780 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6781 		if (func_id != BPF_FUNC_sk_select_reuseport)
6782 			goto error;
6783 		break;
6784 	case BPF_MAP_TYPE_QUEUE:
6785 	case BPF_MAP_TYPE_STACK:
6786 		if (func_id != BPF_FUNC_map_peek_elem &&
6787 		    func_id != BPF_FUNC_map_pop_elem &&
6788 		    func_id != BPF_FUNC_map_push_elem)
6789 			goto error;
6790 		break;
6791 	case BPF_MAP_TYPE_SK_STORAGE:
6792 		if (func_id != BPF_FUNC_sk_storage_get &&
6793 		    func_id != BPF_FUNC_sk_storage_delete)
6794 			goto error;
6795 		break;
6796 	case BPF_MAP_TYPE_INODE_STORAGE:
6797 		if (func_id != BPF_FUNC_inode_storage_get &&
6798 		    func_id != BPF_FUNC_inode_storage_delete)
6799 			goto error;
6800 		break;
6801 	case BPF_MAP_TYPE_TASK_STORAGE:
6802 		if (func_id != BPF_FUNC_task_storage_get &&
6803 		    func_id != BPF_FUNC_task_storage_delete)
6804 			goto error;
6805 		break;
6806 	case BPF_MAP_TYPE_CGRP_STORAGE:
6807 		if (func_id != BPF_FUNC_cgrp_storage_get &&
6808 		    func_id != BPF_FUNC_cgrp_storage_delete)
6809 			goto error;
6810 		break;
6811 	case BPF_MAP_TYPE_BLOOM_FILTER:
6812 		if (func_id != BPF_FUNC_map_peek_elem &&
6813 		    func_id != BPF_FUNC_map_push_elem)
6814 			goto error;
6815 		break;
6816 	default:
6817 		break;
6818 	}
6819 
6820 	/* ... and second from the function itself. */
6821 	switch (func_id) {
6822 	case BPF_FUNC_tail_call:
6823 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6824 			goto error;
6825 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6826 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6827 			return -EINVAL;
6828 		}
6829 		break;
6830 	case BPF_FUNC_perf_event_read:
6831 	case BPF_FUNC_perf_event_output:
6832 	case BPF_FUNC_perf_event_read_value:
6833 	case BPF_FUNC_skb_output:
6834 	case BPF_FUNC_xdp_output:
6835 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6836 			goto error;
6837 		break;
6838 	case BPF_FUNC_ringbuf_output:
6839 	case BPF_FUNC_ringbuf_reserve:
6840 	case BPF_FUNC_ringbuf_query:
6841 	case BPF_FUNC_ringbuf_reserve_dynptr:
6842 	case BPF_FUNC_ringbuf_submit_dynptr:
6843 	case BPF_FUNC_ringbuf_discard_dynptr:
6844 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6845 			goto error;
6846 		break;
6847 	case BPF_FUNC_user_ringbuf_drain:
6848 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6849 			goto error;
6850 		break;
6851 	case BPF_FUNC_get_stackid:
6852 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6853 			goto error;
6854 		break;
6855 	case BPF_FUNC_current_task_under_cgroup:
6856 	case BPF_FUNC_skb_under_cgroup:
6857 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6858 			goto error;
6859 		break;
6860 	case BPF_FUNC_redirect_map:
6861 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6862 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6863 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6864 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6865 			goto error;
6866 		break;
6867 	case BPF_FUNC_sk_redirect_map:
6868 	case BPF_FUNC_msg_redirect_map:
6869 	case BPF_FUNC_sock_map_update:
6870 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6871 			goto error;
6872 		break;
6873 	case BPF_FUNC_sk_redirect_hash:
6874 	case BPF_FUNC_msg_redirect_hash:
6875 	case BPF_FUNC_sock_hash_update:
6876 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6877 			goto error;
6878 		break;
6879 	case BPF_FUNC_get_local_storage:
6880 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6881 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6882 			goto error;
6883 		break;
6884 	case BPF_FUNC_sk_select_reuseport:
6885 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6886 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6887 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6888 			goto error;
6889 		break;
6890 	case BPF_FUNC_map_pop_elem:
6891 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6892 		    map->map_type != BPF_MAP_TYPE_STACK)
6893 			goto error;
6894 		break;
6895 	case BPF_FUNC_map_peek_elem:
6896 	case BPF_FUNC_map_push_elem:
6897 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6898 		    map->map_type != BPF_MAP_TYPE_STACK &&
6899 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6900 			goto error;
6901 		break;
6902 	case BPF_FUNC_map_lookup_percpu_elem:
6903 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6904 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6905 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6906 			goto error;
6907 		break;
6908 	case BPF_FUNC_sk_storage_get:
6909 	case BPF_FUNC_sk_storage_delete:
6910 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6911 			goto error;
6912 		break;
6913 	case BPF_FUNC_inode_storage_get:
6914 	case BPF_FUNC_inode_storage_delete:
6915 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6916 			goto error;
6917 		break;
6918 	case BPF_FUNC_task_storage_get:
6919 	case BPF_FUNC_task_storage_delete:
6920 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6921 			goto error;
6922 		break;
6923 	case BPF_FUNC_cgrp_storage_get:
6924 	case BPF_FUNC_cgrp_storage_delete:
6925 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6926 			goto error;
6927 		break;
6928 	default:
6929 		break;
6930 	}
6931 
6932 	return 0;
6933 error:
6934 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6935 		map->map_type, func_id_name(func_id), func_id);
6936 	return -EINVAL;
6937 }
6938 
6939 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6940 {
6941 	int count = 0;
6942 
6943 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6944 		count++;
6945 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6946 		count++;
6947 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6948 		count++;
6949 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6950 		count++;
6951 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6952 		count++;
6953 
6954 	/* We only support one arg being in raw mode at the moment,
6955 	 * which is sufficient for the helper functions we have
6956 	 * right now.
6957 	 */
6958 	return count <= 1;
6959 }
6960 
6961 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6962 {
6963 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6964 	bool has_size = fn->arg_size[arg] != 0;
6965 	bool is_next_size = false;
6966 
6967 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6968 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6969 
6970 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6971 		return is_next_size;
6972 
6973 	return has_size == is_next_size || is_next_size == is_fixed;
6974 }
6975 
6976 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6977 {
6978 	/* bpf_xxx(..., buf, len) call will access 'len'
6979 	 * bytes from memory 'buf'. Both arg types need
6980 	 * to be paired, so make sure there's no buggy
6981 	 * helper function specification.
6982 	 */
6983 	if (arg_type_is_mem_size(fn->arg1_type) ||
6984 	    check_args_pair_invalid(fn, 0) ||
6985 	    check_args_pair_invalid(fn, 1) ||
6986 	    check_args_pair_invalid(fn, 2) ||
6987 	    check_args_pair_invalid(fn, 3) ||
6988 	    check_args_pair_invalid(fn, 4))
6989 		return false;
6990 
6991 	return true;
6992 }
6993 
6994 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6995 {
6996 	int i;
6997 
6998 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6999 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7000 			return !!fn->arg_btf_id[i];
7001 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7002 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7003 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7004 		    /* arg_btf_id and arg_size are in a union. */
7005 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7006 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7007 			return false;
7008 	}
7009 
7010 	return true;
7011 }
7012 
7013 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7014 {
7015 	return check_raw_mode_ok(fn) &&
7016 	       check_arg_pair_ok(fn) &&
7017 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7018 }
7019 
7020 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7021  * are now invalid, so turn them into unknown SCALAR_VALUE.
7022  */
7023 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7024 {
7025 	struct bpf_func_state *state;
7026 	struct bpf_reg_state *reg;
7027 
7028 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7029 		if (reg_is_pkt_pointer_any(reg))
7030 			__mark_reg_unknown(env, reg);
7031 	}));
7032 }
7033 
7034 enum {
7035 	AT_PKT_END = -1,
7036 	BEYOND_PKT_END = -2,
7037 };
7038 
7039 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7040 {
7041 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7042 	struct bpf_reg_state *reg = &state->regs[regn];
7043 
7044 	if (reg->type != PTR_TO_PACKET)
7045 		/* PTR_TO_PACKET_META is not supported yet */
7046 		return;
7047 
7048 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7049 	 * How far beyond pkt_end it goes is unknown.
7050 	 * if (!range_open) it's the case of pkt >= pkt_end
7051 	 * if (range_open) it's the case of pkt > pkt_end
7052 	 * hence this pointer is at least 1 byte bigger than pkt_end
7053 	 */
7054 	if (range_open)
7055 		reg->range = BEYOND_PKT_END;
7056 	else
7057 		reg->range = AT_PKT_END;
7058 }
7059 
7060 /* The pointer with the specified id has released its reference to kernel
7061  * resources. Identify all copies of the same pointer and clear the reference.
7062  */
7063 static int release_reference(struct bpf_verifier_env *env,
7064 			     int ref_obj_id)
7065 {
7066 	struct bpf_func_state *state;
7067 	struct bpf_reg_state *reg;
7068 	int err;
7069 
7070 	err = release_reference_state(cur_func(env), ref_obj_id);
7071 	if (err)
7072 		return err;
7073 
7074 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7075 		if (reg->ref_obj_id == ref_obj_id) {
7076 			if (!env->allow_ptr_leaks)
7077 				__mark_reg_not_init(env, reg);
7078 			else
7079 				__mark_reg_unknown(env, reg);
7080 		}
7081 	}));
7082 
7083 	return 0;
7084 }
7085 
7086 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7087 				    struct bpf_reg_state *regs)
7088 {
7089 	int i;
7090 
7091 	/* after the call registers r0 - r5 were scratched */
7092 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7093 		mark_reg_not_init(env, regs, caller_saved[i]);
7094 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7095 	}
7096 }
7097 
7098 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7099 				   struct bpf_func_state *caller,
7100 				   struct bpf_func_state *callee,
7101 				   int insn_idx);
7102 
7103 static int set_callee_state(struct bpf_verifier_env *env,
7104 			    struct bpf_func_state *caller,
7105 			    struct bpf_func_state *callee, int insn_idx);
7106 
7107 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7108 			     int *insn_idx, int subprog,
7109 			     set_callee_state_fn set_callee_state_cb)
7110 {
7111 	struct bpf_verifier_state *state = env->cur_state;
7112 	struct bpf_func_info_aux *func_info_aux;
7113 	struct bpf_func_state *caller, *callee;
7114 	int err;
7115 	bool is_global = false;
7116 
7117 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7118 		verbose(env, "the call stack of %d frames is too deep\n",
7119 			state->curframe + 2);
7120 		return -E2BIG;
7121 	}
7122 
7123 	caller = state->frame[state->curframe];
7124 	if (state->frame[state->curframe + 1]) {
7125 		verbose(env, "verifier bug. Frame %d already allocated\n",
7126 			state->curframe + 1);
7127 		return -EFAULT;
7128 	}
7129 
7130 	func_info_aux = env->prog->aux->func_info_aux;
7131 	if (func_info_aux)
7132 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7133 	err = btf_check_subprog_call(env, subprog, caller->regs);
7134 	if (err == -EFAULT)
7135 		return err;
7136 	if (is_global) {
7137 		if (err) {
7138 			verbose(env, "Caller passes invalid args into func#%d\n",
7139 				subprog);
7140 			return err;
7141 		} else {
7142 			if (env->log.level & BPF_LOG_LEVEL)
7143 				verbose(env,
7144 					"Func#%d is global and valid. Skipping.\n",
7145 					subprog);
7146 			clear_caller_saved_regs(env, caller->regs);
7147 
7148 			/* All global functions return a 64-bit SCALAR_VALUE */
7149 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7150 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7151 
7152 			/* continue with next insn after call */
7153 			return 0;
7154 		}
7155 	}
7156 
7157 	/* set_callee_state is used for direct subprog calls, but we are
7158 	 * interested in validating only BPF helpers that can call subprogs as
7159 	 * callbacks
7160 	 */
7161 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7162 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7163 			func_id_name(insn->imm), insn->imm);
7164 		return -EFAULT;
7165 	}
7166 
7167 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7168 	    insn->src_reg == 0 &&
7169 	    insn->imm == BPF_FUNC_timer_set_callback) {
7170 		struct bpf_verifier_state *async_cb;
7171 
7172 		/* there is no real recursion here. timer callbacks are async */
7173 		env->subprog_info[subprog].is_async_cb = true;
7174 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7175 					 *insn_idx, subprog);
7176 		if (!async_cb)
7177 			return -EFAULT;
7178 		callee = async_cb->frame[0];
7179 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7180 
7181 		/* Convert bpf_timer_set_callback() args into timer callback args */
7182 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7183 		if (err)
7184 			return err;
7185 
7186 		clear_caller_saved_regs(env, caller->regs);
7187 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7188 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7189 		/* continue with next insn after call */
7190 		return 0;
7191 	}
7192 
7193 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7194 	if (!callee)
7195 		return -ENOMEM;
7196 	state->frame[state->curframe + 1] = callee;
7197 
7198 	/* callee cannot access r0, r6 - r9 for reading and has to write
7199 	 * into its own stack before reading from it.
7200 	 * callee can read/write into caller's stack
7201 	 */
7202 	init_func_state(env, callee,
7203 			/* remember the callsite, it will be used by bpf_exit */
7204 			*insn_idx /* callsite */,
7205 			state->curframe + 1 /* frameno within this callchain */,
7206 			subprog /* subprog number within this prog */);
7207 
7208 	/* Transfer references to the callee */
7209 	err = copy_reference_state(callee, caller);
7210 	if (err)
7211 		goto err_out;
7212 
7213 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7214 	if (err)
7215 		goto err_out;
7216 
7217 	clear_caller_saved_regs(env, caller->regs);
7218 
7219 	/* only increment it after check_reg_arg() finished */
7220 	state->curframe++;
7221 
7222 	/* and go analyze first insn of the callee */
7223 	*insn_idx = env->subprog_info[subprog].start - 1;
7224 
7225 	if (env->log.level & BPF_LOG_LEVEL) {
7226 		verbose(env, "caller:\n");
7227 		print_verifier_state(env, caller, true);
7228 		verbose(env, "callee:\n");
7229 		print_verifier_state(env, callee, true);
7230 	}
7231 	return 0;
7232 
7233 err_out:
7234 	free_func_state(callee);
7235 	state->frame[state->curframe + 1] = NULL;
7236 	return err;
7237 }
7238 
7239 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7240 				   struct bpf_func_state *caller,
7241 				   struct bpf_func_state *callee)
7242 {
7243 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7244 	 *      void *callback_ctx, u64 flags);
7245 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7246 	 *      void *callback_ctx);
7247 	 */
7248 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7249 
7250 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7251 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7252 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7253 
7254 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7255 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7256 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7257 
7258 	/* pointer to stack or null */
7259 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7260 
7261 	/* unused */
7262 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7263 	return 0;
7264 }
7265 
7266 static int set_callee_state(struct bpf_verifier_env *env,
7267 			    struct bpf_func_state *caller,
7268 			    struct bpf_func_state *callee, int insn_idx)
7269 {
7270 	int i;
7271 
7272 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7273 	 * pointers, which connects us up to the liveness chain
7274 	 */
7275 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7276 		callee->regs[i] = caller->regs[i];
7277 	return 0;
7278 }
7279 
7280 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7281 			   int *insn_idx)
7282 {
7283 	int subprog, target_insn;
7284 
7285 	target_insn = *insn_idx + insn->imm + 1;
7286 	subprog = find_subprog(env, target_insn);
7287 	if (subprog < 0) {
7288 		verbose(env, "verifier bug. No program starts at insn %d\n",
7289 			target_insn);
7290 		return -EFAULT;
7291 	}
7292 
7293 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7294 }
7295 
7296 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7297 				       struct bpf_func_state *caller,
7298 				       struct bpf_func_state *callee,
7299 				       int insn_idx)
7300 {
7301 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7302 	struct bpf_map *map;
7303 	int err;
7304 
7305 	if (bpf_map_ptr_poisoned(insn_aux)) {
7306 		verbose(env, "tail_call abusing map_ptr\n");
7307 		return -EINVAL;
7308 	}
7309 
7310 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7311 	if (!map->ops->map_set_for_each_callback_args ||
7312 	    !map->ops->map_for_each_callback) {
7313 		verbose(env, "callback function not allowed for map\n");
7314 		return -ENOTSUPP;
7315 	}
7316 
7317 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7318 	if (err)
7319 		return err;
7320 
7321 	callee->in_callback_fn = true;
7322 	callee->callback_ret_range = tnum_range(0, 1);
7323 	return 0;
7324 }
7325 
7326 static int set_loop_callback_state(struct bpf_verifier_env *env,
7327 				   struct bpf_func_state *caller,
7328 				   struct bpf_func_state *callee,
7329 				   int insn_idx)
7330 {
7331 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7332 	 *	    u64 flags);
7333 	 * callback_fn(u32 index, void *callback_ctx);
7334 	 */
7335 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7336 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7337 
7338 	/* unused */
7339 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7340 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7341 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7342 
7343 	callee->in_callback_fn = true;
7344 	callee->callback_ret_range = tnum_range(0, 1);
7345 	return 0;
7346 }
7347 
7348 static int set_timer_callback_state(struct bpf_verifier_env *env,
7349 				    struct bpf_func_state *caller,
7350 				    struct bpf_func_state *callee,
7351 				    int insn_idx)
7352 {
7353 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7354 
7355 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7356 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7357 	 */
7358 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7359 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7360 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7361 
7362 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7363 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7364 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7365 
7366 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7367 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7368 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7369 
7370 	/* unused */
7371 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7372 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7373 	callee->in_async_callback_fn = true;
7374 	callee->callback_ret_range = tnum_range(0, 1);
7375 	return 0;
7376 }
7377 
7378 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7379 				       struct bpf_func_state *caller,
7380 				       struct bpf_func_state *callee,
7381 				       int insn_idx)
7382 {
7383 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7384 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7385 	 * (callback_fn)(struct task_struct *task,
7386 	 *               struct vm_area_struct *vma, void *callback_ctx);
7387 	 */
7388 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7389 
7390 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7391 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7392 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7393 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7394 
7395 	/* pointer to stack or null */
7396 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7397 
7398 	/* unused */
7399 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7400 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7401 	callee->in_callback_fn = true;
7402 	callee->callback_ret_range = tnum_range(0, 1);
7403 	return 0;
7404 }
7405 
7406 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7407 					   struct bpf_func_state *caller,
7408 					   struct bpf_func_state *callee,
7409 					   int insn_idx)
7410 {
7411 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7412 	 *			  callback_ctx, u64 flags);
7413 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7414 	 */
7415 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7416 	mark_dynptr_cb_reg(&callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7417 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7418 
7419 	/* unused */
7420 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7421 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7422 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7423 
7424 	callee->in_callback_fn = true;
7425 	callee->callback_ret_range = tnum_range(0, 1);
7426 	return 0;
7427 }
7428 
7429 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7430 {
7431 	struct bpf_verifier_state *state = env->cur_state;
7432 	struct bpf_func_state *caller, *callee;
7433 	struct bpf_reg_state *r0;
7434 	int err;
7435 
7436 	callee = state->frame[state->curframe];
7437 	r0 = &callee->regs[BPF_REG_0];
7438 	if (r0->type == PTR_TO_STACK) {
7439 		/* technically it's ok to return caller's stack pointer
7440 		 * (or caller's caller's pointer) back to the caller,
7441 		 * since these pointers are valid. Only current stack
7442 		 * pointer will be invalid as soon as function exits,
7443 		 * but let's be conservative
7444 		 */
7445 		verbose(env, "cannot return stack pointer to the caller\n");
7446 		return -EINVAL;
7447 	}
7448 
7449 	caller = state->frame[state->curframe - 1];
7450 	if (callee->in_callback_fn) {
7451 		/* enforce R0 return value range [0, 1]. */
7452 		struct tnum range = callee->callback_ret_range;
7453 
7454 		if (r0->type != SCALAR_VALUE) {
7455 			verbose(env, "R0 not a scalar value\n");
7456 			return -EACCES;
7457 		}
7458 		if (!tnum_in(range, r0->var_off)) {
7459 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7460 			return -EINVAL;
7461 		}
7462 	} else {
7463 		/* return to the caller whatever r0 had in the callee */
7464 		caller->regs[BPF_REG_0] = *r0;
7465 	}
7466 
7467 	/* callback_fn frame should have released its own additions to parent's
7468 	 * reference state at this point, or check_reference_leak would
7469 	 * complain, hence it must be the same as the caller. There is no need
7470 	 * to copy it back.
7471 	 */
7472 	if (!callee->in_callback_fn) {
7473 		/* Transfer references to the caller */
7474 		err = copy_reference_state(caller, callee);
7475 		if (err)
7476 			return err;
7477 	}
7478 
7479 	*insn_idx = callee->callsite + 1;
7480 	if (env->log.level & BPF_LOG_LEVEL) {
7481 		verbose(env, "returning from callee:\n");
7482 		print_verifier_state(env, callee, true);
7483 		verbose(env, "to caller at %d:\n", *insn_idx);
7484 		print_verifier_state(env, caller, true);
7485 	}
7486 	/* clear everything in the callee */
7487 	free_func_state(callee);
7488 	state->frame[state->curframe--] = NULL;
7489 	return 0;
7490 }
7491 
7492 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7493 				   int func_id,
7494 				   struct bpf_call_arg_meta *meta)
7495 {
7496 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7497 
7498 	if (ret_type != RET_INTEGER ||
7499 	    (func_id != BPF_FUNC_get_stack &&
7500 	     func_id != BPF_FUNC_get_task_stack &&
7501 	     func_id != BPF_FUNC_probe_read_str &&
7502 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7503 	     func_id != BPF_FUNC_probe_read_user_str))
7504 		return;
7505 
7506 	ret_reg->smax_value = meta->msize_max_value;
7507 	ret_reg->s32_max_value = meta->msize_max_value;
7508 	ret_reg->smin_value = -MAX_ERRNO;
7509 	ret_reg->s32_min_value = -MAX_ERRNO;
7510 	reg_bounds_sync(ret_reg);
7511 }
7512 
7513 static int
7514 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7515 		int func_id, int insn_idx)
7516 {
7517 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7518 	struct bpf_map *map = meta->map_ptr;
7519 
7520 	if (func_id != BPF_FUNC_tail_call &&
7521 	    func_id != BPF_FUNC_map_lookup_elem &&
7522 	    func_id != BPF_FUNC_map_update_elem &&
7523 	    func_id != BPF_FUNC_map_delete_elem &&
7524 	    func_id != BPF_FUNC_map_push_elem &&
7525 	    func_id != BPF_FUNC_map_pop_elem &&
7526 	    func_id != BPF_FUNC_map_peek_elem &&
7527 	    func_id != BPF_FUNC_for_each_map_elem &&
7528 	    func_id != BPF_FUNC_redirect_map &&
7529 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7530 		return 0;
7531 
7532 	if (map == NULL) {
7533 		verbose(env, "kernel subsystem misconfigured verifier\n");
7534 		return -EINVAL;
7535 	}
7536 
7537 	/* In case of read-only, some additional restrictions
7538 	 * need to be applied in order to prevent altering the
7539 	 * state of the map from program side.
7540 	 */
7541 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7542 	    (func_id == BPF_FUNC_map_delete_elem ||
7543 	     func_id == BPF_FUNC_map_update_elem ||
7544 	     func_id == BPF_FUNC_map_push_elem ||
7545 	     func_id == BPF_FUNC_map_pop_elem)) {
7546 		verbose(env, "write into map forbidden\n");
7547 		return -EACCES;
7548 	}
7549 
7550 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7551 		bpf_map_ptr_store(aux, meta->map_ptr,
7552 				  !meta->map_ptr->bypass_spec_v1);
7553 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7554 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7555 				  !meta->map_ptr->bypass_spec_v1);
7556 	return 0;
7557 }
7558 
7559 static int
7560 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7561 		int func_id, int insn_idx)
7562 {
7563 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7564 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7565 	struct bpf_map *map = meta->map_ptr;
7566 	u64 val, max;
7567 	int err;
7568 
7569 	if (func_id != BPF_FUNC_tail_call)
7570 		return 0;
7571 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7572 		verbose(env, "kernel subsystem misconfigured verifier\n");
7573 		return -EINVAL;
7574 	}
7575 
7576 	reg = &regs[BPF_REG_3];
7577 	val = reg->var_off.value;
7578 	max = map->max_entries;
7579 
7580 	if (!(register_is_const(reg) && val < max)) {
7581 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7582 		return 0;
7583 	}
7584 
7585 	err = mark_chain_precision(env, BPF_REG_3);
7586 	if (err)
7587 		return err;
7588 	if (bpf_map_key_unseen(aux))
7589 		bpf_map_key_store(aux, val);
7590 	else if (!bpf_map_key_poisoned(aux) &&
7591 		  bpf_map_key_immediate(aux) != val)
7592 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7593 	return 0;
7594 }
7595 
7596 static int check_reference_leak(struct bpf_verifier_env *env)
7597 {
7598 	struct bpf_func_state *state = cur_func(env);
7599 	bool refs_lingering = false;
7600 	int i;
7601 
7602 	if (state->frameno && !state->in_callback_fn)
7603 		return 0;
7604 
7605 	for (i = 0; i < state->acquired_refs; i++) {
7606 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7607 			continue;
7608 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7609 			state->refs[i].id, state->refs[i].insn_idx);
7610 		refs_lingering = true;
7611 	}
7612 	return refs_lingering ? -EINVAL : 0;
7613 }
7614 
7615 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7616 				   struct bpf_reg_state *regs)
7617 {
7618 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7619 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7620 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7621 	struct bpf_bprintf_data data = {};
7622 	int err, fmt_map_off, num_args;
7623 	u64 fmt_addr;
7624 	char *fmt;
7625 
7626 	/* data must be an array of u64 */
7627 	if (data_len_reg->var_off.value % 8)
7628 		return -EINVAL;
7629 	num_args = data_len_reg->var_off.value / 8;
7630 
7631 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7632 	 * and map_direct_value_addr is set.
7633 	 */
7634 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7635 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7636 						  fmt_map_off);
7637 	if (err) {
7638 		verbose(env, "verifier bug\n");
7639 		return -EFAULT;
7640 	}
7641 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7642 
7643 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7644 	 * can focus on validating the format specifiers.
7645 	 */
7646 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7647 	if (err < 0)
7648 		verbose(env, "Invalid format string\n");
7649 
7650 	return err;
7651 }
7652 
7653 static int check_get_func_ip(struct bpf_verifier_env *env)
7654 {
7655 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7656 	int func_id = BPF_FUNC_get_func_ip;
7657 
7658 	if (type == BPF_PROG_TYPE_TRACING) {
7659 		if (!bpf_prog_has_trampoline(env->prog)) {
7660 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7661 				func_id_name(func_id), func_id);
7662 			return -ENOTSUPP;
7663 		}
7664 		return 0;
7665 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7666 		return 0;
7667 	}
7668 
7669 	verbose(env, "func %s#%d not supported for program type %d\n",
7670 		func_id_name(func_id), func_id, type);
7671 	return -ENOTSUPP;
7672 }
7673 
7674 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7675 {
7676 	return &env->insn_aux_data[env->insn_idx];
7677 }
7678 
7679 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7680 {
7681 	struct bpf_reg_state *regs = cur_regs(env);
7682 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7683 	bool reg_is_null = register_is_null(reg);
7684 
7685 	if (reg_is_null)
7686 		mark_chain_precision(env, BPF_REG_4);
7687 
7688 	return reg_is_null;
7689 }
7690 
7691 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7692 {
7693 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7694 
7695 	if (!state->initialized) {
7696 		state->initialized = 1;
7697 		state->fit_for_inline = loop_flag_is_zero(env);
7698 		state->callback_subprogno = subprogno;
7699 		return;
7700 	}
7701 
7702 	if (!state->fit_for_inline)
7703 		return;
7704 
7705 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7706 				 state->callback_subprogno == subprogno);
7707 }
7708 
7709 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7710 			     int *insn_idx_p)
7711 {
7712 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7713 	const struct bpf_func_proto *fn = NULL;
7714 	enum bpf_return_type ret_type;
7715 	enum bpf_type_flag ret_flag;
7716 	struct bpf_reg_state *regs;
7717 	struct bpf_call_arg_meta meta;
7718 	int insn_idx = *insn_idx_p;
7719 	bool changes_data;
7720 	int i, err, func_id;
7721 
7722 	/* find function prototype */
7723 	func_id = insn->imm;
7724 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7725 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7726 			func_id);
7727 		return -EINVAL;
7728 	}
7729 
7730 	if (env->ops->get_func_proto)
7731 		fn = env->ops->get_func_proto(func_id, env->prog);
7732 	if (!fn) {
7733 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7734 			func_id);
7735 		return -EINVAL;
7736 	}
7737 
7738 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7739 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7740 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7741 		return -EINVAL;
7742 	}
7743 
7744 	if (fn->allowed && !fn->allowed(env->prog)) {
7745 		verbose(env, "helper call is not allowed in probe\n");
7746 		return -EINVAL;
7747 	}
7748 
7749 	if (!env->prog->aux->sleepable && fn->might_sleep) {
7750 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
7751 		return -EINVAL;
7752 	}
7753 
7754 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7755 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7756 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7757 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7758 			func_id_name(func_id), func_id);
7759 		return -EINVAL;
7760 	}
7761 
7762 	memset(&meta, 0, sizeof(meta));
7763 	meta.pkt_access = fn->pkt_access;
7764 
7765 	err = check_func_proto(fn, func_id);
7766 	if (err) {
7767 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7768 			func_id_name(func_id), func_id);
7769 		return err;
7770 	}
7771 
7772 	if (env->cur_state->active_rcu_lock) {
7773 		if (fn->might_sleep) {
7774 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
7775 				func_id_name(func_id), func_id);
7776 			return -EINVAL;
7777 		}
7778 
7779 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
7780 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
7781 	}
7782 
7783 	meta.func_id = func_id;
7784 	/* check args */
7785 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7786 		err = check_func_arg(env, i, &meta, fn);
7787 		if (err)
7788 			return err;
7789 	}
7790 
7791 	err = record_func_map(env, &meta, func_id, insn_idx);
7792 	if (err)
7793 		return err;
7794 
7795 	err = record_func_key(env, &meta, func_id, insn_idx);
7796 	if (err)
7797 		return err;
7798 
7799 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7800 	 * is inferred from register state.
7801 	 */
7802 	for (i = 0; i < meta.access_size; i++) {
7803 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7804 				       BPF_WRITE, -1, false);
7805 		if (err)
7806 			return err;
7807 	}
7808 
7809 	regs = cur_regs(env);
7810 
7811 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7812 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
7813 	 * is safe to do directly.
7814 	 */
7815 	if (meta.uninit_dynptr_regno) {
7816 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
7817 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
7818 			return -EFAULT;
7819 		}
7820 		/* we write BPF_DW bits (8 bytes) at a time */
7821 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7822 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7823 					       i, BPF_DW, BPF_WRITE, -1, false);
7824 			if (err)
7825 				return err;
7826 		}
7827 
7828 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7829 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7830 					      insn_idx);
7831 		if (err)
7832 			return err;
7833 	}
7834 
7835 	if (meta.release_regno) {
7836 		err = -EINVAL;
7837 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7838 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
7839 		 * is safe to do directly.
7840 		 */
7841 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
7842 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
7843 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
7844 				return -EFAULT;
7845 			}
7846 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7847 		} else if (meta.ref_obj_id) {
7848 			err = release_reference(env, meta.ref_obj_id);
7849 		} else if (register_is_null(&regs[meta.release_regno])) {
7850 			/* meta.ref_obj_id can only be 0 if register that is meant to be
7851 			 * released is NULL, which must be > R0.
7852 			 */
7853 			err = 0;
7854 		}
7855 		if (err) {
7856 			verbose(env, "func %s#%d reference has not been acquired before\n",
7857 				func_id_name(func_id), func_id);
7858 			return err;
7859 		}
7860 	}
7861 
7862 	switch (func_id) {
7863 	case BPF_FUNC_tail_call:
7864 		err = check_reference_leak(env);
7865 		if (err) {
7866 			verbose(env, "tail_call would lead to reference leak\n");
7867 			return err;
7868 		}
7869 		break;
7870 	case BPF_FUNC_get_local_storage:
7871 		/* check that flags argument in get_local_storage(map, flags) is 0,
7872 		 * this is required because get_local_storage() can't return an error.
7873 		 */
7874 		if (!register_is_null(&regs[BPF_REG_2])) {
7875 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7876 			return -EINVAL;
7877 		}
7878 		break;
7879 	case BPF_FUNC_for_each_map_elem:
7880 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7881 					set_map_elem_callback_state);
7882 		break;
7883 	case BPF_FUNC_timer_set_callback:
7884 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7885 					set_timer_callback_state);
7886 		break;
7887 	case BPF_FUNC_find_vma:
7888 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7889 					set_find_vma_callback_state);
7890 		break;
7891 	case BPF_FUNC_snprintf:
7892 		err = check_bpf_snprintf_call(env, regs);
7893 		break;
7894 	case BPF_FUNC_loop:
7895 		update_loop_inline_state(env, meta.subprogno);
7896 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7897 					set_loop_callback_state);
7898 		break;
7899 	case BPF_FUNC_dynptr_from_mem:
7900 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7901 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7902 				reg_type_str(env, regs[BPF_REG_1].type));
7903 			return -EACCES;
7904 		}
7905 		break;
7906 	case BPF_FUNC_set_retval:
7907 		if (prog_type == BPF_PROG_TYPE_LSM &&
7908 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7909 			if (!env->prog->aux->attach_func_proto->type) {
7910 				/* Make sure programs that attach to void
7911 				 * hooks don't try to modify return value.
7912 				 */
7913 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7914 				return -EINVAL;
7915 			}
7916 		}
7917 		break;
7918 	case BPF_FUNC_dynptr_data:
7919 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7920 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7921 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7922 
7923 				if (meta.ref_obj_id) {
7924 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7925 					return -EFAULT;
7926 				}
7927 
7928 				meta.ref_obj_id = dynptr_ref_obj_id(env, reg);
7929 				break;
7930 			}
7931 		}
7932 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7933 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7934 			return -EFAULT;
7935 		}
7936 		break;
7937 	case BPF_FUNC_user_ringbuf_drain:
7938 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7939 					set_user_ringbuf_callback_state);
7940 		break;
7941 	}
7942 
7943 	if (err)
7944 		return err;
7945 
7946 	/* reset caller saved regs */
7947 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7948 		mark_reg_not_init(env, regs, caller_saved[i]);
7949 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7950 	}
7951 
7952 	/* helper call returns 64-bit value. */
7953 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7954 
7955 	/* update return register (already marked as written above) */
7956 	ret_type = fn->ret_type;
7957 	ret_flag = type_flag(ret_type);
7958 
7959 	switch (base_type(ret_type)) {
7960 	case RET_INTEGER:
7961 		/* sets type to SCALAR_VALUE */
7962 		mark_reg_unknown(env, regs, BPF_REG_0);
7963 		break;
7964 	case RET_VOID:
7965 		regs[BPF_REG_0].type = NOT_INIT;
7966 		break;
7967 	case RET_PTR_TO_MAP_VALUE:
7968 		/* There is no offset yet applied, variable or fixed */
7969 		mark_reg_known_zero(env, regs, BPF_REG_0);
7970 		/* remember map_ptr, so that check_map_access()
7971 		 * can check 'value_size' boundary of memory access
7972 		 * to map element returned from bpf_map_lookup_elem()
7973 		 */
7974 		if (meta.map_ptr == NULL) {
7975 			verbose(env,
7976 				"kernel subsystem misconfigured verifier\n");
7977 			return -EINVAL;
7978 		}
7979 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7980 		regs[BPF_REG_0].map_uid = meta.map_uid;
7981 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7982 		if (!type_may_be_null(ret_type) &&
7983 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7984 			regs[BPF_REG_0].id = ++env->id_gen;
7985 		}
7986 		break;
7987 	case RET_PTR_TO_SOCKET:
7988 		mark_reg_known_zero(env, regs, BPF_REG_0);
7989 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7990 		break;
7991 	case RET_PTR_TO_SOCK_COMMON:
7992 		mark_reg_known_zero(env, regs, BPF_REG_0);
7993 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7994 		break;
7995 	case RET_PTR_TO_TCP_SOCK:
7996 		mark_reg_known_zero(env, regs, BPF_REG_0);
7997 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7998 		break;
7999 	case RET_PTR_TO_MEM:
8000 		mark_reg_known_zero(env, regs, BPF_REG_0);
8001 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8002 		regs[BPF_REG_0].mem_size = meta.mem_size;
8003 		break;
8004 	case RET_PTR_TO_MEM_OR_BTF_ID:
8005 	{
8006 		const struct btf_type *t;
8007 
8008 		mark_reg_known_zero(env, regs, BPF_REG_0);
8009 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8010 		if (!btf_type_is_struct(t)) {
8011 			u32 tsize;
8012 			const struct btf_type *ret;
8013 			const char *tname;
8014 
8015 			/* resolve the type size of ksym. */
8016 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8017 			if (IS_ERR(ret)) {
8018 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8019 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8020 					tname, PTR_ERR(ret));
8021 				return -EINVAL;
8022 			}
8023 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8024 			regs[BPF_REG_0].mem_size = tsize;
8025 		} else {
8026 			/* MEM_RDONLY may be carried from ret_flag, but it
8027 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8028 			 * it will confuse the check of PTR_TO_BTF_ID in
8029 			 * check_mem_access().
8030 			 */
8031 			ret_flag &= ~MEM_RDONLY;
8032 
8033 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8034 			regs[BPF_REG_0].btf = meta.ret_btf;
8035 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8036 		}
8037 		break;
8038 	}
8039 	case RET_PTR_TO_BTF_ID:
8040 	{
8041 		struct btf *ret_btf;
8042 		int ret_btf_id;
8043 
8044 		mark_reg_known_zero(env, regs, BPF_REG_0);
8045 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8046 		if (func_id == BPF_FUNC_kptr_xchg) {
8047 			ret_btf = meta.kptr_field->kptr.btf;
8048 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8049 		} else {
8050 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8051 				verbose(env, "verifier internal error:");
8052 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8053 					func_id_name(func_id));
8054 				return -EINVAL;
8055 			}
8056 			ret_btf = btf_vmlinux;
8057 			ret_btf_id = *fn->ret_btf_id;
8058 		}
8059 		if (ret_btf_id == 0) {
8060 			verbose(env, "invalid return type %u of func %s#%d\n",
8061 				base_type(ret_type), func_id_name(func_id),
8062 				func_id);
8063 			return -EINVAL;
8064 		}
8065 		regs[BPF_REG_0].btf = ret_btf;
8066 		regs[BPF_REG_0].btf_id = ret_btf_id;
8067 		break;
8068 	}
8069 	default:
8070 		verbose(env, "unknown return type %u of func %s#%d\n",
8071 			base_type(ret_type), func_id_name(func_id), func_id);
8072 		return -EINVAL;
8073 	}
8074 
8075 	if (type_may_be_null(regs[BPF_REG_0].type))
8076 		regs[BPF_REG_0].id = ++env->id_gen;
8077 
8078 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8079 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8080 			func_id_name(func_id), func_id);
8081 		return -EFAULT;
8082 	}
8083 
8084 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8085 		/* For release_reference() */
8086 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8087 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8088 		int id = acquire_reference_state(env, insn_idx);
8089 
8090 		if (id < 0)
8091 			return id;
8092 		/* For mark_ptr_or_null_reg() */
8093 		regs[BPF_REG_0].id = id;
8094 		/* For release_reference() */
8095 		regs[BPF_REG_0].ref_obj_id = id;
8096 	}
8097 
8098 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8099 
8100 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8101 	if (err)
8102 		return err;
8103 
8104 	if ((func_id == BPF_FUNC_get_stack ||
8105 	     func_id == BPF_FUNC_get_task_stack) &&
8106 	    !env->prog->has_callchain_buf) {
8107 		const char *err_str;
8108 
8109 #ifdef CONFIG_PERF_EVENTS
8110 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8111 		err_str = "cannot get callchain buffer for func %s#%d\n";
8112 #else
8113 		err = -ENOTSUPP;
8114 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8115 #endif
8116 		if (err) {
8117 			verbose(env, err_str, func_id_name(func_id), func_id);
8118 			return err;
8119 		}
8120 
8121 		env->prog->has_callchain_buf = true;
8122 	}
8123 
8124 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8125 		env->prog->call_get_stack = true;
8126 
8127 	if (func_id == BPF_FUNC_get_func_ip) {
8128 		if (check_get_func_ip(env))
8129 			return -ENOTSUPP;
8130 		env->prog->call_get_func_ip = true;
8131 	}
8132 
8133 	if (changes_data)
8134 		clear_all_pkt_pointers(env);
8135 	return 0;
8136 }
8137 
8138 /* mark_btf_func_reg_size() is used when the reg size is determined by
8139  * the BTF func_proto's return value size and argument.
8140  */
8141 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8142 				   size_t reg_size)
8143 {
8144 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8145 
8146 	if (regno == BPF_REG_0) {
8147 		/* Function return value */
8148 		reg->live |= REG_LIVE_WRITTEN;
8149 		reg->subreg_def = reg_size == sizeof(u64) ?
8150 			DEF_NOT_SUBREG : env->insn_idx + 1;
8151 	} else {
8152 		/* Function argument */
8153 		if (reg_size == sizeof(u64)) {
8154 			mark_insn_zext(env, reg);
8155 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8156 		} else {
8157 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8158 		}
8159 	}
8160 }
8161 
8162 struct bpf_kfunc_call_arg_meta {
8163 	/* In parameters */
8164 	struct btf *btf;
8165 	u32 func_id;
8166 	u32 kfunc_flags;
8167 	const struct btf_type *func_proto;
8168 	const char *func_name;
8169 	/* Out parameters */
8170 	u32 ref_obj_id;
8171 	u8 release_regno;
8172 	bool r0_rdonly;
8173 	u32 ret_btf_id;
8174 	u64 r0_size;
8175 	struct {
8176 		u64 value;
8177 		bool found;
8178 	} arg_constant;
8179 	struct {
8180 		struct btf *btf;
8181 		u32 btf_id;
8182 	} arg_obj_drop;
8183 	struct {
8184 		struct btf_field *field;
8185 	} arg_list_head;
8186 };
8187 
8188 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8189 {
8190 	return meta->kfunc_flags & KF_ACQUIRE;
8191 }
8192 
8193 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8194 {
8195 	return meta->kfunc_flags & KF_RET_NULL;
8196 }
8197 
8198 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8199 {
8200 	return meta->kfunc_flags & KF_RELEASE;
8201 }
8202 
8203 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8204 {
8205 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8206 }
8207 
8208 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8209 {
8210 	return meta->kfunc_flags & KF_SLEEPABLE;
8211 }
8212 
8213 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8214 {
8215 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8216 }
8217 
8218 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8219 {
8220 	return meta->kfunc_flags & KF_RCU;
8221 }
8222 
8223 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8224 {
8225 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8226 }
8227 
8228 static bool __kfunc_param_match_suffix(const struct btf *btf,
8229 				       const struct btf_param *arg,
8230 				       const char *suffix)
8231 {
8232 	int suffix_len = strlen(suffix), len;
8233 	const char *param_name;
8234 
8235 	/* In the future, this can be ported to use BTF tagging */
8236 	param_name = btf_name_by_offset(btf, arg->name_off);
8237 	if (str_is_empty(param_name))
8238 		return false;
8239 	len = strlen(param_name);
8240 	if (len < suffix_len)
8241 		return false;
8242 	param_name += len - suffix_len;
8243 	return !strncmp(param_name, suffix, suffix_len);
8244 }
8245 
8246 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8247 				  const struct btf_param *arg,
8248 				  const struct bpf_reg_state *reg)
8249 {
8250 	const struct btf_type *t;
8251 
8252 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8253 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8254 		return false;
8255 
8256 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8257 }
8258 
8259 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8260 {
8261 	return __kfunc_param_match_suffix(btf, arg, "__k");
8262 }
8263 
8264 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8265 {
8266 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8267 }
8268 
8269 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8270 {
8271 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8272 }
8273 
8274 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8275 					  const struct btf_param *arg,
8276 					  const char *name)
8277 {
8278 	int len, target_len = strlen(name);
8279 	const char *param_name;
8280 
8281 	param_name = btf_name_by_offset(btf, arg->name_off);
8282 	if (str_is_empty(param_name))
8283 		return false;
8284 	len = strlen(param_name);
8285 	if (len != target_len)
8286 		return false;
8287 	if (strcmp(param_name, name))
8288 		return false;
8289 
8290 	return true;
8291 }
8292 
8293 enum {
8294 	KF_ARG_DYNPTR_ID,
8295 	KF_ARG_LIST_HEAD_ID,
8296 	KF_ARG_LIST_NODE_ID,
8297 };
8298 
8299 BTF_ID_LIST(kf_arg_btf_ids)
8300 BTF_ID(struct, bpf_dynptr_kern)
8301 BTF_ID(struct, bpf_list_head)
8302 BTF_ID(struct, bpf_list_node)
8303 
8304 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8305 				    const struct btf_param *arg, int type)
8306 {
8307 	const struct btf_type *t;
8308 	u32 res_id;
8309 
8310 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8311 	if (!t)
8312 		return false;
8313 	if (!btf_type_is_ptr(t))
8314 		return false;
8315 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8316 	if (!t)
8317 		return false;
8318 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8319 }
8320 
8321 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8322 {
8323 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8324 }
8325 
8326 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8327 {
8328 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8329 }
8330 
8331 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8332 {
8333 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8334 }
8335 
8336 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8337 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8338 					const struct btf *btf,
8339 					const struct btf_type *t, int rec)
8340 {
8341 	const struct btf_type *member_type;
8342 	const struct btf_member *member;
8343 	u32 i;
8344 
8345 	if (!btf_type_is_struct(t))
8346 		return false;
8347 
8348 	for_each_member(i, t, member) {
8349 		const struct btf_array *array;
8350 
8351 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8352 		if (btf_type_is_struct(member_type)) {
8353 			if (rec >= 3) {
8354 				verbose(env, "max struct nesting depth exceeded\n");
8355 				return false;
8356 			}
8357 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8358 				return false;
8359 			continue;
8360 		}
8361 		if (btf_type_is_array(member_type)) {
8362 			array = btf_array(member_type);
8363 			if (!array->nelems)
8364 				return false;
8365 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8366 			if (!btf_type_is_scalar(member_type))
8367 				return false;
8368 			continue;
8369 		}
8370 		if (!btf_type_is_scalar(member_type))
8371 			return false;
8372 	}
8373 	return true;
8374 }
8375 
8376 
8377 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8378 #ifdef CONFIG_NET
8379 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8380 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8381 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8382 #endif
8383 };
8384 
8385 enum kfunc_ptr_arg_type {
8386 	KF_ARG_PTR_TO_CTX,
8387 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8388 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8389 	KF_ARG_PTR_TO_DYNPTR,
8390 	KF_ARG_PTR_TO_LIST_HEAD,
8391 	KF_ARG_PTR_TO_LIST_NODE,
8392 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8393 	KF_ARG_PTR_TO_MEM,
8394 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8395 };
8396 
8397 enum special_kfunc_type {
8398 	KF_bpf_obj_new_impl,
8399 	KF_bpf_obj_drop_impl,
8400 	KF_bpf_list_push_front,
8401 	KF_bpf_list_push_back,
8402 	KF_bpf_list_pop_front,
8403 	KF_bpf_list_pop_back,
8404 	KF_bpf_cast_to_kern_ctx,
8405 	KF_bpf_rdonly_cast,
8406 	KF_bpf_rcu_read_lock,
8407 	KF_bpf_rcu_read_unlock,
8408 };
8409 
8410 BTF_SET_START(special_kfunc_set)
8411 BTF_ID(func, bpf_obj_new_impl)
8412 BTF_ID(func, bpf_obj_drop_impl)
8413 BTF_ID(func, bpf_list_push_front)
8414 BTF_ID(func, bpf_list_push_back)
8415 BTF_ID(func, bpf_list_pop_front)
8416 BTF_ID(func, bpf_list_pop_back)
8417 BTF_ID(func, bpf_cast_to_kern_ctx)
8418 BTF_ID(func, bpf_rdonly_cast)
8419 BTF_SET_END(special_kfunc_set)
8420 
8421 BTF_ID_LIST(special_kfunc_list)
8422 BTF_ID(func, bpf_obj_new_impl)
8423 BTF_ID(func, bpf_obj_drop_impl)
8424 BTF_ID(func, bpf_list_push_front)
8425 BTF_ID(func, bpf_list_push_back)
8426 BTF_ID(func, bpf_list_pop_front)
8427 BTF_ID(func, bpf_list_pop_back)
8428 BTF_ID(func, bpf_cast_to_kern_ctx)
8429 BTF_ID(func, bpf_rdonly_cast)
8430 BTF_ID(func, bpf_rcu_read_lock)
8431 BTF_ID(func, bpf_rcu_read_unlock)
8432 
8433 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8434 {
8435 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8436 }
8437 
8438 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8439 {
8440 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8441 }
8442 
8443 static enum kfunc_ptr_arg_type
8444 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8445 		       struct bpf_kfunc_call_arg_meta *meta,
8446 		       const struct btf_type *t, const struct btf_type *ref_t,
8447 		       const char *ref_tname, const struct btf_param *args,
8448 		       int argno, int nargs)
8449 {
8450 	u32 regno = argno + 1;
8451 	struct bpf_reg_state *regs = cur_regs(env);
8452 	struct bpf_reg_state *reg = &regs[regno];
8453 	bool arg_mem_size = false;
8454 
8455 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8456 		return KF_ARG_PTR_TO_CTX;
8457 
8458 	/* In this function, we verify the kfunc's BTF as per the argument type,
8459 	 * leaving the rest of the verification with respect to the register
8460 	 * type to our caller. When a set of conditions hold in the BTF type of
8461 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8462 	 */
8463 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8464 		return KF_ARG_PTR_TO_CTX;
8465 
8466 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8467 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8468 
8469 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8470 		if (!btf_type_is_ptr(ref_t)) {
8471 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8472 			return -EINVAL;
8473 		}
8474 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8475 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8476 		if (!btf_type_is_struct(ref_t)) {
8477 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8478 				meta->func_name, btf_type_str(ref_t), ref_tname);
8479 			return -EINVAL;
8480 		}
8481 		return KF_ARG_PTR_TO_KPTR;
8482 	}
8483 
8484 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8485 		return KF_ARG_PTR_TO_DYNPTR;
8486 
8487 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8488 		return KF_ARG_PTR_TO_LIST_HEAD;
8489 
8490 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8491 		return KF_ARG_PTR_TO_LIST_NODE;
8492 
8493 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8494 		if (!btf_type_is_struct(ref_t)) {
8495 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8496 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8497 			return -EINVAL;
8498 		}
8499 		return KF_ARG_PTR_TO_BTF_ID;
8500 	}
8501 
8502 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8503 		arg_mem_size = true;
8504 
8505 	/* This is the catch all argument type of register types supported by
8506 	 * check_helper_mem_access. However, we only allow when argument type is
8507 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8508 	 * arg_mem_size is true, the pointer can be void *.
8509 	 */
8510 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8511 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8512 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8513 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8514 		return -EINVAL;
8515 	}
8516 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8517 }
8518 
8519 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8520 					struct bpf_reg_state *reg,
8521 					const struct btf_type *ref_t,
8522 					const char *ref_tname, u32 ref_id,
8523 					struct bpf_kfunc_call_arg_meta *meta,
8524 					int argno)
8525 {
8526 	const struct btf_type *reg_ref_t;
8527 	bool strict_type_match = false;
8528 	const struct btf *reg_btf;
8529 	const char *reg_ref_tname;
8530 	u32 reg_ref_id;
8531 
8532 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
8533 		reg_btf = reg->btf;
8534 		reg_ref_id = reg->btf_id;
8535 	} else {
8536 		reg_btf = btf_vmlinux;
8537 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8538 	}
8539 
8540 	if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8541 		strict_type_match = true;
8542 
8543 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8544 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8545 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8546 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8547 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8548 			btf_type_str(reg_ref_t), reg_ref_tname);
8549 		return -EINVAL;
8550 	}
8551 	return 0;
8552 }
8553 
8554 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8555 				      struct bpf_reg_state *reg,
8556 				      const struct btf_type *ref_t,
8557 				      const char *ref_tname,
8558 				      struct bpf_kfunc_call_arg_meta *meta,
8559 				      int argno)
8560 {
8561 	struct btf_field *kptr_field;
8562 
8563 	/* check_func_arg_reg_off allows var_off for
8564 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8565 	 * off_desc.
8566 	 */
8567 	if (!tnum_is_const(reg->var_off)) {
8568 		verbose(env, "arg#0 must have constant offset\n");
8569 		return -EINVAL;
8570 	}
8571 
8572 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8573 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8574 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8575 			reg->off + reg->var_off.value);
8576 		return -EINVAL;
8577 	}
8578 
8579 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8580 				  kptr_field->kptr.btf_id, true)) {
8581 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8582 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8583 		return -EINVAL;
8584 	}
8585 	return 0;
8586 }
8587 
8588 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8589 {
8590 	struct bpf_func_state *state = cur_func(env);
8591 	struct bpf_reg_state *reg;
8592 	int i;
8593 
8594 	/* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8595 	 * subprogs, no global functions. This means that the references would
8596 	 * not be released inside the critical section but they may be added to
8597 	 * the reference state, and the acquired_refs are never copied out for a
8598 	 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8599 	 * critical sections.
8600 	 */
8601 	if (!ref_obj_id) {
8602 		verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8603 		return -EFAULT;
8604 	}
8605 	for (i = 0; i < state->acquired_refs; i++) {
8606 		if (state->refs[i].id == ref_obj_id) {
8607 			if (state->refs[i].release_on_unlock) {
8608 				verbose(env, "verifier internal error: expected false release_on_unlock");
8609 				return -EFAULT;
8610 			}
8611 			state->refs[i].release_on_unlock = true;
8612 			/* Now mark everyone sharing same ref_obj_id as untrusted */
8613 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8614 				if (reg->ref_obj_id == ref_obj_id)
8615 					reg->type |= PTR_UNTRUSTED;
8616 			}));
8617 			return 0;
8618 		}
8619 	}
8620 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8621 	return -EFAULT;
8622 }
8623 
8624 /* Implementation details:
8625  *
8626  * Each register points to some region of memory, which we define as an
8627  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8628  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8629  * allocation. The lock and the data it protects are colocated in the same
8630  * memory region.
8631  *
8632  * Hence, everytime a register holds a pointer value pointing to such
8633  * allocation, the verifier preserves a unique reg->id for it.
8634  *
8635  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8636  * bpf_spin_lock is called.
8637  *
8638  * To enable this, lock state in the verifier captures two values:
8639  *	active_lock.ptr = Register's type specific pointer
8640  *	active_lock.id  = A unique ID for each register pointer value
8641  *
8642  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8643  * supported register types.
8644  *
8645  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8646  * allocated objects is the reg->btf pointer.
8647  *
8648  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8649  * can establish the provenance of the map value statically for each distinct
8650  * lookup into such maps. They always contain a single map value hence unique
8651  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8652  *
8653  * So, in case of global variables, they use array maps with max_entries = 1,
8654  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8655  * into the same map value as max_entries is 1, as described above).
8656  *
8657  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8658  * outer map pointer (in verifier context), but each lookup into an inner map
8659  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8660  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8661  * will get different reg->id assigned to each lookup, hence different
8662  * active_lock.id.
8663  *
8664  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8665  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8666  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8667  */
8668 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8669 {
8670 	void *ptr;
8671 	u32 id;
8672 
8673 	switch ((int)reg->type) {
8674 	case PTR_TO_MAP_VALUE:
8675 		ptr = reg->map_ptr;
8676 		break;
8677 	case PTR_TO_BTF_ID | MEM_ALLOC:
8678 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8679 		ptr = reg->btf;
8680 		break;
8681 	default:
8682 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
8683 		return -EFAULT;
8684 	}
8685 	id = reg->id;
8686 
8687 	if (!env->cur_state->active_lock.ptr)
8688 		return -EINVAL;
8689 	if (env->cur_state->active_lock.ptr != ptr ||
8690 	    env->cur_state->active_lock.id != id) {
8691 		verbose(env, "held lock and object are not in the same allocation\n");
8692 		return -EINVAL;
8693 	}
8694 	return 0;
8695 }
8696 
8697 static bool is_bpf_list_api_kfunc(u32 btf_id)
8698 {
8699 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8700 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8701 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8702 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8703 }
8704 
8705 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8706 					   struct bpf_reg_state *reg, u32 regno,
8707 					   struct bpf_kfunc_call_arg_meta *meta)
8708 {
8709 	struct btf_field *field;
8710 	struct btf_record *rec;
8711 	u32 list_head_off;
8712 
8713 	if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8714 		verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8715 		return -EFAULT;
8716 	}
8717 
8718 	if (!tnum_is_const(reg->var_off)) {
8719 		verbose(env,
8720 			"R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8721 			regno);
8722 		return -EINVAL;
8723 	}
8724 
8725 	rec = reg_btf_record(reg);
8726 	list_head_off = reg->off + reg->var_off.value;
8727 	field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8728 	if (!field) {
8729 		verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8730 		return -EINVAL;
8731 	}
8732 
8733 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8734 	if (check_reg_allocation_locked(env, reg)) {
8735 		verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8736 			rec->spin_lock_off);
8737 		return -EINVAL;
8738 	}
8739 
8740 	if (meta->arg_list_head.field) {
8741 		verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8742 		return -EFAULT;
8743 	}
8744 	meta->arg_list_head.field = field;
8745 	return 0;
8746 }
8747 
8748 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8749 					   struct bpf_reg_state *reg, u32 regno,
8750 					   struct bpf_kfunc_call_arg_meta *meta)
8751 {
8752 	const struct btf_type *et, *t;
8753 	struct btf_field *field;
8754 	struct btf_record *rec;
8755 	u32 list_node_off;
8756 
8757 	if (meta->btf != btf_vmlinux ||
8758 	    (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8759 	     meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8760 		verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8761 		return -EFAULT;
8762 	}
8763 
8764 	if (!tnum_is_const(reg->var_off)) {
8765 		verbose(env,
8766 			"R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8767 			regno);
8768 		return -EINVAL;
8769 	}
8770 
8771 	rec = reg_btf_record(reg);
8772 	list_node_off = reg->off + reg->var_off.value;
8773 	field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8774 	if (!field || field->offset != list_node_off) {
8775 		verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8776 		return -EINVAL;
8777 	}
8778 
8779 	field = meta->arg_list_head.field;
8780 
8781 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
8782 	t = btf_type_by_id(reg->btf, reg->btf_id);
8783 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
8784 				  field->graph_root.value_btf_id, true)) {
8785 		verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8786 			"in struct %s, but arg is at offset=%d in struct %s\n",
8787 			field->graph_root.node_offset,
8788 			btf_name_by_offset(field->graph_root.btf, et->name_off),
8789 			list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8790 		return -EINVAL;
8791 	}
8792 
8793 	if (list_node_off != field->graph_root.node_offset) {
8794 		verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8795 			list_node_off, field->graph_root.node_offset,
8796 			btf_name_by_offset(field->graph_root.btf, et->name_off));
8797 		return -EINVAL;
8798 	}
8799 	/* Set arg#1 for expiration after unlock */
8800 	return ref_set_release_on_unlock(env, reg->ref_obj_id);
8801 }
8802 
8803 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8804 {
8805 	const char *func_name = meta->func_name, *ref_tname;
8806 	const struct btf *btf = meta->btf;
8807 	const struct btf_param *args;
8808 	u32 i, nargs;
8809 	int ret;
8810 
8811 	args = (const struct btf_param *)(meta->func_proto + 1);
8812 	nargs = btf_type_vlen(meta->func_proto);
8813 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8814 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8815 			MAX_BPF_FUNC_REG_ARGS);
8816 		return -EINVAL;
8817 	}
8818 
8819 	/* Check that BTF function arguments match actual types that the
8820 	 * verifier sees.
8821 	 */
8822 	for (i = 0; i < nargs; i++) {
8823 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8824 		const struct btf_type *t, *ref_t, *resolve_ret;
8825 		enum bpf_arg_type arg_type = ARG_DONTCARE;
8826 		u32 regno = i + 1, ref_id, type_size;
8827 		bool is_ret_buf_sz = false;
8828 		int kf_arg_type;
8829 
8830 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8831 
8832 		if (is_kfunc_arg_ignore(btf, &args[i]))
8833 			continue;
8834 
8835 		if (btf_type_is_scalar(t)) {
8836 			if (reg->type != SCALAR_VALUE) {
8837 				verbose(env, "R%d is not a scalar\n", regno);
8838 				return -EINVAL;
8839 			}
8840 
8841 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8842 				if (meta->arg_constant.found) {
8843 					verbose(env, "verifier internal error: only one constant argument permitted\n");
8844 					return -EFAULT;
8845 				}
8846 				if (!tnum_is_const(reg->var_off)) {
8847 					verbose(env, "R%d must be a known constant\n", regno);
8848 					return -EINVAL;
8849 				}
8850 				ret = mark_chain_precision(env, regno);
8851 				if (ret < 0)
8852 					return ret;
8853 				meta->arg_constant.found = true;
8854 				meta->arg_constant.value = reg->var_off.value;
8855 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8856 				meta->r0_rdonly = true;
8857 				is_ret_buf_sz = true;
8858 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8859 				is_ret_buf_sz = true;
8860 			}
8861 
8862 			if (is_ret_buf_sz) {
8863 				if (meta->r0_size) {
8864 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8865 					return -EINVAL;
8866 				}
8867 
8868 				if (!tnum_is_const(reg->var_off)) {
8869 					verbose(env, "R%d is not a const\n", regno);
8870 					return -EINVAL;
8871 				}
8872 
8873 				meta->r0_size = reg->var_off.value;
8874 				ret = mark_chain_precision(env, regno);
8875 				if (ret)
8876 					return ret;
8877 			}
8878 			continue;
8879 		}
8880 
8881 		if (!btf_type_is_ptr(t)) {
8882 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8883 			return -EINVAL;
8884 		}
8885 
8886 		if (reg->ref_obj_id) {
8887 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
8888 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8889 					regno, reg->ref_obj_id,
8890 					meta->ref_obj_id);
8891 				return -EFAULT;
8892 			}
8893 			meta->ref_obj_id = reg->ref_obj_id;
8894 			if (is_kfunc_release(meta))
8895 				meta->release_regno = regno;
8896 		}
8897 
8898 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8899 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8900 
8901 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8902 		if (kf_arg_type < 0)
8903 			return kf_arg_type;
8904 
8905 		switch (kf_arg_type) {
8906 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8907 		case KF_ARG_PTR_TO_BTF_ID:
8908 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
8909 				break;
8910 
8911 			if (!is_trusted_reg(reg)) {
8912 				if (!is_kfunc_rcu(meta)) {
8913 					verbose(env, "R%d must be referenced or trusted\n", regno);
8914 					return -EINVAL;
8915 				}
8916 				if (!is_rcu_reg(reg)) {
8917 					verbose(env, "R%d must be a rcu pointer\n", regno);
8918 					return -EINVAL;
8919 				}
8920 			}
8921 
8922 			fallthrough;
8923 		case KF_ARG_PTR_TO_CTX:
8924 			/* Trusted arguments have the same offset checks as release arguments */
8925 			arg_type |= OBJ_RELEASE;
8926 			break;
8927 		case KF_ARG_PTR_TO_KPTR:
8928 		case KF_ARG_PTR_TO_DYNPTR:
8929 		case KF_ARG_PTR_TO_LIST_HEAD:
8930 		case KF_ARG_PTR_TO_LIST_NODE:
8931 		case KF_ARG_PTR_TO_MEM:
8932 		case KF_ARG_PTR_TO_MEM_SIZE:
8933 			/* Trusted by default */
8934 			break;
8935 		default:
8936 			WARN_ON_ONCE(1);
8937 			return -EFAULT;
8938 		}
8939 
8940 		if (is_kfunc_release(meta) && reg->ref_obj_id)
8941 			arg_type |= OBJ_RELEASE;
8942 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8943 		if (ret < 0)
8944 			return ret;
8945 
8946 		switch (kf_arg_type) {
8947 		case KF_ARG_PTR_TO_CTX:
8948 			if (reg->type != PTR_TO_CTX) {
8949 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8950 				return -EINVAL;
8951 			}
8952 
8953 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8954 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8955 				if (ret < 0)
8956 					return -EINVAL;
8957 				meta->ret_btf_id  = ret;
8958 			}
8959 			break;
8960 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8961 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8962 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
8963 				return -EINVAL;
8964 			}
8965 			if (!reg->ref_obj_id) {
8966 				verbose(env, "allocated object must be referenced\n");
8967 				return -EINVAL;
8968 			}
8969 			if (meta->btf == btf_vmlinux &&
8970 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8971 				meta->arg_obj_drop.btf = reg->btf;
8972 				meta->arg_obj_drop.btf_id = reg->btf_id;
8973 			}
8974 			break;
8975 		case KF_ARG_PTR_TO_KPTR:
8976 			if (reg->type != PTR_TO_MAP_VALUE) {
8977 				verbose(env, "arg#0 expected pointer to map value\n");
8978 				return -EINVAL;
8979 			}
8980 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8981 			if (ret < 0)
8982 				return ret;
8983 			break;
8984 		case KF_ARG_PTR_TO_DYNPTR:
8985 			if (reg->type != PTR_TO_STACK &&
8986 			    reg->type != CONST_PTR_TO_DYNPTR) {
8987 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
8988 				return -EINVAL;
8989 			}
8990 
8991 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
8992 			if (ret < 0)
8993 				return ret;
8994 			break;
8995 		case KF_ARG_PTR_TO_LIST_HEAD:
8996 			if (reg->type != PTR_TO_MAP_VALUE &&
8997 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8998 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8999 				return -EINVAL;
9000 			}
9001 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9002 				verbose(env, "allocated object must be referenced\n");
9003 				return -EINVAL;
9004 			}
9005 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9006 			if (ret < 0)
9007 				return ret;
9008 			break;
9009 		case KF_ARG_PTR_TO_LIST_NODE:
9010 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9011 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9012 				return -EINVAL;
9013 			}
9014 			if (!reg->ref_obj_id) {
9015 				verbose(env, "allocated object must be referenced\n");
9016 				return -EINVAL;
9017 			}
9018 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9019 			if (ret < 0)
9020 				return ret;
9021 			break;
9022 		case KF_ARG_PTR_TO_BTF_ID:
9023 			/* Only base_type is checked, further checks are done here */
9024 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9025 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9026 			    !reg2btf_ids[base_type(reg->type)]) {
9027 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9028 				verbose(env, "expected %s or socket\n",
9029 					reg_type_str(env, base_type(reg->type) |
9030 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9031 				return -EINVAL;
9032 			}
9033 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9034 			if (ret < 0)
9035 				return ret;
9036 			break;
9037 		case KF_ARG_PTR_TO_MEM:
9038 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9039 			if (IS_ERR(resolve_ret)) {
9040 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9041 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9042 				return -EINVAL;
9043 			}
9044 			ret = check_mem_reg(env, reg, regno, type_size);
9045 			if (ret < 0)
9046 				return ret;
9047 			break;
9048 		case KF_ARG_PTR_TO_MEM_SIZE:
9049 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9050 			if (ret < 0) {
9051 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9052 				return ret;
9053 			}
9054 			/* Skip next '__sz' argument */
9055 			i++;
9056 			break;
9057 		}
9058 	}
9059 
9060 	if (is_kfunc_release(meta) && !meta->release_regno) {
9061 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9062 			func_name);
9063 		return -EINVAL;
9064 	}
9065 
9066 	return 0;
9067 }
9068 
9069 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9070 			    int *insn_idx_p)
9071 {
9072 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9073 	struct bpf_reg_state *regs = cur_regs(env);
9074 	const char *func_name, *ptr_type_name;
9075 	bool sleepable, rcu_lock, rcu_unlock;
9076 	struct bpf_kfunc_call_arg_meta meta;
9077 	u32 i, nargs, func_id, ptr_type_id;
9078 	int err, insn_idx = *insn_idx_p;
9079 	const struct btf_param *args;
9080 	const struct btf_type *ret_t;
9081 	struct btf *desc_btf;
9082 	u32 *kfunc_flags;
9083 
9084 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9085 	if (!insn->imm)
9086 		return 0;
9087 
9088 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9089 	if (IS_ERR(desc_btf))
9090 		return PTR_ERR(desc_btf);
9091 
9092 	func_id = insn->imm;
9093 	func = btf_type_by_id(desc_btf, func_id);
9094 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9095 	func_proto = btf_type_by_id(desc_btf, func->type);
9096 
9097 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9098 	if (!kfunc_flags) {
9099 		verbose(env, "calling kernel function %s is not allowed\n",
9100 			func_name);
9101 		return -EACCES;
9102 	}
9103 
9104 	/* Prepare kfunc call metadata */
9105 	memset(&meta, 0, sizeof(meta));
9106 	meta.btf = desc_btf;
9107 	meta.func_id = func_id;
9108 	meta.kfunc_flags = *kfunc_flags;
9109 	meta.func_proto = func_proto;
9110 	meta.func_name = func_name;
9111 
9112 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9113 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9114 		return -EACCES;
9115 	}
9116 
9117 	sleepable = is_kfunc_sleepable(&meta);
9118 	if (sleepable && !env->prog->aux->sleepable) {
9119 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9120 		return -EACCES;
9121 	}
9122 
9123 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9124 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9125 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9126 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9127 		return -EACCES;
9128 	}
9129 
9130 	if (env->cur_state->active_rcu_lock) {
9131 		struct bpf_func_state *state;
9132 		struct bpf_reg_state *reg;
9133 
9134 		if (rcu_lock) {
9135 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9136 			return -EINVAL;
9137 		} else if (rcu_unlock) {
9138 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9139 				if (reg->type & MEM_RCU) {
9140 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9141 					reg->type |= PTR_UNTRUSTED;
9142 				}
9143 			}));
9144 			env->cur_state->active_rcu_lock = false;
9145 		} else if (sleepable) {
9146 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9147 			return -EACCES;
9148 		}
9149 	} else if (rcu_lock) {
9150 		env->cur_state->active_rcu_lock = true;
9151 	} else if (rcu_unlock) {
9152 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9153 		return -EINVAL;
9154 	}
9155 
9156 	/* Check the arguments */
9157 	err = check_kfunc_args(env, &meta);
9158 	if (err < 0)
9159 		return err;
9160 	/* In case of release function, we get register number of refcounted
9161 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9162 	 */
9163 	if (meta.release_regno) {
9164 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9165 		if (err) {
9166 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9167 				func_name, func_id);
9168 			return err;
9169 		}
9170 	}
9171 
9172 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9173 		mark_reg_not_init(env, regs, caller_saved[i]);
9174 
9175 	/* Check return type */
9176 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9177 
9178 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9179 		/* Only exception is bpf_obj_new_impl */
9180 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9181 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9182 			return -EINVAL;
9183 		}
9184 	}
9185 
9186 	if (btf_type_is_scalar(t)) {
9187 		mark_reg_unknown(env, regs, BPF_REG_0);
9188 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9189 	} else if (btf_type_is_ptr(t)) {
9190 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9191 
9192 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9193 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9194 				struct btf *ret_btf;
9195 				u32 ret_btf_id;
9196 
9197 				if (unlikely(!bpf_global_ma_set))
9198 					return -ENOMEM;
9199 
9200 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9201 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9202 					return -EINVAL;
9203 				}
9204 
9205 				ret_btf = env->prog->aux->btf;
9206 				ret_btf_id = meta.arg_constant.value;
9207 
9208 				/* This may be NULL due to user not supplying a BTF */
9209 				if (!ret_btf) {
9210 					verbose(env, "bpf_obj_new requires prog BTF\n");
9211 					return -EINVAL;
9212 				}
9213 
9214 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9215 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9216 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9217 					return -EINVAL;
9218 				}
9219 
9220 				mark_reg_known_zero(env, regs, BPF_REG_0);
9221 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9222 				regs[BPF_REG_0].btf = ret_btf;
9223 				regs[BPF_REG_0].btf_id = ret_btf_id;
9224 
9225 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9226 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9227 					btf_find_struct_meta(ret_btf, ret_btf_id);
9228 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9229 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9230 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9231 							     meta.arg_obj_drop.btf_id);
9232 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9233 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9234 				struct btf_field *field = meta.arg_list_head.field;
9235 
9236 				mark_reg_known_zero(env, regs, BPF_REG_0);
9237 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9238 				regs[BPF_REG_0].btf = field->graph_root.btf;
9239 				regs[BPF_REG_0].btf_id = field->graph_root.value_btf_id;
9240 				regs[BPF_REG_0].off = field->graph_root.node_offset;
9241 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9242 				mark_reg_known_zero(env, regs, BPF_REG_0);
9243 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9244 				regs[BPF_REG_0].btf = desc_btf;
9245 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9246 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9247 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9248 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9249 					verbose(env,
9250 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9251 					return -EINVAL;
9252 				}
9253 
9254 				mark_reg_known_zero(env, regs, BPF_REG_0);
9255 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9256 				regs[BPF_REG_0].btf = desc_btf;
9257 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9258 			} else {
9259 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9260 					meta.func_name);
9261 				return -EFAULT;
9262 			}
9263 		} else if (!__btf_type_is_struct(ptr_type)) {
9264 			if (!meta.r0_size) {
9265 				ptr_type_name = btf_name_by_offset(desc_btf,
9266 								   ptr_type->name_off);
9267 				verbose(env,
9268 					"kernel function %s returns pointer type %s %s is not supported\n",
9269 					func_name,
9270 					btf_type_str(ptr_type),
9271 					ptr_type_name);
9272 				return -EINVAL;
9273 			}
9274 
9275 			mark_reg_known_zero(env, regs, BPF_REG_0);
9276 			regs[BPF_REG_0].type = PTR_TO_MEM;
9277 			regs[BPF_REG_0].mem_size = meta.r0_size;
9278 
9279 			if (meta.r0_rdonly)
9280 				regs[BPF_REG_0].type |= MEM_RDONLY;
9281 
9282 			/* Ensures we don't access the memory after a release_reference() */
9283 			if (meta.ref_obj_id)
9284 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9285 		} else {
9286 			mark_reg_known_zero(env, regs, BPF_REG_0);
9287 			regs[BPF_REG_0].btf = desc_btf;
9288 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9289 			regs[BPF_REG_0].btf_id = ptr_type_id;
9290 		}
9291 
9292 		if (is_kfunc_ret_null(&meta)) {
9293 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9294 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9295 			regs[BPF_REG_0].id = ++env->id_gen;
9296 		}
9297 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9298 		if (is_kfunc_acquire(&meta)) {
9299 			int id = acquire_reference_state(env, insn_idx);
9300 
9301 			if (id < 0)
9302 				return id;
9303 			if (is_kfunc_ret_null(&meta))
9304 				regs[BPF_REG_0].id = id;
9305 			regs[BPF_REG_0].ref_obj_id = id;
9306 		}
9307 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9308 			regs[BPF_REG_0].id = ++env->id_gen;
9309 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9310 
9311 	nargs = btf_type_vlen(func_proto);
9312 	args = (const struct btf_param *)(func_proto + 1);
9313 	for (i = 0; i < nargs; i++) {
9314 		u32 regno = i + 1;
9315 
9316 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9317 		if (btf_type_is_ptr(t))
9318 			mark_btf_func_reg_size(env, regno, sizeof(void *));
9319 		else
9320 			/* scalar. ensured by btf_check_kfunc_arg_match() */
9321 			mark_btf_func_reg_size(env, regno, t->size);
9322 	}
9323 
9324 	return 0;
9325 }
9326 
9327 static bool signed_add_overflows(s64 a, s64 b)
9328 {
9329 	/* Do the add in u64, where overflow is well-defined */
9330 	s64 res = (s64)((u64)a + (u64)b);
9331 
9332 	if (b < 0)
9333 		return res > a;
9334 	return res < a;
9335 }
9336 
9337 static bool signed_add32_overflows(s32 a, s32 b)
9338 {
9339 	/* Do the add in u32, where overflow is well-defined */
9340 	s32 res = (s32)((u32)a + (u32)b);
9341 
9342 	if (b < 0)
9343 		return res > a;
9344 	return res < a;
9345 }
9346 
9347 static bool signed_sub_overflows(s64 a, s64 b)
9348 {
9349 	/* Do the sub in u64, where overflow is well-defined */
9350 	s64 res = (s64)((u64)a - (u64)b);
9351 
9352 	if (b < 0)
9353 		return res < a;
9354 	return res > a;
9355 }
9356 
9357 static bool signed_sub32_overflows(s32 a, s32 b)
9358 {
9359 	/* Do the sub in u32, where overflow is well-defined */
9360 	s32 res = (s32)((u32)a - (u32)b);
9361 
9362 	if (b < 0)
9363 		return res < a;
9364 	return res > a;
9365 }
9366 
9367 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9368 				  const struct bpf_reg_state *reg,
9369 				  enum bpf_reg_type type)
9370 {
9371 	bool known = tnum_is_const(reg->var_off);
9372 	s64 val = reg->var_off.value;
9373 	s64 smin = reg->smin_value;
9374 
9375 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9376 		verbose(env, "math between %s pointer and %lld is not allowed\n",
9377 			reg_type_str(env, type), val);
9378 		return false;
9379 	}
9380 
9381 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9382 		verbose(env, "%s pointer offset %d is not allowed\n",
9383 			reg_type_str(env, type), reg->off);
9384 		return false;
9385 	}
9386 
9387 	if (smin == S64_MIN) {
9388 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9389 			reg_type_str(env, type));
9390 		return false;
9391 	}
9392 
9393 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9394 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
9395 			smin, reg_type_str(env, type));
9396 		return false;
9397 	}
9398 
9399 	return true;
9400 }
9401 
9402 enum {
9403 	REASON_BOUNDS	= -1,
9404 	REASON_TYPE	= -2,
9405 	REASON_PATHS	= -3,
9406 	REASON_LIMIT	= -4,
9407 	REASON_STACK	= -5,
9408 };
9409 
9410 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9411 			      u32 *alu_limit, bool mask_to_left)
9412 {
9413 	u32 max = 0, ptr_limit = 0;
9414 
9415 	switch (ptr_reg->type) {
9416 	case PTR_TO_STACK:
9417 		/* Offset 0 is out-of-bounds, but acceptable start for the
9418 		 * left direction, see BPF_REG_FP. Also, unknown scalar
9419 		 * offset where we would need to deal with min/max bounds is
9420 		 * currently prohibited for unprivileged.
9421 		 */
9422 		max = MAX_BPF_STACK + mask_to_left;
9423 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9424 		break;
9425 	case PTR_TO_MAP_VALUE:
9426 		max = ptr_reg->map_ptr->value_size;
9427 		ptr_limit = (mask_to_left ?
9428 			     ptr_reg->smin_value :
9429 			     ptr_reg->umax_value) + ptr_reg->off;
9430 		break;
9431 	default:
9432 		return REASON_TYPE;
9433 	}
9434 
9435 	if (ptr_limit >= max)
9436 		return REASON_LIMIT;
9437 	*alu_limit = ptr_limit;
9438 	return 0;
9439 }
9440 
9441 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9442 				    const struct bpf_insn *insn)
9443 {
9444 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9445 }
9446 
9447 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9448 				       u32 alu_state, u32 alu_limit)
9449 {
9450 	/* If we arrived here from different branches with different
9451 	 * state or limits to sanitize, then this won't work.
9452 	 */
9453 	if (aux->alu_state &&
9454 	    (aux->alu_state != alu_state ||
9455 	     aux->alu_limit != alu_limit))
9456 		return REASON_PATHS;
9457 
9458 	/* Corresponding fixup done in do_misc_fixups(). */
9459 	aux->alu_state = alu_state;
9460 	aux->alu_limit = alu_limit;
9461 	return 0;
9462 }
9463 
9464 static int sanitize_val_alu(struct bpf_verifier_env *env,
9465 			    struct bpf_insn *insn)
9466 {
9467 	struct bpf_insn_aux_data *aux = cur_aux(env);
9468 
9469 	if (can_skip_alu_sanitation(env, insn))
9470 		return 0;
9471 
9472 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9473 }
9474 
9475 static bool sanitize_needed(u8 opcode)
9476 {
9477 	return opcode == BPF_ADD || opcode == BPF_SUB;
9478 }
9479 
9480 struct bpf_sanitize_info {
9481 	struct bpf_insn_aux_data aux;
9482 	bool mask_to_left;
9483 };
9484 
9485 static struct bpf_verifier_state *
9486 sanitize_speculative_path(struct bpf_verifier_env *env,
9487 			  const struct bpf_insn *insn,
9488 			  u32 next_idx, u32 curr_idx)
9489 {
9490 	struct bpf_verifier_state *branch;
9491 	struct bpf_reg_state *regs;
9492 
9493 	branch = push_stack(env, next_idx, curr_idx, true);
9494 	if (branch && insn) {
9495 		regs = branch->frame[branch->curframe]->regs;
9496 		if (BPF_SRC(insn->code) == BPF_K) {
9497 			mark_reg_unknown(env, regs, insn->dst_reg);
9498 		} else if (BPF_SRC(insn->code) == BPF_X) {
9499 			mark_reg_unknown(env, regs, insn->dst_reg);
9500 			mark_reg_unknown(env, regs, insn->src_reg);
9501 		}
9502 	}
9503 	return branch;
9504 }
9505 
9506 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9507 			    struct bpf_insn *insn,
9508 			    const struct bpf_reg_state *ptr_reg,
9509 			    const struct bpf_reg_state *off_reg,
9510 			    struct bpf_reg_state *dst_reg,
9511 			    struct bpf_sanitize_info *info,
9512 			    const bool commit_window)
9513 {
9514 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9515 	struct bpf_verifier_state *vstate = env->cur_state;
9516 	bool off_is_imm = tnum_is_const(off_reg->var_off);
9517 	bool off_is_neg = off_reg->smin_value < 0;
9518 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
9519 	u8 opcode = BPF_OP(insn->code);
9520 	u32 alu_state, alu_limit;
9521 	struct bpf_reg_state tmp;
9522 	bool ret;
9523 	int err;
9524 
9525 	if (can_skip_alu_sanitation(env, insn))
9526 		return 0;
9527 
9528 	/* We already marked aux for masking from non-speculative
9529 	 * paths, thus we got here in the first place. We only care
9530 	 * to explore bad access from here.
9531 	 */
9532 	if (vstate->speculative)
9533 		goto do_sim;
9534 
9535 	if (!commit_window) {
9536 		if (!tnum_is_const(off_reg->var_off) &&
9537 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9538 			return REASON_BOUNDS;
9539 
9540 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9541 				     (opcode == BPF_SUB && !off_is_neg);
9542 	}
9543 
9544 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9545 	if (err < 0)
9546 		return err;
9547 
9548 	if (commit_window) {
9549 		/* In commit phase we narrow the masking window based on
9550 		 * the observed pointer move after the simulated operation.
9551 		 */
9552 		alu_state = info->aux.alu_state;
9553 		alu_limit = abs(info->aux.alu_limit - alu_limit);
9554 	} else {
9555 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9556 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9557 		alu_state |= ptr_is_dst_reg ?
9558 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9559 
9560 		/* Limit pruning on unknown scalars to enable deep search for
9561 		 * potential masking differences from other program paths.
9562 		 */
9563 		if (!off_is_imm)
9564 			env->explore_alu_limits = true;
9565 	}
9566 
9567 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9568 	if (err < 0)
9569 		return err;
9570 do_sim:
9571 	/* If we're in commit phase, we're done here given we already
9572 	 * pushed the truncated dst_reg into the speculative verification
9573 	 * stack.
9574 	 *
9575 	 * Also, when register is a known constant, we rewrite register-based
9576 	 * operation to immediate-based, and thus do not need masking (and as
9577 	 * a consequence, do not need to simulate the zero-truncation either).
9578 	 */
9579 	if (commit_window || off_is_imm)
9580 		return 0;
9581 
9582 	/* Simulate and find potential out-of-bounds access under
9583 	 * speculative execution from truncation as a result of
9584 	 * masking when off was not within expected range. If off
9585 	 * sits in dst, then we temporarily need to move ptr there
9586 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9587 	 * for cases where we use K-based arithmetic in one direction
9588 	 * and truncated reg-based in the other in order to explore
9589 	 * bad access.
9590 	 */
9591 	if (!ptr_is_dst_reg) {
9592 		tmp = *dst_reg;
9593 		*dst_reg = *ptr_reg;
9594 	}
9595 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9596 					env->insn_idx);
9597 	if (!ptr_is_dst_reg && ret)
9598 		*dst_reg = tmp;
9599 	return !ret ? REASON_STACK : 0;
9600 }
9601 
9602 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9603 {
9604 	struct bpf_verifier_state *vstate = env->cur_state;
9605 
9606 	/* If we simulate paths under speculation, we don't update the
9607 	 * insn as 'seen' such that when we verify unreachable paths in
9608 	 * the non-speculative domain, sanitize_dead_code() can still
9609 	 * rewrite/sanitize them.
9610 	 */
9611 	if (!vstate->speculative)
9612 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9613 }
9614 
9615 static int sanitize_err(struct bpf_verifier_env *env,
9616 			const struct bpf_insn *insn, int reason,
9617 			const struct bpf_reg_state *off_reg,
9618 			const struct bpf_reg_state *dst_reg)
9619 {
9620 	static const char *err = "pointer arithmetic with it prohibited for !root";
9621 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9622 	u32 dst = insn->dst_reg, src = insn->src_reg;
9623 
9624 	switch (reason) {
9625 	case REASON_BOUNDS:
9626 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9627 			off_reg == dst_reg ? dst : src, err);
9628 		break;
9629 	case REASON_TYPE:
9630 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9631 			off_reg == dst_reg ? src : dst, err);
9632 		break;
9633 	case REASON_PATHS:
9634 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9635 			dst, op, err);
9636 		break;
9637 	case REASON_LIMIT:
9638 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9639 			dst, op, err);
9640 		break;
9641 	case REASON_STACK:
9642 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9643 			dst, err);
9644 		break;
9645 	default:
9646 		verbose(env, "verifier internal error: unknown reason (%d)\n",
9647 			reason);
9648 		break;
9649 	}
9650 
9651 	return -EACCES;
9652 }
9653 
9654 /* check that stack access falls within stack limits and that 'reg' doesn't
9655  * have a variable offset.
9656  *
9657  * Variable offset is prohibited for unprivileged mode for simplicity since it
9658  * requires corresponding support in Spectre masking for stack ALU.  See also
9659  * retrieve_ptr_limit().
9660  *
9661  *
9662  * 'off' includes 'reg->off'.
9663  */
9664 static int check_stack_access_for_ptr_arithmetic(
9665 				struct bpf_verifier_env *env,
9666 				int regno,
9667 				const struct bpf_reg_state *reg,
9668 				int off)
9669 {
9670 	if (!tnum_is_const(reg->var_off)) {
9671 		char tn_buf[48];
9672 
9673 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9674 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9675 			regno, tn_buf, off);
9676 		return -EACCES;
9677 	}
9678 
9679 	if (off >= 0 || off < -MAX_BPF_STACK) {
9680 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
9681 			"prohibited for !root; off=%d\n", regno, off);
9682 		return -EACCES;
9683 	}
9684 
9685 	return 0;
9686 }
9687 
9688 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9689 				 const struct bpf_insn *insn,
9690 				 const struct bpf_reg_state *dst_reg)
9691 {
9692 	u32 dst = insn->dst_reg;
9693 
9694 	/* For unprivileged we require that resulting offset must be in bounds
9695 	 * in order to be able to sanitize access later on.
9696 	 */
9697 	if (env->bypass_spec_v1)
9698 		return 0;
9699 
9700 	switch (dst_reg->type) {
9701 	case PTR_TO_STACK:
9702 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9703 					dst_reg->off + dst_reg->var_off.value))
9704 			return -EACCES;
9705 		break;
9706 	case PTR_TO_MAP_VALUE:
9707 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9708 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9709 				"prohibited for !root\n", dst);
9710 			return -EACCES;
9711 		}
9712 		break;
9713 	default:
9714 		break;
9715 	}
9716 
9717 	return 0;
9718 }
9719 
9720 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9721  * Caller should also handle BPF_MOV case separately.
9722  * If we return -EACCES, caller may want to try again treating pointer as a
9723  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9724  */
9725 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9726 				   struct bpf_insn *insn,
9727 				   const struct bpf_reg_state *ptr_reg,
9728 				   const struct bpf_reg_state *off_reg)
9729 {
9730 	struct bpf_verifier_state *vstate = env->cur_state;
9731 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9732 	struct bpf_reg_state *regs = state->regs, *dst_reg;
9733 	bool known = tnum_is_const(off_reg->var_off);
9734 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9735 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9736 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9737 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9738 	struct bpf_sanitize_info info = {};
9739 	u8 opcode = BPF_OP(insn->code);
9740 	u32 dst = insn->dst_reg;
9741 	int ret;
9742 
9743 	dst_reg = &regs[dst];
9744 
9745 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9746 	    smin_val > smax_val || umin_val > umax_val) {
9747 		/* Taint dst register if offset had invalid bounds derived from
9748 		 * e.g. dead branches.
9749 		 */
9750 		__mark_reg_unknown(env, dst_reg);
9751 		return 0;
9752 	}
9753 
9754 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
9755 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
9756 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9757 			__mark_reg_unknown(env, dst_reg);
9758 			return 0;
9759 		}
9760 
9761 		verbose(env,
9762 			"R%d 32-bit pointer arithmetic prohibited\n",
9763 			dst);
9764 		return -EACCES;
9765 	}
9766 
9767 	if (ptr_reg->type & PTR_MAYBE_NULL) {
9768 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9769 			dst, reg_type_str(env, ptr_reg->type));
9770 		return -EACCES;
9771 	}
9772 
9773 	switch (base_type(ptr_reg->type)) {
9774 	case CONST_PTR_TO_MAP:
9775 		/* smin_val represents the known value */
9776 		if (known && smin_val == 0 && opcode == BPF_ADD)
9777 			break;
9778 		fallthrough;
9779 	case PTR_TO_PACKET_END:
9780 	case PTR_TO_SOCKET:
9781 	case PTR_TO_SOCK_COMMON:
9782 	case PTR_TO_TCP_SOCK:
9783 	case PTR_TO_XDP_SOCK:
9784 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9785 			dst, reg_type_str(env, ptr_reg->type));
9786 		return -EACCES;
9787 	default:
9788 		break;
9789 	}
9790 
9791 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9792 	 * The id may be overwritten later if we create a new variable offset.
9793 	 */
9794 	dst_reg->type = ptr_reg->type;
9795 	dst_reg->id = ptr_reg->id;
9796 
9797 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9798 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9799 		return -EINVAL;
9800 
9801 	/* pointer types do not carry 32-bit bounds at the moment. */
9802 	__mark_reg32_unbounded(dst_reg);
9803 
9804 	if (sanitize_needed(opcode)) {
9805 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9806 				       &info, false);
9807 		if (ret < 0)
9808 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9809 	}
9810 
9811 	switch (opcode) {
9812 	case BPF_ADD:
9813 		/* We can take a fixed offset as long as it doesn't overflow
9814 		 * the s32 'off' field
9815 		 */
9816 		if (known && (ptr_reg->off + smin_val ==
9817 			      (s64)(s32)(ptr_reg->off + smin_val))) {
9818 			/* pointer += K.  Accumulate it into fixed offset */
9819 			dst_reg->smin_value = smin_ptr;
9820 			dst_reg->smax_value = smax_ptr;
9821 			dst_reg->umin_value = umin_ptr;
9822 			dst_reg->umax_value = umax_ptr;
9823 			dst_reg->var_off = ptr_reg->var_off;
9824 			dst_reg->off = ptr_reg->off + smin_val;
9825 			dst_reg->raw = ptr_reg->raw;
9826 			break;
9827 		}
9828 		/* A new variable offset is created.  Note that off_reg->off
9829 		 * == 0, since it's a scalar.
9830 		 * dst_reg gets the pointer type and since some positive
9831 		 * integer value was added to the pointer, give it a new 'id'
9832 		 * if it's a PTR_TO_PACKET.
9833 		 * this creates a new 'base' pointer, off_reg (variable) gets
9834 		 * added into the variable offset, and we copy the fixed offset
9835 		 * from ptr_reg.
9836 		 */
9837 		if (signed_add_overflows(smin_ptr, smin_val) ||
9838 		    signed_add_overflows(smax_ptr, smax_val)) {
9839 			dst_reg->smin_value = S64_MIN;
9840 			dst_reg->smax_value = S64_MAX;
9841 		} else {
9842 			dst_reg->smin_value = smin_ptr + smin_val;
9843 			dst_reg->smax_value = smax_ptr + smax_val;
9844 		}
9845 		if (umin_ptr + umin_val < umin_ptr ||
9846 		    umax_ptr + umax_val < umax_ptr) {
9847 			dst_reg->umin_value = 0;
9848 			dst_reg->umax_value = U64_MAX;
9849 		} else {
9850 			dst_reg->umin_value = umin_ptr + umin_val;
9851 			dst_reg->umax_value = umax_ptr + umax_val;
9852 		}
9853 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9854 		dst_reg->off = ptr_reg->off;
9855 		dst_reg->raw = ptr_reg->raw;
9856 		if (reg_is_pkt_pointer(ptr_reg)) {
9857 			dst_reg->id = ++env->id_gen;
9858 			/* something was added to pkt_ptr, set range to zero */
9859 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9860 		}
9861 		break;
9862 	case BPF_SUB:
9863 		if (dst_reg == off_reg) {
9864 			/* scalar -= pointer.  Creates an unknown scalar */
9865 			verbose(env, "R%d tried to subtract pointer from scalar\n",
9866 				dst);
9867 			return -EACCES;
9868 		}
9869 		/* We don't allow subtraction from FP, because (according to
9870 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
9871 		 * be able to deal with it.
9872 		 */
9873 		if (ptr_reg->type == PTR_TO_STACK) {
9874 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
9875 				dst);
9876 			return -EACCES;
9877 		}
9878 		if (known && (ptr_reg->off - smin_val ==
9879 			      (s64)(s32)(ptr_reg->off - smin_val))) {
9880 			/* pointer -= K.  Subtract it from fixed offset */
9881 			dst_reg->smin_value = smin_ptr;
9882 			dst_reg->smax_value = smax_ptr;
9883 			dst_reg->umin_value = umin_ptr;
9884 			dst_reg->umax_value = umax_ptr;
9885 			dst_reg->var_off = ptr_reg->var_off;
9886 			dst_reg->id = ptr_reg->id;
9887 			dst_reg->off = ptr_reg->off - smin_val;
9888 			dst_reg->raw = ptr_reg->raw;
9889 			break;
9890 		}
9891 		/* A new variable offset is created.  If the subtrahend is known
9892 		 * nonnegative, then any reg->range we had before is still good.
9893 		 */
9894 		if (signed_sub_overflows(smin_ptr, smax_val) ||
9895 		    signed_sub_overflows(smax_ptr, smin_val)) {
9896 			/* Overflow possible, we know nothing */
9897 			dst_reg->smin_value = S64_MIN;
9898 			dst_reg->smax_value = S64_MAX;
9899 		} else {
9900 			dst_reg->smin_value = smin_ptr - smax_val;
9901 			dst_reg->smax_value = smax_ptr - smin_val;
9902 		}
9903 		if (umin_ptr < umax_val) {
9904 			/* Overflow possible, we know nothing */
9905 			dst_reg->umin_value = 0;
9906 			dst_reg->umax_value = U64_MAX;
9907 		} else {
9908 			/* Cannot overflow (as long as bounds are consistent) */
9909 			dst_reg->umin_value = umin_ptr - umax_val;
9910 			dst_reg->umax_value = umax_ptr - umin_val;
9911 		}
9912 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9913 		dst_reg->off = ptr_reg->off;
9914 		dst_reg->raw = ptr_reg->raw;
9915 		if (reg_is_pkt_pointer(ptr_reg)) {
9916 			dst_reg->id = ++env->id_gen;
9917 			/* something was added to pkt_ptr, set range to zero */
9918 			if (smin_val < 0)
9919 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9920 		}
9921 		break;
9922 	case BPF_AND:
9923 	case BPF_OR:
9924 	case BPF_XOR:
9925 		/* bitwise ops on pointers are troublesome, prohibit. */
9926 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9927 			dst, bpf_alu_string[opcode >> 4]);
9928 		return -EACCES;
9929 	default:
9930 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
9931 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9932 			dst, bpf_alu_string[opcode >> 4]);
9933 		return -EACCES;
9934 	}
9935 
9936 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9937 		return -EINVAL;
9938 	reg_bounds_sync(dst_reg);
9939 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9940 		return -EACCES;
9941 	if (sanitize_needed(opcode)) {
9942 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9943 				       &info, true);
9944 		if (ret < 0)
9945 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9946 	}
9947 
9948 	return 0;
9949 }
9950 
9951 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9952 				 struct bpf_reg_state *src_reg)
9953 {
9954 	s32 smin_val = src_reg->s32_min_value;
9955 	s32 smax_val = src_reg->s32_max_value;
9956 	u32 umin_val = src_reg->u32_min_value;
9957 	u32 umax_val = src_reg->u32_max_value;
9958 
9959 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9960 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9961 		dst_reg->s32_min_value = S32_MIN;
9962 		dst_reg->s32_max_value = S32_MAX;
9963 	} else {
9964 		dst_reg->s32_min_value += smin_val;
9965 		dst_reg->s32_max_value += smax_val;
9966 	}
9967 	if (dst_reg->u32_min_value + umin_val < umin_val ||
9968 	    dst_reg->u32_max_value + umax_val < umax_val) {
9969 		dst_reg->u32_min_value = 0;
9970 		dst_reg->u32_max_value = U32_MAX;
9971 	} else {
9972 		dst_reg->u32_min_value += umin_val;
9973 		dst_reg->u32_max_value += umax_val;
9974 	}
9975 }
9976 
9977 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9978 			       struct bpf_reg_state *src_reg)
9979 {
9980 	s64 smin_val = src_reg->smin_value;
9981 	s64 smax_val = src_reg->smax_value;
9982 	u64 umin_val = src_reg->umin_value;
9983 	u64 umax_val = src_reg->umax_value;
9984 
9985 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9986 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
9987 		dst_reg->smin_value = S64_MIN;
9988 		dst_reg->smax_value = S64_MAX;
9989 	} else {
9990 		dst_reg->smin_value += smin_val;
9991 		dst_reg->smax_value += smax_val;
9992 	}
9993 	if (dst_reg->umin_value + umin_val < umin_val ||
9994 	    dst_reg->umax_value + umax_val < umax_val) {
9995 		dst_reg->umin_value = 0;
9996 		dst_reg->umax_value = U64_MAX;
9997 	} else {
9998 		dst_reg->umin_value += umin_val;
9999 		dst_reg->umax_value += umax_val;
10000 	}
10001 }
10002 
10003 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10004 				 struct bpf_reg_state *src_reg)
10005 {
10006 	s32 smin_val = src_reg->s32_min_value;
10007 	s32 smax_val = src_reg->s32_max_value;
10008 	u32 umin_val = src_reg->u32_min_value;
10009 	u32 umax_val = src_reg->u32_max_value;
10010 
10011 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10012 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10013 		/* Overflow possible, we know nothing */
10014 		dst_reg->s32_min_value = S32_MIN;
10015 		dst_reg->s32_max_value = S32_MAX;
10016 	} else {
10017 		dst_reg->s32_min_value -= smax_val;
10018 		dst_reg->s32_max_value -= smin_val;
10019 	}
10020 	if (dst_reg->u32_min_value < umax_val) {
10021 		/* Overflow possible, we know nothing */
10022 		dst_reg->u32_min_value = 0;
10023 		dst_reg->u32_max_value = U32_MAX;
10024 	} else {
10025 		/* Cannot overflow (as long as bounds are consistent) */
10026 		dst_reg->u32_min_value -= umax_val;
10027 		dst_reg->u32_max_value -= umin_val;
10028 	}
10029 }
10030 
10031 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10032 			       struct bpf_reg_state *src_reg)
10033 {
10034 	s64 smin_val = src_reg->smin_value;
10035 	s64 smax_val = src_reg->smax_value;
10036 	u64 umin_val = src_reg->umin_value;
10037 	u64 umax_val = src_reg->umax_value;
10038 
10039 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10040 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10041 		/* Overflow possible, we know nothing */
10042 		dst_reg->smin_value = S64_MIN;
10043 		dst_reg->smax_value = S64_MAX;
10044 	} else {
10045 		dst_reg->smin_value -= smax_val;
10046 		dst_reg->smax_value -= smin_val;
10047 	}
10048 	if (dst_reg->umin_value < umax_val) {
10049 		/* Overflow possible, we know nothing */
10050 		dst_reg->umin_value = 0;
10051 		dst_reg->umax_value = U64_MAX;
10052 	} else {
10053 		/* Cannot overflow (as long as bounds are consistent) */
10054 		dst_reg->umin_value -= umax_val;
10055 		dst_reg->umax_value -= umin_val;
10056 	}
10057 }
10058 
10059 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10060 				 struct bpf_reg_state *src_reg)
10061 {
10062 	s32 smin_val = src_reg->s32_min_value;
10063 	u32 umin_val = src_reg->u32_min_value;
10064 	u32 umax_val = src_reg->u32_max_value;
10065 
10066 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10067 		/* Ain't nobody got time to multiply that sign */
10068 		__mark_reg32_unbounded(dst_reg);
10069 		return;
10070 	}
10071 	/* Both values are positive, so we can work with unsigned and
10072 	 * copy the result to signed (unless it exceeds S32_MAX).
10073 	 */
10074 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10075 		/* Potential overflow, we know nothing */
10076 		__mark_reg32_unbounded(dst_reg);
10077 		return;
10078 	}
10079 	dst_reg->u32_min_value *= umin_val;
10080 	dst_reg->u32_max_value *= umax_val;
10081 	if (dst_reg->u32_max_value > S32_MAX) {
10082 		/* Overflow possible, we know nothing */
10083 		dst_reg->s32_min_value = S32_MIN;
10084 		dst_reg->s32_max_value = S32_MAX;
10085 	} else {
10086 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10087 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10088 	}
10089 }
10090 
10091 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10092 			       struct bpf_reg_state *src_reg)
10093 {
10094 	s64 smin_val = src_reg->smin_value;
10095 	u64 umin_val = src_reg->umin_value;
10096 	u64 umax_val = src_reg->umax_value;
10097 
10098 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10099 		/* Ain't nobody got time to multiply that sign */
10100 		__mark_reg64_unbounded(dst_reg);
10101 		return;
10102 	}
10103 	/* Both values are positive, so we can work with unsigned and
10104 	 * copy the result to signed (unless it exceeds S64_MAX).
10105 	 */
10106 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10107 		/* Potential overflow, we know nothing */
10108 		__mark_reg64_unbounded(dst_reg);
10109 		return;
10110 	}
10111 	dst_reg->umin_value *= umin_val;
10112 	dst_reg->umax_value *= umax_val;
10113 	if (dst_reg->umax_value > S64_MAX) {
10114 		/* Overflow possible, we know nothing */
10115 		dst_reg->smin_value = S64_MIN;
10116 		dst_reg->smax_value = S64_MAX;
10117 	} else {
10118 		dst_reg->smin_value = dst_reg->umin_value;
10119 		dst_reg->smax_value = dst_reg->umax_value;
10120 	}
10121 }
10122 
10123 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10124 				 struct bpf_reg_state *src_reg)
10125 {
10126 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10127 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10128 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10129 	s32 smin_val = src_reg->s32_min_value;
10130 	u32 umax_val = src_reg->u32_max_value;
10131 
10132 	if (src_known && dst_known) {
10133 		__mark_reg32_known(dst_reg, var32_off.value);
10134 		return;
10135 	}
10136 
10137 	/* We get our minimum from the var_off, since that's inherently
10138 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10139 	 */
10140 	dst_reg->u32_min_value = var32_off.value;
10141 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10142 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10143 		/* Lose signed bounds when ANDing negative numbers,
10144 		 * ain't nobody got time for that.
10145 		 */
10146 		dst_reg->s32_min_value = S32_MIN;
10147 		dst_reg->s32_max_value = S32_MAX;
10148 	} else {
10149 		/* ANDing two positives gives a positive, so safe to
10150 		 * cast result into s64.
10151 		 */
10152 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10153 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10154 	}
10155 }
10156 
10157 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10158 			       struct bpf_reg_state *src_reg)
10159 {
10160 	bool src_known = tnum_is_const(src_reg->var_off);
10161 	bool dst_known = tnum_is_const(dst_reg->var_off);
10162 	s64 smin_val = src_reg->smin_value;
10163 	u64 umax_val = src_reg->umax_value;
10164 
10165 	if (src_known && dst_known) {
10166 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10167 		return;
10168 	}
10169 
10170 	/* We get our minimum from the var_off, since that's inherently
10171 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10172 	 */
10173 	dst_reg->umin_value = dst_reg->var_off.value;
10174 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10175 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10176 		/* Lose signed bounds when ANDing negative numbers,
10177 		 * ain't nobody got time for that.
10178 		 */
10179 		dst_reg->smin_value = S64_MIN;
10180 		dst_reg->smax_value = S64_MAX;
10181 	} else {
10182 		/* ANDing two positives gives a positive, so safe to
10183 		 * cast result into s64.
10184 		 */
10185 		dst_reg->smin_value = dst_reg->umin_value;
10186 		dst_reg->smax_value = dst_reg->umax_value;
10187 	}
10188 	/* We may learn something more from the var_off */
10189 	__update_reg_bounds(dst_reg);
10190 }
10191 
10192 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10193 				struct bpf_reg_state *src_reg)
10194 {
10195 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10196 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10197 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10198 	s32 smin_val = src_reg->s32_min_value;
10199 	u32 umin_val = src_reg->u32_min_value;
10200 
10201 	if (src_known && dst_known) {
10202 		__mark_reg32_known(dst_reg, var32_off.value);
10203 		return;
10204 	}
10205 
10206 	/* We get our maximum from the var_off, and our minimum is the
10207 	 * maximum of the operands' minima
10208 	 */
10209 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10210 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10211 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10212 		/* Lose signed bounds when ORing negative numbers,
10213 		 * ain't nobody got time for that.
10214 		 */
10215 		dst_reg->s32_min_value = S32_MIN;
10216 		dst_reg->s32_max_value = S32_MAX;
10217 	} else {
10218 		/* ORing two positives gives a positive, so safe to
10219 		 * cast result into s64.
10220 		 */
10221 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10222 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10223 	}
10224 }
10225 
10226 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10227 			      struct bpf_reg_state *src_reg)
10228 {
10229 	bool src_known = tnum_is_const(src_reg->var_off);
10230 	bool dst_known = tnum_is_const(dst_reg->var_off);
10231 	s64 smin_val = src_reg->smin_value;
10232 	u64 umin_val = src_reg->umin_value;
10233 
10234 	if (src_known && dst_known) {
10235 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10236 		return;
10237 	}
10238 
10239 	/* We get our maximum from the var_off, and our minimum is the
10240 	 * maximum of the operands' minima
10241 	 */
10242 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10243 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10244 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10245 		/* Lose signed bounds when ORing negative numbers,
10246 		 * ain't nobody got time for that.
10247 		 */
10248 		dst_reg->smin_value = S64_MIN;
10249 		dst_reg->smax_value = S64_MAX;
10250 	} else {
10251 		/* ORing two positives gives a positive, so safe to
10252 		 * cast result into s64.
10253 		 */
10254 		dst_reg->smin_value = dst_reg->umin_value;
10255 		dst_reg->smax_value = dst_reg->umax_value;
10256 	}
10257 	/* We may learn something more from the var_off */
10258 	__update_reg_bounds(dst_reg);
10259 }
10260 
10261 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10262 				 struct bpf_reg_state *src_reg)
10263 {
10264 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10265 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10266 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10267 	s32 smin_val = src_reg->s32_min_value;
10268 
10269 	if (src_known && dst_known) {
10270 		__mark_reg32_known(dst_reg, var32_off.value);
10271 		return;
10272 	}
10273 
10274 	/* We get both minimum and maximum from the var32_off. */
10275 	dst_reg->u32_min_value = var32_off.value;
10276 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10277 
10278 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10279 		/* XORing two positive sign numbers gives a positive,
10280 		 * so safe to cast u32 result into s32.
10281 		 */
10282 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10283 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10284 	} else {
10285 		dst_reg->s32_min_value = S32_MIN;
10286 		dst_reg->s32_max_value = S32_MAX;
10287 	}
10288 }
10289 
10290 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10291 			       struct bpf_reg_state *src_reg)
10292 {
10293 	bool src_known = tnum_is_const(src_reg->var_off);
10294 	bool dst_known = tnum_is_const(dst_reg->var_off);
10295 	s64 smin_val = src_reg->smin_value;
10296 
10297 	if (src_known && dst_known) {
10298 		/* dst_reg->var_off.value has been updated earlier */
10299 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10300 		return;
10301 	}
10302 
10303 	/* We get both minimum and maximum from the var_off. */
10304 	dst_reg->umin_value = dst_reg->var_off.value;
10305 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10306 
10307 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10308 		/* XORing two positive sign numbers gives a positive,
10309 		 * so safe to cast u64 result into s64.
10310 		 */
10311 		dst_reg->smin_value = dst_reg->umin_value;
10312 		dst_reg->smax_value = dst_reg->umax_value;
10313 	} else {
10314 		dst_reg->smin_value = S64_MIN;
10315 		dst_reg->smax_value = S64_MAX;
10316 	}
10317 
10318 	__update_reg_bounds(dst_reg);
10319 }
10320 
10321 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10322 				   u64 umin_val, u64 umax_val)
10323 {
10324 	/* We lose all sign bit information (except what we can pick
10325 	 * up from var_off)
10326 	 */
10327 	dst_reg->s32_min_value = S32_MIN;
10328 	dst_reg->s32_max_value = S32_MAX;
10329 	/* If we might shift our top bit out, then we know nothing */
10330 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10331 		dst_reg->u32_min_value = 0;
10332 		dst_reg->u32_max_value = U32_MAX;
10333 	} else {
10334 		dst_reg->u32_min_value <<= umin_val;
10335 		dst_reg->u32_max_value <<= umax_val;
10336 	}
10337 }
10338 
10339 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10340 				 struct bpf_reg_state *src_reg)
10341 {
10342 	u32 umax_val = src_reg->u32_max_value;
10343 	u32 umin_val = src_reg->u32_min_value;
10344 	/* u32 alu operation will zext upper bits */
10345 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10346 
10347 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10348 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10349 	/* Not required but being careful mark reg64 bounds as unknown so
10350 	 * that we are forced to pick them up from tnum and zext later and
10351 	 * if some path skips this step we are still safe.
10352 	 */
10353 	__mark_reg64_unbounded(dst_reg);
10354 	__update_reg32_bounds(dst_reg);
10355 }
10356 
10357 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10358 				   u64 umin_val, u64 umax_val)
10359 {
10360 	/* Special case <<32 because it is a common compiler pattern to sign
10361 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10362 	 * positive we know this shift will also be positive so we can track
10363 	 * bounds correctly. Otherwise we lose all sign bit information except
10364 	 * what we can pick up from var_off. Perhaps we can generalize this
10365 	 * later to shifts of any length.
10366 	 */
10367 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10368 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10369 	else
10370 		dst_reg->smax_value = S64_MAX;
10371 
10372 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10373 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10374 	else
10375 		dst_reg->smin_value = S64_MIN;
10376 
10377 	/* If we might shift our top bit out, then we know nothing */
10378 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10379 		dst_reg->umin_value = 0;
10380 		dst_reg->umax_value = U64_MAX;
10381 	} else {
10382 		dst_reg->umin_value <<= umin_val;
10383 		dst_reg->umax_value <<= umax_val;
10384 	}
10385 }
10386 
10387 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10388 			       struct bpf_reg_state *src_reg)
10389 {
10390 	u64 umax_val = src_reg->umax_value;
10391 	u64 umin_val = src_reg->umin_value;
10392 
10393 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
10394 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10395 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10396 
10397 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10398 	/* We may learn something more from the var_off */
10399 	__update_reg_bounds(dst_reg);
10400 }
10401 
10402 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10403 				 struct bpf_reg_state *src_reg)
10404 {
10405 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10406 	u32 umax_val = src_reg->u32_max_value;
10407 	u32 umin_val = src_reg->u32_min_value;
10408 
10409 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10410 	 * be negative, then either:
10411 	 * 1) src_reg might be zero, so the sign bit of the result is
10412 	 *    unknown, so we lose our signed bounds
10413 	 * 2) it's known negative, thus the unsigned bounds capture the
10414 	 *    signed bounds
10415 	 * 3) the signed bounds cross zero, so they tell us nothing
10416 	 *    about the result
10417 	 * If the value in dst_reg is known nonnegative, then again the
10418 	 * unsigned bounds capture the signed bounds.
10419 	 * Thus, in all cases it suffices to blow away our signed bounds
10420 	 * and rely on inferring new ones from the unsigned bounds and
10421 	 * var_off of the result.
10422 	 */
10423 	dst_reg->s32_min_value = S32_MIN;
10424 	dst_reg->s32_max_value = S32_MAX;
10425 
10426 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
10427 	dst_reg->u32_min_value >>= umax_val;
10428 	dst_reg->u32_max_value >>= umin_val;
10429 
10430 	__mark_reg64_unbounded(dst_reg);
10431 	__update_reg32_bounds(dst_reg);
10432 }
10433 
10434 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10435 			       struct bpf_reg_state *src_reg)
10436 {
10437 	u64 umax_val = src_reg->umax_value;
10438 	u64 umin_val = src_reg->umin_value;
10439 
10440 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10441 	 * be negative, then either:
10442 	 * 1) src_reg might be zero, so the sign bit of the result is
10443 	 *    unknown, so we lose our signed bounds
10444 	 * 2) it's known negative, thus the unsigned bounds capture the
10445 	 *    signed bounds
10446 	 * 3) the signed bounds cross zero, so they tell us nothing
10447 	 *    about the result
10448 	 * If the value in dst_reg is known nonnegative, then again the
10449 	 * unsigned bounds capture the signed bounds.
10450 	 * Thus, in all cases it suffices to blow away our signed bounds
10451 	 * and rely on inferring new ones from the unsigned bounds and
10452 	 * var_off of the result.
10453 	 */
10454 	dst_reg->smin_value = S64_MIN;
10455 	dst_reg->smax_value = S64_MAX;
10456 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10457 	dst_reg->umin_value >>= umax_val;
10458 	dst_reg->umax_value >>= umin_val;
10459 
10460 	/* Its not easy to operate on alu32 bounds here because it depends
10461 	 * on bits being shifted in. Take easy way out and mark unbounded
10462 	 * so we can recalculate later from tnum.
10463 	 */
10464 	__mark_reg32_unbounded(dst_reg);
10465 	__update_reg_bounds(dst_reg);
10466 }
10467 
10468 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10469 				  struct bpf_reg_state *src_reg)
10470 {
10471 	u64 umin_val = src_reg->u32_min_value;
10472 
10473 	/* Upon reaching here, src_known is true and
10474 	 * umax_val is equal to umin_val.
10475 	 */
10476 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10477 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10478 
10479 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10480 
10481 	/* blow away the dst_reg umin_value/umax_value and rely on
10482 	 * dst_reg var_off to refine the result.
10483 	 */
10484 	dst_reg->u32_min_value = 0;
10485 	dst_reg->u32_max_value = U32_MAX;
10486 
10487 	__mark_reg64_unbounded(dst_reg);
10488 	__update_reg32_bounds(dst_reg);
10489 }
10490 
10491 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10492 				struct bpf_reg_state *src_reg)
10493 {
10494 	u64 umin_val = src_reg->umin_value;
10495 
10496 	/* Upon reaching here, src_known is true and umax_val is equal
10497 	 * to umin_val.
10498 	 */
10499 	dst_reg->smin_value >>= umin_val;
10500 	dst_reg->smax_value >>= umin_val;
10501 
10502 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10503 
10504 	/* blow away the dst_reg umin_value/umax_value and rely on
10505 	 * dst_reg var_off to refine the result.
10506 	 */
10507 	dst_reg->umin_value = 0;
10508 	dst_reg->umax_value = U64_MAX;
10509 
10510 	/* Its not easy to operate on alu32 bounds here because it depends
10511 	 * on bits being shifted in from upper 32-bits. Take easy way out
10512 	 * and mark unbounded so we can recalculate later from tnum.
10513 	 */
10514 	__mark_reg32_unbounded(dst_reg);
10515 	__update_reg_bounds(dst_reg);
10516 }
10517 
10518 /* WARNING: This function does calculations on 64-bit values, but the actual
10519  * execution may occur on 32-bit values. Therefore, things like bitshifts
10520  * need extra checks in the 32-bit case.
10521  */
10522 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10523 				      struct bpf_insn *insn,
10524 				      struct bpf_reg_state *dst_reg,
10525 				      struct bpf_reg_state src_reg)
10526 {
10527 	struct bpf_reg_state *regs = cur_regs(env);
10528 	u8 opcode = BPF_OP(insn->code);
10529 	bool src_known;
10530 	s64 smin_val, smax_val;
10531 	u64 umin_val, umax_val;
10532 	s32 s32_min_val, s32_max_val;
10533 	u32 u32_min_val, u32_max_val;
10534 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10535 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10536 	int ret;
10537 
10538 	smin_val = src_reg.smin_value;
10539 	smax_val = src_reg.smax_value;
10540 	umin_val = src_reg.umin_value;
10541 	umax_val = src_reg.umax_value;
10542 
10543 	s32_min_val = src_reg.s32_min_value;
10544 	s32_max_val = src_reg.s32_max_value;
10545 	u32_min_val = src_reg.u32_min_value;
10546 	u32_max_val = src_reg.u32_max_value;
10547 
10548 	if (alu32) {
10549 		src_known = tnum_subreg_is_const(src_reg.var_off);
10550 		if ((src_known &&
10551 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10552 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10553 			/* Taint dst register if offset had invalid bounds
10554 			 * derived from e.g. dead branches.
10555 			 */
10556 			__mark_reg_unknown(env, dst_reg);
10557 			return 0;
10558 		}
10559 	} else {
10560 		src_known = tnum_is_const(src_reg.var_off);
10561 		if ((src_known &&
10562 		     (smin_val != smax_val || umin_val != umax_val)) ||
10563 		    smin_val > smax_val || umin_val > umax_val) {
10564 			/* Taint dst register if offset had invalid bounds
10565 			 * derived from e.g. dead branches.
10566 			 */
10567 			__mark_reg_unknown(env, dst_reg);
10568 			return 0;
10569 		}
10570 	}
10571 
10572 	if (!src_known &&
10573 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10574 		__mark_reg_unknown(env, dst_reg);
10575 		return 0;
10576 	}
10577 
10578 	if (sanitize_needed(opcode)) {
10579 		ret = sanitize_val_alu(env, insn);
10580 		if (ret < 0)
10581 			return sanitize_err(env, insn, ret, NULL, NULL);
10582 	}
10583 
10584 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10585 	 * There are two classes of instructions: The first class we track both
10586 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
10587 	 * greatest amount of precision when alu operations are mixed with jmp32
10588 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10589 	 * and BPF_OR. This is possible because these ops have fairly easy to
10590 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10591 	 * See alu32 verifier tests for examples. The second class of
10592 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10593 	 * with regards to tracking sign/unsigned bounds because the bits may
10594 	 * cross subreg boundaries in the alu64 case. When this happens we mark
10595 	 * the reg unbounded in the subreg bound space and use the resulting
10596 	 * tnum to calculate an approximation of the sign/unsigned bounds.
10597 	 */
10598 	switch (opcode) {
10599 	case BPF_ADD:
10600 		scalar32_min_max_add(dst_reg, &src_reg);
10601 		scalar_min_max_add(dst_reg, &src_reg);
10602 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10603 		break;
10604 	case BPF_SUB:
10605 		scalar32_min_max_sub(dst_reg, &src_reg);
10606 		scalar_min_max_sub(dst_reg, &src_reg);
10607 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10608 		break;
10609 	case BPF_MUL:
10610 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10611 		scalar32_min_max_mul(dst_reg, &src_reg);
10612 		scalar_min_max_mul(dst_reg, &src_reg);
10613 		break;
10614 	case BPF_AND:
10615 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10616 		scalar32_min_max_and(dst_reg, &src_reg);
10617 		scalar_min_max_and(dst_reg, &src_reg);
10618 		break;
10619 	case BPF_OR:
10620 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10621 		scalar32_min_max_or(dst_reg, &src_reg);
10622 		scalar_min_max_or(dst_reg, &src_reg);
10623 		break;
10624 	case BPF_XOR:
10625 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10626 		scalar32_min_max_xor(dst_reg, &src_reg);
10627 		scalar_min_max_xor(dst_reg, &src_reg);
10628 		break;
10629 	case BPF_LSH:
10630 		if (umax_val >= insn_bitness) {
10631 			/* Shifts greater than 31 or 63 are undefined.
10632 			 * This includes shifts by a negative number.
10633 			 */
10634 			mark_reg_unknown(env, regs, insn->dst_reg);
10635 			break;
10636 		}
10637 		if (alu32)
10638 			scalar32_min_max_lsh(dst_reg, &src_reg);
10639 		else
10640 			scalar_min_max_lsh(dst_reg, &src_reg);
10641 		break;
10642 	case BPF_RSH:
10643 		if (umax_val >= insn_bitness) {
10644 			/* Shifts greater than 31 or 63 are undefined.
10645 			 * This includes shifts by a negative number.
10646 			 */
10647 			mark_reg_unknown(env, regs, insn->dst_reg);
10648 			break;
10649 		}
10650 		if (alu32)
10651 			scalar32_min_max_rsh(dst_reg, &src_reg);
10652 		else
10653 			scalar_min_max_rsh(dst_reg, &src_reg);
10654 		break;
10655 	case BPF_ARSH:
10656 		if (umax_val >= insn_bitness) {
10657 			/* Shifts greater than 31 or 63 are undefined.
10658 			 * This includes shifts by a negative number.
10659 			 */
10660 			mark_reg_unknown(env, regs, insn->dst_reg);
10661 			break;
10662 		}
10663 		if (alu32)
10664 			scalar32_min_max_arsh(dst_reg, &src_reg);
10665 		else
10666 			scalar_min_max_arsh(dst_reg, &src_reg);
10667 		break;
10668 	default:
10669 		mark_reg_unknown(env, regs, insn->dst_reg);
10670 		break;
10671 	}
10672 
10673 	/* ALU32 ops are zero extended into 64bit register */
10674 	if (alu32)
10675 		zext_32_to_64(dst_reg);
10676 	reg_bounds_sync(dst_reg);
10677 	return 0;
10678 }
10679 
10680 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10681  * and var_off.
10682  */
10683 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10684 				   struct bpf_insn *insn)
10685 {
10686 	struct bpf_verifier_state *vstate = env->cur_state;
10687 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10688 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10689 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10690 	u8 opcode = BPF_OP(insn->code);
10691 	int err;
10692 
10693 	dst_reg = &regs[insn->dst_reg];
10694 	src_reg = NULL;
10695 	if (dst_reg->type != SCALAR_VALUE)
10696 		ptr_reg = dst_reg;
10697 	else
10698 		/* Make sure ID is cleared otherwise dst_reg min/max could be
10699 		 * incorrectly propagated into other registers by find_equal_scalars()
10700 		 */
10701 		dst_reg->id = 0;
10702 	if (BPF_SRC(insn->code) == BPF_X) {
10703 		src_reg = &regs[insn->src_reg];
10704 		if (src_reg->type != SCALAR_VALUE) {
10705 			if (dst_reg->type != SCALAR_VALUE) {
10706 				/* Combining two pointers by any ALU op yields
10707 				 * an arbitrary scalar. Disallow all math except
10708 				 * pointer subtraction
10709 				 */
10710 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10711 					mark_reg_unknown(env, regs, insn->dst_reg);
10712 					return 0;
10713 				}
10714 				verbose(env, "R%d pointer %s pointer prohibited\n",
10715 					insn->dst_reg,
10716 					bpf_alu_string[opcode >> 4]);
10717 				return -EACCES;
10718 			} else {
10719 				/* scalar += pointer
10720 				 * This is legal, but we have to reverse our
10721 				 * src/dest handling in computing the range
10722 				 */
10723 				err = mark_chain_precision(env, insn->dst_reg);
10724 				if (err)
10725 					return err;
10726 				return adjust_ptr_min_max_vals(env, insn,
10727 							       src_reg, dst_reg);
10728 			}
10729 		} else if (ptr_reg) {
10730 			/* pointer += scalar */
10731 			err = mark_chain_precision(env, insn->src_reg);
10732 			if (err)
10733 				return err;
10734 			return adjust_ptr_min_max_vals(env, insn,
10735 						       dst_reg, src_reg);
10736 		} else if (dst_reg->precise) {
10737 			/* if dst_reg is precise, src_reg should be precise as well */
10738 			err = mark_chain_precision(env, insn->src_reg);
10739 			if (err)
10740 				return err;
10741 		}
10742 	} else {
10743 		/* Pretend the src is a reg with a known value, since we only
10744 		 * need to be able to read from this state.
10745 		 */
10746 		off_reg.type = SCALAR_VALUE;
10747 		__mark_reg_known(&off_reg, insn->imm);
10748 		src_reg = &off_reg;
10749 		if (ptr_reg) /* pointer += K */
10750 			return adjust_ptr_min_max_vals(env, insn,
10751 						       ptr_reg, src_reg);
10752 	}
10753 
10754 	/* Got here implies adding two SCALAR_VALUEs */
10755 	if (WARN_ON_ONCE(ptr_reg)) {
10756 		print_verifier_state(env, state, true);
10757 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
10758 		return -EINVAL;
10759 	}
10760 	if (WARN_ON(!src_reg)) {
10761 		print_verifier_state(env, state, true);
10762 		verbose(env, "verifier internal error: no src_reg\n");
10763 		return -EINVAL;
10764 	}
10765 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10766 }
10767 
10768 /* check validity of 32-bit and 64-bit arithmetic operations */
10769 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10770 {
10771 	struct bpf_reg_state *regs = cur_regs(env);
10772 	u8 opcode = BPF_OP(insn->code);
10773 	int err;
10774 
10775 	if (opcode == BPF_END || opcode == BPF_NEG) {
10776 		if (opcode == BPF_NEG) {
10777 			if (BPF_SRC(insn->code) != BPF_K ||
10778 			    insn->src_reg != BPF_REG_0 ||
10779 			    insn->off != 0 || insn->imm != 0) {
10780 				verbose(env, "BPF_NEG uses reserved fields\n");
10781 				return -EINVAL;
10782 			}
10783 		} else {
10784 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10785 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10786 			    BPF_CLASS(insn->code) == BPF_ALU64) {
10787 				verbose(env, "BPF_END uses reserved fields\n");
10788 				return -EINVAL;
10789 			}
10790 		}
10791 
10792 		/* check src operand */
10793 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10794 		if (err)
10795 			return err;
10796 
10797 		if (is_pointer_value(env, insn->dst_reg)) {
10798 			verbose(env, "R%d pointer arithmetic prohibited\n",
10799 				insn->dst_reg);
10800 			return -EACCES;
10801 		}
10802 
10803 		/* check dest operand */
10804 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
10805 		if (err)
10806 			return err;
10807 
10808 	} else if (opcode == BPF_MOV) {
10809 
10810 		if (BPF_SRC(insn->code) == BPF_X) {
10811 			if (insn->imm != 0 || insn->off != 0) {
10812 				verbose(env, "BPF_MOV uses reserved fields\n");
10813 				return -EINVAL;
10814 			}
10815 
10816 			/* check src operand */
10817 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10818 			if (err)
10819 				return err;
10820 		} else {
10821 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10822 				verbose(env, "BPF_MOV uses reserved fields\n");
10823 				return -EINVAL;
10824 			}
10825 		}
10826 
10827 		/* check dest operand, mark as required later */
10828 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10829 		if (err)
10830 			return err;
10831 
10832 		if (BPF_SRC(insn->code) == BPF_X) {
10833 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
10834 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10835 
10836 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10837 				/* case: R1 = R2
10838 				 * copy register state to dest reg
10839 				 */
10840 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10841 					/* Assign src and dst registers the same ID
10842 					 * that will be used by find_equal_scalars()
10843 					 * to propagate min/max range.
10844 					 */
10845 					src_reg->id = ++env->id_gen;
10846 				*dst_reg = *src_reg;
10847 				dst_reg->live |= REG_LIVE_WRITTEN;
10848 				dst_reg->subreg_def = DEF_NOT_SUBREG;
10849 			} else {
10850 				/* R1 = (u32) R2 */
10851 				if (is_pointer_value(env, insn->src_reg)) {
10852 					verbose(env,
10853 						"R%d partial copy of pointer\n",
10854 						insn->src_reg);
10855 					return -EACCES;
10856 				} else if (src_reg->type == SCALAR_VALUE) {
10857 					*dst_reg = *src_reg;
10858 					/* Make sure ID is cleared otherwise
10859 					 * dst_reg min/max could be incorrectly
10860 					 * propagated into src_reg by find_equal_scalars()
10861 					 */
10862 					dst_reg->id = 0;
10863 					dst_reg->live |= REG_LIVE_WRITTEN;
10864 					dst_reg->subreg_def = env->insn_idx + 1;
10865 				} else {
10866 					mark_reg_unknown(env, regs,
10867 							 insn->dst_reg);
10868 				}
10869 				zext_32_to_64(dst_reg);
10870 				reg_bounds_sync(dst_reg);
10871 			}
10872 		} else {
10873 			/* case: R = imm
10874 			 * remember the value we stored into this reg
10875 			 */
10876 			/* clear any state __mark_reg_known doesn't set */
10877 			mark_reg_unknown(env, regs, insn->dst_reg);
10878 			regs[insn->dst_reg].type = SCALAR_VALUE;
10879 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10880 				__mark_reg_known(regs + insn->dst_reg,
10881 						 insn->imm);
10882 			} else {
10883 				__mark_reg_known(regs + insn->dst_reg,
10884 						 (u32)insn->imm);
10885 			}
10886 		}
10887 
10888 	} else if (opcode > BPF_END) {
10889 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10890 		return -EINVAL;
10891 
10892 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
10893 
10894 		if (BPF_SRC(insn->code) == BPF_X) {
10895 			if (insn->imm != 0 || insn->off != 0) {
10896 				verbose(env, "BPF_ALU uses reserved fields\n");
10897 				return -EINVAL;
10898 			}
10899 			/* check src1 operand */
10900 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10901 			if (err)
10902 				return err;
10903 		} else {
10904 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10905 				verbose(env, "BPF_ALU uses reserved fields\n");
10906 				return -EINVAL;
10907 			}
10908 		}
10909 
10910 		/* check src2 operand */
10911 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10912 		if (err)
10913 			return err;
10914 
10915 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10916 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10917 			verbose(env, "div by zero\n");
10918 			return -EINVAL;
10919 		}
10920 
10921 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10922 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10923 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10924 
10925 			if (insn->imm < 0 || insn->imm >= size) {
10926 				verbose(env, "invalid shift %d\n", insn->imm);
10927 				return -EINVAL;
10928 			}
10929 		}
10930 
10931 		/* check dest operand */
10932 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10933 		if (err)
10934 			return err;
10935 
10936 		return adjust_reg_min_max_vals(env, insn);
10937 	}
10938 
10939 	return 0;
10940 }
10941 
10942 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10943 				   struct bpf_reg_state *dst_reg,
10944 				   enum bpf_reg_type type,
10945 				   bool range_right_open)
10946 {
10947 	struct bpf_func_state *state;
10948 	struct bpf_reg_state *reg;
10949 	int new_range;
10950 
10951 	if (dst_reg->off < 0 ||
10952 	    (dst_reg->off == 0 && range_right_open))
10953 		/* This doesn't give us any range */
10954 		return;
10955 
10956 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
10957 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10958 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
10959 		 * than pkt_end, but that's because it's also less than pkt.
10960 		 */
10961 		return;
10962 
10963 	new_range = dst_reg->off;
10964 	if (range_right_open)
10965 		new_range++;
10966 
10967 	/* Examples for register markings:
10968 	 *
10969 	 * pkt_data in dst register:
10970 	 *
10971 	 *   r2 = r3;
10972 	 *   r2 += 8;
10973 	 *   if (r2 > pkt_end) goto <handle exception>
10974 	 *   <access okay>
10975 	 *
10976 	 *   r2 = r3;
10977 	 *   r2 += 8;
10978 	 *   if (r2 < pkt_end) goto <access okay>
10979 	 *   <handle exception>
10980 	 *
10981 	 *   Where:
10982 	 *     r2 == dst_reg, pkt_end == src_reg
10983 	 *     r2=pkt(id=n,off=8,r=0)
10984 	 *     r3=pkt(id=n,off=0,r=0)
10985 	 *
10986 	 * pkt_data in src register:
10987 	 *
10988 	 *   r2 = r3;
10989 	 *   r2 += 8;
10990 	 *   if (pkt_end >= r2) goto <access okay>
10991 	 *   <handle exception>
10992 	 *
10993 	 *   r2 = r3;
10994 	 *   r2 += 8;
10995 	 *   if (pkt_end <= r2) goto <handle exception>
10996 	 *   <access okay>
10997 	 *
10998 	 *   Where:
10999 	 *     pkt_end == dst_reg, r2 == src_reg
11000 	 *     r2=pkt(id=n,off=8,r=0)
11001 	 *     r3=pkt(id=n,off=0,r=0)
11002 	 *
11003 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11004 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11005 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11006 	 * the check.
11007 	 */
11008 
11009 	/* If our ids match, then we must have the same max_value.  And we
11010 	 * don't care about the other reg's fixed offset, since if it's too big
11011 	 * the range won't allow anything.
11012 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11013 	 */
11014 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11015 		if (reg->type == type && reg->id == dst_reg->id)
11016 			/* keep the maximum range already checked */
11017 			reg->range = max(reg->range, new_range);
11018 	}));
11019 }
11020 
11021 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11022 {
11023 	struct tnum subreg = tnum_subreg(reg->var_off);
11024 	s32 sval = (s32)val;
11025 
11026 	switch (opcode) {
11027 	case BPF_JEQ:
11028 		if (tnum_is_const(subreg))
11029 			return !!tnum_equals_const(subreg, val);
11030 		break;
11031 	case BPF_JNE:
11032 		if (tnum_is_const(subreg))
11033 			return !tnum_equals_const(subreg, val);
11034 		break;
11035 	case BPF_JSET:
11036 		if ((~subreg.mask & subreg.value) & val)
11037 			return 1;
11038 		if (!((subreg.mask | subreg.value) & val))
11039 			return 0;
11040 		break;
11041 	case BPF_JGT:
11042 		if (reg->u32_min_value > val)
11043 			return 1;
11044 		else if (reg->u32_max_value <= val)
11045 			return 0;
11046 		break;
11047 	case BPF_JSGT:
11048 		if (reg->s32_min_value > sval)
11049 			return 1;
11050 		else if (reg->s32_max_value <= sval)
11051 			return 0;
11052 		break;
11053 	case BPF_JLT:
11054 		if (reg->u32_max_value < val)
11055 			return 1;
11056 		else if (reg->u32_min_value >= val)
11057 			return 0;
11058 		break;
11059 	case BPF_JSLT:
11060 		if (reg->s32_max_value < sval)
11061 			return 1;
11062 		else if (reg->s32_min_value >= sval)
11063 			return 0;
11064 		break;
11065 	case BPF_JGE:
11066 		if (reg->u32_min_value >= val)
11067 			return 1;
11068 		else if (reg->u32_max_value < val)
11069 			return 0;
11070 		break;
11071 	case BPF_JSGE:
11072 		if (reg->s32_min_value >= sval)
11073 			return 1;
11074 		else if (reg->s32_max_value < sval)
11075 			return 0;
11076 		break;
11077 	case BPF_JLE:
11078 		if (reg->u32_max_value <= val)
11079 			return 1;
11080 		else if (reg->u32_min_value > val)
11081 			return 0;
11082 		break;
11083 	case BPF_JSLE:
11084 		if (reg->s32_max_value <= sval)
11085 			return 1;
11086 		else if (reg->s32_min_value > sval)
11087 			return 0;
11088 		break;
11089 	}
11090 
11091 	return -1;
11092 }
11093 
11094 
11095 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11096 {
11097 	s64 sval = (s64)val;
11098 
11099 	switch (opcode) {
11100 	case BPF_JEQ:
11101 		if (tnum_is_const(reg->var_off))
11102 			return !!tnum_equals_const(reg->var_off, val);
11103 		break;
11104 	case BPF_JNE:
11105 		if (tnum_is_const(reg->var_off))
11106 			return !tnum_equals_const(reg->var_off, val);
11107 		break;
11108 	case BPF_JSET:
11109 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11110 			return 1;
11111 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11112 			return 0;
11113 		break;
11114 	case BPF_JGT:
11115 		if (reg->umin_value > val)
11116 			return 1;
11117 		else if (reg->umax_value <= val)
11118 			return 0;
11119 		break;
11120 	case BPF_JSGT:
11121 		if (reg->smin_value > sval)
11122 			return 1;
11123 		else if (reg->smax_value <= sval)
11124 			return 0;
11125 		break;
11126 	case BPF_JLT:
11127 		if (reg->umax_value < val)
11128 			return 1;
11129 		else if (reg->umin_value >= val)
11130 			return 0;
11131 		break;
11132 	case BPF_JSLT:
11133 		if (reg->smax_value < sval)
11134 			return 1;
11135 		else if (reg->smin_value >= sval)
11136 			return 0;
11137 		break;
11138 	case BPF_JGE:
11139 		if (reg->umin_value >= val)
11140 			return 1;
11141 		else if (reg->umax_value < val)
11142 			return 0;
11143 		break;
11144 	case BPF_JSGE:
11145 		if (reg->smin_value >= sval)
11146 			return 1;
11147 		else if (reg->smax_value < sval)
11148 			return 0;
11149 		break;
11150 	case BPF_JLE:
11151 		if (reg->umax_value <= val)
11152 			return 1;
11153 		else if (reg->umin_value > val)
11154 			return 0;
11155 		break;
11156 	case BPF_JSLE:
11157 		if (reg->smax_value <= sval)
11158 			return 1;
11159 		else if (reg->smin_value > sval)
11160 			return 0;
11161 		break;
11162 	}
11163 
11164 	return -1;
11165 }
11166 
11167 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11168  * and return:
11169  *  1 - branch will be taken and "goto target" will be executed
11170  *  0 - branch will not be taken and fall-through to next insn
11171  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11172  *      range [0,10]
11173  */
11174 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11175 			   bool is_jmp32)
11176 {
11177 	if (__is_pointer_value(false, reg)) {
11178 		if (!reg_type_not_null(reg->type))
11179 			return -1;
11180 
11181 		/* If pointer is valid tests against zero will fail so we can
11182 		 * use this to direct branch taken.
11183 		 */
11184 		if (val != 0)
11185 			return -1;
11186 
11187 		switch (opcode) {
11188 		case BPF_JEQ:
11189 			return 0;
11190 		case BPF_JNE:
11191 			return 1;
11192 		default:
11193 			return -1;
11194 		}
11195 	}
11196 
11197 	if (is_jmp32)
11198 		return is_branch32_taken(reg, val, opcode);
11199 	return is_branch64_taken(reg, val, opcode);
11200 }
11201 
11202 static int flip_opcode(u32 opcode)
11203 {
11204 	/* How can we transform "a <op> b" into "b <op> a"? */
11205 	static const u8 opcode_flip[16] = {
11206 		/* these stay the same */
11207 		[BPF_JEQ  >> 4] = BPF_JEQ,
11208 		[BPF_JNE  >> 4] = BPF_JNE,
11209 		[BPF_JSET >> 4] = BPF_JSET,
11210 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11211 		[BPF_JGE  >> 4] = BPF_JLE,
11212 		[BPF_JGT  >> 4] = BPF_JLT,
11213 		[BPF_JLE  >> 4] = BPF_JGE,
11214 		[BPF_JLT  >> 4] = BPF_JGT,
11215 		[BPF_JSGE >> 4] = BPF_JSLE,
11216 		[BPF_JSGT >> 4] = BPF_JSLT,
11217 		[BPF_JSLE >> 4] = BPF_JSGE,
11218 		[BPF_JSLT >> 4] = BPF_JSGT
11219 	};
11220 	return opcode_flip[opcode >> 4];
11221 }
11222 
11223 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11224 				   struct bpf_reg_state *src_reg,
11225 				   u8 opcode)
11226 {
11227 	struct bpf_reg_state *pkt;
11228 
11229 	if (src_reg->type == PTR_TO_PACKET_END) {
11230 		pkt = dst_reg;
11231 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11232 		pkt = src_reg;
11233 		opcode = flip_opcode(opcode);
11234 	} else {
11235 		return -1;
11236 	}
11237 
11238 	if (pkt->range >= 0)
11239 		return -1;
11240 
11241 	switch (opcode) {
11242 	case BPF_JLE:
11243 		/* pkt <= pkt_end */
11244 		fallthrough;
11245 	case BPF_JGT:
11246 		/* pkt > pkt_end */
11247 		if (pkt->range == BEYOND_PKT_END)
11248 			/* pkt has at last one extra byte beyond pkt_end */
11249 			return opcode == BPF_JGT;
11250 		break;
11251 	case BPF_JLT:
11252 		/* pkt < pkt_end */
11253 		fallthrough;
11254 	case BPF_JGE:
11255 		/* pkt >= pkt_end */
11256 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11257 			return opcode == BPF_JGE;
11258 		break;
11259 	}
11260 	return -1;
11261 }
11262 
11263 /* Adjusts the register min/max values in the case that the dst_reg is the
11264  * variable register that we are working on, and src_reg is a constant or we're
11265  * simply doing a BPF_K check.
11266  * In JEQ/JNE cases we also adjust the var_off values.
11267  */
11268 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11269 			    struct bpf_reg_state *false_reg,
11270 			    u64 val, u32 val32,
11271 			    u8 opcode, bool is_jmp32)
11272 {
11273 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
11274 	struct tnum false_64off = false_reg->var_off;
11275 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
11276 	struct tnum true_64off = true_reg->var_off;
11277 	s64 sval = (s64)val;
11278 	s32 sval32 = (s32)val32;
11279 
11280 	/* If the dst_reg is a pointer, we can't learn anything about its
11281 	 * variable offset from the compare (unless src_reg were a pointer into
11282 	 * the same object, but we don't bother with that.
11283 	 * Since false_reg and true_reg have the same type by construction, we
11284 	 * only need to check one of them for pointerness.
11285 	 */
11286 	if (__is_pointer_value(false, false_reg))
11287 		return;
11288 
11289 	switch (opcode) {
11290 	/* JEQ/JNE comparison doesn't change the register equivalence.
11291 	 *
11292 	 * r1 = r2;
11293 	 * if (r1 == 42) goto label;
11294 	 * ...
11295 	 * label: // here both r1 and r2 are known to be 42.
11296 	 *
11297 	 * Hence when marking register as known preserve it's ID.
11298 	 */
11299 	case BPF_JEQ:
11300 		if (is_jmp32) {
11301 			__mark_reg32_known(true_reg, val32);
11302 			true_32off = tnum_subreg(true_reg->var_off);
11303 		} else {
11304 			___mark_reg_known(true_reg, val);
11305 			true_64off = true_reg->var_off;
11306 		}
11307 		break;
11308 	case BPF_JNE:
11309 		if (is_jmp32) {
11310 			__mark_reg32_known(false_reg, val32);
11311 			false_32off = tnum_subreg(false_reg->var_off);
11312 		} else {
11313 			___mark_reg_known(false_reg, val);
11314 			false_64off = false_reg->var_off;
11315 		}
11316 		break;
11317 	case BPF_JSET:
11318 		if (is_jmp32) {
11319 			false_32off = tnum_and(false_32off, tnum_const(~val32));
11320 			if (is_power_of_2(val32))
11321 				true_32off = tnum_or(true_32off,
11322 						     tnum_const(val32));
11323 		} else {
11324 			false_64off = tnum_and(false_64off, tnum_const(~val));
11325 			if (is_power_of_2(val))
11326 				true_64off = tnum_or(true_64off,
11327 						     tnum_const(val));
11328 		}
11329 		break;
11330 	case BPF_JGE:
11331 	case BPF_JGT:
11332 	{
11333 		if (is_jmp32) {
11334 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11335 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11336 
11337 			false_reg->u32_max_value = min(false_reg->u32_max_value,
11338 						       false_umax);
11339 			true_reg->u32_min_value = max(true_reg->u32_min_value,
11340 						      true_umin);
11341 		} else {
11342 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11343 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11344 
11345 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
11346 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
11347 		}
11348 		break;
11349 	}
11350 	case BPF_JSGE:
11351 	case BPF_JSGT:
11352 	{
11353 		if (is_jmp32) {
11354 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11355 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11356 
11357 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11358 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11359 		} else {
11360 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11361 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11362 
11363 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
11364 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
11365 		}
11366 		break;
11367 	}
11368 	case BPF_JLE:
11369 	case BPF_JLT:
11370 	{
11371 		if (is_jmp32) {
11372 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11373 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11374 
11375 			false_reg->u32_min_value = max(false_reg->u32_min_value,
11376 						       false_umin);
11377 			true_reg->u32_max_value = min(true_reg->u32_max_value,
11378 						      true_umax);
11379 		} else {
11380 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11381 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11382 
11383 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
11384 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
11385 		}
11386 		break;
11387 	}
11388 	case BPF_JSLE:
11389 	case BPF_JSLT:
11390 	{
11391 		if (is_jmp32) {
11392 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11393 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11394 
11395 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11396 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11397 		} else {
11398 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11399 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11400 
11401 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
11402 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
11403 		}
11404 		break;
11405 	}
11406 	default:
11407 		return;
11408 	}
11409 
11410 	if (is_jmp32) {
11411 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11412 					     tnum_subreg(false_32off));
11413 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11414 					    tnum_subreg(true_32off));
11415 		__reg_combine_32_into_64(false_reg);
11416 		__reg_combine_32_into_64(true_reg);
11417 	} else {
11418 		false_reg->var_off = false_64off;
11419 		true_reg->var_off = true_64off;
11420 		__reg_combine_64_into_32(false_reg);
11421 		__reg_combine_64_into_32(true_reg);
11422 	}
11423 }
11424 
11425 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11426  * the variable reg.
11427  */
11428 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11429 				struct bpf_reg_state *false_reg,
11430 				u64 val, u32 val32,
11431 				u8 opcode, bool is_jmp32)
11432 {
11433 	opcode = flip_opcode(opcode);
11434 	/* This uses zero as "not present in table"; luckily the zero opcode,
11435 	 * BPF_JA, can't get here.
11436 	 */
11437 	if (opcode)
11438 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11439 }
11440 
11441 /* Regs are known to be equal, so intersect their min/max/var_off */
11442 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11443 				  struct bpf_reg_state *dst_reg)
11444 {
11445 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11446 							dst_reg->umin_value);
11447 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11448 							dst_reg->umax_value);
11449 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11450 							dst_reg->smin_value);
11451 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11452 							dst_reg->smax_value);
11453 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11454 							     dst_reg->var_off);
11455 	reg_bounds_sync(src_reg);
11456 	reg_bounds_sync(dst_reg);
11457 }
11458 
11459 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11460 				struct bpf_reg_state *true_dst,
11461 				struct bpf_reg_state *false_src,
11462 				struct bpf_reg_state *false_dst,
11463 				u8 opcode)
11464 {
11465 	switch (opcode) {
11466 	case BPF_JEQ:
11467 		__reg_combine_min_max(true_src, true_dst);
11468 		break;
11469 	case BPF_JNE:
11470 		__reg_combine_min_max(false_src, false_dst);
11471 		break;
11472 	}
11473 }
11474 
11475 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11476 				 struct bpf_reg_state *reg, u32 id,
11477 				 bool is_null)
11478 {
11479 	if (type_may_be_null(reg->type) && reg->id == id &&
11480 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11481 		/* Old offset (both fixed and variable parts) should have been
11482 		 * known-zero, because we don't allow pointer arithmetic on
11483 		 * pointers that might be NULL. If we see this happening, don't
11484 		 * convert the register.
11485 		 *
11486 		 * But in some cases, some helpers that return local kptrs
11487 		 * advance offset for the returned pointer. In those cases, it
11488 		 * is fine to expect to see reg->off.
11489 		 */
11490 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11491 			return;
11492 		if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11493 			return;
11494 		if (is_null) {
11495 			reg->type = SCALAR_VALUE;
11496 			/* We don't need id and ref_obj_id from this point
11497 			 * onwards anymore, thus we should better reset it,
11498 			 * so that state pruning has chances to take effect.
11499 			 */
11500 			reg->id = 0;
11501 			reg->ref_obj_id = 0;
11502 
11503 			return;
11504 		}
11505 
11506 		mark_ptr_not_null_reg(reg);
11507 
11508 		if (!reg_may_point_to_spin_lock(reg)) {
11509 			/* For not-NULL ptr, reg->ref_obj_id will be reset
11510 			 * in release_reference().
11511 			 *
11512 			 * reg->id is still used by spin_lock ptr. Other
11513 			 * than spin_lock ptr type, reg->id can be reset.
11514 			 */
11515 			reg->id = 0;
11516 		}
11517 	}
11518 }
11519 
11520 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11521  * be folded together at some point.
11522  */
11523 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11524 				  bool is_null)
11525 {
11526 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11527 	struct bpf_reg_state *regs = state->regs, *reg;
11528 	u32 ref_obj_id = regs[regno].ref_obj_id;
11529 	u32 id = regs[regno].id;
11530 
11531 	if (ref_obj_id && ref_obj_id == id && is_null)
11532 		/* regs[regno] is in the " == NULL" branch.
11533 		 * No one could have freed the reference state before
11534 		 * doing the NULL check.
11535 		 */
11536 		WARN_ON_ONCE(release_reference_state(state, id));
11537 
11538 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11539 		mark_ptr_or_null_reg(state, reg, id, is_null);
11540 	}));
11541 }
11542 
11543 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11544 				   struct bpf_reg_state *dst_reg,
11545 				   struct bpf_reg_state *src_reg,
11546 				   struct bpf_verifier_state *this_branch,
11547 				   struct bpf_verifier_state *other_branch)
11548 {
11549 	if (BPF_SRC(insn->code) != BPF_X)
11550 		return false;
11551 
11552 	/* Pointers are always 64-bit. */
11553 	if (BPF_CLASS(insn->code) == BPF_JMP32)
11554 		return false;
11555 
11556 	switch (BPF_OP(insn->code)) {
11557 	case BPF_JGT:
11558 		if ((dst_reg->type == PTR_TO_PACKET &&
11559 		     src_reg->type == PTR_TO_PACKET_END) ||
11560 		    (dst_reg->type == PTR_TO_PACKET_META &&
11561 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11562 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11563 			find_good_pkt_pointers(this_branch, dst_reg,
11564 					       dst_reg->type, false);
11565 			mark_pkt_end(other_branch, insn->dst_reg, true);
11566 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11567 			    src_reg->type == PTR_TO_PACKET) ||
11568 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11569 			    src_reg->type == PTR_TO_PACKET_META)) {
11570 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
11571 			find_good_pkt_pointers(other_branch, src_reg,
11572 					       src_reg->type, true);
11573 			mark_pkt_end(this_branch, insn->src_reg, false);
11574 		} else {
11575 			return false;
11576 		}
11577 		break;
11578 	case BPF_JLT:
11579 		if ((dst_reg->type == PTR_TO_PACKET &&
11580 		     src_reg->type == PTR_TO_PACKET_END) ||
11581 		    (dst_reg->type == PTR_TO_PACKET_META &&
11582 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11583 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11584 			find_good_pkt_pointers(other_branch, dst_reg,
11585 					       dst_reg->type, true);
11586 			mark_pkt_end(this_branch, insn->dst_reg, false);
11587 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11588 			    src_reg->type == PTR_TO_PACKET) ||
11589 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11590 			    src_reg->type == PTR_TO_PACKET_META)) {
11591 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
11592 			find_good_pkt_pointers(this_branch, src_reg,
11593 					       src_reg->type, false);
11594 			mark_pkt_end(other_branch, insn->src_reg, true);
11595 		} else {
11596 			return false;
11597 		}
11598 		break;
11599 	case BPF_JGE:
11600 		if ((dst_reg->type == PTR_TO_PACKET &&
11601 		     src_reg->type == PTR_TO_PACKET_END) ||
11602 		    (dst_reg->type == PTR_TO_PACKET_META &&
11603 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11604 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11605 			find_good_pkt_pointers(this_branch, dst_reg,
11606 					       dst_reg->type, true);
11607 			mark_pkt_end(other_branch, insn->dst_reg, false);
11608 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11609 			    src_reg->type == PTR_TO_PACKET) ||
11610 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11611 			    src_reg->type == PTR_TO_PACKET_META)) {
11612 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11613 			find_good_pkt_pointers(other_branch, src_reg,
11614 					       src_reg->type, false);
11615 			mark_pkt_end(this_branch, insn->src_reg, true);
11616 		} else {
11617 			return false;
11618 		}
11619 		break;
11620 	case BPF_JLE:
11621 		if ((dst_reg->type == PTR_TO_PACKET &&
11622 		     src_reg->type == PTR_TO_PACKET_END) ||
11623 		    (dst_reg->type == PTR_TO_PACKET_META &&
11624 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11625 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11626 			find_good_pkt_pointers(other_branch, dst_reg,
11627 					       dst_reg->type, false);
11628 			mark_pkt_end(this_branch, insn->dst_reg, true);
11629 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11630 			    src_reg->type == PTR_TO_PACKET) ||
11631 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11632 			    src_reg->type == PTR_TO_PACKET_META)) {
11633 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11634 			find_good_pkt_pointers(this_branch, src_reg,
11635 					       src_reg->type, true);
11636 			mark_pkt_end(other_branch, insn->src_reg, false);
11637 		} else {
11638 			return false;
11639 		}
11640 		break;
11641 	default:
11642 		return false;
11643 	}
11644 
11645 	return true;
11646 }
11647 
11648 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11649 			       struct bpf_reg_state *known_reg)
11650 {
11651 	struct bpf_func_state *state;
11652 	struct bpf_reg_state *reg;
11653 
11654 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11655 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11656 			*reg = *known_reg;
11657 	}));
11658 }
11659 
11660 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11661 			     struct bpf_insn *insn, int *insn_idx)
11662 {
11663 	struct bpf_verifier_state *this_branch = env->cur_state;
11664 	struct bpf_verifier_state *other_branch;
11665 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11666 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11667 	struct bpf_reg_state *eq_branch_regs;
11668 	u8 opcode = BPF_OP(insn->code);
11669 	bool is_jmp32;
11670 	int pred = -1;
11671 	int err;
11672 
11673 	/* Only conditional jumps are expected to reach here. */
11674 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
11675 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11676 		return -EINVAL;
11677 	}
11678 
11679 	if (BPF_SRC(insn->code) == BPF_X) {
11680 		if (insn->imm != 0) {
11681 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11682 			return -EINVAL;
11683 		}
11684 
11685 		/* check src1 operand */
11686 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
11687 		if (err)
11688 			return err;
11689 
11690 		if (is_pointer_value(env, insn->src_reg)) {
11691 			verbose(env, "R%d pointer comparison prohibited\n",
11692 				insn->src_reg);
11693 			return -EACCES;
11694 		}
11695 		src_reg = &regs[insn->src_reg];
11696 	} else {
11697 		if (insn->src_reg != BPF_REG_0) {
11698 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11699 			return -EINVAL;
11700 		}
11701 	}
11702 
11703 	/* check src2 operand */
11704 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11705 	if (err)
11706 		return err;
11707 
11708 	dst_reg = &regs[insn->dst_reg];
11709 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11710 
11711 	if (BPF_SRC(insn->code) == BPF_K) {
11712 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11713 	} else if (src_reg->type == SCALAR_VALUE &&
11714 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11715 		pred = is_branch_taken(dst_reg,
11716 				       tnum_subreg(src_reg->var_off).value,
11717 				       opcode,
11718 				       is_jmp32);
11719 	} else if (src_reg->type == SCALAR_VALUE &&
11720 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11721 		pred = is_branch_taken(dst_reg,
11722 				       src_reg->var_off.value,
11723 				       opcode,
11724 				       is_jmp32);
11725 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
11726 		   reg_is_pkt_pointer_any(src_reg) &&
11727 		   !is_jmp32) {
11728 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11729 	}
11730 
11731 	if (pred >= 0) {
11732 		/* If we get here with a dst_reg pointer type it is because
11733 		 * above is_branch_taken() special cased the 0 comparison.
11734 		 */
11735 		if (!__is_pointer_value(false, dst_reg))
11736 			err = mark_chain_precision(env, insn->dst_reg);
11737 		if (BPF_SRC(insn->code) == BPF_X && !err &&
11738 		    !__is_pointer_value(false, src_reg))
11739 			err = mark_chain_precision(env, insn->src_reg);
11740 		if (err)
11741 			return err;
11742 	}
11743 
11744 	if (pred == 1) {
11745 		/* Only follow the goto, ignore fall-through. If needed, push
11746 		 * the fall-through branch for simulation under speculative
11747 		 * execution.
11748 		 */
11749 		if (!env->bypass_spec_v1 &&
11750 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
11751 					       *insn_idx))
11752 			return -EFAULT;
11753 		*insn_idx += insn->off;
11754 		return 0;
11755 	} else if (pred == 0) {
11756 		/* Only follow the fall-through branch, since that's where the
11757 		 * program will go. If needed, push the goto branch for
11758 		 * simulation under speculative execution.
11759 		 */
11760 		if (!env->bypass_spec_v1 &&
11761 		    !sanitize_speculative_path(env, insn,
11762 					       *insn_idx + insn->off + 1,
11763 					       *insn_idx))
11764 			return -EFAULT;
11765 		return 0;
11766 	}
11767 
11768 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11769 				  false);
11770 	if (!other_branch)
11771 		return -EFAULT;
11772 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11773 
11774 	/* detect if we are comparing against a constant value so we can adjust
11775 	 * our min/max values for our dst register.
11776 	 * this is only legit if both are scalars (or pointers to the same
11777 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11778 	 * because otherwise the different base pointers mean the offsets aren't
11779 	 * comparable.
11780 	 */
11781 	if (BPF_SRC(insn->code) == BPF_X) {
11782 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11783 
11784 		if (dst_reg->type == SCALAR_VALUE &&
11785 		    src_reg->type == SCALAR_VALUE) {
11786 			if (tnum_is_const(src_reg->var_off) ||
11787 			    (is_jmp32 &&
11788 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
11789 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
11790 						dst_reg,
11791 						src_reg->var_off.value,
11792 						tnum_subreg(src_reg->var_off).value,
11793 						opcode, is_jmp32);
11794 			else if (tnum_is_const(dst_reg->var_off) ||
11795 				 (is_jmp32 &&
11796 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
11797 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11798 						    src_reg,
11799 						    dst_reg->var_off.value,
11800 						    tnum_subreg(dst_reg->var_off).value,
11801 						    opcode, is_jmp32);
11802 			else if (!is_jmp32 &&
11803 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
11804 				/* Comparing for equality, we can combine knowledge */
11805 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
11806 						    &other_branch_regs[insn->dst_reg],
11807 						    src_reg, dst_reg, opcode);
11808 			if (src_reg->id &&
11809 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11810 				find_equal_scalars(this_branch, src_reg);
11811 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11812 			}
11813 
11814 		}
11815 	} else if (dst_reg->type == SCALAR_VALUE) {
11816 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
11817 					dst_reg, insn->imm, (u32)insn->imm,
11818 					opcode, is_jmp32);
11819 	}
11820 
11821 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11822 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11823 		find_equal_scalars(this_branch, dst_reg);
11824 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11825 	}
11826 
11827 	/* if one pointer register is compared to another pointer
11828 	 * register check if PTR_MAYBE_NULL could be lifted.
11829 	 * E.g. register A - maybe null
11830 	 *      register B - not null
11831 	 * for JNE A, B, ... - A is not null in the false branch;
11832 	 * for JEQ A, B, ... - A is not null in the true branch.
11833 	 *
11834 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
11835 	 * not need to be null checked by the BPF program, i.e.,
11836 	 * could be null even without PTR_MAYBE_NULL marking, so
11837 	 * only propagate nullness when neither reg is that type.
11838 	 */
11839 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11840 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11841 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
11842 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
11843 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
11844 		eq_branch_regs = NULL;
11845 		switch (opcode) {
11846 		case BPF_JEQ:
11847 			eq_branch_regs = other_branch_regs;
11848 			break;
11849 		case BPF_JNE:
11850 			eq_branch_regs = regs;
11851 			break;
11852 		default:
11853 			/* do nothing */
11854 			break;
11855 		}
11856 		if (eq_branch_regs) {
11857 			if (type_may_be_null(src_reg->type))
11858 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11859 			else
11860 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11861 		}
11862 	}
11863 
11864 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11865 	 * NOTE: these optimizations below are related with pointer comparison
11866 	 *       which will never be JMP32.
11867 	 */
11868 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11869 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11870 	    type_may_be_null(dst_reg->type)) {
11871 		/* Mark all identical registers in each branch as either
11872 		 * safe or unknown depending R == 0 or R != 0 conditional.
11873 		 */
11874 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11875 				      opcode == BPF_JNE);
11876 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11877 				      opcode == BPF_JEQ);
11878 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11879 					   this_branch, other_branch) &&
11880 		   is_pointer_value(env, insn->dst_reg)) {
11881 		verbose(env, "R%d pointer comparison prohibited\n",
11882 			insn->dst_reg);
11883 		return -EACCES;
11884 	}
11885 	if (env->log.level & BPF_LOG_LEVEL)
11886 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
11887 	return 0;
11888 }
11889 
11890 /* verify BPF_LD_IMM64 instruction */
11891 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11892 {
11893 	struct bpf_insn_aux_data *aux = cur_aux(env);
11894 	struct bpf_reg_state *regs = cur_regs(env);
11895 	struct bpf_reg_state *dst_reg;
11896 	struct bpf_map *map;
11897 	int err;
11898 
11899 	if (BPF_SIZE(insn->code) != BPF_DW) {
11900 		verbose(env, "invalid BPF_LD_IMM insn\n");
11901 		return -EINVAL;
11902 	}
11903 	if (insn->off != 0) {
11904 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11905 		return -EINVAL;
11906 	}
11907 
11908 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
11909 	if (err)
11910 		return err;
11911 
11912 	dst_reg = &regs[insn->dst_reg];
11913 	if (insn->src_reg == 0) {
11914 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11915 
11916 		dst_reg->type = SCALAR_VALUE;
11917 		__mark_reg_known(&regs[insn->dst_reg], imm);
11918 		return 0;
11919 	}
11920 
11921 	/* All special src_reg cases are listed below. From this point onwards
11922 	 * we either succeed and assign a corresponding dst_reg->type after
11923 	 * zeroing the offset, or fail and reject the program.
11924 	 */
11925 	mark_reg_known_zero(env, regs, insn->dst_reg);
11926 
11927 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11928 		dst_reg->type = aux->btf_var.reg_type;
11929 		switch (base_type(dst_reg->type)) {
11930 		case PTR_TO_MEM:
11931 			dst_reg->mem_size = aux->btf_var.mem_size;
11932 			break;
11933 		case PTR_TO_BTF_ID:
11934 			dst_reg->btf = aux->btf_var.btf;
11935 			dst_reg->btf_id = aux->btf_var.btf_id;
11936 			break;
11937 		default:
11938 			verbose(env, "bpf verifier is misconfigured\n");
11939 			return -EFAULT;
11940 		}
11941 		return 0;
11942 	}
11943 
11944 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
11945 		struct bpf_prog_aux *aux = env->prog->aux;
11946 		u32 subprogno = find_subprog(env,
11947 					     env->insn_idx + insn->imm + 1);
11948 
11949 		if (!aux->func_info) {
11950 			verbose(env, "missing btf func_info\n");
11951 			return -EINVAL;
11952 		}
11953 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11954 			verbose(env, "callback function not static\n");
11955 			return -EINVAL;
11956 		}
11957 
11958 		dst_reg->type = PTR_TO_FUNC;
11959 		dst_reg->subprogno = subprogno;
11960 		return 0;
11961 	}
11962 
11963 	map = env->used_maps[aux->map_index];
11964 	dst_reg->map_ptr = map;
11965 
11966 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11967 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11968 		dst_reg->type = PTR_TO_MAP_VALUE;
11969 		dst_reg->off = aux->map_off;
11970 		WARN_ON_ONCE(map->max_entries != 1);
11971 		/* We want reg->id to be same (0) as map_value is not distinct */
11972 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11973 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11974 		dst_reg->type = CONST_PTR_TO_MAP;
11975 	} else {
11976 		verbose(env, "bpf verifier is misconfigured\n");
11977 		return -EINVAL;
11978 	}
11979 
11980 	return 0;
11981 }
11982 
11983 static bool may_access_skb(enum bpf_prog_type type)
11984 {
11985 	switch (type) {
11986 	case BPF_PROG_TYPE_SOCKET_FILTER:
11987 	case BPF_PROG_TYPE_SCHED_CLS:
11988 	case BPF_PROG_TYPE_SCHED_ACT:
11989 		return true;
11990 	default:
11991 		return false;
11992 	}
11993 }
11994 
11995 /* verify safety of LD_ABS|LD_IND instructions:
11996  * - they can only appear in the programs where ctx == skb
11997  * - since they are wrappers of function calls, they scratch R1-R5 registers,
11998  *   preserve R6-R9, and store return value into R0
11999  *
12000  * Implicit input:
12001  *   ctx == skb == R6 == CTX
12002  *
12003  * Explicit input:
12004  *   SRC == any register
12005  *   IMM == 32-bit immediate
12006  *
12007  * Output:
12008  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12009  */
12010 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12011 {
12012 	struct bpf_reg_state *regs = cur_regs(env);
12013 	static const int ctx_reg = BPF_REG_6;
12014 	u8 mode = BPF_MODE(insn->code);
12015 	int i, err;
12016 
12017 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12018 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12019 		return -EINVAL;
12020 	}
12021 
12022 	if (!env->ops->gen_ld_abs) {
12023 		verbose(env, "bpf verifier is misconfigured\n");
12024 		return -EINVAL;
12025 	}
12026 
12027 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12028 	    BPF_SIZE(insn->code) == BPF_DW ||
12029 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12030 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12031 		return -EINVAL;
12032 	}
12033 
12034 	/* check whether implicit source operand (register R6) is readable */
12035 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12036 	if (err)
12037 		return err;
12038 
12039 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12040 	 * gen_ld_abs() may terminate the program at runtime, leading to
12041 	 * reference leak.
12042 	 */
12043 	err = check_reference_leak(env);
12044 	if (err) {
12045 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12046 		return err;
12047 	}
12048 
12049 	if (env->cur_state->active_lock.ptr) {
12050 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12051 		return -EINVAL;
12052 	}
12053 
12054 	if (env->cur_state->active_rcu_lock) {
12055 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12056 		return -EINVAL;
12057 	}
12058 
12059 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12060 		verbose(env,
12061 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12062 		return -EINVAL;
12063 	}
12064 
12065 	if (mode == BPF_IND) {
12066 		/* check explicit source operand */
12067 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12068 		if (err)
12069 			return err;
12070 	}
12071 
12072 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12073 	if (err < 0)
12074 		return err;
12075 
12076 	/* reset caller saved regs to unreadable */
12077 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12078 		mark_reg_not_init(env, regs, caller_saved[i]);
12079 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12080 	}
12081 
12082 	/* mark destination R0 register as readable, since it contains
12083 	 * the value fetched from the packet.
12084 	 * Already marked as written above.
12085 	 */
12086 	mark_reg_unknown(env, regs, BPF_REG_0);
12087 	/* ld_abs load up to 32-bit skb data. */
12088 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12089 	return 0;
12090 }
12091 
12092 static int check_return_code(struct bpf_verifier_env *env)
12093 {
12094 	struct tnum enforce_attach_type_range = tnum_unknown;
12095 	const struct bpf_prog *prog = env->prog;
12096 	struct bpf_reg_state *reg;
12097 	struct tnum range = tnum_range(0, 1);
12098 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12099 	int err;
12100 	struct bpf_func_state *frame = env->cur_state->frame[0];
12101 	const bool is_subprog = frame->subprogno;
12102 
12103 	/* LSM and struct_ops func-ptr's return type could be "void" */
12104 	if (!is_subprog) {
12105 		switch (prog_type) {
12106 		case BPF_PROG_TYPE_LSM:
12107 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12108 				/* See below, can be 0 or 0-1 depending on hook. */
12109 				break;
12110 			fallthrough;
12111 		case BPF_PROG_TYPE_STRUCT_OPS:
12112 			if (!prog->aux->attach_func_proto->type)
12113 				return 0;
12114 			break;
12115 		default:
12116 			break;
12117 		}
12118 	}
12119 
12120 	/* eBPF calling convention is such that R0 is used
12121 	 * to return the value from eBPF program.
12122 	 * Make sure that it's readable at this time
12123 	 * of bpf_exit, which means that program wrote
12124 	 * something into it earlier
12125 	 */
12126 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12127 	if (err)
12128 		return err;
12129 
12130 	if (is_pointer_value(env, BPF_REG_0)) {
12131 		verbose(env, "R0 leaks addr as return value\n");
12132 		return -EACCES;
12133 	}
12134 
12135 	reg = cur_regs(env) + BPF_REG_0;
12136 
12137 	if (frame->in_async_callback_fn) {
12138 		/* enforce return zero from async callbacks like timer */
12139 		if (reg->type != SCALAR_VALUE) {
12140 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12141 				reg_type_str(env, reg->type));
12142 			return -EINVAL;
12143 		}
12144 
12145 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12146 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12147 			return -EINVAL;
12148 		}
12149 		return 0;
12150 	}
12151 
12152 	if (is_subprog) {
12153 		if (reg->type != SCALAR_VALUE) {
12154 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12155 				reg_type_str(env, reg->type));
12156 			return -EINVAL;
12157 		}
12158 		return 0;
12159 	}
12160 
12161 	switch (prog_type) {
12162 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12163 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12164 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12165 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12166 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12167 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12168 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12169 			range = tnum_range(1, 1);
12170 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12171 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12172 			range = tnum_range(0, 3);
12173 		break;
12174 	case BPF_PROG_TYPE_CGROUP_SKB:
12175 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12176 			range = tnum_range(0, 3);
12177 			enforce_attach_type_range = tnum_range(2, 3);
12178 		}
12179 		break;
12180 	case BPF_PROG_TYPE_CGROUP_SOCK:
12181 	case BPF_PROG_TYPE_SOCK_OPS:
12182 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12183 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12184 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12185 		break;
12186 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12187 		if (!env->prog->aux->attach_btf_id)
12188 			return 0;
12189 		range = tnum_const(0);
12190 		break;
12191 	case BPF_PROG_TYPE_TRACING:
12192 		switch (env->prog->expected_attach_type) {
12193 		case BPF_TRACE_FENTRY:
12194 		case BPF_TRACE_FEXIT:
12195 			range = tnum_const(0);
12196 			break;
12197 		case BPF_TRACE_RAW_TP:
12198 		case BPF_MODIFY_RETURN:
12199 			return 0;
12200 		case BPF_TRACE_ITER:
12201 			break;
12202 		default:
12203 			return -ENOTSUPP;
12204 		}
12205 		break;
12206 	case BPF_PROG_TYPE_SK_LOOKUP:
12207 		range = tnum_range(SK_DROP, SK_PASS);
12208 		break;
12209 
12210 	case BPF_PROG_TYPE_LSM:
12211 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12212 			/* Regular BPF_PROG_TYPE_LSM programs can return
12213 			 * any value.
12214 			 */
12215 			return 0;
12216 		}
12217 		if (!env->prog->aux->attach_func_proto->type) {
12218 			/* Make sure programs that attach to void
12219 			 * hooks don't try to modify return value.
12220 			 */
12221 			range = tnum_range(1, 1);
12222 		}
12223 		break;
12224 
12225 	case BPF_PROG_TYPE_EXT:
12226 		/* freplace program can return anything as its return value
12227 		 * depends on the to-be-replaced kernel func or bpf program.
12228 		 */
12229 	default:
12230 		return 0;
12231 	}
12232 
12233 	if (reg->type != SCALAR_VALUE) {
12234 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12235 			reg_type_str(env, reg->type));
12236 		return -EINVAL;
12237 	}
12238 
12239 	if (!tnum_in(range, reg->var_off)) {
12240 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12241 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12242 		    prog_type == BPF_PROG_TYPE_LSM &&
12243 		    !prog->aux->attach_func_proto->type)
12244 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12245 		return -EINVAL;
12246 	}
12247 
12248 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12249 	    tnum_in(enforce_attach_type_range, reg->var_off))
12250 		env->prog->enforce_expected_attach_type = 1;
12251 	return 0;
12252 }
12253 
12254 /* non-recursive DFS pseudo code
12255  * 1  procedure DFS-iterative(G,v):
12256  * 2      label v as discovered
12257  * 3      let S be a stack
12258  * 4      S.push(v)
12259  * 5      while S is not empty
12260  * 6            t <- S.peek()
12261  * 7            if t is what we're looking for:
12262  * 8                return t
12263  * 9            for all edges e in G.adjacentEdges(t) do
12264  * 10               if edge e is already labelled
12265  * 11                   continue with the next edge
12266  * 12               w <- G.adjacentVertex(t,e)
12267  * 13               if vertex w is not discovered and not explored
12268  * 14                   label e as tree-edge
12269  * 15                   label w as discovered
12270  * 16                   S.push(w)
12271  * 17                   continue at 5
12272  * 18               else if vertex w is discovered
12273  * 19                   label e as back-edge
12274  * 20               else
12275  * 21                   // vertex w is explored
12276  * 22                   label e as forward- or cross-edge
12277  * 23           label t as explored
12278  * 24           S.pop()
12279  *
12280  * convention:
12281  * 0x10 - discovered
12282  * 0x11 - discovered and fall-through edge labelled
12283  * 0x12 - discovered and fall-through and branch edges labelled
12284  * 0x20 - explored
12285  */
12286 
12287 enum {
12288 	DISCOVERED = 0x10,
12289 	EXPLORED = 0x20,
12290 	FALLTHROUGH = 1,
12291 	BRANCH = 2,
12292 };
12293 
12294 static u32 state_htab_size(struct bpf_verifier_env *env)
12295 {
12296 	return env->prog->len;
12297 }
12298 
12299 static struct bpf_verifier_state_list **explored_state(
12300 					struct bpf_verifier_env *env,
12301 					int idx)
12302 {
12303 	struct bpf_verifier_state *cur = env->cur_state;
12304 	struct bpf_func_state *state = cur->frame[cur->curframe];
12305 
12306 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12307 }
12308 
12309 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
12310 {
12311 	env->insn_aux_data[idx].prune_point = true;
12312 }
12313 
12314 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
12315 {
12316 	return env->insn_aux_data[insn_idx].prune_point;
12317 }
12318 
12319 enum {
12320 	DONE_EXPLORING = 0,
12321 	KEEP_EXPLORING = 1,
12322 };
12323 
12324 /* t, w, e - match pseudo-code above:
12325  * t - index of current instruction
12326  * w - next instruction
12327  * e - edge
12328  */
12329 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12330 		     bool loop_ok)
12331 {
12332 	int *insn_stack = env->cfg.insn_stack;
12333 	int *insn_state = env->cfg.insn_state;
12334 
12335 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12336 		return DONE_EXPLORING;
12337 
12338 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12339 		return DONE_EXPLORING;
12340 
12341 	if (w < 0 || w >= env->prog->len) {
12342 		verbose_linfo(env, t, "%d: ", t);
12343 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
12344 		return -EINVAL;
12345 	}
12346 
12347 	if (e == BRANCH) {
12348 		/* mark branch target for state pruning */
12349 		mark_prune_point(env, w);
12350 		mark_jmp_point(env, w);
12351 	}
12352 
12353 	if (insn_state[w] == 0) {
12354 		/* tree-edge */
12355 		insn_state[t] = DISCOVERED | e;
12356 		insn_state[w] = DISCOVERED;
12357 		if (env->cfg.cur_stack >= env->prog->len)
12358 			return -E2BIG;
12359 		insn_stack[env->cfg.cur_stack++] = w;
12360 		return KEEP_EXPLORING;
12361 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12362 		if (loop_ok && env->bpf_capable)
12363 			return DONE_EXPLORING;
12364 		verbose_linfo(env, t, "%d: ", t);
12365 		verbose_linfo(env, w, "%d: ", w);
12366 		verbose(env, "back-edge from insn %d to %d\n", t, w);
12367 		return -EINVAL;
12368 	} else if (insn_state[w] == EXPLORED) {
12369 		/* forward- or cross-edge */
12370 		insn_state[t] = DISCOVERED | e;
12371 	} else {
12372 		verbose(env, "insn state internal bug\n");
12373 		return -EFAULT;
12374 	}
12375 	return DONE_EXPLORING;
12376 }
12377 
12378 static int visit_func_call_insn(int t, struct bpf_insn *insns,
12379 				struct bpf_verifier_env *env,
12380 				bool visit_callee)
12381 {
12382 	int ret;
12383 
12384 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12385 	if (ret)
12386 		return ret;
12387 
12388 	mark_prune_point(env, t + 1);
12389 	/* when we exit from subprog, we need to record non-linear history */
12390 	mark_jmp_point(env, t + 1);
12391 
12392 	if (visit_callee) {
12393 		mark_prune_point(env, t);
12394 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12395 				/* It's ok to allow recursion from CFG point of
12396 				 * view. __check_func_call() will do the actual
12397 				 * check.
12398 				 */
12399 				bpf_pseudo_func(insns + t));
12400 	}
12401 	return ret;
12402 }
12403 
12404 /* Visits the instruction at index t and returns one of the following:
12405  *  < 0 - an error occurred
12406  *  DONE_EXPLORING - the instruction was fully explored
12407  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12408  */
12409 static int visit_insn(int t, struct bpf_verifier_env *env)
12410 {
12411 	struct bpf_insn *insns = env->prog->insnsi;
12412 	int ret;
12413 
12414 	if (bpf_pseudo_func(insns + t))
12415 		return visit_func_call_insn(t, insns, env, true);
12416 
12417 	/* All non-branch instructions have a single fall-through edge. */
12418 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12419 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
12420 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
12421 
12422 	switch (BPF_OP(insns[t].code)) {
12423 	case BPF_EXIT:
12424 		return DONE_EXPLORING;
12425 
12426 	case BPF_CALL:
12427 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
12428 			/* Mark this call insn as a prune point to trigger
12429 			 * is_state_visited() check before call itself is
12430 			 * processed by __check_func_call(). Otherwise new
12431 			 * async state will be pushed for further exploration.
12432 			 */
12433 			mark_prune_point(env, t);
12434 		return visit_func_call_insn(t, insns, env,
12435 					    insns[t].src_reg == BPF_PSEUDO_CALL);
12436 
12437 	case BPF_JA:
12438 		if (BPF_SRC(insns[t].code) != BPF_K)
12439 			return -EINVAL;
12440 
12441 		/* unconditional jump with single edge */
12442 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12443 				true);
12444 		if (ret)
12445 			return ret;
12446 
12447 		mark_prune_point(env, t + insns[t].off + 1);
12448 		mark_jmp_point(env, t + insns[t].off + 1);
12449 
12450 		return ret;
12451 
12452 	default:
12453 		/* conditional jump with two edges */
12454 		mark_prune_point(env, t);
12455 
12456 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12457 		if (ret)
12458 			return ret;
12459 
12460 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12461 	}
12462 }
12463 
12464 /* non-recursive depth-first-search to detect loops in BPF program
12465  * loop == back-edge in directed graph
12466  */
12467 static int check_cfg(struct bpf_verifier_env *env)
12468 {
12469 	int insn_cnt = env->prog->len;
12470 	int *insn_stack, *insn_state;
12471 	int ret = 0;
12472 	int i;
12473 
12474 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12475 	if (!insn_state)
12476 		return -ENOMEM;
12477 
12478 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12479 	if (!insn_stack) {
12480 		kvfree(insn_state);
12481 		return -ENOMEM;
12482 	}
12483 
12484 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12485 	insn_stack[0] = 0; /* 0 is the first instruction */
12486 	env->cfg.cur_stack = 1;
12487 
12488 	while (env->cfg.cur_stack > 0) {
12489 		int t = insn_stack[env->cfg.cur_stack - 1];
12490 
12491 		ret = visit_insn(t, env);
12492 		switch (ret) {
12493 		case DONE_EXPLORING:
12494 			insn_state[t] = EXPLORED;
12495 			env->cfg.cur_stack--;
12496 			break;
12497 		case KEEP_EXPLORING:
12498 			break;
12499 		default:
12500 			if (ret > 0) {
12501 				verbose(env, "visit_insn internal bug\n");
12502 				ret = -EFAULT;
12503 			}
12504 			goto err_free;
12505 		}
12506 	}
12507 
12508 	if (env->cfg.cur_stack < 0) {
12509 		verbose(env, "pop stack internal bug\n");
12510 		ret = -EFAULT;
12511 		goto err_free;
12512 	}
12513 
12514 	for (i = 0; i < insn_cnt; i++) {
12515 		if (insn_state[i] != EXPLORED) {
12516 			verbose(env, "unreachable insn %d\n", i);
12517 			ret = -EINVAL;
12518 			goto err_free;
12519 		}
12520 	}
12521 	ret = 0; /* cfg looks good */
12522 
12523 err_free:
12524 	kvfree(insn_state);
12525 	kvfree(insn_stack);
12526 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
12527 	return ret;
12528 }
12529 
12530 static int check_abnormal_return(struct bpf_verifier_env *env)
12531 {
12532 	int i;
12533 
12534 	for (i = 1; i < env->subprog_cnt; i++) {
12535 		if (env->subprog_info[i].has_ld_abs) {
12536 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12537 			return -EINVAL;
12538 		}
12539 		if (env->subprog_info[i].has_tail_call) {
12540 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12541 			return -EINVAL;
12542 		}
12543 	}
12544 	return 0;
12545 }
12546 
12547 /* The minimum supported BTF func info size */
12548 #define MIN_BPF_FUNCINFO_SIZE	8
12549 #define MAX_FUNCINFO_REC_SIZE	252
12550 
12551 static int check_btf_func(struct bpf_verifier_env *env,
12552 			  const union bpf_attr *attr,
12553 			  bpfptr_t uattr)
12554 {
12555 	const struct btf_type *type, *func_proto, *ret_type;
12556 	u32 i, nfuncs, urec_size, min_size;
12557 	u32 krec_size = sizeof(struct bpf_func_info);
12558 	struct bpf_func_info *krecord;
12559 	struct bpf_func_info_aux *info_aux = NULL;
12560 	struct bpf_prog *prog;
12561 	const struct btf *btf;
12562 	bpfptr_t urecord;
12563 	u32 prev_offset = 0;
12564 	bool scalar_return;
12565 	int ret = -ENOMEM;
12566 
12567 	nfuncs = attr->func_info_cnt;
12568 	if (!nfuncs) {
12569 		if (check_abnormal_return(env))
12570 			return -EINVAL;
12571 		return 0;
12572 	}
12573 
12574 	if (nfuncs != env->subprog_cnt) {
12575 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12576 		return -EINVAL;
12577 	}
12578 
12579 	urec_size = attr->func_info_rec_size;
12580 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12581 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
12582 	    urec_size % sizeof(u32)) {
12583 		verbose(env, "invalid func info rec size %u\n", urec_size);
12584 		return -EINVAL;
12585 	}
12586 
12587 	prog = env->prog;
12588 	btf = prog->aux->btf;
12589 
12590 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12591 	min_size = min_t(u32, krec_size, urec_size);
12592 
12593 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12594 	if (!krecord)
12595 		return -ENOMEM;
12596 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12597 	if (!info_aux)
12598 		goto err_free;
12599 
12600 	for (i = 0; i < nfuncs; i++) {
12601 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12602 		if (ret) {
12603 			if (ret == -E2BIG) {
12604 				verbose(env, "nonzero tailing record in func info");
12605 				/* set the size kernel expects so loader can zero
12606 				 * out the rest of the record.
12607 				 */
12608 				if (copy_to_bpfptr_offset(uattr,
12609 							  offsetof(union bpf_attr, func_info_rec_size),
12610 							  &min_size, sizeof(min_size)))
12611 					ret = -EFAULT;
12612 			}
12613 			goto err_free;
12614 		}
12615 
12616 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12617 			ret = -EFAULT;
12618 			goto err_free;
12619 		}
12620 
12621 		/* check insn_off */
12622 		ret = -EINVAL;
12623 		if (i == 0) {
12624 			if (krecord[i].insn_off) {
12625 				verbose(env,
12626 					"nonzero insn_off %u for the first func info record",
12627 					krecord[i].insn_off);
12628 				goto err_free;
12629 			}
12630 		} else if (krecord[i].insn_off <= prev_offset) {
12631 			verbose(env,
12632 				"same or smaller insn offset (%u) than previous func info record (%u)",
12633 				krecord[i].insn_off, prev_offset);
12634 			goto err_free;
12635 		}
12636 
12637 		if (env->subprog_info[i].start != krecord[i].insn_off) {
12638 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12639 			goto err_free;
12640 		}
12641 
12642 		/* check type_id */
12643 		type = btf_type_by_id(btf, krecord[i].type_id);
12644 		if (!type || !btf_type_is_func(type)) {
12645 			verbose(env, "invalid type id %d in func info",
12646 				krecord[i].type_id);
12647 			goto err_free;
12648 		}
12649 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12650 
12651 		func_proto = btf_type_by_id(btf, type->type);
12652 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12653 			/* btf_func_check() already verified it during BTF load */
12654 			goto err_free;
12655 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12656 		scalar_return =
12657 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12658 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12659 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12660 			goto err_free;
12661 		}
12662 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12663 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12664 			goto err_free;
12665 		}
12666 
12667 		prev_offset = krecord[i].insn_off;
12668 		bpfptr_add(&urecord, urec_size);
12669 	}
12670 
12671 	prog->aux->func_info = krecord;
12672 	prog->aux->func_info_cnt = nfuncs;
12673 	prog->aux->func_info_aux = info_aux;
12674 	return 0;
12675 
12676 err_free:
12677 	kvfree(krecord);
12678 	kfree(info_aux);
12679 	return ret;
12680 }
12681 
12682 static void adjust_btf_func(struct bpf_verifier_env *env)
12683 {
12684 	struct bpf_prog_aux *aux = env->prog->aux;
12685 	int i;
12686 
12687 	if (!aux->func_info)
12688 		return;
12689 
12690 	for (i = 0; i < env->subprog_cnt; i++)
12691 		aux->func_info[i].insn_off = env->subprog_info[i].start;
12692 }
12693 
12694 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
12695 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
12696 
12697 static int check_btf_line(struct bpf_verifier_env *env,
12698 			  const union bpf_attr *attr,
12699 			  bpfptr_t uattr)
12700 {
12701 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12702 	struct bpf_subprog_info *sub;
12703 	struct bpf_line_info *linfo;
12704 	struct bpf_prog *prog;
12705 	const struct btf *btf;
12706 	bpfptr_t ulinfo;
12707 	int err;
12708 
12709 	nr_linfo = attr->line_info_cnt;
12710 	if (!nr_linfo)
12711 		return 0;
12712 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12713 		return -EINVAL;
12714 
12715 	rec_size = attr->line_info_rec_size;
12716 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12717 	    rec_size > MAX_LINEINFO_REC_SIZE ||
12718 	    rec_size & (sizeof(u32) - 1))
12719 		return -EINVAL;
12720 
12721 	/* Need to zero it in case the userspace may
12722 	 * pass in a smaller bpf_line_info object.
12723 	 */
12724 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12725 			 GFP_KERNEL | __GFP_NOWARN);
12726 	if (!linfo)
12727 		return -ENOMEM;
12728 
12729 	prog = env->prog;
12730 	btf = prog->aux->btf;
12731 
12732 	s = 0;
12733 	sub = env->subprog_info;
12734 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12735 	expected_size = sizeof(struct bpf_line_info);
12736 	ncopy = min_t(u32, expected_size, rec_size);
12737 	for (i = 0; i < nr_linfo; i++) {
12738 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12739 		if (err) {
12740 			if (err == -E2BIG) {
12741 				verbose(env, "nonzero tailing record in line_info");
12742 				if (copy_to_bpfptr_offset(uattr,
12743 							  offsetof(union bpf_attr, line_info_rec_size),
12744 							  &expected_size, sizeof(expected_size)))
12745 					err = -EFAULT;
12746 			}
12747 			goto err_free;
12748 		}
12749 
12750 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12751 			err = -EFAULT;
12752 			goto err_free;
12753 		}
12754 
12755 		/*
12756 		 * Check insn_off to ensure
12757 		 * 1) strictly increasing AND
12758 		 * 2) bounded by prog->len
12759 		 *
12760 		 * The linfo[0].insn_off == 0 check logically falls into
12761 		 * the later "missing bpf_line_info for func..." case
12762 		 * because the first linfo[0].insn_off must be the
12763 		 * first sub also and the first sub must have
12764 		 * subprog_info[0].start == 0.
12765 		 */
12766 		if ((i && linfo[i].insn_off <= prev_offset) ||
12767 		    linfo[i].insn_off >= prog->len) {
12768 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12769 				i, linfo[i].insn_off, prev_offset,
12770 				prog->len);
12771 			err = -EINVAL;
12772 			goto err_free;
12773 		}
12774 
12775 		if (!prog->insnsi[linfo[i].insn_off].code) {
12776 			verbose(env,
12777 				"Invalid insn code at line_info[%u].insn_off\n",
12778 				i);
12779 			err = -EINVAL;
12780 			goto err_free;
12781 		}
12782 
12783 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12784 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12785 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12786 			err = -EINVAL;
12787 			goto err_free;
12788 		}
12789 
12790 		if (s != env->subprog_cnt) {
12791 			if (linfo[i].insn_off == sub[s].start) {
12792 				sub[s].linfo_idx = i;
12793 				s++;
12794 			} else if (sub[s].start < linfo[i].insn_off) {
12795 				verbose(env, "missing bpf_line_info for func#%u\n", s);
12796 				err = -EINVAL;
12797 				goto err_free;
12798 			}
12799 		}
12800 
12801 		prev_offset = linfo[i].insn_off;
12802 		bpfptr_add(&ulinfo, rec_size);
12803 	}
12804 
12805 	if (s != env->subprog_cnt) {
12806 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12807 			env->subprog_cnt - s, s);
12808 		err = -EINVAL;
12809 		goto err_free;
12810 	}
12811 
12812 	prog->aux->linfo = linfo;
12813 	prog->aux->nr_linfo = nr_linfo;
12814 
12815 	return 0;
12816 
12817 err_free:
12818 	kvfree(linfo);
12819 	return err;
12820 }
12821 
12822 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
12823 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
12824 
12825 static int check_core_relo(struct bpf_verifier_env *env,
12826 			   const union bpf_attr *attr,
12827 			   bpfptr_t uattr)
12828 {
12829 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12830 	struct bpf_core_relo core_relo = {};
12831 	struct bpf_prog *prog = env->prog;
12832 	const struct btf *btf = prog->aux->btf;
12833 	struct bpf_core_ctx ctx = {
12834 		.log = &env->log,
12835 		.btf = btf,
12836 	};
12837 	bpfptr_t u_core_relo;
12838 	int err;
12839 
12840 	nr_core_relo = attr->core_relo_cnt;
12841 	if (!nr_core_relo)
12842 		return 0;
12843 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12844 		return -EINVAL;
12845 
12846 	rec_size = attr->core_relo_rec_size;
12847 	if (rec_size < MIN_CORE_RELO_SIZE ||
12848 	    rec_size > MAX_CORE_RELO_SIZE ||
12849 	    rec_size % sizeof(u32))
12850 		return -EINVAL;
12851 
12852 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12853 	expected_size = sizeof(struct bpf_core_relo);
12854 	ncopy = min_t(u32, expected_size, rec_size);
12855 
12856 	/* Unlike func_info and line_info, copy and apply each CO-RE
12857 	 * relocation record one at a time.
12858 	 */
12859 	for (i = 0; i < nr_core_relo; i++) {
12860 		/* future proofing when sizeof(bpf_core_relo) changes */
12861 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12862 		if (err) {
12863 			if (err == -E2BIG) {
12864 				verbose(env, "nonzero tailing record in core_relo");
12865 				if (copy_to_bpfptr_offset(uattr,
12866 							  offsetof(union bpf_attr, core_relo_rec_size),
12867 							  &expected_size, sizeof(expected_size)))
12868 					err = -EFAULT;
12869 			}
12870 			break;
12871 		}
12872 
12873 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12874 			err = -EFAULT;
12875 			break;
12876 		}
12877 
12878 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12879 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12880 				i, core_relo.insn_off, prog->len);
12881 			err = -EINVAL;
12882 			break;
12883 		}
12884 
12885 		err = bpf_core_apply(&ctx, &core_relo, i,
12886 				     &prog->insnsi[core_relo.insn_off / 8]);
12887 		if (err)
12888 			break;
12889 		bpfptr_add(&u_core_relo, rec_size);
12890 	}
12891 	return err;
12892 }
12893 
12894 static int check_btf_info(struct bpf_verifier_env *env,
12895 			  const union bpf_attr *attr,
12896 			  bpfptr_t uattr)
12897 {
12898 	struct btf *btf;
12899 	int err;
12900 
12901 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
12902 		if (check_abnormal_return(env))
12903 			return -EINVAL;
12904 		return 0;
12905 	}
12906 
12907 	btf = btf_get_by_fd(attr->prog_btf_fd);
12908 	if (IS_ERR(btf))
12909 		return PTR_ERR(btf);
12910 	if (btf_is_kernel(btf)) {
12911 		btf_put(btf);
12912 		return -EACCES;
12913 	}
12914 	env->prog->aux->btf = btf;
12915 
12916 	err = check_btf_func(env, attr, uattr);
12917 	if (err)
12918 		return err;
12919 
12920 	err = check_btf_line(env, attr, uattr);
12921 	if (err)
12922 		return err;
12923 
12924 	err = check_core_relo(env, attr, uattr);
12925 	if (err)
12926 		return err;
12927 
12928 	return 0;
12929 }
12930 
12931 /* check %cur's range satisfies %old's */
12932 static bool range_within(struct bpf_reg_state *old,
12933 			 struct bpf_reg_state *cur)
12934 {
12935 	return old->umin_value <= cur->umin_value &&
12936 	       old->umax_value >= cur->umax_value &&
12937 	       old->smin_value <= cur->smin_value &&
12938 	       old->smax_value >= cur->smax_value &&
12939 	       old->u32_min_value <= cur->u32_min_value &&
12940 	       old->u32_max_value >= cur->u32_max_value &&
12941 	       old->s32_min_value <= cur->s32_min_value &&
12942 	       old->s32_max_value >= cur->s32_max_value;
12943 }
12944 
12945 /* If in the old state two registers had the same id, then they need to have
12946  * the same id in the new state as well.  But that id could be different from
12947  * the old state, so we need to track the mapping from old to new ids.
12948  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12949  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12950  * regs with a different old id could still have new id 9, we don't care about
12951  * that.
12952  * So we look through our idmap to see if this old id has been seen before.  If
12953  * so, we require the new id to match; otherwise, we add the id pair to the map.
12954  */
12955 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12956 {
12957 	unsigned int i;
12958 
12959 	/* either both IDs should be set or both should be zero */
12960 	if (!!old_id != !!cur_id)
12961 		return false;
12962 
12963 	if (old_id == 0) /* cur_id == 0 as well */
12964 		return true;
12965 
12966 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12967 		if (!idmap[i].old) {
12968 			/* Reached an empty slot; haven't seen this id before */
12969 			idmap[i].old = old_id;
12970 			idmap[i].cur = cur_id;
12971 			return true;
12972 		}
12973 		if (idmap[i].old == old_id)
12974 			return idmap[i].cur == cur_id;
12975 	}
12976 	/* We ran out of idmap slots, which should be impossible */
12977 	WARN_ON_ONCE(1);
12978 	return false;
12979 }
12980 
12981 static void clean_func_state(struct bpf_verifier_env *env,
12982 			     struct bpf_func_state *st)
12983 {
12984 	enum bpf_reg_liveness live;
12985 	int i, j;
12986 
12987 	for (i = 0; i < BPF_REG_FP; i++) {
12988 		live = st->regs[i].live;
12989 		/* liveness must not touch this register anymore */
12990 		st->regs[i].live |= REG_LIVE_DONE;
12991 		if (!(live & REG_LIVE_READ))
12992 			/* since the register is unused, clear its state
12993 			 * to make further comparison simpler
12994 			 */
12995 			__mark_reg_not_init(env, &st->regs[i]);
12996 	}
12997 
12998 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12999 		live = st->stack[i].spilled_ptr.live;
13000 		/* liveness must not touch this stack slot anymore */
13001 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13002 		if (!(live & REG_LIVE_READ)) {
13003 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13004 			for (j = 0; j < BPF_REG_SIZE; j++)
13005 				st->stack[i].slot_type[j] = STACK_INVALID;
13006 		}
13007 	}
13008 }
13009 
13010 static void clean_verifier_state(struct bpf_verifier_env *env,
13011 				 struct bpf_verifier_state *st)
13012 {
13013 	int i;
13014 
13015 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13016 		/* all regs in this state in all frames were already marked */
13017 		return;
13018 
13019 	for (i = 0; i <= st->curframe; i++)
13020 		clean_func_state(env, st->frame[i]);
13021 }
13022 
13023 /* the parentage chains form a tree.
13024  * the verifier states are added to state lists at given insn and
13025  * pushed into state stack for future exploration.
13026  * when the verifier reaches bpf_exit insn some of the verifer states
13027  * stored in the state lists have their final liveness state already,
13028  * but a lot of states will get revised from liveness point of view when
13029  * the verifier explores other branches.
13030  * Example:
13031  * 1: r0 = 1
13032  * 2: if r1 == 100 goto pc+1
13033  * 3: r0 = 2
13034  * 4: exit
13035  * when the verifier reaches exit insn the register r0 in the state list of
13036  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13037  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13038  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13039  *
13040  * Since the verifier pushes the branch states as it sees them while exploring
13041  * the program the condition of walking the branch instruction for the second
13042  * time means that all states below this branch were already explored and
13043  * their final liveness marks are already propagated.
13044  * Hence when the verifier completes the search of state list in is_state_visited()
13045  * we can call this clean_live_states() function to mark all liveness states
13046  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13047  * will not be used.
13048  * This function also clears the registers and stack for states that !READ
13049  * to simplify state merging.
13050  *
13051  * Important note here that walking the same branch instruction in the callee
13052  * doesn't meant that the states are DONE. The verifier has to compare
13053  * the callsites
13054  */
13055 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13056 			      struct bpf_verifier_state *cur)
13057 {
13058 	struct bpf_verifier_state_list *sl;
13059 	int i;
13060 
13061 	sl = *explored_state(env, insn);
13062 	while (sl) {
13063 		if (sl->state.branches)
13064 			goto next;
13065 		if (sl->state.insn_idx != insn ||
13066 		    sl->state.curframe != cur->curframe)
13067 			goto next;
13068 		for (i = 0; i <= cur->curframe; i++)
13069 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13070 				goto next;
13071 		clean_verifier_state(env, &sl->state);
13072 next:
13073 		sl = sl->next;
13074 	}
13075 }
13076 
13077 static bool regs_exact(const struct bpf_reg_state *rold,
13078 		       const struct bpf_reg_state *rcur,
13079 		       struct bpf_id_pair *idmap)
13080 {
13081 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13082 	       check_ids(rold->id, rcur->id, idmap) &&
13083 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13084 }
13085 
13086 /* Returns true if (rold safe implies rcur safe) */
13087 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13088 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13089 {
13090 	if (!(rold->live & REG_LIVE_READ))
13091 		/* explored state didn't use this */
13092 		return true;
13093 	if (rold->type == NOT_INIT)
13094 		/* explored state can't have used this */
13095 		return true;
13096 	if (rcur->type == NOT_INIT)
13097 		return false;
13098 
13099 	/* Enforce that register types have to match exactly, including their
13100 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13101 	 * rule.
13102 	 *
13103 	 * One can make a point that using a pointer register as unbounded
13104 	 * SCALAR would be technically acceptable, but this could lead to
13105 	 * pointer leaks because scalars are allowed to leak while pointers
13106 	 * are not. We could make this safe in special cases if root is
13107 	 * calling us, but it's probably not worth the hassle.
13108 	 *
13109 	 * Also, register types that are *not* MAYBE_NULL could technically be
13110 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13111 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13112 	 * to the same map).
13113 	 * However, if the old MAYBE_NULL register then got NULL checked,
13114 	 * doing so could have affected others with the same id, and we can't
13115 	 * check for that because we lost the id when we converted to
13116 	 * a non-MAYBE_NULL variant.
13117 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13118 	 * non-MAYBE_NULL registers as well.
13119 	 */
13120 	if (rold->type != rcur->type)
13121 		return false;
13122 
13123 	switch (base_type(rold->type)) {
13124 	case SCALAR_VALUE:
13125 		if (regs_exact(rold, rcur, idmap))
13126 			return true;
13127 		if (env->explore_alu_limits)
13128 			return false;
13129 		if (!rold->precise)
13130 			return true;
13131 		/* new val must satisfy old val knowledge */
13132 		return range_within(rold, rcur) &&
13133 		       tnum_in(rold->var_off, rcur->var_off);
13134 	case PTR_TO_MAP_KEY:
13135 	case PTR_TO_MAP_VALUE:
13136 		/* If the new min/max/var_off satisfy the old ones and
13137 		 * everything else matches, we are OK.
13138 		 */
13139 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13140 		       range_within(rold, rcur) &&
13141 		       tnum_in(rold->var_off, rcur->var_off) &&
13142 		       check_ids(rold->id, rcur->id, idmap);
13143 	case PTR_TO_PACKET_META:
13144 	case PTR_TO_PACKET:
13145 		/* We must have at least as much range as the old ptr
13146 		 * did, so that any accesses which were safe before are
13147 		 * still safe.  This is true even if old range < old off,
13148 		 * since someone could have accessed through (ptr - k), or
13149 		 * even done ptr -= k in a register, to get a safe access.
13150 		 */
13151 		if (rold->range > rcur->range)
13152 			return false;
13153 		/* If the offsets don't match, we can't trust our alignment;
13154 		 * nor can we be sure that we won't fall out of range.
13155 		 */
13156 		if (rold->off != rcur->off)
13157 			return false;
13158 		/* id relations must be preserved */
13159 		if (!check_ids(rold->id, rcur->id, idmap))
13160 			return false;
13161 		/* new val must satisfy old val knowledge */
13162 		return range_within(rold, rcur) &&
13163 		       tnum_in(rold->var_off, rcur->var_off);
13164 	case PTR_TO_STACK:
13165 		/* two stack pointers are equal only if they're pointing to
13166 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13167 		 */
13168 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13169 	default:
13170 		return regs_exact(rold, rcur, idmap);
13171 	}
13172 }
13173 
13174 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13175 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13176 {
13177 	int i, spi;
13178 
13179 	/* walk slots of the explored stack and ignore any additional
13180 	 * slots in the current stack, since explored(safe) state
13181 	 * didn't use them
13182 	 */
13183 	for (i = 0; i < old->allocated_stack; i++) {
13184 		spi = i / BPF_REG_SIZE;
13185 
13186 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13187 			i += BPF_REG_SIZE - 1;
13188 			/* explored state didn't use this */
13189 			continue;
13190 		}
13191 
13192 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13193 			continue;
13194 
13195 		/* explored stack has more populated slots than current stack
13196 		 * and these slots were used
13197 		 */
13198 		if (i >= cur->allocated_stack)
13199 			return false;
13200 
13201 		/* if old state was safe with misc data in the stack
13202 		 * it will be safe with zero-initialized stack.
13203 		 * The opposite is not true
13204 		 */
13205 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13206 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13207 			continue;
13208 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13209 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13210 			/* Ex: old explored (safe) state has STACK_SPILL in
13211 			 * this stack slot, but current has STACK_MISC ->
13212 			 * this verifier states are not equivalent,
13213 			 * return false to continue verification of this path
13214 			 */
13215 			return false;
13216 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13217 			continue;
13218 		if (!is_spilled_reg(&old->stack[spi]))
13219 			continue;
13220 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
13221 			     &cur->stack[spi].spilled_ptr, idmap))
13222 			/* when explored and current stack slot are both storing
13223 			 * spilled registers, check that stored pointers types
13224 			 * are the same as well.
13225 			 * Ex: explored safe path could have stored
13226 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13227 			 * but current path has stored:
13228 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13229 			 * such verifier states are not equivalent.
13230 			 * return false to continue verification of this path
13231 			 */
13232 			return false;
13233 	}
13234 	return true;
13235 }
13236 
13237 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
13238 		    struct bpf_id_pair *idmap)
13239 {
13240 	int i;
13241 
13242 	if (old->acquired_refs != cur->acquired_refs)
13243 		return false;
13244 
13245 	for (i = 0; i < old->acquired_refs; i++) {
13246 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
13247 			return false;
13248 	}
13249 
13250 	return true;
13251 }
13252 
13253 /* compare two verifier states
13254  *
13255  * all states stored in state_list are known to be valid, since
13256  * verifier reached 'bpf_exit' instruction through them
13257  *
13258  * this function is called when verifier exploring different branches of
13259  * execution popped from the state stack. If it sees an old state that has
13260  * more strict register state and more strict stack state then this execution
13261  * branch doesn't need to be explored further, since verifier already
13262  * concluded that more strict state leads to valid finish.
13263  *
13264  * Therefore two states are equivalent if register state is more conservative
13265  * and explored stack state is more conservative than the current one.
13266  * Example:
13267  *       explored                   current
13268  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13269  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13270  *
13271  * In other words if current stack state (one being explored) has more
13272  * valid slots than old one that already passed validation, it means
13273  * the verifier can stop exploring and conclude that current state is valid too
13274  *
13275  * Similarly with registers. If explored state has register type as invalid
13276  * whereas register type in current state is meaningful, it means that
13277  * the current state will reach 'bpf_exit' instruction safely
13278  */
13279 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13280 			      struct bpf_func_state *cur)
13281 {
13282 	int i;
13283 
13284 	for (i = 0; i < MAX_BPF_REG; i++)
13285 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
13286 			     env->idmap_scratch))
13287 			return false;
13288 
13289 	if (!stacksafe(env, old, cur, env->idmap_scratch))
13290 		return false;
13291 
13292 	if (!refsafe(old, cur, env->idmap_scratch))
13293 		return false;
13294 
13295 	return true;
13296 }
13297 
13298 static bool states_equal(struct bpf_verifier_env *env,
13299 			 struct bpf_verifier_state *old,
13300 			 struct bpf_verifier_state *cur)
13301 {
13302 	int i;
13303 
13304 	if (old->curframe != cur->curframe)
13305 		return false;
13306 
13307 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13308 
13309 	/* Verification state from speculative execution simulation
13310 	 * must never prune a non-speculative execution one.
13311 	 */
13312 	if (old->speculative && !cur->speculative)
13313 		return false;
13314 
13315 	if (old->active_lock.ptr != cur->active_lock.ptr)
13316 		return false;
13317 
13318 	/* Old and cur active_lock's have to be either both present
13319 	 * or both absent.
13320 	 */
13321 	if (!!old->active_lock.id != !!cur->active_lock.id)
13322 		return false;
13323 
13324 	if (old->active_lock.id &&
13325 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
13326 		return false;
13327 
13328 	if (old->active_rcu_lock != cur->active_rcu_lock)
13329 		return false;
13330 
13331 	/* for states to be equal callsites have to be the same
13332 	 * and all frame states need to be equivalent
13333 	 */
13334 	for (i = 0; i <= old->curframe; i++) {
13335 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
13336 			return false;
13337 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13338 			return false;
13339 	}
13340 	return true;
13341 }
13342 
13343 /* Return 0 if no propagation happened. Return negative error code if error
13344  * happened. Otherwise, return the propagated bit.
13345  */
13346 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13347 				  struct bpf_reg_state *reg,
13348 				  struct bpf_reg_state *parent_reg)
13349 {
13350 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13351 	u8 flag = reg->live & REG_LIVE_READ;
13352 	int err;
13353 
13354 	/* When comes here, read flags of PARENT_REG or REG could be any of
13355 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13356 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13357 	 */
13358 	if (parent_flag == REG_LIVE_READ64 ||
13359 	    /* Or if there is no read flag from REG. */
13360 	    !flag ||
13361 	    /* Or if the read flag from REG is the same as PARENT_REG. */
13362 	    parent_flag == flag)
13363 		return 0;
13364 
13365 	err = mark_reg_read(env, reg, parent_reg, flag);
13366 	if (err)
13367 		return err;
13368 
13369 	return flag;
13370 }
13371 
13372 /* A write screens off any subsequent reads; but write marks come from the
13373  * straight-line code between a state and its parent.  When we arrive at an
13374  * equivalent state (jump target or such) we didn't arrive by the straight-line
13375  * code, so read marks in the state must propagate to the parent regardless
13376  * of the state's write marks. That's what 'parent == state->parent' comparison
13377  * in mark_reg_read() is for.
13378  */
13379 static int propagate_liveness(struct bpf_verifier_env *env,
13380 			      const struct bpf_verifier_state *vstate,
13381 			      struct bpf_verifier_state *vparent)
13382 {
13383 	struct bpf_reg_state *state_reg, *parent_reg;
13384 	struct bpf_func_state *state, *parent;
13385 	int i, frame, err = 0;
13386 
13387 	if (vparent->curframe != vstate->curframe) {
13388 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
13389 		     vparent->curframe, vstate->curframe);
13390 		return -EFAULT;
13391 	}
13392 	/* Propagate read liveness of registers... */
13393 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13394 	for (frame = 0; frame <= vstate->curframe; frame++) {
13395 		parent = vparent->frame[frame];
13396 		state = vstate->frame[frame];
13397 		parent_reg = parent->regs;
13398 		state_reg = state->regs;
13399 		/* We don't need to worry about FP liveness, it's read-only */
13400 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13401 			err = propagate_liveness_reg(env, &state_reg[i],
13402 						     &parent_reg[i]);
13403 			if (err < 0)
13404 				return err;
13405 			if (err == REG_LIVE_READ64)
13406 				mark_insn_zext(env, &parent_reg[i]);
13407 		}
13408 
13409 		/* Propagate stack slots. */
13410 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13411 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13412 			parent_reg = &parent->stack[i].spilled_ptr;
13413 			state_reg = &state->stack[i].spilled_ptr;
13414 			err = propagate_liveness_reg(env, state_reg,
13415 						     parent_reg);
13416 			if (err < 0)
13417 				return err;
13418 		}
13419 	}
13420 	return 0;
13421 }
13422 
13423 /* find precise scalars in the previous equivalent state and
13424  * propagate them into the current state
13425  */
13426 static int propagate_precision(struct bpf_verifier_env *env,
13427 			       const struct bpf_verifier_state *old)
13428 {
13429 	struct bpf_reg_state *state_reg;
13430 	struct bpf_func_state *state;
13431 	int i, err = 0, fr;
13432 
13433 	for (fr = old->curframe; fr >= 0; fr--) {
13434 		state = old->frame[fr];
13435 		state_reg = state->regs;
13436 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13437 			if (state_reg->type != SCALAR_VALUE ||
13438 			    !state_reg->precise)
13439 				continue;
13440 			if (env->log.level & BPF_LOG_LEVEL2)
13441 				verbose(env, "frame %d: propagating r%d\n", i, fr);
13442 			err = mark_chain_precision_frame(env, fr, i);
13443 			if (err < 0)
13444 				return err;
13445 		}
13446 
13447 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13448 			if (!is_spilled_reg(&state->stack[i]))
13449 				continue;
13450 			state_reg = &state->stack[i].spilled_ptr;
13451 			if (state_reg->type != SCALAR_VALUE ||
13452 			    !state_reg->precise)
13453 				continue;
13454 			if (env->log.level & BPF_LOG_LEVEL2)
13455 				verbose(env, "frame %d: propagating fp%d\n",
13456 					(-i - 1) * BPF_REG_SIZE, fr);
13457 			err = mark_chain_precision_stack_frame(env, fr, i);
13458 			if (err < 0)
13459 				return err;
13460 		}
13461 	}
13462 	return 0;
13463 }
13464 
13465 static bool states_maybe_looping(struct bpf_verifier_state *old,
13466 				 struct bpf_verifier_state *cur)
13467 {
13468 	struct bpf_func_state *fold, *fcur;
13469 	int i, fr = cur->curframe;
13470 
13471 	if (old->curframe != fr)
13472 		return false;
13473 
13474 	fold = old->frame[fr];
13475 	fcur = cur->frame[fr];
13476 	for (i = 0; i < MAX_BPF_REG; i++)
13477 		if (memcmp(&fold->regs[i], &fcur->regs[i],
13478 			   offsetof(struct bpf_reg_state, parent)))
13479 			return false;
13480 	return true;
13481 }
13482 
13483 
13484 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13485 {
13486 	struct bpf_verifier_state_list *new_sl;
13487 	struct bpf_verifier_state_list *sl, **pprev;
13488 	struct bpf_verifier_state *cur = env->cur_state, *new;
13489 	int i, j, err, states_cnt = 0;
13490 	bool add_new_state = env->test_state_freq ? true : false;
13491 
13492 	/* bpf progs typically have pruning point every 4 instructions
13493 	 * http://vger.kernel.org/bpfconf2019.html#session-1
13494 	 * Do not add new state for future pruning if the verifier hasn't seen
13495 	 * at least 2 jumps and at least 8 instructions.
13496 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13497 	 * In tests that amounts to up to 50% reduction into total verifier
13498 	 * memory consumption and 20% verifier time speedup.
13499 	 */
13500 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13501 	    env->insn_processed - env->prev_insn_processed >= 8)
13502 		add_new_state = true;
13503 
13504 	pprev = explored_state(env, insn_idx);
13505 	sl = *pprev;
13506 
13507 	clean_live_states(env, insn_idx, cur);
13508 
13509 	while (sl) {
13510 		states_cnt++;
13511 		if (sl->state.insn_idx != insn_idx)
13512 			goto next;
13513 
13514 		if (sl->state.branches) {
13515 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13516 
13517 			if (frame->in_async_callback_fn &&
13518 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13519 				/* Different async_entry_cnt means that the verifier is
13520 				 * processing another entry into async callback.
13521 				 * Seeing the same state is not an indication of infinite
13522 				 * loop or infinite recursion.
13523 				 * But finding the same state doesn't mean that it's safe
13524 				 * to stop processing the current state. The previous state
13525 				 * hasn't yet reached bpf_exit, since state.branches > 0.
13526 				 * Checking in_async_callback_fn alone is not enough either.
13527 				 * Since the verifier still needs to catch infinite loops
13528 				 * inside async callbacks.
13529 				 */
13530 			} else if (states_maybe_looping(&sl->state, cur) &&
13531 				   states_equal(env, &sl->state, cur)) {
13532 				verbose_linfo(env, insn_idx, "; ");
13533 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13534 				return -EINVAL;
13535 			}
13536 			/* if the verifier is processing a loop, avoid adding new state
13537 			 * too often, since different loop iterations have distinct
13538 			 * states and may not help future pruning.
13539 			 * This threshold shouldn't be too low to make sure that
13540 			 * a loop with large bound will be rejected quickly.
13541 			 * The most abusive loop will be:
13542 			 * r1 += 1
13543 			 * if r1 < 1000000 goto pc-2
13544 			 * 1M insn_procssed limit / 100 == 10k peak states.
13545 			 * This threshold shouldn't be too high either, since states
13546 			 * at the end of the loop are likely to be useful in pruning.
13547 			 */
13548 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13549 			    env->insn_processed - env->prev_insn_processed < 100)
13550 				add_new_state = false;
13551 			goto miss;
13552 		}
13553 		if (states_equal(env, &sl->state, cur)) {
13554 			sl->hit_cnt++;
13555 			/* reached equivalent register/stack state,
13556 			 * prune the search.
13557 			 * Registers read by the continuation are read by us.
13558 			 * If we have any write marks in env->cur_state, they
13559 			 * will prevent corresponding reads in the continuation
13560 			 * from reaching our parent (an explored_state).  Our
13561 			 * own state will get the read marks recorded, but
13562 			 * they'll be immediately forgotten as we're pruning
13563 			 * this state and will pop a new one.
13564 			 */
13565 			err = propagate_liveness(env, &sl->state, cur);
13566 
13567 			/* if previous state reached the exit with precision and
13568 			 * current state is equivalent to it (except precsion marks)
13569 			 * the precision needs to be propagated back in
13570 			 * the current state.
13571 			 */
13572 			err = err ? : push_jmp_history(env, cur);
13573 			err = err ? : propagate_precision(env, &sl->state);
13574 			if (err)
13575 				return err;
13576 			return 1;
13577 		}
13578 miss:
13579 		/* when new state is not going to be added do not increase miss count.
13580 		 * Otherwise several loop iterations will remove the state
13581 		 * recorded earlier. The goal of these heuristics is to have
13582 		 * states from some iterations of the loop (some in the beginning
13583 		 * and some at the end) to help pruning.
13584 		 */
13585 		if (add_new_state)
13586 			sl->miss_cnt++;
13587 		/* heuristic to determine whether this state is beneficial
13588 		 * to keep checking from state equivalence point of view.
13589 		 * Higher numbers increase max_states_per_insn and verification time,
13590 		 * but do not meaningfully decrease insn_processed.
13591 		 */
13592 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13593 			/* the state is unlikely to be useful. Remove it to
13594 			 * speed up verification
13595 			 */
13596 			*pprev = sl->next;
13597 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13598 				u32 br = sl->state.branches;
13599 
13600 				WARN_ONCE(br,
13601 					  "BUG live_done but branches_to_explore %d\n",
13602 					  br);
13603 				free_verifier_state(&sl->state, false);
13604 				kfree(sl);
13605 				env->peak_states--;
13606 			} else {
13607 				/* cannot free this state, since parentage chain may
13608 				 * walk it later. Add it for free_list instead to
13609 				 * be freed at the end of verification
13610 				 */
13611 				sl->next = env->free_list;
13612 				env->free_list = sl;
13613 			}
13614 			sl = *pprev;
13615 			continue;
13616 		}
13617 next:
13618 		pprev = &sl->next;
13619 		sl = *pprev;
13620 	}
13621 
13622 	if (env->max_states_per_insn < states_cnt)
13623 		env->max_states_per_insn = states_cnt;
13624 
13625 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13626 		return 0;
13627 
13628 	if (!add_new_state)
13629 		return 0;
13630 
13631 	/* There were no equivalent states, remember the current one.
13632 	 * Technically the current state is not proven to be safe yet,
13633 	 * but it will either reach outer most bpf_exit (which means it's safe)
13634 	 * or it will be rejected. When there are no loops the verifier won't be
13635 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13636 	 * again on the way to bpf_exit.
13637 	 * When looping the sl->state.branches will be > 0 and this state
13638 	 * will not be considered for equivalence until branches == 0.
13639 	 */
13640 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13641 	if (!new_sl)
13642 		return -ENOMEM;
13643 	env->total_states++;
13644 	env->peak_states++;
13645 	env->prev_jmps_processed = env->jmps_processed;
13646 	env->prev_insn_processed = env->insn_processed;
13647 
13648 	/* forget precise markings we inherited, see __mark_chain_precision */
13649 	if (env->bpf_capable)
13650 		mark_all_scalars_imprecise(env, cur);
13651 
13652 	/* add new state to the head of linked list */
13653 	new = &new_sl->state;
13654 	err = copy_verifier_state(new, cur);
13655 	if (err) {
13656 		free_verifier_state(new, false);
13657 		kfree(new_sl);
13658 		return err;
13659 	}
13660 	new->insn_idx = insn_idx;
13661 	WARN_ONCE(new->branches != 1,
13662 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13663 
13664 	cur->parent = new;
13665 	cur->first_insn_idx = insn_idx;
13666 	clear_jmp_history(cur);
13667 	new_sl->next = *explored_state(env, insn_idx);
13668 	*explored_state(env, insn_idx) = new_sl;
13669 	/* connect new state to parentage chain. Current frame needs all
13670 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
13671 	 * to the stack implicitly by JITs) so in callers' frames connect just
13672 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13673 	 * the state of the call instruction (with WRITTEN set), and r0 comes
13674 	 * from callee with its full parentage chain, anyway.
13675 	 */
13676 	/* clear write marks in current state: the writes we did are not writes
13677 	 * our child did, so they don't screen off its reads from us.
13678 	 * (There are no read marks in current state, because reads always mark
13679 	 * their parent and current state never has children yet.  Only
13680 	 * explored_states can get read marks.)
13681 	 */
13682 	for (j = 0; j <= cur->curframe; j++) {
13683 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13684 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13685 		for (i = 0; i < BPF_REG_FP; i++)
13686 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13687 	}
13688 
13689 	/* all stack frames are accessible from callee, clear them all */
13690 	for (j = 0; j <= cur->curframe; j++) {
13691 		struct bpf_func_state *frame = cur->frame[j];
13692 		struct bpf_func_state *newframe = new->frame[j];
13693 
13694 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13695 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13696 			frame->stack[i].spilled_ptr.parent =
13697 						&newframe->stack[i].spilled_ptr;
13698 		}
13699 	}
13700 	return 0;
13701 }
13702 
13703 /* Return true if it's OK to have the same insn return a different type. */
13704 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13705 {
13706 	switch (base_type(type)) {
13707 	case PTR_TO_CTX:
13708 	case PTR_TO_SOCKET:
13709 	case PTR_TO_SOCK_COMMON:
13710 	case PTR_TO_TCP_SOCK:
13711 	case PTR_TO_XDP_SOCK:
13712 	case PTR_TO_BTF_ID:
13713 		return false;
13714 	default:
13715 		return true;
13716 	}
13717 }
13718 
13719 /* If an instruction was previously used with particular pointer types, then we
13720  * need to be careful to avoid cases such as the below, where it may be ok
13721  * for one branch accessing the pointer, but not ok for the other branch:
13722  *
13723  * R1 = sock_ptr
13724  * goto X;
13725  * ...
13726  * R1 = some_other_valid_ptr;
13727  * goto X;
13728  * ...
13729  * R2 = *(u32 *)(R1 + 0);
13730  */
13731 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13732 {
13733 	return src != prev && (!reg_type_mismatch_ok(src) ||
13734 			       !reg_type_mismatch_ok(prev));
13735 }
13736 
13737 static int do_check(struct bpf_verifier_env *env)
13738 {
13739 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13740 	struct bpf_verifier_state *state = env->cur_state;
13741 	struct bpf_insn *insns = env->prog->insnsi;
13742 	struct bpf_reg_state *regs;
13743 	int insn_cnt = env->prog->len;
13744 	bool do_print_state = false;
13745 	int prev_insn_idx = -1;
13746 
13747 	for (;;) {
13748 		struct bpf_insn *insn;
13749 		u8 class;
13750 		int err;
13751 
13752 		env->prev_insn_idx = prev_insn_idx;
13753 		if (env->insn_idx >= insn_cnt) {
13754 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
13755 				env->insn_idx, insn_cnt);
13756 			return -EFAULT;
13757 		}
13758 
13759 		insn = &insns[env->insn_idx];
13760 		class = BPF_CLASS(insn->code);
13761 
13762 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13763 			verbose(env,
13764 				"BPF program is too large. Processed %d insn\n",
13765 				env->insn_processed);
13766 			return -E2BIG;
13767 		}
13768 
13769 		state->last_insn_idx = env->prev_insn_idx;
13770 
13771 		if (is_prune_point(env, env->insn_idx)) {
13772 			err = is_state_visited(env, env->insn_idx);
13773 			if (err < 0)
13774 				return err;
13775 			if (err == 1) {
13776 				/* found equivalent state, can prune the search */
13777 				if (env->log.level & BPF_LOG_LEVEL) {
13778 					if (do_print_state)
13779 						verbose(env, "\nfrom %d to %d%s: safe\n",
13780 							env->prev_insn_idx, env->insn_idx,
13781 							env->cur_state->speculative ?
13782 							" (speculative execution)" : "");
13783 					else
13784 						verbose(env, "%d: safe\n", env->insn_idx);
13785 				}
13786 				goto process_bpf_exit;
13787 			}
13788 		}
13789 
13790 		if (is_jmp_point(env, env->insn_idx)) {
13791 			err = push_jmp_history(env, state);
13792 			if (err)
13793 				return err;
13794 		}
13795 
13796 		if (signal_pending(current))
13797 			return -EAGAIN;
13798 
13799 		if (need_resched())
13800 			cond_resched();
13801 
13802 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13803 			verbose(env, "\nfrom %d to %d%s:",
13804 				env->prev_insn_idx, env->insn_idx,
13805 				env->cur_state->speculative ?
13806 				" (speculative execution)" : "");
13807 			print_verifier_state(env, state->frame[state->curframe], true);
13808 			do_print_state = false;
13809 		}
13810 
13811 		if (env->log.level & BPF_LOG_LEVEL) {
13812 			const struct bpf_insn_cbs cbs = {
13813 				.cb_call	= disasm_kfunc_name,
13814 				.cb_print	= verbose,
13815 				.private_data	= env,
13816 			};
13817 
13818 			if (verifier_state_scratched(env))
13819 				print_insn_state(env, state->frame[state->curframe]);
13820 
13821 			verbose_linfo(env, env->insn_idx, "; ");
13822 			env->prev_log_len = env->log.len_used;
13823 			verbose(env, "%d: ", env->insn_idx);
13824 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13825 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13826 			env->prev_log_len = env->log.len_used;
13827 		}
13828 
13829 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
13830 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13831 							   env->prev_insn_idx);
13832 			if (err)
13833 				return err;
13834 		}
13835 
13836 		regs = cur_regs(env);
13837 		sanitize_mark_insn_seen(env);
13838 		prev_insn_idx = env->insn_idx;
13839 
13840 		if (class == BPF_ALU || class == BPF_ALU64) {
13841 			err = check_alu_op(env, insn);
13842 			if (err)
13843 				return err;
13844 
13845 		} else if (class == BPF_LDX) {
13846 			enum bpf_reg_type *prev_src_type, src_reg_type;
13847 
13848 			/* check for reserved fields is already done */
13849 
13850 			/* check src operand */
13851 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13852 			if (err)
13853 				return err;
13854 
13855 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13856 			if (err)
13857 				return err;
13858 
13859 			src_reg_type = regs[insn->src_reg].type;
13860 
13861 			/* check that memory (src_reg + off) is readable,
13862 			 * the state of dst_reg will be updated by this func
13863 			 */
13864 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
13865 					       insn->off, BPF_SIZE(insn->code),
13866 					       BPF_READ, insn->dst_reg, false);
13867 			if (err)
13868 				return err;
13869 
13870 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13871 
13872 			if (*prev_src_type == NOT_INIT) {
13873 				/* saw a valid insn
13874 				 * dst_reg = *(u32 *)(src_reg + off)
13875 				 * save type to validate intersecting paths
13876 				 */
13877 				*prev_src_type = src_reg_type;
13878 
13879 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13880 				/* ABuser program is trying to use the same insn
13881 				 * dst_reg = *(u32*) (src_reg + off)
13882 				 * with different pointer types:
13883 				 * src_reg == ctx in one branch and
13884 				 * src_reg == stack|map in some other branch.
13885 				 * Reject it.
13886 				 */
13887 				verbose(env, "same insn cannot be used with different pointers\n");
13888 				return -EINVAL;
13889 			}
13890 
13891 		} else if (class == BPF_STX) {
13892 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
13893 
13894 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13895 				err = check_atomic(env, env->insn_idx, insn);
13896 				if (err)
13897 					return err;
13898 				env->insn_idx++;
13899 				continue;
13900 			}
13901 
13902 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13903 				verbose(env, "BPF_STX uses reserved fields\n");
13904 				return -EINVAL;
13905 			}
13906 
13907 			/* check src1 operand */
13908 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13909 			if (err)
13910 				return err;
13911 			/* check src2 operand */
13912 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13913 			if (err)
13914 				return err;
13915 
13916 			dst_reg_type = regs[insn->dst_reg].type;
13917 
13918 			/* check that memory (dst_reg + off) is writeable */
13919 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13920 					       insn->off, BPF_SIZE(insn->code),
13921 					       BPF_WRITE, insn->src_reg, false);
13922 			if (err)
13923 				return err;
13924 
13925 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13926 
13927 			if (*prev_dst_type == NOT_INIT) {
13928 				*prev_dst_type = dst_reg_type;
13929 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13930 				verbose(env, "same insn cannot be used with different pointers\n");
13931 				return -EINVAL;
13932 			}
13933 
13934 		} else if (class == BPF_ST) {
13935 			if (BPF_MODE(insn->code) != BPF_MEM ||
13936 			    insn->src_reg != BPF_REG_0) {
13937 				verbose(env, "BPF_ST uses reserved fields\n");
13938 				return -EINVAL;
13939 			}
13940 			/* check src operand */
13941 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13942 			if (err)
13943 				return err;
13944 
13945 			if (is_ctx_reg(env, insn->dst_reg)) {
13946 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13947 					insn->dst_reg,
13948 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13949 				return -EACCES;
13950 			}
13951 
13952 			/* check that memory (dst_reg + off) is writeable */
13953 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13954 					       insn->off, BPF_SIZE(insn->code),
13955 					       BPF_WRITE, -1, false);
13956 			if (err)
13957 				return err;
13958 
13959 		} else if (class == BPF_JMP || class == BPF_JMP32) {
13960 			u8 opcode = BPF_OP(insn->code);
13961 
13962 			env->jmps_processed++;
13963 			if (opcode == BPF_CALL) {
13964 				if (BPF_SRC(insn->code) != BPF_K ||
13965 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13966 				     && insn->off != 0) ||
13967 				    (insn->src_reg != BPF_REG_0 &&
13968 				     insn->src_reg != BPF_PSEUDO_CALL &&
13969 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13970 				    insn->dst_reg != BPF_REG_0 ||
13971 				    class == BPF_JMP32) {
13972 					verbose(env, "BPF_CALL uses reserved fields\n");
13973 					return -EINVAL;
13974 				}
13975 
13976 				if (env->cur_state->active_lock.ptr) {
13977 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13978 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
13979 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13980 					     (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13981 						verbose(env, "function calls are not allowed while holding a lock\n");
13982 						return -EINVAL;
13983 					}
13984 				}
13985 				if (insn->src_reg == BPF_PSEUDO_CALL)
13986 					err = check_func_call(env, insn, &env->insn_idx);
13987 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13988 					err = check_kfunc_call(env, insn, &env->insn_idx);
13989 				else
13990 					err = check_helper_call(env, insn, &env->insn_idx);
13991 				if (err)
13992 					return err;
13993 			} else if (opcode == BPF_JA) {
13994 				if (BPF_SRC(insn->code) != BPF_K ||
13995 				    insn->imm != 0 ||
13996 				    insn->src_reg != BPF_REG_0 ||
13997 				    insn->dst_reg != BPF_REG_0 ||
13998 				    class == BPF_JMP32) {
13999 					verbose(env, "BPF_JA uses reserved fields\n");
14000 					return -EINVAL;
14001 				}
14002 
14003 				env->insn_idx += insn->off + 1;
14004 				continue;
14005 
14006 			} else if (opcode == BPF_EXIT) {
14007 				if (BPF_SRC(insn->code) != BPF_K ||
14008 				    insn->imm != 0 ||
14009 				    insn->src_reg != BPF_REG_0 ||
14010 				    insn->dst_reg != BPF_REG_0 ||
14011 				    class == BPF_JMP32) {
14012 					verbose(env, "BPF_EXIT uses reserved fields\n");
14013 					return -EINVAL;
14014 				}
14015 
14016 				if (env->cur_state->active_lock.ptr) {
14017 					verbose(env, "bpf_spin_unlock is missing\n");
14018 					return -EINVAL;
14019 				}
14020 
14021 				if (env->cur_state->active_rcu_lock) {
14022 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14023 					return -EINVAL;
14024 				}
14025 
14026 				/* We must do check_reference_leak here before
14027 				 * prepare_func_exit to handle the case when
14028 				 * state->curframe > 0, it may be a callback
14029 				 * function, for which reference_state must
14030 				 * match caller reference state when it exits.
14031 				 */
14032 				err = check_reference_leak(env);
14033 				if (err)
14034 					return err;
14035 
14036 				if (state->curframe) {
14037 					/* exit from nested function */
14038 					err = prepare_func_exit(env, &env->insn_idx);
14039 					if (err)
14040 						return err;
14041 					do_print_state = true;
14042 					continue;
14043 				}
14044 
14045 				err = check_return_code(env);
14046 				if (err)
14047 					return err;
14048 process_bpf_exit:
14049 				mark_verifier_state_scratched(env);
14050 				update_branch_counts(env, env->cur_state);
14051 				err = pop_stack(env, &prev_insn_idx,
14052 						&env->insn_idx, pop_log);
14053 				if (err < 0) {
14054 					if (err != -ENOENT)
14055 						return err;
14056 					break;
14057 				} else {
14058 					do_print_state = true;
14059 					continue;
14060 				}
14061 			} else {
14062 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14063 				if (err)
14064 					return err;
14065 			}
14066 		} else if (class == BPF_LD) {
14067 			u8 mode = BPF_MODE(insn->code);
14068 
14069 			if (mode == BPF_ABS || mode == BPF_IND) {
14070 				err = check_ld_abs(env, insn);
14071 				if (err)
14072 					return err;
14073 
14074 			} else if (mode == BPF_IMM) {
14075 				err = check_ld_imm(env, insn);
14076 				if (err)
14077 					return err;
14078 
14079 				env->insn_idx++;
14080 				sanitize_mark_insn_seen(env);
14081 			} else {
14082 				verbose(env, "invalid BPF_LD mode\n");
14083 				return -EINVAL;
14084 			}
14085 		} else {
14086 			verbose(env, "unknown insn class %d\n", class);
14087 			return -EINVAL;
14088 		}
14089 
14090 		env->insn_idx++;
14091 	}
14092 
14093 	return 0;
14094 }
14095 
14096 static int find_btf_percpu_datasec(struct btf *btf)
14097 {
14098 	const struct btf_type *t;
14099 	const char *tname;
14100 	int i, n;
14101 
14102 	/*
14103 	 * Both vmlinux and module each have their own ".data..percpu"
14104 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14105 	 * types to look at only module's own BTF types.
14106 	 */
14107 	n = btf_nr_types(btf);
14108 	if (btf_is_module(btf))
14109 		i = btf_nr_types(btf_vmlinux);
14110 	else
14111 		i = 1;
14112 
14113 	for(; i < n; i++) {
14114 		t = btf_type_by_id(btf, i);
14115 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14116 			continue;
14117 
14118 		tname = btf_name_by_offset(btf, t->name_off);
14119 		if (!strcmp(tname, ".data..percpu"))
14120 			return i;
14121 	}
14122 
14123 	return -ENOENT;
14124 }
14125 
14126 /* replace pseudo btf_id with kernel symbol address */
14127 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14128 			       struct bpf_insn *insn,
14129 			       struct bpf_insn_aux_data *aux)
14130 {
14131 	const struct btf_var_secinfo *vsi;
14132 	const struct btf_type *datasec;
14133 	struct btf_mod_pair *btf_mod;
14134 	const struct btf_type *t;
14135 	const char *sym_name;
14136 	bool percpu = false;
14137 	u32 type, id = insn->imm;
14138 	struct btf *btf;
14139 	s32 datasec_id;
14140 	u64 addr;
14141 	int i, btf_fd, err;
14142 
14143 	btf_fd = insn[1].imm;
14144 	if (btf_fd) {
14145 		btf = btf_get_by_fd(btf_fd);
14146 		if (IS_ERR(btf)) {
14147 			verbose(env, "invalid module BTF object FD specified.\n");
14148 			return -EINVAL;
14149 		}
14150 	} else {
14151 		if (!btf_vmlinux) {
14152 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14153 			return -EINVAL;
14154 		}
14155 		btf = btf_vmlinux;
14156 		btf_get(btf);
14157 	}
14158 
14159 	t = btf_type_by_id(btf, id);
14160 	if (!t) {
14161 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14162 		err = -ENOENT;
14163 		goto err_put;
14164 	}
14165 
14166 	if (!btf_type_is_var(t)) {
14167 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14168 		err = -EINVAL;
14169 		goto err_put;
14170 	}
14171 
14172 	sym_name = btf_name_by_offset(btf, t->name_off);
14173 	addr = kallsyms_lookup_name(sym_name);
14174 	if (!addr) {
14175 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14176 			sym_name);
14177 		err = -ENOENT;
14178 		goto err_put;
14179 	}
14180 
14181 	datasec_id = find_btf_percpu_datasec(btf);
14182 	if (datasec_id > 0) {
14183 		datasec = btf_type_by_id(btf, datasec_id);
14184 		for_each_vsi(i, datasec, vsi) {
14185 			if (vsi->type == id) {
14186 				percpu = true;
14187 				break;
14188 			}
14189 		}
14190 	}
14191 
14192 	insn[0].imm = (u32)addr;
14193 	insn[1].imm = addr >> 32;
14194 
14195 	type = t->type;
14196 	t = btf_type_skip_modifiers(btf, type, NULL);
14197 	if (percpu) {
14198 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14199 		aux->btf_var.btf = btf;
14200 		aux->btf_var.btf_id = type;
14201 	} else if (!btf_type_is_struct(t)) {
14202 		const struct btf_type *ret;
14203 		const char *tname;
14204 		u32 tsize;
14205 
14206 		/* resolve the type size of ksym. */
14207 		ret = btf_resolve_size(btf, t, &tsize);
14208 		if (IS_ERR(ret)) {
14209 			tname = btf_name_by_offset(btf, t->name_off);
14210 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14211 				tname, PTR_ERR(ret));
14212 			err = -EINVAL;
14213 			goto err_put;
14214 		}
14215 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14216 		aux->btf_var.mem_size = tsize;
14217 	} else {
14218 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14219 		aux->btf_var.btf = btf;
14220 		aux->btf_var.btf_id = type;
14221 	}
14222 
14223 	/* check whether we recorded this BTF (and maybe module) already */
14224 	for (i = 0; i < env->used_btf_cnt; i++) {
14225 		if (env->used_btfs[i].btf == btf) {
14226 			btf_put(btf);
14227 			return 0;
14228 		}
14229 	}
14230 
14231 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14232 		err = -E2BIG;
14233 		goto err_put;
14234 	}
14235 
14236 	btf_mod = &env->used_btfs[env->used_btf_cnt];
14237 	btf_mod->btf = btf;
14238 	btf_mod->module = NULL;
14239 
14240 	/* if we reference variables from kernel module, bump its refcount */
14241 	if (btf_is_module(btf)) {
14242 		btf_mod->module = btf_try_get_module(btf);
14243 		if (!btf_mod->module) {
14244 			err = -ENXIO;
14245 			goto err_put;
14246 		}
14247 	}
14248 
14249 	env->used_btf_cnt++;
14250 
14251 	return 0;
14252 err_put:
14253 	btf_put(btf);
14254 	return err;
14255 }
14256 
14257 static bool is_tracing_prog_type(enum bpf_prog_type type)
14258 {
14259 	switch (type) {
14260 	case BPF_PROG_TYPE_KPROBE:
14261 	case BPF_PROG_TYPE_TRACEPOINT:
14262 	case BPF_PROG_TYPE_PERF_EVENT:
14263 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14264 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14265 		return true;
14266 	default:
14267 		return false;
14268 	}
14269 }
14270 
14271 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14272 					struct bpf_map *map,
14273 					struct bpf_prog *prog)
14274 
14275 {
14276 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14277 
14278 	if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14279 		if (is_tracing_prog_type(prog_type)) {
14280 			verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14281 			return -EINVAL;
14282 		}
14283 	}
14284 
14285 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14286 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14287 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14288 			return -EINVAL;
14289 		}
14290 
14291 		if (is_tracing_prog_type(prog_type)) {
14292 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14293 			return -EINVAL;
14294 		}
14295 
14296 		if (prog->aux->sleepable) {
14297 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14298 			return -EINVAL;
14299 		}
14300 	}
14301 
14302 	if (btf_record_has_field(map->record, BPF_TIMER)) {
14303 		if (is_tracing_prog_type(prog_type)) {
14304 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
14305 			return -EINVAL;
14306 		}
14307 	}
14308 
14309 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
14310 	    !bpf_offload_prog_map_match(prog, map)) {
14311 		verbose(env, "offload device mismatch between prog and map\n");
14312 		return -EINVAL;
14313 	}
14314 
14315 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14316 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14317 		return -EINVAL;
14318 	}
14319 
14320 	if (prog->aux->sleepable)
14321 		switch (map->map_type) {
14322 		case BPF_MAP_TYPE_HASH:
14323 		case BPF_MAP_TYPE_LRU_HASH:
14324 		case BPF_MAP_TYPE_ARRAY:
14325 		case BPF_MAP_TYPE_PERCPU_HASH:
14326 		case BPF_MAP_TYPE_PERCPU_ARRAY:
14327 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14328 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14329 		case BPF_MAP_TYPE_HASH_OF_MAPS:
14330 		case BPF_MAP_TYPE_RINGBUF:
14331 		case BPF_MAP_TYPE_USER_RINGBUF:
14332 		case BPF_MAP_TYPE_INODE_STORAGE:
14333 		case BPF_MAP_TYPE_SK_STORAGE:
14334 		case BPF_MAP_TYPE_TASK_STORAGE:
14335 		case BPF_MAP_TYPE_CGRP_STORAGE:
14336 			break;
14337 		default:
14338 			verbose(env,
14339 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14340 			return -EINVAL;
14341 		}
14342 
14343 	return 0;
14344 }
14345 
14346 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14347 {
14348 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14349 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14350 }
14351 
14352 /* find and rewrite pseudo imm in ld_imm64 instructions:
14353  *
14354  * 1. if it accesses map FD, replace it with actual map pointer.
14355  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14356  *
14357  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14358  */
14359 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14360 {
14361 	struct bpf_insn *insn = env->prog->insnsi;
14362 	int insn_cnt = env->prog->len;
14363 	int i, j, err;
14364 
14365 	err = bpf_prog_calc_tag(env->prog);
14366 	if (err)
14367 		return err;
14368 
14369 	for (i = 0; i < insn_cnt; i++, insn++) {
14370 		if (BPF_CLASS(insn->code) == BPF_LDX &&
14371 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14372 			verbose(env, "BPF_LDX uses reserved fields\n");
14373 			return -EINVAL;
14374 		}
14375 
14376 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14377 			struct bpf_insn_aux_data *aux;
14378 			struct bpf_map *map;
14379 			struct fd f;
14380 			u64 addr;
14381 			u32 fd;
14382 
14383 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
14384 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14385 			    insn[1].off != 0) {
14386 				verbose(env, "invalid bpf_ld_imm64 insn\n");
14387 				return -EINVAL;
14388 			}
14389 
14390 			if (insn[0].src_reg == 0)
14391 				/* valid generic load 64-bit imm */
14392 				goto next_insn;
14393 
14394 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14395 				aux = &env->insn_aux_data[i];
14396 				err = check_pseudo_btf_id(env, insn, aux);
14397 				if (err)
14398 					return err;
14399 				goto next_insn;
14400 			}
14401 
14402 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14403 				aux = &env->insn_aux_data[i];
14404 				aux->ptr_type = PTR_TO_FUNC;
14405 				goto next_insn;
14406 			}
14407 
14408 			/* In final convert_pseudo_ld_imm64() step, this is
14409 			 * converted into regular 64-bit imm load insn.
14410 			 */
14411 			switch (insn[0].src_reg) {
14412 			case BPF_PSEUDO_MAP_VALUE:
14413 			case BPF_PSEUDO_MAP_IDX_VALUE:
14414 				break;
14415 			case BPF_PSEUDO_MAP_FD:
14416 			case BPF_PSEUDO_MAP_IDX:
14417 				if (insn[1].imm == 0)
14418 					break;
14419 				fallthrough;
14420 			default:
14421 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14422 				return -EINVAL;
14423 			}
14424 
14425 			switch (insn[0].src_reg) {
14426 			case BPF_PSEUDO_MAP_IDX_VALUE:
14427 			case BPF_PSEUDO_MAP_IDX:
14428 				if (bpfptr_is_null(env->fd_array)) {
14429 					verbose(env, "fd_idx without fd_array is invalid\n");
14430 					return -EPROTO;
14431 				}
14432 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
14433 							    insn[0].imm * sizeof(fd),
14434 							    sizeof(fd)))
14435 					return -EFAULT;
14436 				break;
14437 			default:
14438 				fd = insn[0].imm;
14439 				break;
14440 			}
14441 
14442 			f = fdget(fd);
14443 			map = __bpf_map_get(f);
14444 			if (IS_ERR(map)) {
14445 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
14446 					insn[0].imm);
14447 				return PTR_ERR(map);
14448 			}
14449 
14450 			err = check_map_prog_compatibility(env, map, env->prog);
14451 			if (err) {
14452 				fdput(f);
14453 				return err;
14454 			}
14455 
14456 			aux = &env->insn_aux_data[i];
14457 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14458 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14459 				addr = (unsigned long)map;
14460 			} else {
14461 				u32 off = insn[1].imm;
14462 
14463 				if (off >= BPF_MAX_VAR_OFF) {
14464 					verbose(env, "direct value offset of %u is not allowed\n", off);
14465 					fdput(f);
14466 					return -EINVAL;
14467 				}
14468 
14469 				if (!map->ops->map_direct_value_addr) {
14470 					verbose(env, "no direct value access support for this map type\n");
14471 					fdput(f);
14472 					return -EINVAL;
14473 				}
14474 
14475 				err = map->ops->map_direct_value_addr(map, &addr, off);
14476 				if (err) {
14477 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14478 						map->value_size, off);
14479 					fdput(f);
14480 					return err;
14481 				}
14482 
14483 				aux->map_off = off;
14484 				addr += off;
14485 			}
14486 
14487 			insn[0].imm = (u32)addr;
14488 			insn[1].imm = addr >> 32;
14489 
14490 			/* check whether we recorded this map already */
14491 			for (j = 0; j < env->used_map_cnt; j++) {
14492 				if (env->used_maps[j] == map) {
14493 					aux->map_index = j;
14494 					fdput(f);
14495 					goto next_insn;
14496 				}
14497 			}
14498 
14499 			if (env->used_map_cnt >= MAX_USED_MAPS) {
14500 				fdput(f);
14501 				return -E2BIG;
14502 			}
14503 
14504 			/* hold the map. If the program is rejected by verifier,
14505 			 * the map will be released by release_maps() or it
14506 			 * will be used by the valid program until it's unloaded
14507 			 * and all maps are released in free_used_maps()
14508 			 */
14509 			bpf_map_inc(map);
14510 
14511 			aux->map_index = env->used_map_cnt;
14512 			env->used_maps[env->used_map_cnt++] = map;
14513 
14514 			if (bpf_map_is_cgroup_storage(map) &&
14515 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
14516 				verbose(env, "only one cgroup storage of each type is allowed\n");
14517 				fdput(f);
14518 				return -EBUSY;
14519 			}
14520 
14521 			fdput(f);
14522 next_insn:
14523 			insn++;
14524 			i++;
14525 			continue;
14526 		}
14527 
14528 		/* Basic sanity check before we invest more work here. */
14529 		if (!bpf_opcode_in_insntable(insn->code)) {
14530 			verbose(env, "unknown opcode %02x\n", insn->code);
14531 			return -EINVAL;
14532 		}
14533 	}
14534 
14535 	/* now all pseudo BPF_LD_IMM64 instructions load valid
14536 	 * 'struct bpf_map *' into a register instead of user map_fd.
14537 	 * These pointers will be used later by verifier to validate map access.
14538 	 */
14539 	return 0;
14540 }
14541 
14542 /* drop refcnt of maps used by the rejected program */
14543 static void release_maps(struct bpf_verifier_env *env)
14544 {
14545 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
14546 			     env->used_map_cnt);
14547 }
14548 
14549 /* drop refcnt of maps used by the rejected program */
14550 static void release_btfs(struct bpf_verifier_env *env)
14551 {
14552 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14553 			     env->used_btf_cnt);
14554 }
14555 
14556 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14557 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14558 {
14559 	struct bpf_insn *insn = env->prog->insnsi;
14560 	int insn_cnt = env->prog->len;
14561 	int i;
14562 
14563 	for (i = 0; i < insn_cnt; i++, insn++) {
14564 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14565 			continue;
14566 		if (insn->src_reg == BPF_PSEUDO_FUNC)
14567 			continue;
14568 		insn->src_reg = 0;
14569 	}
14570 }
14571 
14572 /* single env->prog->insni[off] instruction was replaced with the range
14573  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14574  * [0, off) and [off, end) to new locations, so the patched range stays zero
14575  */
14576 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14577 				 struct bpf_insn_aux_data *new_data,
14578 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
14579 {
14580 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14581 	struct bpf_insn *insn = new_prog->insnsi;
14582 	u32 old_seen = old_data[off].seen;
14583 	u32 prog_len;
14584 	int i;
14585 
14586 	/* aux info at OFF always needs adjustment, no matter fast path
14587 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14588 	 * original insn at old prog.
14589 	 */
14590 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14591 
14592 	if (cnt == 1)
14593 		return;
14594 	prog_len = new_prog->len;
14595 
14596 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14597 	memcpy(new_data + off + cnt - 1, old_data + off,
14598 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14599 	for (i = off; i < off + cnt - 1; i++) {
14600 		/* Expand insni[off]'s seen count to the patched range. */
14601 		new_data[i].seen = old_seen;
14602 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
14603 	}
14604 	env->insn_aux_data = new_data;
14605 	vfree(old_data);
14606 }
14607 
14608 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14609 {
14610 	int i;
14611 
14612 	if (len == 1)
14613 		return;
14614 	/* NOTE: fake 'exit' subprog should be updated as well. */
14615 	for (i = 0; i <= env->subprog_cnt; i++) {
14616 		if (env->subprog_info[i].start <= off)
14617 			continue;
14618 		env->subprog_info[i].start += len - 1;
14619 	}
14620 }
14621 
14622 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14623 {
14624 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14625 	int i, sz = prog->aux->size_poke_tab;
14626 	struct bpf_jit_poke_descriptor *desc;
14627 
14628 	for (i = 0; i < sz; i++) {
14629 		desc = &tab[i];
14630 		if (desc->insn_idx <= off)
14631 			continue;
14632 		desc->insn_idx += len - 1;
14633 	}
14634 }
14635 
14636 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14637 					    const struct bpf_insn *patch, u32 len)
14638 {
14639 	struct bpf_prog *new_prog;
14640 	struct bpf_insn_aux_data *new_data = NULL;
14641 
14642 	if (len > 1) {
14643 		new_data = vzalloc(array_size(env->prog->len + len - 1,
14644 					      sizeof(struct bpf_insn_aux_data)));
14645 		if (!new_data)
14646 			return NULL;
14647 	}
14648 
14649 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14650 	if (IS_ERR(new_prog)) {
14651 		if (PTR_ERR(new_prog) == -ERANGE)
14652 			verbose(env,
14653 				"insn %d cannot be patched due to 16-bit range\n",
14654 				env->insn_aux_data[off].orig_idx);
14655 		vfree(new_data);
14656 		return NULL;
14657 	}
14658 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
14659 	adjust_subprog_starts(env, off, len);
14660 	adjust_poke_descs(new_prog, off, len);
14661 	return new_prog;
14662 }
14663 
14664 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14665 					      u32 off, u32 cnt)
14666 {
14667 	int i, j;
14668 
14669 	/* find first prog starting at or after off (first to remove) */
14670 	for (i = 0; i < env->subprog_cnt; i++)
14671 		if (env->subprog_info[i].start >= off)
14672 			break;
14673 	/* find first prog starting at or after off + cnt (first to stay) */
14674 	for (j = i; j < env->subprog_cnt; j++)
14675 		if (env->subprog_info[j].start >= off + cnt)
14676 			break;
14677 	/* if j doesn't start exactly at off + cnt, we are just removing
14678 	 * the front of previous prog
14679 	 */
14680 	if (env->subprog_info[j].start != off + cnt)
14681 		j--;
14682 
14683 	if (j > i) {
14684 		struct bpf_prog_aux *aux = env->prog->aux;
14685 		int move;
14686 
14687 		/* move fake 'exit' subprog as well */
14688 		move = env->subprog_cnt + 1 - j;
14689 
14690 		memmove(env->subprog_info + i,
14691 			env->subprog_info + j,
14692 			sizeof(*env->subprog_info) * move);
14693 		env->subprog_cnt -= j - i;
14694 
14695 		/* remove func_info */
14696 		if (aux->func_info) {
14697 			move = aux->func_info_cnt - j;
14698 
14699 			memmove(aux->func_info + i,
14700 				aux->func_info + j,
14701 				sizeof(*aux->func_info) * move);
14702 			aux->func_info_cnt -= j - i;
14703 			/* func_info->insn_off is set after all code rewrites,
14704 			 * in adjust_btf_func() - no need to adjust
14705 			 */
14706 		}
14707 	} else {
14708 		/* convert i from "first prog to remove" to "first to adjust" */
14709 		if (env->subprog_info[i].start == off)
14710 			i++;
14711 	}
14712 
14713 	/* update fake 'exit' subprog as well */
14714 	for (; i <= env->subprog_cnt; i++)
14715 		env->subprog_info[i].start -= cnt;
14716 
14717 	return 0;
14718 }
14719 
14720 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14721 				      u32 cnt)
14722 {
14723 	struct bpf_prog *prog = env->prog;
14724 	u32 i, l_off, l_cnt, nr_linfo;
14725 	struct bpf_line_info *linfo;
14726 
14727 	nr_linfo = prog->aux->nr_linfo;
14728 	if (!nr_linfo)
14729 		return 0;
14730 
14731 	linfo = prog->aux->linfo;
14732 
14733 	/* find first line info to remove, count lines to be removed */
14734 	for (i = 0; i < nr_linfo; i++)
14735 		if (linfo[i].insn_off >= off)
14736 			break;
14737 
14738 	l_off = i;
14739 	l_cnt = 0;
14740 	for (; i < nr_linfo; i++)
14741 		if (linfo[i].insn_off < off + cnt)
14742 			l_cnt++;
14743 		else
14744 			break;
14745 
14746 	/* First live insn doesn't match first live linfo, it needs to "inherit"
14747 	 * last removed linfo.  prog is already modified, so prog->len == off
14748 	 * means no live instructions after (tail of the program was removed).
14749 	 */
14750 	if (prog->len != off && l_cnt &&
14751 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14752 		l_cnt--;
14753 		linfo[--i].insn_off = off + cnt;
14754 	}
14755 
14756 	/* remove the line info which refer to the removed instructions */
14757 	if (l_cnt) {
14758 		memmove(linfo + l_off, linfo + i,
14759 			sizeof(*linfo) * (nr_linfo - i));
14760 
14761 		prog->aux->nr_linfo -= l_cnt;
14762 		nr_linfo = prog->aux->nr_linfo;
14763 	}
14764 
14765 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
14766 	for (i = l_off; i < nr_linfo; i++)
14767 		linfo[i].insn_off -= cnt;
14768 
14769 	/* fix up all subprogs (incl. 'exit') which start >= off */
14770 	for (i = 0; i <= env->subprog_cnt; i++)
14771 		if (env->subprog_info[i].linfo_idx > l_off) {
14772 			/* program may have started in the removed region but
14773 			 * may not be fully removed
14774 			 */
14775 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14776 				env->subprog_info[i].linfo_idx -= l_cnt;
14777 			else
14778 				env->subprog_info[i].linfo_idx = l_off;
14779 		}
14780 
14781 	return 0;
14782 }
14783 
14784 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14785 {
14786 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14787 	unsigned int orig_prog_len = env->prog->len;
14788 	int err;
14789 
14790 	if (bpf_prog_is_dev_bound(env->prog->aux))
14791 		bpf_prog_offload_remove_insns(env, off, cnt);
14792 
14793 	err = bpf_remove_insns(env->prog, off, cnt);
14794 	if (err)
14795 		return err;
14796 
14797 	err = adjust_subprog_starts_after_remove(env, off, cnt);
14798 	if (err)
14799 		return err;
14800 
14801 	err = bpf_adj_linfo_after_remove(env, off, cnt);
14802 	if (err)
14803 		return err;
14804 
14805 	memmove(aux_data + off,	aux_data + off + cnt,
14806 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
14807 
14808 	return 0;
14809 }
14810 
14811 /* The verifier does more data flow analysis than llvm and will not
14812  * explore branches that are dead at run time. Malicious programs can
14813  * have dead code too. Therefore replace all dead at-run-time code
14814  * with 'ja -1'.
14815  *
14816  * Just nops are not optimal, e.g. if they would sit at the end of the
14817  * program and through another bug we would manage to jump there, then
14818  * we'd execute beyond program memory otherwise. Returning exception
14819  * code also wouldn't work since we can have subprogs where the dead
14820  * code could be located.
14821  */
14822 static void sanitize_dead_code(struct bpf_verifier_env *env)
14823 {
14824 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14825 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14826 	struct bpf_insn *insn = env->prog->insnsi;
14827 	const int insn_cnt = env->prog->len;
14828 	int i;
14829 
14830 	for (i = 0; i < insn_cnt; i++) {
14831 		if (aux_data[i].seen)
14832 			continue;
14833 		memcpy(insn + i, &trap, sizeof(trap));
14834 		aux_data[i].zext_dst = false;
14835 	}
14836 }
14837 
14838 static bool insn_is_cond_jump(u8 code)
14839 {
14840 	u8 op;
14841 
14842 	if (BPF_CLASS(code) == BPF_JMP32)
14843 		return true;
14844 
14845 	if (BPF_CLASS(code) != BPF_JMP)
14846 		return false;
14847 
14848 	op = BPF_OP(code);
14849 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14850 }
14851 
14852 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14853 {
14854 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14855 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14856 	struct bpf_insn *insn = env->prog->insnsi;
14857 	const int insn_cnt = env->prog->len;
14858 	int i;
14859 
14860 	for (i = 0; i < insn_cnt; i++, insn++) {
14861 		if (!insn_is_cond_jump(insn->code))
14862 			continue;
14863 
14864 		if (!aux_data[i + 1].seen)
14865 			ja.off = insn->off;
14866 		else if (!aux_data[i + 1 + insn->off].seen)
14867 			ja.off = 0;
14868 		else
14869 			continue;
14870 
14871 		if (bpf_prog_is_dev_bound(env->prog->aux))
14872 			bpf_prog_offload_replace_insn(env, i, &ja);
14873 
14874 		memcpy(insn, &ja, sizeof(ja));
14875 	}
14876 }
14877 
14878 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14879 {
14880 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14881 	int insn_cnt = env->prog->len;
14882 	int i, err;
14883 
14884 	for (i = 0; i < insn_cnt; i++) {
14885 		int j;
14886 
14887 		j = 0;
14888 		while (i + j < insn_cnt && !aux_data[i + j].seen)
14889 			j++;
14890 		if (!j)
14891 			continue;
14892 
14893 		err = verifier_remove_insns(env, i, j);
14894 		if (err)
14895 			return err;
14896 		insn_cnt = env->prog->len;
14897 	}
14898 
14899 	return 0;
14900 }
14901 
14902 static int opt_remove_nops(struct bpf_verifier_env *env)
14903 {
14904 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14905 	struct bpf_insn *insn = env->prog->insnsi;
14906 	int insn_cnt = env->prog->len;
14907 	int i, err;
14908 
14909 	for (i = 0; i < insn_cnt; i++) {
14910 		if (memcmp(&insn[i], &ja, sizeof(ja)))
14911 			continue;
14912 
14913 		err = verifier_remove_insns(env, i, 1);
14914 		if (err)
14915 			return err;
14916 		insn_cnt--;
14917 		i--;
14918 	}
14919 
14920 	return 0;
14921 }
14922 
14923 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14924 					 const union bpf_attr *attr)
14925 {
14926 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14927 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
14928 	int i, patch_len, delta = 0, len = env->prog->len;
14929 	struct bpf_insn *insns = env->prog->insnsi;
14930 	struct bpf_prog *new_prog;
14931 	bool rnd_hi32;
14932 
14933 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14934 	zext_patch[1] = BPF_ZEXT_REG(0);
14935 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14936 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14937 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14938 	for (i = 0; i < len; i++) {
14939 		int adj_idx = i + delta;
14940 		struct bpf_insn insn;
14941 		int load_reg;
14942 
14943 		insn = insns[adj_idx];
14944 		load_reg = insn_def_regno(&insn);
14945 		if (!aux[adj_idx].zext_dst) {
14946 			u8 code, class;
14947 			u32 imm_rnd;
14948 
14949 			if (!rnd_hi32)
14950 				continue;
14951 
14952 			code = insn.code;
14953 			class = BPF_CLASS(code);
14954 			if (load_reg == -1)
14955 				continue;
14956 
14957 			/* NOTE: arg "reg" (the fourth one) is only used for
14958 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
14959 			 *       here.
14960 			 */
14961 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14962 				if (class == BPF_LD &&
14963 				    BPF_MODE(code) == BPF_IMM)
14964 					i++;
14965 				continue;
14966 			}
14967 
14968 			/* ctx load could be transformed into wider load. */
14969 			if (class == BPF_LDX &&
14970 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
14971 				continue;
14972 
14973 			imm_rnd = get_random_u32();
14974 			rnd_hi32_patch[0] = insn;
14975 			rnd_hi32_patch[1].imm = imm_rnd;
14976 			rnd_hi32_patch[3].dst_reg = load_reg;
14977 			patch = rnd_hi32_patch;
14978 			patch_len = 4;
14979 			goto apply_patch_buffer;
14980 		}
14981 
14982 		/* Add in an zero-extend instruction if a) the JIT has requested
14983 		 * it or b) it's a CMPXCHG.
14984 		 *
14985 		 * The latter is because: BPF_CMPXCHG always loads a value into
14986 		 * R0, therefore always zero-extends. However some archs'
14987 		 * equivalent instruction only does this load when the
14988 		 * comparison is successful. This detail of CMPXCHG is
14989 		 * orthogonal to the general zero-extension behaviour of the
14990 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
14991 		 */
14992 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14993 			continue;
14994 
14995 		/* Zero-extension is done by the caller. */
14996 		if (bpf_pseudo_kfunc_call(&insn))
14997 			continue;
14998 
14999 		if (WARN_ON(load_reg == -1)) {
15000 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15001 			return -EFAULT;
15002 		}
15003 
15004 		zext_patch[0] = insn;
15005 		zext_patch[1].dst_reg = load_reg;
15006 		zext_patch[1].src_reg = load_reg;
15007 		patch = zext_patch;
15008 		patch_len = 2;
15009 apply_patch_buffer:
15010 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15011 		if (!new_prog)
15012 			return -ENOMEM;
15013 		env->prog = new_prog;
15014 		insns = new_prog->insnsi;
15015 		aux = env->insn_aux_data;
15016 		delta += patch_len - 1;
15017 	}
15018 
15019 	return 0;
15020 }
15021 
15022 /* convert load instructions that access fields of a context type into a
15023  * sequence of instructions that access fields of the underlying structure:
15024  *     struct __sk_buff    -> struct sk_buff
15025  *     struct bpf_sock_ops -> struct sock
15026  */
15027 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15028 {
15029 	const struct bpf_verifier_ops *ops = env->ops;
15030 	int i, cnt, size, ctx_field_size, delta = 0;
15031 	const int insn_cnt = env->prog->len;
15032 	struct bpf_insn insn_buf[16], *insn;
15033 	u32 target_size, size_default, off;
15034 	struct bpf_prog *new_prog;
15035 	enum bpf_access_type type;
15036 	bool is_narrower_load;
15037 
15038 	if (ops->gen_prologue || env->seen_direct_write) {
15039 		if (!ops->gen_prologue) {
15040 			verbose(env, "bpf verifier is misconfigured\n");
15041 			return -EINVAL;
15042 		}
15043 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15044 					env->prog);
15045 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15046 			verbose(env, "bpf verifier is misconfigured\n");
15047 			return -EINVAL;
15048 		} else if (cnt) {
15049 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15050 			if (!new_prog)
15051 				return -ENOMEM;
15052 
15053 			env->prog = new_prog;
15054 			delta += cnt - 1;
15055 		}
15056 	}
15057 
15058 	if (bpf_prog_is_dev_bound(env->prog->aux))
15059 		return 0;
15060 
15061 	insn = env->prog->insnsi + delta;
15062 
15063 	for (i = 0; i < insn_cnt; i++, insn++) {
15064 		bpf_convert_ctx_access_t convert_ctx_access;
15065 		bool ctx_access;
15066 
15067 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15068 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15069 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15070 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15071 			type = BPF_READ;
15072 			ctx_access = true;
15073 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15074 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15075 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15076 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15077 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15078 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15079 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15080 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15081 			type = BPF_WRITE;
15082 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15083 		} else {
15084 			continue;
15085 		}
15086 
15087 		if (type == BPF_WRITE &&
15088 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15089 			struct bpf_insn patch[] = {
15090 				*insn,
15091 				BPF_ST_NOSPEC(),
15092 			};
15093 
15094 			cnt = ARRAY_SIZE(patch);
15095 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15096 			if (!new_prog)
15097 				return -ENOMEM;
15098 
15099 			delta    += cnt - 1;
15100 			env->prog = new_prog;
15101 			insn      = new_prog->insnsi + i + delta;
15102 			continue;
15103 		}
15104 
15105 		if (!ctx_access)
15106 			continue;
15107 
15108 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15109 		case PTR_TO_CTX:
15110 			if (!ops->convert_ctx_access)
15111 				continue;
15112 			convert_ctx_access = ops->convert_ctx_access;
15113 			break;
15114 		case PTR_TO_SOCKET:
15115 		case PTR_TO_SOCK_COMMON:
15116 			convert_ctx_access = bpf_sock_convert_ctx_access;
15117 			break;
15118 		case PTR_TO_TCP_SOCK:
15119 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15120 			break;
15121 		case PTR_TO_XDP_SOCK:
15122 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15123 			break;
15124 		case PTR_TO_BTF_ID:
15125 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15126 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15127 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15128 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15129 		 * any faults for loads into such types. BPF_WRITE is disallowed
15130 		 * for this case.
15131 		 */
15132 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15133 			if (type == BPF_READ) {
15134 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15135 					BPF_SIZE((insn)->code);
15136 				env->prog->aux->num_exentries++;
15137 			}
15138 			continue;
15139 		default:
15140 			continue;
15141 		}
15142 
15143 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15144 		size = BPF_LDST_BYTES(insn);
15145 
15146 		/* If the read access is a narrower load of the field,
15147 		 * convert to a 4/8-byte load, to minimum program type specific
15148 		 * convert_ctx_access changes. If conversion is successful,
15149 		 * we will apply proper mask to the result.
15150 		 */
15151 		is_narrower_load = size < ctx_field_size;
15152 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15153 		off = insn->off;
15154 		if (is_narrower_load) {
15155 			u8 size_code;
15156 
15157 			if (type == BPF_WRITE) {
15158 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15159 				return -EINVAL;
15160 			}
15161 
15162 			size_code = BPF_H;
15163 			if (ctx_field_size == 4)
15164 				size_code = BPF_W;
15165 			else if (ctx_field_size == 8)
15166 				size_code = BPF_DW;
15167 
15168 			insn->off = off & ~(size_default - 1);
15169 			insn->code = BPF_LDX | BPF_MEM | size_code;
15170 		}
15171 
15172 		target_size = 0;
15173 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15174 					 &target_size);
15175 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15176 		    (ctx_field_size && !target_size)) {
15177 			verbose(env, "bpf verifier is misconfigured\n");
15178 			return -EINVAL;
15179 		}
15180 
15181 		if (is_narrower_load && size < target_size) {
15182 			u8 shift = bpf_ctx_narrow_access_offset(
15183 				off, size, size_default) * 8;
15184 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15185 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15186 				return -EINVAL;
15187 			}
15188 			if (ctx_field_size <= 4) {
15189 				if (shift)
15190 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15191 									insn->dst_reg,
15192 									shift);
15193 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15194 								(1 << size * 8) - 1);
15195 			} else {
15196 				if (shift)
15197 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15198 									insn->dst_reg,
15199 									shift);
15200 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15201 								(1ULL << size * 8) - 1);
15202 			}
15203 		}
15204 
15205 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15206 		if (!new_prog)
15207 			return -ENOMEM;
15208 
15209 		delta += cnt - 1;
15210 
15211 		/* keep walking new program and skip insns we just inserted */
15212 		env->prog = new_prog;
15213 		insn      = new_prog->insnsi + i + delta;
15214 	}
15215 
15216 	return 0;
15217 }
15218 
15219 static int jit_subprogs(struct bpf_verifier_env *env)
15220 {
15221 	struct bpf_prog *prog = env->prog, **func, *tmp;
15222 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15223 	struct bpf_map *map_ptr;
15224 	struct bpf_insn *insn;
15225 	void *old_bpf_func;
15226 	int err, num_exentries;
15227 
15228 	if (env->subprog_cnt <= 1)
15229 		return 0;
15230 
15231 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15232 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15233 			continue;
15234 
15235 		/* Upon error here we cannot fall back to interpreter but
15236 		 * need a hard reject of the program. Thus -EFAULT is
15237 		 * propagated in any case.
15238 		 */
15239 		subprog = find_subprog(env, i + insn->imm + 1);
15240 		if (subprog < 0) {
15241 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15242 				  i + insn->imm + 1);
15243 			return -EFAULT;
15244 		}
15245 		/* temporarily remember subprog id inside insn instead of
15246 		 * aux_data, since next loop will split up all insns into funcs
15247 		 */
15248 		insn->off = subprog;
15249 		/* remember original imm in case JIT fails and fallback
15250 		 * to interpreter will be needed
15251 		 */
15252 		env->insn_aux_data[i].call_imm = insn->imm;
15253 		/* point imm to __bpf_call_base+1 from JITs point of view */
15254 		insn->imm = 1;
15255 		if (bpf_pseudo_func(insn))
15256 			/* jit (e.g. x86_64) may emit fewer instructions
15257 			 * if it learns a u32 imm is the same as a u64 imm.
15258 			 * Force a non zero here.
15259 			 */
15260 			insn[1].imm = 1;
15261 	}
15262 
15263 	err = bpf_prog_alloc_jited_linfo(prog);
15264 	if (err)
15265 		goto out_undo_insn;
15266 
15267 	err = -ENOMEM;
15268 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15269 	if (!func)
15270 		goto out_undo_insn;
15271 
15272 	for (i = 0; i < env->subprog_cnt; i++) {
15273 		subprog_start = subprog_end;
15274 		subprog_end = env->subprog_info[i + 1].start;
15275 
15276 		len = subprog_end - subprog_start;
15277 		/* bpf_prog_run() doesn't call subprogs directly,
15278 		 * hence main prog stats include the runtime of subprogs.
15279 		 * subprogs don't have IDs and not reachable via prog_get_next_id
15280 		 * func[i]->stats will never be accessed and stays NULL
15281 		 */
15282 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15283 		if (!func[i])
15284 			goto out_free;
15285 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15286 		       len * sizeof(struct bpf_insn));
15287 		func[i]->type = prog->type;
15288 		func[i]->len = len;
15289 		if (bpf_prog_calc_tag(func[i]))
15290 			goto out_free;
15291 		func[i]->is_func = 1;
15292 		func[i]->aux->func_idx = i;
15293 		/* Below members will be freed only at prog->aux */
15294 		func[i]->aux->btf = prog->aux->btf;
15295 		func[i]->aux->func_info = prog->aux->func_info;
15296 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15297 		func[i]->aux->poke_tab = prog->aux->poke_tab;
15298 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15299 
15300 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
15301 			struct bpf_jit_poke_descriptor *poke;
15302 
15303 			poke = &prog->aux->poke_tab[j];
15304 			if (poke->insn_idx < subprog_end &&
15305 			    poke->insn_idx >= subprog_start)
15306 				poke->aux = func[i]->aux;
15307 		}
15308 
15309 		func[i]->aux->name[0] = 'F';
15310 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15311 		func[i]->jit_requested = 1;
15312 		func[i]->blinding_requested = prog->blinding_requested;
15313 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15314 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15315 		func[i]->aux->linfo = prog->aux->linfo;
15316 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15317 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15318 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15319 		num_exentries = 0;
15320 		insn = func[i]->insnsi;
15321 		for (j = 0; j < func[i]->len; j++, insn++) {
15322 			if (BPF_CLASS(insn->code) == BPF_LDX &&
15323 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
15324 				num_exentries++;
15325 		}
15326 		func[i]->aux->num_exentries = num_exentries;
15327 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15328 		func[i] = bpf_int_jit_compile(func[i]);
15329 		if (!func[i]->jited) {
15330 			err = -ENOTSUPP;
15331 			goto out_free;
15332 		}
15333 		cond_resched();
15334 	}
15335 
15336 	/* at this point all bpf functions were successfully JITed
15337 	 * now populate all bpf_calls with correct addresses and
15338 	 * run last pass of JIT
15339 	 */
15340 	for (i = 0; i < env->subprog_cnt; i++) {
15341 		insn = func[i]->insnsi;
15342 		for (j = 0; j < func[i]->len; j++, insn++) {
15343 			if (bpf_pseudo_func(insn)) {
15344 				subprog = insn->off;
15345 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15346 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15347 				continue;
15348 			}
15349 			if (!bpf_pseudo_call(insn))
15350 				continue;
15351 			subprog = insn->off;
15352 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15353 		}
15354 
15355 		/* we use the aux data to keep a list of the start addresses
15356 		 * of the JITed images for each function in the program
15357 		 *
15358 		 * for some architectures, such as powerpc64, the imm field
15359 		 * might not be large enough to hold the offset of the start
15360 		 * address of the callee's JITed image from __bpf_call_base
15361 		 *
15362 		 * in such cases, we can lookup the start address of a callee
15363 		 * by using its subprog id, available from the off field of
15364 		 * the call instruction, as an index for this list
15365 		 */
15366 		func[i]->aux->func = func;
15367 		func[i]->aux->func_cnt = env->subprog_cnt;
15368 	}
15369 	for (i = 0; i < env->subprog_cnt; i++) {
15370 		old_bpf_func = func[i]->bpf_func;
15371 		tmp = bpf_int_jit_compile(func[i]);
15372 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15373 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15374 			err = -ENOTSUPP;
15375 			goto out_free;
15376 		}
15377 		cond_resched();
15378 	}
15379 
15380 	/* finally lock prog and jit images for all functions and
15381 	 * populate kallsysm
15382 	 */
15383 	for (i = 0; i < env->subprog_cnt; i++) {
15384 		bpf_prog_lock_ro(func[i]);
15385 		bpf_prog_kallsyms_add(func[i]);
15386 	}
15387 
15388 	/* Last step: make now unused interpreter insns from main
15389 	 * prog consistent for later dump requests, so they can
15390 	 * later look the same as if they were interpreted only.
15391 	 */
15392 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15393 		if (bpf_pseudo_func(insn)) {
15394 			insn[0].imm = env->insn_aux_data[i].call_imm;
15395 			insn[1].imm = insn->off;
15396 			insn->off = 0;
15397 			continue;
15398 		}
15399 		if (!bpf_pseudo_call(insn))
15400 			continue;
15401 		insn->off = env->insn_aux_data[i].call_imm;
15402 		subprog = find_subprog(env, i + insn->off + 1);
15403 		insn->imm = subprog;
15404 	}
15405 
15406 	prog->jited = 1;
15407 	prog->bpf_func = func[0]->bpf_func;
15408 	prog->jited_len = func[0]->jited_len;
15409 	prog->aux->func = func;
15410 	prog->aux->func_cnt = env->subprog_cnt;
15411 	bpf_prog_jit_attempt_done(prog);
15412 	return 0;
15413 out_free:
15414 	/* We failed JIT'ing, so at this point we need to unregister poke
15415 	 * descriptors from subprogs, so that kernel is not attempting to
15416 	 * patch it anymore as we're freeing the subprog JIT memory.
15417 	 */
15418 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15419 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15420 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15421 	}
15422 	/* At this point we're guaranteed that poke descriptors are not
15423 	 * live anymore. We can just unlink its descriptor table as it's
15424 	 * released with the main prog.
15425 	 */
15426 	for (i = 0; i < env->subprog_cnt; i++) {
15427 		if (!func[i])
15428 			continue;
15429 		func[i]->aux->poke_tab = NULL;
15430 		bpf_jit_free(func[i]);
15431 	}
15432 	kfree(func);
15433 out_undo_insn:
15434 	/* cleanup main prog to be interpreted */
15435 	prog->jit_requested = 0;
15436 	prog->blinding_requested = 0;
15437 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15438 		if (!bpf_pseudo_call(insn))
15439 			continue;
15440 		insn->off = 0;
15441 		insn->imm = env->insn_aux_data[i].call_imm;
15442 	}
15443 	bpf_prog_jit_attempt_done(prog);
15444 	return err;
15445 }
15446 
15447 static int fixup_call_args(struct bpf_verifier_env *env)
15448 {
15449 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15450 	struct bpf_prog *prog = env->prog;
15451 	struct bpf_insn *insn = prog->insnsi;
15452 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15453 	int i, depth;
15454 #endif
15455 	int err = 0;
15456 
15457 	if (env->prog->jit_requested &&
15458 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
15459 		err = jit_subprogs(env);
15460 		if (err == 0)
15461 			return 0;
15462 		if (err == -EFAULT)
15463 			return err;
15464 	}
15465 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15466 	if (has_kfunc_call) {
15467 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15468 		return -EINVAL;
15469 	}
15470 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15471 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
15472 		 * have to be rejected, since interpreter doesn't support them yet.
15473 		 */
15474 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15475 		return -EINVAL;
15476 	}
15477 	for (i = 0; i < prog->len; i++, insn++) {
15478 		if (bpf_pseudo_func(insn)) {
15479 			/* When JIT fails the progs with callback calls
15480 			 * have to be rejected, since interpreter doesn't support them yet.
15481 			 */
15482 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
15483 			return -EINVAL;
15484 		}
15485 
15486 		if (!bpf_pseudo_call(insn))
15487 			continue;
15488 		depth = get_callee_stack_depth(env, insn, i);
15489 		if (depth < 0)
15490 			return depth;
15491 		bpf_patch_call_args(insn, depth);
15492 	}
15493 	err = 0;
15494 #endif
15495 	return err;
15496 }
15497 
15498 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15499 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15500 {
15501 	const struct bpf_kfunc_desc *desc;
15502 
15503 	if (!insn->imm) {
15504 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15505 		return -EINVAL;
15506 	}
15507 
15508 	/* insn->imm has the btf func_id. Replace it with
15509 	 * an address (relative to __bpf_call_base).
15510 	 */
15511 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15512 	if (!desc) {
15513 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15514 			insn->imm);
15515 		return -EFAULT;
15516 	}
15517 
15518 	*cnt = 0;
15519 	insn->imm = desc->imm;
15520 	if (insn->off)
15521 		return 0;
15522 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15523 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15524 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15525 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15526 
15527 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15528 		insn_buf[1] = addr[0];
15529 		insn_buf[2] = addr[1];
15530 		insn_buf[3] = *insn;
15531 		*cnt = 4;
15532 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15533 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15534 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15535 
15536 		insn_buf[0] = addr[0];
15537 		insn_buf[1] = addr[1];
15538 		insn_buf[2] = *insn;
15539 		*cnt = 3;
15540 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15541 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15542 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15543 		*cnt = 1;
15544 	}
15545 	return 0;
15546 }
15547 
15548 /* Do various post-verification rewrites in a single program pass.
15549  * These rewrites simplify JIT and interpreter implementations.
15550  */
15551 static int do_misc_fixups(struct bpf_verifier_env *env)
15552 {
15553 	struct bpf_prog *prog = env->prog;
15554 	enum bpf_attach_type eatype = prog->expected_attach_type;
15555 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15556 	struct bpf_insn *insn = prog->insnsi;
15557 	const struct bpf_func_proto *fn;
15558 	const int insn_cnt = prog->len;
15559 	const struct bpf_map_ops *ops;
15560 	struct bpf_insn_aux_data *aux;
15561 	struct bpf_insn insn_buf[16];
15562 	struct bpf_prog *new_prog;
15563 	struct bpf_map *map_ptr;
15564 	int i, ret, cnt, delta = 0;
15565 
15566 	for (i = 0; i < insn_cnt; i++, insn++) {
15567 		/* Make divide-by-zero exceptions impossible. */
15568 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15569 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15570 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15571 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15572 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15573 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15574 			struct bpf_insn *patchlet;
15575 			struct bpf_insn chk_and_div[] = {
15576 				/* [R,W]x div 0 -> 0 */
15577 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15578 					     BPF_JNE | BPF_K, insn->src_reg,
15579 					     0, 2, 0),
15580 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15581 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15582 				*insn,
15583 			};
15584 			struct bpf_insn chk_and_mod[] = {
15585 				/* [R,W]x mod 0 -> [R,W]x */
15586 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15587 					     BPF_JEQ | BPF_K, insn->src_reg,
15588 					     0, 1 + (is64 ? 0 : 1), 0),
15589 				*insn,
15590 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15591 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15592 			};
15593 
15594 			patchlet = isdiv ? chk_and_div : chk_and_mod;
15595 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15596 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15597 
15598 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15599 			if (!new_prog)
15600 				return -ENOMEM;
15601 
15602 			delta    += cnt - 1;
15603 			env->prog = prog = new_prog;
15604 			insn      = new_prog->insnsi + i + delta;
15605 			continue;
15606 		}
15607 
15608 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15609 		if (BPF_CLASS(insn->code) == BPF_LD &&
15610 		    (BPF_MODE(insn->code) == BPF_ABS ||
15611 		     BPF_MODE(insn->code) == BPF_IND)) {
15612 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
15613 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15614 				verbose(env, "bpf verifier is misconfigured\n");
15615 				return -EINVAL;
15616 			}
15617 
15618 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15619 			if (!new_prog)
15620 				return -ENOMEM;
15621 
15622 			delta    += cnt - 1;
15623 			env->prog = prog = new_prog;
15624 			insn      = new_prog->insnsi + i + delta;
15625 			continue;
15626 		}
15627 
15628 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
15629 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15630 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15631 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15632 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15633 			struct bpf_insn *patch = &insn_buf[0];
15634 			bool issrc, isneg, isimm;
15635 			u32 off_reg;
15636 
15637 			aux = &env->insn_aux_data[i + delta];
15638 			if (!aux->alu_state ||
15639 			    aux->alu_state == BPF_ALU_NON_POINTER)
15640 				continue;
15641 
15642 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15643 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15644 				BPF_ALU_SANITIZE_SRC;
15645 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15646 
15647 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
15648 			if (isimm) {
15649 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15650 			} else {
15651 				if (isneg)
15652 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15653 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15654 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15655 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15656 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15657 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15658 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15659 			}
15660 			if (!issrc)
15661 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15662 			insn->src_reg = BPF_REG_AX;
15663 			if (isneg)
15664 				insn->code = insn->code == code_add ?
15665 					     code_sub : code_add;
15666 			*patch++ = *insn;
15667 			if (issrc && isneg && !isimm)
15668 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15669 			cnt = patch - insn_buf;
15670 
15671 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15672 			if (!new_prog)
15673 				return -ENOMEM;
15674 
15675 			delta    += cnt - 1;
15676 			env->prog = prog = new_prog;
15677 			insn      = new_prog->insnsi + i + delta;
15678 			continue;
15679 		}
15680 
15681 		if (insn->code != (BPF_JMP | BPF_CALL))
15682 			continue;
15683 		if (insn->src_reg == BPF_PSEUDO_CALL)
15684 			continue;
15685 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15686 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15687 			if (ret)
15688 				return ret;
15689 			if (cnt == 0)
15690 				continue;
15691 
15692 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15693 			if (!new_prog)
15694 				return -ENOMEM;
15695 
15696 			delta	 += cnt - 1;
15697 			env->prog = prog = new_prog;
15698 			insn	  = new_prog->insnsi + i + delta;
15699 			continue;
15700 		}
15701 
15702 		if (insn->imm == BPF_FUNC_get_route_realm)
15703 			prog->dst_needed = 1;
15704 		if (insn->imm == BPF_FUNC_get_prandom_u32)
15705 			bpf_user_rnd_init_once();
15706 		if (insn->imm == BPF_FUNC_override_return)
15707 			prog->kprobe_override = 1;
15708 		if (insn->imm == BPF_FUNC_tail_call) {
15709 			/* If we tail call into other programs, we
15710 			 * cannot make any assumptions since they can
15711 			 * be replaced dynamically during runtime in
15712 			 * the program array.
15713 			 */
15714 			prog->cb_access = 1;
15715 			if (!allow_tail_call_in_subprogs(env))
15716 				prog->aux->stack_depth = MAX_BPF_STACK;
15717 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15718 
15719 			/* mark bpf_tail_call as different opcode to avoid
15720 			 * conditional branch in the interpreter for every normal
15721 			 * call and to prevent accidental JITing by JIT compiler
15722 			 * that doesn't support bpf_tail_call yet
15723 			 */
15724 			insn->imm = 0;
15725 			insn->code = BPF_JMP | BPF_TAIL_CALL;
15726 
15727 			aux = &env->insn_aux_data[i + delta];
15728 			if (env->bpf_capable && !prog->blinding_requested &&
15729 			    prog->jit_requested &&
15730 			    !bpf_map_key_poisoned(aux) &&
15731 			    !bpf_map_ptr_poisoned(aux) &&
15732 			    !bpf_map_ptr_unpriv(aux)) {
15733 				struct bpf_jit_poke_descriptor desc = {
15734 					.reason = BPF_POKE_REASON_TAIL_CALL,
15735 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15736 					.tail_call.key = bpf_map_key_immediate(aux),
15737 					.insn_idx = i + delta,
15738 				};
15739 
15740 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
15741 				if (ret < 0) {
15742 					verbose(env, "adding tail call poke descriptor failed\n");
15743 					return ret;
15744 				}
15745 
15746 				insn->imm = ret + 1;
15747 				continue;
15748 			}
15749 
15750 			if (!bpf_map_ptr_unpriv(aux))
15751 				continue;
15752 
15753 			/* instead of changing every JIT dealing with tail_call
15754 			 * emit two extra insns:
15755 			 * if (index >= max_entries) goto out;
15756 			 * index &= array->index_mask;
15757 			 * to avoid out-of-bounds cpu speculation
15758 			 */
15759 			if (bpf_map_ptr_poisoned(aux)) {
15760 				verbose(env, "tail_call abusing map_ptr\n");
15761 				return -EINVAL;
15762 			}
15763 
15764 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15765 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15766 						  map_ptr->max_entries, 2);
15767 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15768 						    container_of(map_ptr,
15769 								 struct bpf_array,
15770 								 map)->index_mask);
15771 			insn_buf[2] = *insn;
15772 			cnt = 3;
15773 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15774 			if (!new_prog)
15775 				return -ENOMEM;
15776 
15777 			delta    += cnt - 1;
15778 			env->prog = prog = new_prog;
15779 			insn      = new_prog->insnsi + i + delta;
15780 			continue;
15781 		}
15782 
15783 		if (insn->imm == BPF_FUNC_timer_set_callback) {
15784 			/* The verifier will process callback_fn as many times as necessary
15785 			 * with different maps and the register states prepared by
15786 			 * set_timer_callback_state will be accurate.
15787 			 *
15788 			 * The following use case is valid:
15789 			 *   map1 is shared by prog1, prog2, prog3.
15790 			 *   prog1 calls bpf_timer_init for some map1 elements
15791 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
15792 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
15793 			 *   prog3 calls bpf_timer_start for some map1 elements.
15794 			 *     Those that were not both bpf_timer_init-ed and
15795 			 *     bpf_timer_set_callback-ed will return -EINVAL.
15796 			 */
15797 			struct bpf_insn ld_addrs[2] = {
15798 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15799 			};
15800 
15801 			insn_buf[0] = ld_addrs[0];
15802 			insn_buf[1] = ld_addrs[1];
15803 			insn_buf[2] = *insn;
15804 			cnt = 3;
15805 
15806 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15807 			if (!new_prog)
15808 				return -ENOMEM;
15809 
15810 			delta    += cnt - 1;
15811 			env->prog = prog = new_prog;
15812 			insn      = new_prog->insnsi + i + delta;
15813 			goto patch_call_imm;
15814 		}
15815 
15816 		if (is_storage_get_function(insn->imm)) {
15817 			if (!env->prog->aux->sleepable ||
15818 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
15819 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15820 			else
15821 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15822 			insn_buf[1] = *insn;
15823 			cnt = 2;
15824 
15825 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15826 			if (!new_prog)
15827 				return -ENOMEM;
15828 
15829 			delta += cnt - 1;
15830 			env->prog = prog = new_prog;
15831 			insn = new_prog->insnsi + i + delta;
15832 			goto patch_call_imm;
15833 		}
15834 
15835 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15836 		 * and other inlining handlers are currently limited to 64 bit
15837 		 * only.
15838 		 */
15839 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15840 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
15841 		     insn->imm == BPF_FUNC_map_update_elem ||
15842 		     insn->imm == BPF_FUNC_map_delete_elem ||
15843 		     insn->imm == BPF_FUNC_map_push_elem   ||
15844 		     insn->imm == BPF_FUNC_map_pop_elem    ||
15845 		     insn->imm == BPF_FUNC_map_peek_elem   ||
15846 		     insn->imm == BPF_FUNC_redirect_map    ||
15847 		     insn->imm == BPF_FUNC_for_each_map_elem ||
15848 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15849 			aux = &env->insn_aux_data[i + delta];
15850 			if (bpf_map_ptr_poisoned(aux))
15851 				goto patch_call_imm;
15852 
15853 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15854 			ops = map_ptr->ops;
15855 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
15856 			    ops->map_gen_lookup) {
15857 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15858 				if (cnt == -EOPNOTSUPP)
15859 					goto patch_map_ops_generic;
15860 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15861 					verbose(env, "bpf verifier is misconfigured\n");
15862 					return -EINVAL;
15863 				}
15864 
15865 				new_prog = bpf_patch_insn_data(env, i + delta,
15866 							       insn_buf, cnt);
15867 				if (!new_prog)
15868 					return -ENOMEM;
15869 
15870 				delta    += cnt - 1;
15871 				env->prog = prog = new_prog;
15872 				insn      = new_prog->insnsi + i + delta;
15873 				continue;
15874 			}
15875 
15876 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15877 				     (void *(*)(struct bpf_map *map, void *key))NULL));
15878 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15879 				     (int (*)(struct bpf_map *map, void *key))NULL));
15880 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15881 				     (int (*)(struct bpf_map *map, void *key, void *value,
15882 					      u64 flags))NULL));
15883 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15884 				     (int (*)(struct bpf_map *map, void *value,
15885 					      u64 flags))NULL));
15886 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15887 				     (int (*)(struct bpf_map *map, void *value))NULL));
15888 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15889 				     (int (*)(struct bpf_map *map, void *value))NULL));
15890 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
15891 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15892 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15893 				     (int (*)(struct bpf_map *map,
15894 					      bpf_callback_t callback_fn,
15895 					      void *callback_ctx,
15896 					      u64 flags))NULL));
15897 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15898 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15899 
15900 patch_map_ops_generic:
15901 			switch (insn->imm) {
15902 			case BPF_FUNC_map_lookup_elem:
15903 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15904 				continue;
15905 			case BPF_FUNC_map_update_elem:
15906 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15907 				continue;
15908 			case BPF_FUNC_map_delete_elem:
15909 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15910 				continue;
15911 			case BPF_FUNC_map_push_elem:
15912 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15913 				continue;
15914 			case BPF_FUNC_map_pop_elem:
15915 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15916 				continue;
15917 			case BPF_FUNC_map_peek_elem:
15918 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15919 				continue;
15920 			case BPF_FUNC_redirect_map:
15921 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
15922 				continue;
15923 			case BPF_FUNC_for_each_map_elem:
15924 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15925 				continue;
15926 			case BPF_FUNC_map_lookup_percpu_elem:
15927 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15928 				continue;
15929 			}
15930 
15931 			goto patch_call_imm;
15932 		}
15933 
15934 		/* Implement bpf_jiffies64 inline. */
15935 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15936 		    insn->imm == BPF_FUNC_jiffies64) {
15937 			struct bpf_insn ld_jiffies_addr[2] = {
15938 				BPF_LD_IMM64(BPF_REG_0,
15939 					     (unsigned long)&jiffies),
15940 			};
15941 
15942 			insn_buf[0] = ld_jiffies_addr[0];
15943 			insn_buf[1] = ld_jiffies_addr[1];
15944 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15945 						  BPF_REG_0, 0);
15946 			cnt = 3;
15947 
15948 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15949 						       cnt);
15950 			if (!new_prog)
15951 				return -ENOMEM;
15952 
15953 			delta    += cnt - 1;
15954 			env->prog = prog = new_prog;
15955 			insn      = new_prog->insnsi + i + delta;
15956 			continue;
15957 		}
15958 
15959 		/* Implement bpf_get_func_arg inline. */
15960 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15961 		    insn->imm == BPF_FUNC_get_func_arg) {
15962 			/* Load nr_args from ctx - 8 */
15963 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15964 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15965 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15966 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15967 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15968 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15969 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15970 			insn_buf[7] = BPF_JMP_A(1);
15971 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15972 			cnt = 9;
15973 
15974 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15975 			if (!new_prog)
15976 				return -ENOMEM;
15977 
15978 			delta    += cnt - 1;
15979 			env->prog = prog = new_prog;
15980 			insn      = new_prog->insnsi + i + delta;
15981 			continue;
15982 		}
15983 
15984 		/* Implement bpf_get_func_ret inline. */
15985 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15986 		    insn->imm == BPF_FUNC_get_func_ret) {
15987 			if (eatype == BPF_TRACE_FEXIT ||
15988 			    eatype == BPF_MODIFY_RETURN) {
15989 				/* Load nr_args from ctx - 8 */
15990 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15991 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15992 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15993 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15994 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15995 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15996 				cnt = 6;
15997 			} else {
15998 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15999 				cnt = 1;
16000 			}
16001 
16002 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16003 			if (!new_prog)
16004 				return -ENOMEM;
16005 
16006 			delta    += cnt - 1;
16007 			env->prog = prog = new_prog;
16008 			insn      = new_prog->insnsi + i + delta;
16009 			continue;
16010 		}
16011 
16012 		/* Implement get_func_arg_cnt inline. */
16013 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16014 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16015 			/* Load nr_args from ctx - 8 */
16016 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16017 
16018 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16019 			if (!new_prog)
16020 				return -ENOMEM;
16021 
16022 			env->prog = prog = new_prog;
16023 			insn      = new_prog->insnsi + i + delta;
16024 			continue;
16025 		}
16026 
16027 		/* Implement bpf_get_func_ip inline. */
16028 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16029 		    insn->imm == BPF_FUNC_get_func_ip) {
16030 			/* Load IP address from ctx - 16 */
16031 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16032 
16033 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16034 			if (!new_prog)
16035 				return -ENOMEM;
16036 
16037 			env->prog = prog = new_prog;
16038 			insn      = new_prog->insnsi + i + delta;
16039 			continue;
16040 		}
16041 
16042 patch_call_imm:
16043 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16044 		/* all functions that have prototype and verifier allowed
16045 		 * programs to call them, must be real in-kernel functions
16046 		 */
16047 		if (!fn->func) {
16048 			verbose(env,
16049 				"kernel subsystem misconfigured func %s#%d\n",
16050 				func_id_name(insn->imm), insn->imm);
16051 			return -EFAULT;
16052 		}
16053 		insn->imm = fn->func - __bpf_call_base;
16054 	}
16055 
16056 	/* Since poke tab is now finalized, publish aux to tracker. */
16057 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16058 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16059 		if (!map_ptr->ops->map_poke_track ||
16060 		    !map_ptr->ops->map_poke_untrack ||
16061 		    !map_ptr->ops->map_poke_run) {
16062 			verbose(env, "bpf verifier is misconfigured\n");
16063 			return -EINVAL;
16064 		}
16065 
16066 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16067 		if (ret < 0) {
16068 			verbose(env, "tracking tail call prog failed\n");
16069 			return ret;
16070 		}
16071 	}
16072 
16073 	sort_kfunc_descs_by_imm(env->prog);
16074 
16075 	return 0;
16076 }
16077 
16078 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16079 					int position,
16080 					s32 stack_base,
16081 					u32 callback_subprogno,
16082 					u32 *cnt)
16083 {
16084 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16085 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16086 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16087 	int reg_loop_max = BPF_REG_6;
16088 	int reg_loop_cnt = BPF_REG_7;
16089 	int reg_loop_ctx = BPF_REG_8;
16090 
16091 	struct bpf_prog *new_prog;
16092 	u32 callback_start;
16093 	u32 call_insn_offset;
16094 	s32 callback_offset;
16095 
16096 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16097 	 * be careful to modify this code in sync.
16098 	 */
16099 	struct bpf_insn insn_buf[] = {
16100 		/* Return error and jump to the end of the patch if
16101 		 * expected number of iterations is too big.
16102 		 */
16103 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16104 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16105 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16106 		/* spill R6, R7, R8 to use these as loop vars */
16107 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16108 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16109 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16110 		/* initialize loop vars */
16111 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16112 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16113 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16114 		/* loop header,
16115 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16116 		 */
16117 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16118 		/* callback call,
16119 		 * correct callback offset would be set after patching
16120 		 */
16121 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16122 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16123 		BPF_CALL_REL(0),
16124 		/* increment loop counter */
16125 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16126 		/* jump to loop header if callback returned 0 */
16127 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16128 		/* return value of bpf_loop,
16129 		 * set R0 to the number of iterations
16130 		 */
16131 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16132 		/* restore original values of R6, R7, R8 */
16133 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16134 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16135 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16136 	};
16137 
16138 	*cnt = ARRAY_SIZE(insn_buf);
16139 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16140 	if (!new_prog)
16141 		return new_prog;
16142 
16143 	/* callback start is known only after patching */
16144 	callback_start = env->subprog_info[callback_subprogno].start;
16145 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16146 	call_insn_offset = position + 12;
16147 	callback_offset = callback_start - call_insn_offset - 1;
16148 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16149 
16150 	return new_prog;
16151 }
16152 
16153 static bool is_bpf_loop_call(struct bpf_insn *insn)
16154 {
16155 	return insn->code == (BPF_JMP | BPF_CALL) &&
16156 		insn->src_reg == 0 &&
16157 		insn->imm == BPF_FUNC_loop;
16158 }
16159 
16160 /* For all sub-programs in the program (including main) check
16161  * insn_aux_data to see if there are bpf_loop calls that require
16162  * inlining. If such calls are found the calls are replaced with a
16163  * sequence of instructions produced by `inline_bpf_loop` function and
16164  * subprog stack_depth is increased by the size of 3 registers.
16165  * This stack space is used to spill values of the R6, R7, R8.  These
16166  * registers are used to store the loop bound, counter and context
16167  * variables.
16168  */
16169 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16170 {
16171 	struct bpf_subprog_info *subprogs = env->subprog_info;
16172 	int i, cur_subprog = 0, cnt, delta = 0;
16173 	struct bpf_insn *insn = env->prog->insnsi;
16174 	int insn_cnt = env->prog->len;
16175 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16176 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16177 	u16 stack_depth_extra = 0;
16178 
16179 	for (i = 0; i < insn_cnt; i++, insn++) {
16180 		struct bpf_loop_inline_state *inline_state =
16181 			&env->insn_aux_data[i + delta].loop_inline_state;
16182 
16183 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16184 			struct bpf_prog *new_prog;
16185 
16186 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16187 			new_prog = inline_bpf_loop(env,
16188 						   i + delta,
16189 						   -(stack_depth + stack_depth_extra),
16190 						   inline_state->callback_subprogno,
16191 						   &cnt);
16192 			if (!new_prog)
16193 				return -ENOMEM;
16194 
16195 			delta     += cnt - 1;
16196 			env->prog  = new_prog;
16197 			insn       = new_prog->insnsi + i + delta;
16198 		}
16199 
16200 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16201 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16202 			cur_subprog++;
16203 			stack_depth = subprogs[cur_subprog].stack_depth;
16204 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16205 			stack_depth_extra = 0;
16206 		}
16207 	}
16208 
16209 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16210 
16211 	return 0;
16212 }
16213 
16214 static void free_states(struct bpf_verifier_env *env)
16215 {
16216 	struct bpf_verifier_state_list *sl, *sln;
16217 	int i;
16218 
16219 	sl = env->free_list;
16220 	while (sl) {
16221 		sln = sl->next;
16222 		free_verifier_state(&sl->state, false);
16223 		kfree(sl);
16224 		sl = sln;
16225 	}
16226 	env->free_list = NULL;
16227 
16228 	if (!env->explored_states)
16229 		return;
16230 
16231 	for (i = 0; i < state_htab_size(env); i++) {
16232 		sl = env->explored_states[i];
16233 
16234 		while (sl) {
16235 			sln = sl->next;
16236 			free_verifier_state(&sl->state, false);
16237 			kfree(sl);
16238 			sl = sln;
16239 		}
16240 		env->explored_states[i] = NULL;
16241 	}
16242 }
16243 
16244 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16245 {
16246 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16247 	struct bpf_verifier_state *state;
16248 	struct bpf_reg_state *regs;
16249 	int ret, i;
16250 
16251 	env->prev_linfo = NULL;
16252 	env->pass_cnt++;
16253 
16254 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16255 	if (!state)
16256 		return -ENOMEM;
16257 	state->curframe = 0;
16258 	state->speculative = false;
16259 	state->branches = 1;
16260 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16261 	if (!state->frame[0]) {
16262 		kfree(state);
16263 		return -ENOMEM;
16264 	}
16265 	env->cur_state = state;
16266 	init_func_state(env, state->frame[0],
16267 			BPF_MAIN_FUNC /* callsite */,
16268 			0 /* frameno */,
16269 			subprog);
16270 	state->first_insn_idx = env->subprog_info[subprog].start;
16271 	state->last_insn_idx = -1;
16272 
16273 	regs = state->frame[state->curframe]->regs;
16274 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16275 		ret = btf_prepare_func_args(env, subprog, regs);
16276 		if (ret)
16277 			goto out;
16278 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16279 			if (regs[i].type == PTR_TO_CTX)
16280 				mark_reg_known_zero(env, regs, i);
16281 			else if (regs[i].type == SCALAR_VALUE)
16282 				mark_reg_unknown(env, regs, i);
16283 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
16284 				const u32 mem_size = regs[i].mem_size;
16285 
16286 				mark_reg_known_zero(env, regs, i);
16287 				regs[i].mem_size = mem_size;
16288 				regs[i].id = ++env->id_gen;
16289 			}
16290 		}
16291 	} else {
16292 		/* 1st arg to a function */
16293 		regs[BPF_REG_1].type = PTR_TO_CTX;
16294 		mark_reg_known_zero(env, regs, BPF_REG_1);
16295 		ret = btf_check_subprog_arg_match(env, subprog, regs);
16296 		if (ret == -EFAULT)
16297 			/* unlikely verifier bug. abort.
16298 			 * ret == 0 and ret < 0 are sadly acceptable for
16299 			 * main() function due to backward compatibility.
16300 			 * Like socket filter program may be written as:
16301 			 * int bpf_prog(struct pt_regs *ctx)
16302 			 * and never dereference that ctx in the program.
16303 			 * 'struct pt_regs' is a type mismatch for socket
16304 			 * filter that should be using 'struct __sk_buff'.
16305 			 */
16306 			goto out;
16307 	}
16308 
16309 	ret = do_check(env);
16310 out:
16311 	/* check for NULL is necessary, since cur_state can be freed inside
16312 	 * do_check() under memory pressure.
16313 	 */
16314 	if (env->cur_state) {
16315 		free_verifier_state(env->cur_state, true);
16316 		env->cur_state = NULL;
16317 	}
16318 	while (!pop_stack(env, NULL, NULL, false));
16319 	if (!ret && pop_log)
16320 		bpf_vlog_reset(&env->log, 0);
16321 	free_states(env);
16322 	return ret;
16323 }
16324 
16325 /* Verify all global functions in a BPF program one by one based on their BTF.
16326  * All global functions must pass verification. Otherwise the whole program is rejected.
16327  * Consider:
16328  * int bar(int);
16329  * int foo(int f)
16330  * {
16331  *    return bar(f);
16332  * }
16333  * int bar(int b)
16334  * {
16335  *    ...
16336  * }
16337  * foo() will be verified first for R1=any_scalar_value. During verification it
16338  * will be assumed that bar() already verified successfully and call to bar()
16339  * from foo() will be checked for type match only. Later bar() will be verified
16340  * independently to check that it's safe for R1=any_scalar_value.
16341  */
16342 static int do_check_subprogs(struct bpf_verifier_env *env)
16343 {
16344 	struct bpf_prog_aux *aux = env->prog->aux;
16345 	int i, ret;
16346 
16347 	if (!aux->func_info)
16348 		return 0;
16349 
16350 	for (i = 1; i < env->subprog_cnt; i++) {
16351 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16352 			continue;
16353 		env->insn_idx = env->subprog_info[i].start;
16354 		WARN_ON_ONCE(env->insn_idx == 0);
16355 		ret = do_check_common(env, i);
16356 		if (ret) {
16357 			return ret;
16358 		} else if (env->log.level & BPF_LOG_LEVEL) {
16359 			verbose(env,
16360 				"Func#%d is safe for any args that match its prototype\n",
16361 				i);
16362 		}
16363 	}
16364 	return 0;
16365 }
16366 
16367 static int do_check_main(struct bpf_verifier_env *env)
16368 {
16369 	int ret;
16370 
16371 	env->insn_idx = 0;
16372 	ret = do_check_common(env, 0);
16373 	if (!ret)
16374 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16375 	return ret;
16376 }
16377 
16378 
16379 static void print_verification_stats(struct bpf_verifier_env *env)
16380 {
16381 	int i;
16382 
16383 	if (env->log.level & BPF_LOG_STATS) {
16384 		verbose(env, "verification time %lld usec\n",
16385 			div_u64(env->verification_time, 1000));
16386 		verbose(env, "stack depth ");
16387 		for (i = 0; i < env->subprog_cnt; i++) {
16388 			u32 depth = env->subprog_info[i].stack_depth;
16389 
16390 			verbose(env, "%d", depth);
16391 			if (i + 1 < env->subprog_cnt)
16392 				verbose(env, "+");
16393 		}
16394 		verbose(env, "\n");
16395 	}
16396 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16397 		"total_states %d peak_states %d mark_read %d\n",
16398 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16399 		env->max_states_per_insn, env->total_states,
16400 		env->peak_states, env->longest_mark_read_walk);
16401 }
16402 
16403 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16404 {
16405 	const struct btf_type *t, *func_proto;
16406 	const struct bpf_struct_ops *st_ops;
16407 	const struct btf_member *member;
16408 	struct bpf_prog *prog = env->prog;
16409 	u32 btf_id, member_idx;
16410 	const char *mname;
16411 
16412 	if (!prog->gpl_compatible) {
16413 		verbose(env, "struct ops programs must have a GPL compatible license\n");
16414 		return -EINVAL;
16415 	}
16416 
16417 	btf_id = prog->aux->attach_btf_id;
16418 	st_ops = bpf_struct_ops_find(btf_id);
16419 	if (!st_ops) {
16420 		verbose(env, "attach_btf_id %u is not a supported struct\n",
16421 			btf_id);
16422 		return -ENOTSUPP;
16423 	}
16424 
16425 	t = st_ops->type;
16426 	member_idx = prog->expected_attach_type;
16427 	if (member_idx >= btf_type_vlen(t)) {
16428 		verbose(env, "attach to invalid member idx %u of struct %s\n",
16429 			member_idx, st_ops->name);
16430 		return -EINVAL;
16431 	}
16432 
16433 	member = &btf_type_member(t)[member_idx];
16434 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16435 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16436 					       NULL);
16437 	if (!func_proto) {
16438 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16439 			mname, member_idx, st_ops->name);
16440 		return -EINVAL;
16441 	}
16442 
16443 	if (st_ops->check_member) {
16444 		int err = st_ops->check_member(t, member);
16445 
16446 		if (err) {
16447 			verbose(env, "attach to unsupported member %s of struct %s\n",
16448 				mname, st_ops->name);
16449 			return err;
16450 		}
16451 	}
16452 
16453 	prog->aux->attach_func_proto = func_proto;
16454 	prog->aux->attach_func_name = mname;
16455 	env->ops = st_ops->verifier_ops;
16456 
16457 	return 0;
16458 }
16459 #define SECURITY_PREFIX "security_"
16460 
16461 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16462 {
16463 	if (within_error_injection_list(addr) ||
16464 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16465 		return 0;
16466 
16467 	return -EINVAL;
16468 }
16469 
16470 /* list of non-sleepable functions that are otherwise on
16471  * ALLOW_ERROR_INJECTION list
16472  */
16473 BTF_SET_START(btf_non_sleepable_error_inject)
16474 /* Three functions below can be called from sleepable and non-sleepable context.
16475  * Assume non-sleepable from bpf safety point of view.
16476  */
16477 BTF_ID(func, __filemap_add_folio)
16478 BTF_ID(func, should_fail_alloc_page)
16479 BTF_ID(func, should_failslab)
16480 BTF_SET_END(btf_non_sleepable_error_inject)
16481 
16482 static int check_non_sleepable_error_inject(u32 btf_id)
16483 {
16484 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16485 }
16486 
16487 int bpf_check_attach_target(struct bpf_verifier_log *log,
16488 			    const struct bpf_prog *prog,
16489 			    const struct bpf_prog *tgt_prog,
16490 			    u32 btf_id,
16491 			    struct bpf_attach_target_info *tgt_info)
16492 {
16493 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16494 	const char prefix[] = "btf_trace_";
16495 	int ret = 0, subprog = -1, i;
16496 	const struct btf_type *t;
16497 	bool conservative = true;
16498 	const char *tname;
16499 	struct btf *btf;
16500 	long addr = 0;
16501 
16502 	if (!btf_id) {
16503 		bpf_log(log, "Tracing programs must provide btf_id\n");
16504 		return -EINVAL;
16505 	}
16506 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16507 	if (!btf) {
16508 		bpf_log(log,
16509 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16510 		return -EINVAL;
16511 	}
16512 	t = btf_type_by_id(btf, btf_id);
16513 	if (!t) {
16514 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16515 		return -EINVAL;
16516 	}
16517 	tname = btf_name_by_offset(btf, t->name_off);
16518 	if (!tname) {
16519 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16520 		return -EINVAL;
16521 	}
16522 	if (tgt_prog) {
16523 		struct bpf_prog_aux *aux = tgt_prog->aux;
16524 
16525 		for (i = 0; i < aux->func_info_cnt; i++)
16526 			if (aux->func_info[i].type_id == btf_id) {
16527 				subprog = i;
16528 				break;
16529 			}
16530 		if (subprog == -1) {
16531 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
16532 			return -EINVAL;
16533 		}
16534 		conservative = aux->func_info_aux[subprog].unreliable;
16535 		if (prog_extension) {
16536 			if (conservative) {
16537 				bpf_log(log,
16538 					"Cannot replace static functions\n");
16539 				return -EINVAL;
16540 			}
16541 			if (!prog->jit_requested) {
16542 				bpf_log(log,
16543 					"Extension programs should be JITed\n");
16544 				return -EINVAL;
16545 			}
16546 		}
16547 		if (!tgt_prog->jited) {
16548 			bpf_log(log, "Can attach to only JITed progs\n");
16549 			return -EINVAL;
16550 		}
16551 		if (tgt_prog->type == prog->type) {
16552 			/* Cannot fentry/fexit another fentry/fexit program.
16553 			 * Cannot attach program extension to another extension.
16554 			 * It's ok to attach fentry/fexit to extension program.
16555 			 */
16556 			bpf_log(log, "Cannot recursively attach\n");
16557 			return -EINVAL;
16558 		}
16559 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16560 		    prog_extension &&
16561 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16562 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16563 			/* Program extensions can extend all program types
16564 			 * except fentry/fexit. The reason is the following.
16565 			 * The fentry/fexit programs are used for performance
16566 			 * analysis, stats and can be attached to any program
16567 			 * type except themselves. When extension program is
16568 			 * replacing XDP function it is necessary to allow
16569 			 * performance analysis of all functions. Both original
16570 			 * XDP program and its program extension. Hence
16571 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16572 			 * allowed. If extending of fentry/fexit was allowed it
16573 			 * would be possible to create long call chain
16574 			 * fentry->extension->fentry->extension beyond
16575 			 * reasonable stack size. Hence extending fentry is not
16576 			 * allowed.
16577 			 */
16578 			bpf_log(log, "Cannot extend fentry/fexit\n");
16579 			return -EINVAL;
16580 		}
16581 	} else {
16582 		if (prog_extension) {
16583 			bpf_log(log, "Cannot replace kernel functions\n");
16584 			return -EINVAL;
16585 		}
16586 	}
16587 
16588 	switch (prog->expected_attach_type) {
16589 	case BPF_TRACE_RAW_TP:
16590 		if (tgt_prog) {
16591 			bpf_log(log,
16592 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16593 			return -EINVAL;
16594 		}
16595 		if (!btf_type_is_typedef(t)) {
16596 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
16597 				btf_id);
16598 			return -EINVAL;
16599 		}
16600 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16601 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16602 				btf_id, tname);
16603 			return -EINVAL;
16604 		}
16605 		tname += sizeof(prefix) - 1;
16606 		t = btf_type_by_id(btf, t->type);
16607 		if (!btf_type_is_ptr(t))
16608 			/* should never happen in valid vmlinux build */
16609 			return -EINVAL;
16610 		t = btf_type_by_id(btf, t->type);
16611 		if (!btf_type_is_func_proto(t))
16612 			/* should never happen in valid vmlinux build */
16613 			return -EINVAL;
16614 
16615 		break;
16616 	case BPF_TRACE_ITER:
16617 		if (!btf_type_is_func(t)) {
16618 			bpf_log(log, "attach_btf_id %u is not a function\n",
16619 				btf_id);
16620 			return -EINVAL;
16621 		}
16622 		t = btf_type_by_id(btf, t->type);
16623 		if (!btf_type_is_func_proto(t))
16624 			return -EINVAL;
16625 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16626 		if (ret)
16627 			return ret;
16628 		break;
16629 	default:
16630 		if (!prog_extension)
16631 			return -EINVAL;
16632 		fallthrough;
16633 	case BPF_MODIFY_RETURN:
16634 	case BPF_LSM_MAC:
16635 	case BPF_LSM_CGROUP:
16636 	case BPF_TRACE_FENTRY:
16637 	case BPF_TRACE_FEXIT:
16638 		if (!btf_type_is_func(t)) {
16639 			bpf_log(log, "attach_btf_id %u is not a function\n",
16640 				btf_id);
16641 			return -EINVAL;
16642 		}
16643 		if (prog_extension &&
16644 		    btf_check_type_match(log, prog, btf, t))
16645 			return -EINVAL;
16646 		t = btf_type_by_id(btf, t->type);
16647 		if (!btf_type_is_func_proto(t))
16648 			return -EINVAL;
16649 
16650 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16651 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16652 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16653 			return -EINVAL;
16654 
16655 		if (tgt_prog && conservative)
16656 			t = NULL;
16657 
16658 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16659 		if (ret < 0)
16660 			return ret;
16661 
16662 		if (tgt_prog) {
16663 			if (subprog == 0)
16664 				addr = (long) tgt_prog->bpf_func;
16665 			else
16666 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16667 		} else {
16668 			addr = kallsyms_lookup_name(tname);
16669 			if (!addr) {
16670 				bpf_log(log,
16671 					"The address of function %s cannot be found\n",
16672 					tname);
16673 				return -ENOENT;
16674 			}
16675 		}
16676 
16677 		if (prog->aux->sleepable) {
16678 			ret = -EINVAL;
16679 			switch (prog->type) {
16680 			case BPF_PROG_TYPE_TRACING:
16681 
16682 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
16683 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16684 				 */
16685 				if (!check_non_sleepable_error_inject(btf_id) &&
16686 				    within_error_injection_list(addr))
16687 					ret = 0;
16688 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
16689 				 * in the fmodret id set with the KF_SLEEPABLE flag.
16690 				 */
16691 				else {
16692 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
16693 
16694 					if (flags && (*flags & KF_SLEEPABLE))
16695 						ret = 0;
16696 				}
16697 				break;
16698 			case BPF_PROG_TYPE_LSM:
16699 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
16700 				 * Only some of them are sleepable.
16701 				 */
16702 				if (bpf_lsm_is_sleepable_hook(btf_id))
16703 					ret = 0;
16704 				break;
16705 			default:
16706 				break;
16707 			}
16708 			if (ret) {
16709 				bpf_log(log, "%s is not sleepable\n", tname);
16710 				return ret;
16711 			}
16712 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16713 			if (tgt_prog) {
16714 				bpf_log(log, "can't modify return codes of BPF programs\n");
16715 				return -EINVAL;
16716 			}
16717 			ret = -EINVAL;
16718 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
16719 			    !check_attach_modify_return(addr, tname))
16720 				ret = 0;
16721 			if (ret) {
16722 				bpf_log(log, "%s() is not modifiable\n", tname);
16723 				return ret;
16724 			}
16725 		}
16726 
16727 		break;
16728 	}
16729 	tgt_info->tgt_addr = addr;
16730 	tgt_info->tgt_name = tname;
16731 	tgt_info->tgt_type = t;
16732 	return 0;
16733 }
16734 
16735 BTF_SET_START(btf_id_deny)
16736 BTF_ID_UNUSED
16737 #ifdef CONFIG_SMP
16738 BTF_ID(func, migrate_disable)
16739 BTF_ID(func, migrate_enable)
16740 #endif
16741 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16742 BTF_ID(func, rcu_read_unlock_strict)
16743 #endif
16744 BTF_SET_END(btf_id_deny)
16745 
16746 static int check_attach_btf_id(struct bpf_verifier_env *env)
16747 {
16748 	struct bpf_prog *prog = env->prog;
16749 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16750 	struct bpf_attach_target_info tgt_info = {};
16751 	u32 btf_id = prog->aux->attach_btf_id;
16752 	struct bpf_trampoline *tr;
16753 	int ret;
16754 	u64 key;
16755 
16756 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16757 		if (prog->aux->sleepable)
16758 			/* attach_btf_id checked to be zero already */
16759 			return 0;
16760 		verbose(env, "Syscall programs can only be sleepable\n");
16761 		return -EINVAL;
16762 	}
16763 
16764 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16765 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16766 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16767 		return -EINVAL;
16768 	}
16769 
16770 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16771 		return check_struct_ops_btf_id(env);
16772 
16773 	if (prog->type != BPF_PROG_TYPE_TRACING &&
16774 	    prog->type != BPF_PROG_TYPE_LSM &&
16775 	    prog->type != BPF_PROG_TYPE_EXT)
16776 		return 0;
16777 
16778 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16779 	if (ret)
16780 		return ret;
16781 
16782 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16783 		/* to make freplace equivalent to their targets, they need to
16784 		 * inherit env->ops and expected_attach_type for the rest of the
16785 		 * verification
16786 		 */
16787 		env->ops = bpf_verifier_ops[tgt_prog->type];
16788 		prog->expected_attach_type = tgt_prog->expected_attach_type;
16789 	}
16790 
16791 	/* store info about the attachment target that will be used later */
16792 	prog->aux->attach_func_proto = tgt_info.tgt_type;
16793 	prog->aux->attach_func_name = tgt_info.tgt_name;
16794 
16795 	if (tgt_prog) {
16796 		prog->aux->saved_dst_prog_type = tgt_prog->type;
16797 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16798 	}
16799 
16800 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16801 		prog->aux->attach_btf_trace = true;
16802 		return 0;
16803 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16804 		if (!bpf_iter_prog_supported(prog))
16805 			return -EINVAL;
16806 		return 0;
16807 	}
16808 
16809 	if (prog->type == BPF_PROG_TYPE_LSM) {
16810 		ret = bpf_lsm_verify_prog(&env->log, prog);
16811 		if (ret < 0)
16812 			return ret;
16813 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
16814 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
16815 		return -EINVAL;
16816 	}
16817 
16818 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16819 	tr = bpf_trampoline_get(key, &tgt_info);
16820 	if (!tr)
16821 		return -ENOMEM;
16822 
16823 	prog->aux->dst_trampoline = tr;
16824 	return 0;
16825 }
16826 
16827 struct btf *bpf_get_btf_vmlinux(void)
16828 {
16829 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16830 		mutex_lock(&bpf_verifier_lock);
16831 		if (!btf_vmlinux)
16832 			btf_vmlinux = btf_parse_vmlinux();
16833 		mutex_unlock(&bpf_verifier_lock);
16834 	}
16835 	return btf_vmlinux;
16836 }
16837 
16838 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16839 {
16840 	u64 start_time = ktime_get_ns();
16841 	struct bpf_verifier_env *env;
16842 	struct bpf_verifier_log *log;
16843 	int i, len, ret = -EINVAL;
16844 	bool is_priv;
16845 
16846 	/* no program is valid */
16847 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16848 		return -EINVAL;
16849 
16850 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
16851 	 * allocate/free it every time bpf_check() is called
16852 	 */
16853 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16854 	if (!env)
16855 		return -ENOMEM;
16856 	log = &env->log;
16857 
16858 	len = (*prog)->len;
16859 	env->insn_aux_data =
16860 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16861 	ret = -ENOMEM;
16862 	if (!env->insn_aux_data)
16863 		goto err_free_env;
16864 	for (i = 0; i < len; i++)
16865 		env->insn_aux_data[i].orig_idx = i;
16866 	env->prog = *prog;
16867 	env->ops = bpf_verifier_ops[env->prog->type];
16868 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16869 	is_priv = bpf_capable();
16870 
16871 	bpf_get_btf_vmlinux();
16872 
16873 	/* grab the mutex to protect few globals used by verifier */
16874 	if (!is_priv)
16875 		mutex_lock(&bpf_verifier_lock);
16876 
16877 	if (attr->log_level || attr->log_buf || attr->log_size) {
16878 		/* user requested verbose verifier output
16879 		 * and supplied buffer to store the verification trace
16880 		 */
16881 		log->level = attr->log_level;
16882 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16883 		log->len_total = attr->log_size;
16884 
16885 		/* log attributes have to be sane */
16886 		if (!bpf_verifier_log_attr_valid(log)) {
16887 			ret = -EINVAL;
16888 			goto err_unlock;
16889 		}
16890 	}
16891 
16892 	mark_verifier_state_clean(env);
16893 
16894 	if (IS_ERR(btf_vmlinux)) {
16895 		/* Either gcc or pahole or kernel are broken. */
16896 		verbose(env, "in-kernel BTF is malformed\n");
16897 		ret = PTR_ERR(btf_vmlinux);
16898 		goto skip_full_check;
16899 	}
16900 
16901 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16902 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16903 		env->strict_alignment = true;
16904 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16905 		env->strict_alignment = false;
16906 
16907 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16908 	env->allow_uninit_stack = bpf_allow_uninit_stack();
16909 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
16910 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
16911 	env->bpf_capable = bpf_capable();
16912 	env->rcu_tag_supported = btf_vmlinux &&
16913 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
16914 
16915 	if (is_priv)
16916 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16917 
16918 	env->explored_states = kvcalloc(state_htab_size(env),
16919 				       sizeof(struct bpf_verifier_state_list *),
16920 				       GFP_USER);
16921 	ret = -ENOMEM;
16922 	if (!env->explored_states)
16923 		goto skip_full_check;
16924 
16925 	ret = add_subprog_and_kfunc(env);
16926 	if (ret < 0)
16927 		goto skip_full_check;
16928 
16929 	ret = check_subprogs(env);
16930 	if (ret < 0)
16931 		goto skip_full_check;
16932 
16933 	ret = check_btf_info(env, attr, uattr);
16934 	if (ret < 0)
16935 		goto skip_full_check;
16936 
16937 	ret = check_attach_btf_id(env);
16938 	if (ret)
16939 		goto skip_full_check;
16940 
16941 	ret = resolve_pseudo_ldimm64(env);
16942 	if (ret < 0)
16943 		goto skip_full_check;
16944 
16945 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
16946 		ret = bpf_prog_offload_verifier_prep(env->prog);
16947 		if (ret)
16948 			goto skip_full_check;
16949 	}
16950 
16951 	ret = check_cfg(env);
16952 	if (ret < 0)
16953 		goto skip_full_check;
16954 
16955 	ret = do_check_subprogs(env);
16956 	ret = ret ?: do_check_main(env);
16957 
16958 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16959 		ret = bpf_prog_offload_finalize(env);
16960 
16961 skip_full_check:
16962 	kvfree(env->explored_states);
16963 
16964 	if (ret == 0)
16965 		ret = check_max_stack_depth(env);
16966 
16967 	/* instruction rewrites happen after this point */
16968 	if (ret == 0)
16969 		ret = optimize_bpf_loop(env);
16970 
16971 	if (is_priv) {
16972 		if (ret == 0)
16973 			opt_hard_wire_dead_code_branches(env);
16974 		if (ret == 0)
16975 			ret = opt_remove_dead_code(env);
16976 		if (ret == 0)
16977 			ret = opt_remove_nops(env);
16978 	} else {
16979 		if (ret == 0)
16980 			sanitize_dead_code(env);
16981 	}
16982 
16983 	if (ret == 0)
16984 		/* program is valid, convert *(u32*)(ctx + off) accesses */
16985 		ret = convert_ctx_accesses(env);
16986 
16987 	if (ret == 0)
16988 		ret = do_misc_fixups(env);
16989 
16990 	/* do 32-bit optimization after insn patching has done so those patched
16991 	 * insns could be handled correctly.
16992 	 */
16993 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16994 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16995 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16996 								     : false;
16997 	}
16998 
16999 	if (ret == 0)
17000 		ret = fixup_call_args(env);
17001 
17002 	env->verification_time = ktime_get_ns() - start_time;
17003 	print_verification_stats(env);
17004 	env->prog->aux->verified_insns = env->insn_processed;
17005 
17006 	if (log->level && bpf_verifier_log_full(log))
17007 		ret = -ENOSPC;
17008 	if (log->level && !log->ubuf) {
17009 		ret = -EFAULT;
17010 		goto err_release_maps;
17011 	}
17012 
17013 	if (ret)
17014 		goto err_release_maps;
17015 
17016 	if (env->used_map_cnt) {
17017 		/* if program passed verifier, update used_maps in bpf_prog_info */
17018 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17019 							  sizeof(env->used_maps[0]),
17020 							  GFP_KERNEL);
17021 
17022 		if (!env->prog->aux->used_maps) {
17023 			ret = -ENOMEM;
17024 			goto err_release_maps;
17025 		}
17026 
17027 		memcpy(env->prog->aux->used_maps, env->used_maps,
17028 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17029 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17030 	}
17031 	if (env->used_btf_cnt) {
17032 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17033 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17034 							  sizeof(env->used_btfs[0]),
17035 							  GFP_KERNEL);
17036 		if (!env->prog->aux->used_btfs) {
17037 			ret = -ENOMEM;
17038 			goto err_release_maps;
17039 		}
17040 
17041 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17042 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17043 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17044 	}
17045 	if (env->used_map_cnt || env->used_btf_cnt) {
17046 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17047 		 * bpf_ld_imm64 instructions
17048 		 */
17049 		convert_pseudo_ld_imm64(env);
17050 	}
17051 
17052 	adjust_btf_func(env);
17053 
17054 err_release_maps:
17055 	if (!env->prog->aux->used_maps)
17056 		/* if we didn't copy map pointers into bpf_prog_info, release
17057 		 * them now. Otherwise free_used_maps() will release them.
17058 		 */
17059 		release_maps(env);
17060 	if (!env->prog->aux->used_btfs)
17061 		release_btfs(env);
17062 
17063 	/* extension progs temporarily inherit the attach_type of their targets
17064 	   for verification purposes, so set it back to zero before returning
17065 	 */
17066 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17067 		env->prog->expected_attach_type = 0;
17068 
17069 	*prog = env->prog;
17070 err_unlock:
17071 	if (!is_priv)
17072 		mutex_unlock(&bpf_verifier_lock);
17073 	vfree(env->insn_aux_data);
17074 err_free_env:
17075 	kfree(env);
17076 	return ret;
17077 }
17078