xref: /openbmc/linux/kernel/bpf/verifier.c (revision 2d99a7ec)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
195 static int ref_set_non_owning(struct bpf_verifier_env *env,
196 			      struct bpf_reg_state *reg);
197 
198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
199 {
200 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
201 }
202 
203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
204 {
205 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
206 }
207 
208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
209 			      const struct bpf_map *map, bool unpriv)
210 {
211 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
212 	unpriv |= bpf_map_ptr_unpriv(aux);
213 	aux->map_ptr_state = (unsigned long)map |
214 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
215 }
216 
217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
218 {
219 	return aux->map_key_state & BPF_MAP_KEY_POISON;
220 }
221 
222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
223 {
224 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
225 }
226 
227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
230 }
231 
232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
233 {
234 	bool poisoned = bpf_map_key_poisoned(aux);
235 
236 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
237 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
238 }
239 
240 static bool bpf_pseudo_call(const struct bpf_insn *insn)
241 {
242 	return insn->code == (BPF_JMP | BPF_CALL) &&
243 	       insn->src_reg == BPF_PSEUDO_CALL;
244 }
245 
246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
250 }
251 
252 struct bpf_call_arg_meta {
253 	struct bpf_map *map_ptr;
254 	bool raw_mode;
255 	bool pkt_access;
256 	u8 release_regno;
257 	int regno;
258 	int access_size;
259 	int mem_size;
260 	u64 msize_max_value;
261 	int ref_obj_id;
262 	int dynptr_id;
263 	int map_uid;
264 	int func_id;
265 	struct btf *btf;
266 	u32 btf_id;
267 	struct btf *ret_btf;
268 	u32 ret_btf_id;
269 	u32 subprogno;
270 	struct btf_field *kptr_field;
271 	u8 uninit_dynptr_regno;
272 };
273 
274 struct btf *btf_vmlinux;
275 
276 static DEFINE_MUTEX(bpf_verifier_lock);
277 
278 static const struct bpf_line_info *
279 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
280 {
281 	const struct bpf_line_info *linfo;
282 	const struct bpf_prog *prog;
283 	u32 i, nr_linfo;
284 
285 	prog = env->prog;
286 	nr_linfo = prog->aux->nr_linfo;
287 
288 	if (!nr_linfo || insn_off >= prog->len)
289 		return NULL;
290 
291 	linfo = prog->aux->linfo;
292 	for (i = 1; i < nr_linfo; i++)
293 		if (insn_off < linfo[i].insn_off)
294 			break;
295 
296 	return &linfo[i - 1];
297 }
298 
299 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
300 		       va_list args)
301 {
302 	unsigned int n;
303 
304 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
305 
306 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
307 		  "verifier log line truncated - local buffer too short\n");
308 
309 	if (log->level == BPF_LOG_KERNEL) {
310 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
311 
312 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
313 		return;
314 	}
315 
316 	n = min(log->len_total - log->len_used - 1, n);
317 	log->kbuf[n] = '\0';
318 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
319 		log->len_used += n;
320 	else
321 		log->ubuf = NULL;
322 }
323 
324 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
325 {
326 	char zero = 0;
327 
328 	if (!bpf_verifier_log_needed(log))
329 		return;
330 
331 	log->len_used = new_pos;
332 	if (put_user(zero, log->ubuf + new_pos))
333 		log->ubuf = NULL;
334 }
335 
336 /* log_level controls verbosity level of eBPF verifier.
337  * bpf_verifier_log_write() is used to dump the verification trace to the log,
338  * so the user can figure out what's wrong with the program
339  */
340 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
341 					   const char *fmt, ...)
342 {
343 	va_list args;
344 
345 	if (!bpf_verifier_log_needed(&env->log))
346 		return;
347 
348 	va_start(args, fmt);
349 	bpf_verifier_vlog(&env->log, fmt, args);
350 	va_end(args);
351 }
352 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
353 
354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
355 {
356 	struct bpf_verifier_env *env = private_data;
357 	va_list args;
358 
359 	if (!bpf_verifier_log_needed(&env->log))
360 		return;
361 
362 	va_start(args, fmt);
363 	bpf_verifier_vlog(&env->log, fmt, args);
364 	va_end(args);
365 }
366 
367 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
368 			    const char *fmt, ...)
369 {
370 	va_list args;
371 
372 	if (!bpf_verifier_log_needed(log))
373 		return;
374 
375 	va_start(args, fmt);
376 	bpf_verifier_vlog(log, fmt, args);
377 	va_end(args);
378 }
379 EXPORT_SYMBOL_GPL(bpf_log);
380 
381 static const char *ltrim(const char *s)
382 {
383 	while (isspace(*s))
384 		s++;
385 
386 	return s;
387 }
388 
389 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
390 					 u32 insn_off,
391 					 const char *prefix_fmt, ...)
392 {
393 	const struct bpf_line_info *linfo;
394 
395 	if (!bpf_verifier_log_needed(&env->log))
396 		return;
397 
398 	linfo = find_linfo(env, insn_off);
399 	if (!linfo || linfo == env->prev_linfo)
400 		return;
401 
402 	if (prefix_fmt) {
403 		va_list args;
404 
405 		va_start(args, prefix_fmt);
406 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
407 		va_end(args);
408 	}
409 
410 	verbose(env, "%s\n",
411 		ltrim(btf_name_by_offset(env->prog->aux->btf,
412 					 linfo->line_off)));
413 
414 	env->prev_linfo = linfo;
415 }
416 
417 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
418 				   struct bpf_reg_state *reg,
419 				   struct tnum *range, const char *ctx,
420 				   const char *reg_name)
421 {
422 	char tn_buf[48];
423 
424 	verbose(env, "At %s the register %s ", ctx, reg_name);
425 	if (!tnum_is_unknown(reg->var_off)) {
426 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
427 		verbose(env, "has value %s", tn_buf);
428 	} else {
429 		verbose(env, "has unknown scalar value");
430 	}
431 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
432 	verbose(env, " should have been in %s\n", tn_buf);
433 }
434 
435 static bool type_is_pkt_pointer(enum bpf_reg_type type)
436 {
437 	type = base_type(type);
438 	return type == PTR_TO_PACKET ||
439 	       type == PTR_TO_PACKET_META;
440 }
441 
442 static bool type_is_sk_pointer(enum bpf_reg_type type)
443 {
444 	return type == PTR_TO_SOCKET ||
445 		type == PTR_TO_SOCK_COMMON ||
446 		type == PTR_TO_TCP_SOCK ||
447 		type == PTR_TO_XDP_SOCK;
448 }
449 
450 static bool reg_type_not_null(enum bpf_reg_type type)
451 {
452 	return type == PTR_TO_SOCKET ||
453 		type == PTR_TO_TCP_SOCK ||
454 		type == PTR_TO_MAP_VALUE ||
455 		type == PTR_TO_MAP_KEY ||
456 		type == PTR_TO_SOCK_COMMON;
457 }
458 
459 static bool type_is_ptr_alloc_obj(u32 type)
460 {
461 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
462 }
463 
464 static bool type_is_non_owning_ref(u32 type)
465 {
466 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
467 }
468 
469 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
470 {
471 	struct btf_record *rec = NULL;
472 	struct btf_struct_meta *meta;
473 
474 	if (reg->type == PTR_TO_MAP_VALUE) {
475 		rec = reg->map_ptr->record;
476 	} else if (type_is_ptr_alloc_obj(reg->type)) {
477 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
478 		if (meta)
479 			rec = meta->record;
480 	}
481 	return rec;
482 }
483 
484 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
485 {
486 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
487 }
488 
489 static bool type_is_rdonly_mem(u32 type)
490 {
491 	return type & MEM_RDONLY;
492 }
493 
494 static bool type_may_be_null(u32 type)
495 {
496 	return type & PTR_MAYBE_NULL;
497 }
498 
499 static bool is_acquire_function(enum bpf_func_id func_id,
500 				const struct bpf_map *map)
501 {
502 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
503 
504 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
505 	    func_id == BPF_FUNC_sk_lookup_udp ||
506 	    func_id == BPF_FUNC_skc_lookup_tcp ||
507 	    func_id == BPF_FUNC_ringbuf_reserve ||
508 	    func_id == BPF_FUNC_kptr_xchg)
509 		return true;
510 
511 	if (func_id == BPF_FUNC_map_lookup_elem &&
512 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
513 	     map_type == BPF_MAP_TYPE_SOCKHASH))
514 		return true;
515 
516 	return false;
517 }
518 
519 static bool is_ptr_cast_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_tcp_sock ||
522 		func_id == BPF_FUNC_sk_fullsock ||
523 		func_id == BPF_FUNC_skc_to_tcp_sock ||
524 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
525 		func_id == BPF_FUNC_skc_to_udp6_sock ||
526 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
527 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
528 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
529 }
530 
531 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
532 {
533 	return func_id == BPF_FUNC_dynptr_data;
534 }
535 
536 static bool is_callback_calling_function(enum bpf_func_id func_id)
537 {
538 	return func_id == BPF_FUNC_for_each_map_elem ||
539 	       func_id == BPF_FUNC_timer_set_callback ||
540 	       func_id == BPF_FUNC_find_vma ||
541 	       func_id == BPF_FUNC_loop ||
542 	       func_id == BPF_FUNC_user_ringbuf_drain;
543 }
544 
545 static bool is_storage_get_function(enum bpf_func_id func_id)
546 {
547 	return func_id == BPF_FUNC_sk_storage_get ||
548 	       func_id == BPF_FUNC_inode_storage_get ||
549 	       func_id == BPF_FUNC_task_storage_get ||
550 	       func_id == BPF_FUNC_cgrp_storage_get;
551 }
552 
553 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
554 					const struct bpf_map *map)
555 {
556 	int ref_obj_uses = 0;
557 
558 	if (is_ptr_cast_function(func_id))
559 		ref_obj_uses++;
560 	if (is_acquire_function(func_id, map))
561 		ref_obj_uses++;
562 	if (is_dynptr_ref_function(func_id))
563 		ref_obj_uses++;
564 
565 	return ref_obj_uses > 1;
566 }
567 
568 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
569 {
570 	return BPF_CLASS(insn->code) == BPF_STX &&
571 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
572 	       insn->imm == BPF_CMPXCHG;
573 }
574 
575 /* string representation of 'enum bpf_reg_type'
576  *
577  * Note that reg_type_str() can not appear more than once in a single verbose()
578  * statement.
579  */
580 static const char *reg_type_str(struct bpf_verifier_env *env,
581 				enum bpf_reg_type type)
582 {
583 	char postfix[16] = {0}, prefix[64] = {0};
584 	static const char * const str[] = {
585 		[NOT_INIT]		= "?",
586 		[SCALAR_VALUE]		= "scalar",
587 		[PTR_TO_CTX]		= "ctx",
588 		[CONST_PTR_TO_MAP]	= "map_ptr",
589 		[PTR_TO_MAP_VALUE]	= "map_value",
590 		[PTR_TO_STACK]		= "fp",
591 		[PTR_TO_PACKET]		= "pkt",
592 		[PTR_TO_PACKET_META]	= "pkt_meta",
593 		[PTR_TO_PACKET_END]	= "pkt_end",
594 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
595 		[PTR_TO_SOCKET]		= "sock",
596 		[PTR_TO_SOCK_COMMON]	= "sock_common",
597 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
598 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
599 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
600 		[PTR_TO_BTF_ID]		= "ptr_",
601 		[PTR_TO_MEM]		= "mem",
602 		[PTR_TO_BUF]		= "buf",
603 		[PTR_TO_FUNC]		= "func",
604 		[PTR_TO_MAP_KEY]	= "map_key",
605 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
606 	};
607 
608 	if (type & PTR_MAYBE_NULL) {
609 		if (base_type(type) == PTR_TO_BTF_ID)
610 			strncpy(postfix, "or_null_", 16);
611 		else
612 			strncpy(postfix, "_or_null", 16);
613 	}
614 
615 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
616 		 type & MEM_RDONLY ? "rdonly_" : "",
617 		 type & MEM_RINGBUF ? "ringbuf_" : "",
618 		 type & MEM_USER ? "user_" : "",
619 		 type & MEM_PERCPU ? "percpu_" : "",
620 		 type & MEM_RCU ? "rcu_" : "",
621 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
622 		 type & PTR_TRUSTED ? "trusted_" : ""
623 	);
624 
625 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
626 		 prefix, str[base_type(type)], postfix);
627 	return env->type_str_buf;
628 }
629 
630 static char slot_type_char[] = {
631 	[STACK_INVALID]	= '?',
632 	[STACK_SPILL]	= 'r',
633 	[STACK_MISC]	= 'm',
634 	[STACK_ZERO]	= '0',
635 	[STACK_DYNPTR]	= 'd',
636 };
637 
638 static void print_liveness(struct bpf_verifier_env *env,
639 			   enum bpf_reg_liveness live)
640 {
641 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
642 	    verbose(env, "_");
643 	if (live & REG_LIVE_READ)
644 		verbose(env, "r");
645 	if (live & REG_LIVE_WRITTEN)
646 		verbose(env, "w");
647 	if (live & REG_LIVE_DONE)
648 		verbose(env, "D");
649 }
650 
651 static int __get_spi(s32 off)
652 {
653 	return (-off - 1) / BPF_REG_SIZE;
654 }
655 
656 static struct bpf_func_state *func(struct bpf_verifier_env *env,
657 				   const struct bpf_reg_state *reg)
658 {
659 	struct bpf_verifier_state *cur = env->cur_state;
660 
661 	return cur->frame[reg->frameno];
662 }
663 
664 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
665 {
666        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
667 
668        /* We need to check that slots between [spi - nr_slots + 1, spi] are
669 	* within [0, allocated_stack).
670 	*
671 	* Please note that the spi grows downwards. For example, a dynptr
672 	* takes the size of two stack slots; the first slot will be at
673 	* spi and the second slot will be at spi - 1.
674 	*/
675        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
676 }
677 
678 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
679 {
680 	int off, spi;
681 
682 	if (!tnum_is_const(reg->var_off)) {
683 		verbose(env, "dynptr has to be at a constant offset\n");
684 		return -EINVAL;
685 	}
686 
687 	off = reg->off + reg->var_off.value;
688 	if (off % BPF_REG_SIZE) {
689 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
690 		return -EINVAL;
691 	}
692 
693 	spi = __get_spi(off);
694 	if (spi < 1) {
695 		verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
696 		return -EINVAL;
697 	}
698 
699 	if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS))
700 		return -ERANGE;
701 	return spi;
702 }
703 
704 static const char *kernel_type_name(const struct btf* btf, u32 id)
705 {
706 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
707 }
708 
709 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
710 {
711 	env->scratched_regs |= 1U << regno;
712 }
713 
714 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
715 {
716 	env->scratched_stack_slots |= 1ULL << spi;
717 }
718 
719 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
720 {
721 	return (env->scratched_regs >> regno) & 1;
722 }
723 
724 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
725 {
726 	return (env->scratched_stack_slots >> regno) & 1;
727 }
728 
729 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
730 {
731 	return env->scratched_regs || env->scratched_stack_slots;
732 }
733 
734 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
735 {
736 	env->scratched_regs = 0U;
737 	env->scratched_stack_slots = 0ULL;
738 }
739 
740 /* Used for printing the entire verifier state. */
741 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
742 {
743 	env->scratched_regs = ~0U;
744 	env->scratched_stack_slots = ~0ULL;
745 }
746 
747 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
748 {
749 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
750 	case DYNPTR_TYPE_LOCAL:
751 		return BPF_DYNPTR_TYPE_LOCAL;
752 	case DYNPTR_TYPE_RINGBUF:
753 		return BPF_DYNPTR_TYPE_RINGBUF;
754 	default:
755 		return BPF_DYNPTR_TYPE_INVALID;
756 	}
757 }
758 
759 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
760 {
761 	return type == BPF_DYNPTR_TYPE_RINGBUF;
762 }
763 
764 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
765 			      enum bpf_dynptr_type type,
766 			      bool first_slot, int dynptr_id);
767 
768 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
769 				struct bpf_reg_state *reg);
770 
771 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
772 				   struct bpf_reg_state *sreg1,
773 				   struct bpf_reg_state *sreg2,
774 				   enum bpf_dynptr_type type)
775 {
776 	int id = ++env->id_gen;
777 
778 	__mark_dynptr_reg(sreg1, type, true, id);
779 	__mark_dynptr_reg(sreg2, type, false, id);
780 }
781 
782 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
783 			       struct bpf_reg_state *reg,
784 			       enum bpf_dynptr_type type)
785 {
786 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
787 }
788 
789 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
790 				        struct bpf_func_state *state, int spi);
791 
792 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
793 				   enum bpf_arg_type arg_type, int insn_idx)
794 {
795 	struct bpf_func_state *state = func(env, reg);
796 	enum bpf_dynptr_type type;
797 	int spi, i, id, err;
798 
799 	spi = dynptr_get_spi(env, reg);
800 	if (spi < 0)
801 		return spi;
802 
803 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
804 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
805 	 * to ensure that for the following example:
806 	 *	[d1][d1][d2][d2]
807 	 * spi    3   2   1   0
808 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
809 	 * case they do belong to same dynptr, second call won't see slot_type
810 	 * as STACK_DYNPTR and will simply skip destruction.
811 	 */
812 	err = destroy_if_dynptr_stack_slot(env, state, spi);
813 	if (err)
814 		return err;
815 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
816 	if (err)
817 		return err;
818 
819 	for (i = 0; i < BPF_REG_SIZE; i++) {
820 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
821 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
822 	}
823 
824 	type = arg_to_dynptr_type(arg_type);
825 	if (type == BPF_DYNPTR_TYPE_INVALID)
826 		return -EINVAL;
827 
828 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
829 			       &state->stack[spi - 1].spilled_ptr, type);
830 
831 	if (dynptr_type_refcounted(type)) {
832 		/* The id is used to track proper releasing */
833 		id = acquire_reference_state(env, insn_idx);
834 		if (id < 0)
835 			return id;
836 
837 		state->stack[spi].spilled_ptr.ref_obj_id = id;
838 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
839 	}
840 
841 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
842 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
843 
844 	return 0;
845 }
846 
847 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
848 {
849 	struct bpf_func_state *state = func(env, reg);
850 	int spi, i;
851 
852 	spi = dynptr_get_spi(env, reg);
853 	if (spi < 0)
854 		return spi;
855 
856 	for (i = 0; i < BPF_REG_SIZE; i++) {
857 		state->stack[spi].slot_type[i] = STACK_INVALID;
858 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
859 	}
860 
861 	/* Invalidate any slices associated with this dynptr */
862 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
863 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
864 
865 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
866 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
867 
868 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
869 	 *
870 	 * While we don't allow reading STACK_INVALID, it is still possible to
871 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
872 	 * helpers or insns can do partial read of that part without failing,
873 	 * but check_stack_range_initialized, check_stack_read_var_off, and
874 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
875 	 * the slot conservatively. Hence we need to prevent those liveness
876 	 * marking walks.
877 	 *
878 	 * This was not a problem before because STACK_INVALID is only set by
879 	 * default (where the default reg state has its reg->parent as NULL), or
880 	 * in clean_live_states after REG_LIVE_DONE (at which point
881 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
882 	 * verifier state exploration (like we did above). Hence, for our case
883 	 * parentage chain will still be live (i.e. reg->parent may be
884 	 * non-NULL), while earlier reg->parent was NULL, so we need
885 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
886 	 * done later on reads or by mark_dynptr_read as well to unnecessary
887 	 * mark registers in verifier state.
888 	 */
889 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
890 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
891 
892 	return 0;
893 }
894 
895 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
896 			       struct bpf_reg_state *reg);
897 
898 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
899 				        struct bpf_func_state *state, int spi)
900 {
901 	struct bpf_func_state *fstate;
902 	struct bpf_reg_state *dreg;
903 	int i, dynptr_id;
904 
905 	/* We always ensure that STACK_DYNPTR is never set partially,
906 	 * hence just checking for slot_type[0] is enough. This is
907 	 * different for STACK_SPILL, where it may be only set for
908 	 * 1 byte, so code has to use is_spilled_reg.
909 	 */
910 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
911 		return 0;
912 
913 	/* Reposition spi to first slot */
914 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
915 		spi = spi + 1;
916 
917 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
918 		verbose(env, "cannot overwrite referenced dynptr\n");
919 		return -EINVAL;
920 	}
921 
922 	mark_stack_slot_scratched(env, spi);
923 	mark_stack_slot_scratched(env, spi - 1);
924 
925 	/* Writing partially to one dynptr stack slot destroys both. */
926 	for (i = 0; i < BPF_REG_SIZE; i++) {
927 		state->stack[spi].slot_type[i] = STACK_INVALID;
928 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
929 	}
930 
931 	dynptr_id = state->stack[spi].spilled_ptr.id;
932 	/* Invalidate any slices associated with this dynptr */
933 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
934 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
935 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
936 			continue;
937 		if (dreg->dynptr_id == dynptr_id) {
938 			if (!env->allow_ptr_leaks)
939 				__mark_reg_not_init(env, dreg);
940 			else
941 				__mark_reg_unknown(env, dreg);
942 		}
943 	}));
944 
945 	/* Do not release reference state, we are destroying dynptr on stack,
946 	 * not using some helper to release it. Just reset register.
947 	 */
948 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
949 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
950 
951 	/* Same reason as unmark_stack_slots_dynptr above */
952 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
953 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
954 
955 	return 0;
956 }
957 
958 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959 				       int spi)
960 {
961 	if (reg->type == CONST_PTR_TO_DYNPTR)
962 		return false;
963 
964 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
965 	 * will do check_mem_access to check and update stack bounds later, so
966 	 * return true for that case.
967 	 */
968 	if (spi < 0)
969 		return spi == -ERANGE;
970 	/* We allow overwriting existing unreferenced STACK_DYNPTR slots, see
971 	 * mark_stack_slots_dynptr which calls destroy_if_dynptr_stack_slot to
972 	 * ensure dynptr objects at the slots we are touching are completely
973 	 * destructed before we reinitialize them for a new one. For referenced
974 	 * ones, destroy_if_dynptr_stack_slot returns an error early instead of
975 	 * delaying it until the end where the user will get "Unreleased
976 	 * reference" error.
977 	 */
978 	return true;
979 }
980 
981 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
982 				     int spi)
983 {
984 	struct bpf_func_state *state = func(env, reg);
985 	int i;
986 
987 	/* This already represents first slot of initialized bpf_dynptr */
988 	if (reg->type == CONST_PTR_TO_DYNPTR)
989 		return true;
990 
991 	if (spi < 0)
992 		return false;
993 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
994 		return false;
995 
996 	for (i = 0; i < BPF_REG_SIZE; i++) {
997 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
998 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
999 			return false;
1000 	}
1001 
1002 	return true;
1003 }
1004 
1005 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1006 				    enum bpf_arg_type arg_type)
1007 {
1008 	struct bpf_func_state *state = func(env, reg);
1009 	enum bpf_dynptr_type dynptr_type;
1010 	int spi;
1011 
1012 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1013 	if (arg_type == ARG_PTR_TO_DYNPTR)
1014 		return true;
1015 
1016 	dynptr_type = arg_to_dynptr_type(arg_type);
1017 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1018 		return reg->dynptr.type == dynptr_type;
1019 	} else {
1020 		spi = dynptr_get_spi(env, reg);
1021 		if (spi < 0)
1022 			return false;
1023 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1024 	}
1025 }
1026 
1027 /* The reg state of a pointer or a bounded scalar was saved when
1028  * it was spilled to the stack.
1029  */
1030 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1031 {
1032 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1033 }
1034 
1035 static void scrub_spilled_slot(u8 *stype)
1036 {
1037 	if (*stype != STACK_INVALID)
1038 		*stype = STACK_MISC;
1039 }
1040 
1041 static void print_verifier_state(struct bpf_verifier_env *env,
1042 				 const struct bpf_func_state *state,
1043 				 bool print_all)
1044 {
1045 	const struct bpf_reg_state *reg;
1046 	enum bpf_reg_type t;
1047 	int i;
1048 
1049 	if (state->frameno)
1050 		verbose(env, " frame%d:", state->frameno);
1051 	for (i = 0; i < MAX_BPF_REG; i++) {
1052 		reg = &state->regs[i];
1053 		t = reg->type;
1054 		if (t == NOT_INIT)
1055 			continue;
1056 		if (!print_all && !reg_scratched(env, i))
1057 			continue;
1058 		verbose(env, " R%d", i);
1059 		print_liveness(env, reg->live);
1060 		verbose(env, "=");
1061 		if (t == SCALAR_VALUE && reg->precise)
1062 			verbose(env, "P");
1063 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1064 		    tnum_is_const(reg->var_off)) {
1065 			/* reg->off should be 0 for SCALAR_VALUE */
1066 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1067 			verbose(env, "%lld", reg->var_off.value + reg->off);
1068 		} else {
1069 			const char *sep = "";
1070 
1071 			verbose(env, "%s", reg_type_str(env, t));
1072 			if (base_type(t) == PTR_TO_BTF_ID)
1073 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1074 			verbose(env, "(");
1075 /*
1076  * _a stands for append, was shortened to avoid multiline statements below.
1077  * This macro is used to output a comma separated list of attributes.
1078  */
1079 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1080 
1081 			if (reg->id)
1082 				verbose_a("id=%d", reg->id);
1083 			if (reg->ref_obj_id)
1084 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1085 			if (type_is_non_owning_ref(reg->type))
1086 				verbose_a("%s", "non_own_ref");
1087 			if (t != SCALAR_VALUE)
1088 				verbose_a("off=%d", reg->off);
1089 			if (type_is_pkt_pointer(t))
1090 				verbose_a("r=%d", reg->range);
1091 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1092 				 base_type(t) == PTR_TO_MAP_KEY ||
1093 				 base_type(t) == PTR_TO_MAP_VALUE)
1094 				verbose_a("ks=%d,vs=%d",
1095 					  reg->map_ptr->key_size,
1096 					  reg->map_ptr->value_size);
1097 			if (tnum_is_const(reg->var_off)) {
1098 				/* Typically an immediate SCALAR_VALUE, but
1099 				 * could be a pointer whose offset is too big
1100 				 * for reg->off
1101 				 */
1102 				verbose_a("imm=%llx", reg->var_off.value);
1103 			} else {
1104 				if (reg->smin_value != reg->umin_value &&
1105 				    reg->smin_value != S64_MIN)
1106 					verbose_a("smin=%lld", (long long)reg->smin_value);
1107 				if (reg->smax_value != reg->umax_value &&
1108 				    reg->smax_value != S64_MAX)
1109 					verbose_a("smax=%lld", (long long)reg->smax_value);
1110 				if (reg->umin_value != 0)
1111 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1112 				if (reg->umax_value != U64_MAX)
1113 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1114 				if (!tnum_is_unknown(reg->var_off)) {
1115 					char tn_buf[48];
1116 
1117 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1118 					verbose_a("var_off=%s", tn_buf);
1119 				}
1120 				if (reg->s32_min_value != reg->smin_value &&
1121 				    reg->s32_min_value != S32_MIN)
1122 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1123 				if (reg->s32_max_value != reg->smax_value &&
1124 				    reg->s32_max_value != S32_MAX)
1125 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1126 				if (reg->u32_min_value != reg->umin_value &&
1127 				    reg->u32_min_value != U32_MIN)
1128 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1129 				if (reg->u32_max_value != reg->umax_value &&
1130 				    reg->u32_max_value != U32_MAX)
1131 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1132 			}
1133 #undef verbose_a
1134 
1135 			verbose(env, ")");
1136 		}
1137 	}
1138 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1139 		char types_buf[BPF_REG_SIZE + 1];
1140 		bool valid = false;
1141 		int j;
1142 
1143 		for (j = 0; j < BPF_REG_SIZE; j++) {
1144 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1145 				valid = true;
1146 			types_buf[j] = slot_type_char[
1147 					state->stack[i].slot_type[j]];
1148 		}
1149 		types_buf[BPF_REG_SIZE] = 0;
1150 		if (!valid)
1151 			continue;
1152 		if (!print_all && !stack_slot_scratched(env, i))
1153 			continue;
1154 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1155 		print_liveness(env, state->stack[i].spilled_ptr.live);
1156 		if (is_spilled_reg(&state->stack[i])) {
1157 			reg = &state->stack[i].spilled_ptr;
1158 			t = reg->type;
1159 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1160 			if (t == SCALAR_VALUE && reg->precise)
1161 				verbose(env, "P");
1162 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1163 				verbose(env, "%lld", reg->var_off.value + reg->off);
1164 		} else {
1165 			verbose(env, "=%s", types_buf);
1166 		}
1167 	}
1168 	if (state->acquired_refs && state->refs[0].id) {
1169 		verbose(env, " refs=%d", state->refs[0].id);
1170 		for (i = 1; i < state->acquired_refs; i++)
1171 			if (state->refs[i].id)
1172 				verbose(env, ",%d", state->refs[i].id);
1173 	}
1174 	if (state->in_callback_fn)
1175 		verbose(env, " cb");
1176 	if (state->in_async_callback_fn)
1177 		verbose(env, " async_cb");
1178 	verbose(env, "\n");
1179 	mark_verifier_state_clean(env);
1180 }
1181 
1182 static inline u32 vlog_alignment(u32 pos)
1183 {
1184 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1185 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1186 }
1187 
1188 static void print_insn_state(struct bpf_verifier_env *env,
1189 			     const struct bpf_func_state *state)
1190 {
1191 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1192 		/* remove new line character */
1193 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1194 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1195 	} else {
1196 		verbose(env, "%d:", env->insn_idx);
1197 	}
1198 	print_verifier_state(env, state, false);
1199 }
1200 
1201 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1202  * small to hold src. This is different from krealloc since we don't want to preserve
1203  * the contents of dst.
1204  *
1205  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1206  * not be allocated.
1207  */
1208 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1209 {
1210 	size_t alloc_bytes;
1211 	void *orig = dst;
1212 	size_t bytes;
1213 
1214 	if (ZERO_OR_NULL_PTR(src))
1215 		goto out;
1216 
1217 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1218 		return NULL;
1219 
1220 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1221 	dst = krealloc(orig, alloc_bytes, flags);
1222 	if (!dst) {
1223 		kfree(orig);
1224 		return NULL;
1225 	}
1226 
1227 	memcpy(dst, src, bytes);
1228 out:
1229 	return dst ? dst : ZERO_SIZE_PTR;
1230 }
1231 
1232 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1233  * small to hold new_n items. new items are zeroed out if the array grows.
1234  *
1235  * Contrary to krealloc_array, does not free arr if new_n is zero.
1236  */
1237 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1238 {
1239 	size_t alloc_size;
1240 	void *new_arr;
1241 
1242 	if (!new_n || old_n == new_n)
1243 		goto out;
1244 
1245 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1246 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1247 	if (!new_arr) {
1248 		kfree(arr);
1249 		return NULL;
1250 	}
1251 	arr = new_arr;
1252 
1253 	if (new_n > old_n)
1254 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1255 
1256 out:
1257 	return arr ? arr : ZERO_SIZE_PTR;
1258 }
1259 
1260 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1261 {
1262 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1263 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1264 	if (!dst->refs)
1265 		return -ENOMEM;
1266 
1267 	dst->acquired_refs = src->acquired_refs;
1268 	return 0;
1269 }
1270 
1271 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1272 {
1273 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1274 
1275 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1276 				GFP_KERNEL);
1277 	if (!dst->stack)
1278 		return -ENOMEM;
1279 
1280 	dst->allocated_stack = src->allocated_stack;
1281 	return 0;
1282 }
1283 
1284 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1285 {
1286 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1287 				    sizeof(struct bpf_reference_state));
1288 	if (!state->refs)
1289 		return -ENOMEM;
1290 
1291 	state->acquired_refs = n;
1292 	return 0;
1293 }
1294 
1295 static int grow_stack_state(struct bpf_func_state *state, int size)
1296 {
1297 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1298 
1299 	if (old_n >= n)
1300 		return 0;
1301 
1302 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1303 	if (!state->stack)
1304 		return -ENOMEM;
1305 
1306 	state->allocated_stack = size;
1307 	return 0;
1308 }
1309 
1310 /* Acquire a pointer id from the env and update the state->refs to include
1311  * this new pointer reference.
1312  * On success, returns a valid pointer id to associate with the register
1313  * On failure, returns a negative errno.
1314  */
1315 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1316 {
1317 	struct bpf_func_state *state = cur_func(env);
1318 	int new_ofs = state->acquired_refs;
1319 	int id, err;
1320 
1321 	err = resize_reference_state(state, state->acquired_refs + 1);
1322 	if (err)
1323 		return err;
1324 	id = ++env->id_gen;
1325 	state->refs[new_ofs].id = id;
1326 	state->refs[new_ofs].insn_idx = insn_idx;
1327 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1328 
1329 	return id;
1330 }
1331 
1332 /* release function corresponding to acquire_reference_state(). Idempotent. */
1333 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1334 {
1335 	int i, last_idx;
1336 
1337 	last_idx = state->acquired_refs - 1;
1338 	for (i = 0; i < state->acquired_refs; i++) {
1339 		if (state->refs[i].id == ptr_id) {
1340 			/* Cannot release caller references in callbacks */
1341 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1342 				return -EINVAL;
1343 			if (last_idx && i != last_idx)
1344 				memcpy(&state->refs[i], &state->refs[last_idx],
1345 				       sizeof(*state->refs));
1346 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1347 			state->acquired_refs--;
1348 			return 0;
1349 		}
1350 	}
1351 	return -EINVAL;
1352 }
1353 
1354 static void free_func_state(struct bpf_func_state *state)
1355 {
1356 	if (!state)
1357 		return;
1358 	kfree(state->refs);
1359 	kfree(state->stack);
1360 	kfree(state);
1361 }
1362 
1363 static void clear_jmp_history(struct bpf_verifier_state *state)
1364 {
1365 	kfree(state->jmp_history);
1366 	state->jmp_history = NULL;
1367 	state->jmp_history_cnt = 0;
1368 }
1369 
1370 static void free_verifier_state(struct bpf_verifier_state *state,
1371 				bool free_self)
1372 {
1373 	int i;
1374 
1375 	for (i = 0; i <= state->curframe; i++) {
1376 		free_func_state(state->frame[i]);
1377 		state->frame[i] = NULL;
1378 	}
1379 	clear_jmp_history(state);
1380 	if (free_self)
1381 		kfree(state);
1382 }
1383 
1384 /* copy verifier state from src to dst growing dst stack space
1385  * when necessary to accommodate larger src stack
1386  */
1387 static int copy_func_state(struct bpf_func_state *dst,
1388 			   const struct bpf_func_state *src)
1389 {
1390 	int err;
1391 
1392 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1393 	err = copy_reference_state(dst, src);
1394 	if (err)
1395 		return err;
1396 	return copy_stack_state(dst, src);
1397 }
1398 
1399 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1400 			       const struct bpf_verifier_state *src)
1401 {
1402 	struct bpf_func_state *dst;
1403 	int i, err;
1404 
1405 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1406 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1407 					    GFP_USER);
1408 	if (!dst_state->jmp_history)
1409 		return -ENOMEM;
1410 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1411 
1412 	/* if dst has more stack frames then src frame, free them */
1413 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1414 		free_func_state(dst_state->frame[i]);
1415 		dst_state->frame[i] = NULL;
1416 	}
1417 	dst_state->speculative = src->speculative;
1418 	dst_state->active_rcu_lock = src->active_rcu_lock;
1419 	dst_state->curframe = src->curframe;
1420 	dst_state->active_lock.ptr = src->active_lock.ptr;
1421 	dst_state->active_lock.id = src->active_lock.id;
1422 	dst_state->branches = src->branches;
1423 	dst_state->parent = src->parent;
1424 	dst_state->first_insn_idx = src->first_insn_idx;
1425 	dst_state->last_insn_idx = src->last_insn_idx;
1426 	for (i = 0; i <= src->curframe; i++) {
1427 		dst = dst_state->frame[i];
1428 		if (!dst) {
1429 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1430 			if (!dst)
1431 				return -ENOMEM;
1432 			dst_state->frame[i] = dst;
1433 		}
1434 		err = copy_func_state(dst, src->frame[i]);
1435 		if (err)
1436 			return err;
1437 	}
1438 	return 0;
1439 }
1440 
1441 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1442 {
1443 	while (st) {
1444 		u32 br = --st->branches;
1445 
1446 		/* WARN_ON(br > 1) technically makes sense here,
1447 		 * but see comment in push_stack(), hence:
1448 		 */
1449 		WARN_ONCE((int)br < 0,
1450 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1451 			  br);
1452 		if (br)
1453 			break;
1454 		st = st->parent;
1455 	}
1456 }
1457 
1458 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1459 		     int *insn_idx, bool pop_log)
1460 {
1461 	struct bpf_verifier_state *cur = env->cur_state;
1462 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1463 	int err;
1464 
1465 	if (env->head == NULL)
1466 		return -ENOENT;
1467 
1468 	if (cur) {
1469 		err = copy_verifier_state(cur, &head->st);
1470 		if (err)
1471 			return err;
1472 	}
1473 	if (pop_log)
1474 		bpf_vlog_reset(&env->log, head->log_pos);
1475 	if (insn_idx)
1476 		*insn_idx = head->insn_idx;
1477 	if (prev_insn_idx)
1478 		*prev_insn_idx = head->prev_insn_idx;
1479 	elem = head->next;
1480 	free_verifier_state(&head->st, false);
1481 	kfree(head);
1482 	env->head = elem;
1483 	env->stack_size--;
1484 	return 0;
1485 }
1486 
1487 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1488 					     int insn_idx, int prev_insn_idx,
1489 					     bool speculative)
1490 {
1491 	struct bpf_verifier_state *cur = env->cur_state;
1492 	struct bpf_verifier_stack_elem *elem;
1493 	int err;
1494 
1495 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1496 	if (!elem)
1497 		goto err;
1498 
1499 	elem->insn_idx = insn_idx;
1500 	elem->prev_insn_idx = prev_insn_idx;
1501 	elem->next = env->head;
1502 	elem->log_pos = env->log.len_used;
1503 	env->head = elem;
1504 	env->stack_size++;
1505 	err = copy_verifier_state(&elem->st, cur);
1506 	if (err)
1507 		goto err;
1508 	elem->st.speculative |= speculative;
1509 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1510 		verbose(env, "The sequence of %d jumps is too complex.\n",
1511 			env->stack_size);
1512 		goto err;
1513 	}
1514 	if (elem->st.parent) {
1515 		++elem->st.parent->branches;
1516 		/* WARN_ON(branches > 2) technically makes sense here,
1517 		 * but
1518 		 * 1. speculative states will bump 'branches' for non-branch
1519 		 * instructions
1520 		 * 2. is_state_visited() heuristics may decide not to create
1521 		 * a new state for a sequence of branches and all such current
1522 		 * and cloned states will be pointing to a single parent state
1523 		 * which might have large 'branches' count.
1524 		 */
1525 	}
1526 	return &elem->st;
1527 err:
1528 	free_verifier_state(env->cur_state, true);
1529 	env->cur_state = NULL;
1530 	/* pop all elements and return */
1531 	while (!pop_stack(env, NULL, NULL, false));
1532 	return NULL;
1533 }
1534 
1535 #define CALLER_SAVED_REGS 6
1536 static const int caller_saved[CALLER_SAVED_REGS] = {
1537 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1538 };
1539 
1540 /* This helper doesn't clear reg->id */
1541 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1542 {
1543 	reg->var_off = tnum_const(imm);
1544 	reg->smin_value = (s64)imm;
1545 	reg->smax_value = (s64)imm;
1546 	reg->umin_value = imm;
1547 	reg->umax_value = imm;
1548 
1549 	reg->s32_min_value = (s32)imm;
1550 	reg->s32_max_value = (s32)imm;
1551 	reg->u32_min_value = (u32)imm;
1552 	reg->u32_max_value = (u32)imm;
1553 }
1554 
1555 /* Mark the unknown part of a register (variable offset or scalar value) as
1556  * known to have the value @imm.
1557  */
1558 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1559 {
1560 	/* Clear off and union(map_ptr, range) */
1561 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1562 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1563 	reg->id = 0;
1564 	reg->ref_obj_id = 0;
1565 	___mark_reg_known(reg, imm);
1566 }
1567 
1568 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1569 {
1570 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1571 	reg->s32_min_value = (s32)imm;
1572 	reg->s32_max_value = (s32)imm;
1573 	reg->u32_min_value = (u32)imm;
1574 	reg->u32_max_value = (u32)imm;
1575 }
1576 
1577 /* Mark the 'variable offset' part of a register as zero.  This should be
1578  * used only on registers holding a pointer type.
1579  */
1580 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1581 {
1582 	__mark_reg_known(reg, 0);
1583 }
1584 
1585 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1586 {
1587 	__mark_reg_known(reg, 0);
1588 	reg->type = SCALAR_VALUE;
1589 }
1590 
1591 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1592 				struct bpf_reg_state *regs, u32 regno)
1593 {
1594 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1595 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1596 		/* Something bad happened, let's kill all regs */
1597 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1598 			__mark_reg_not_init(env, regs + regno);
1599 		return;
1600 	}
1601 	__mark_reg_known_zero(regs + regno);
1602 }
1603 
1604 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1605 			      bool first_slot, int dynptr_id)
1606 {
1607 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1608 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1609 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1610 	 */
1611 	__mark_reg_known_zero(reg);
1612 	reg->type = CONST_PTR_TO_DYNPTR;
1613 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1614 	reg->id = dynptr_id;
1615 	reg->dynptr.type = type;
1616 	reg->dynptr.first_slot = first_slot;
1617 }
1618 
1619 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1620 {
1621 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1622 		const struct bpf_map *map = reg->map_ptr;
1623 
1624 		if (map->inner_map_meta) {
1625 			reg->type = CONST_PTR_TO_MAP;
1626 			reg->map_ptr = map->inner_map_meta;
1627 			/* transfer reg's id which is unique for every map_lookup_elem
1628 			 * as UID of the inner map.
1629 			 */
1630 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1631 				reg->map_uid = reg->id;
1632 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1633 			reg->type = PTR_TO_XDP_SOCK;
1634 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1635 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1636 			reg->type = PTR_TO_SOCKET;
1637 		} else {
1638 			reg->type = PTR_TO_MAP_VALUE;
1639 		}
1640 		return;
1641 	}
1642 
1643 	reg->type &= ~PTR_MAYBE_NULL;
1644 }
1645 
1646 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1647 				struct btf_field_graph_root *ds_head)
1648 {
1649 	__mark_reg_known_zero(&regs[regno]);
1650 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1651 	regs[regno].btf = ds_head->btf;
1652 	regs[regno].btf_id = ds_head->value_btf_id;
1653 	regs[regno].off = ds_head->node_offset;
1654 }
1655 
1656 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1657 {
1658 	return type_is_pkt_pointer(reg->type);
1659 }
1660 
1661 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1662 {
1663 	return reg_is_pkt_pointer(reg) ||
1664 	       reg->type == PTR_TO_PACKET_END;
1665 }
1666 
1667 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1668 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1669 				    enum bpf_reg_type which)
1670 {
1671 	/* The register can already have a range from prior markings.
1672 	 * This is fine as long as it hasn't been advanced from its
1673 	 * origin.
1674 	 */
1675 	return reg->type == which &&
1676 	       reg->id == 0 &&
1677 	       reg->off == 0 &&
1678 	       tnum_equals_const(reg->var_off, 0);
1679 }
1680 
1681 /* Reset the min/max bounds of a register */
1682 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1683 {
1684 	reg->smin_value = S64_MIN;
1685 	reg->smax_value = S64_MAX;
1686 	reg->umin_value = 0;
1687 	reg->umax_value = U64_MAX;
1688 
1689 	reg->s32_min_value = S32_MIN;
1690 	reg->s32_max_value = S32_MAX;
1691 	reg->u32_min_value = 0;
1692 	reg->u32_max_value = U32_MAX;
1693 }
1694 
1695 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1696 {
1697 	reg->smin_value = S64_MIN;
1698 	reg->smax_value = S64_MAX;
1699 	reg->umin_value = 0;
1700 	reg->umax_value = U64_MAX;
1701 }
1702 
1703 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1704 {
1705 	reg->s32_min_value = S32_MIN;
1706 	reg->s32_max_value = S32_MAX;
1707 	reg->u32_min_value = 0;
1708 	reg->u32_max_value = U32_MAX;
1709 }
1710 
1711 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1712 {
1713 	struct tnum var32_off = tnum_subreg(reg->var_off);
1714 
1715 	/* min signed is max(sign bit) | min(other bits) */
1716 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1717 			var32_off.value | (var32_off.mask & S32_MIN));
1718 	/* max signed is min(sign bit) | max(other bits) */
1719 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1720 			var32_off.value | (var32_off.mask & S32_MAX));
1721 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1722 	reg->u32_max_value = min(reg->u32_max_value,
1723 				 (u32)(var32_off.value | var32_off.mask));
1724 }
1725 
1726 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1727 {
1728 	/* min signed is max(sign bit) | min(other bits) */
1729 	reg->smin_value = max_t(s64, reg->smin_value,
1730 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1731 	/* max signed is min(sign bit) | max(other bits) */
1732 	reg->smax_value = min_t(s64, reg->smax_value,
1733 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1734 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1735 	reg->umax_value = min(reg->umax_value,
1736 			      reg->var_off.value | reg->var_off.mask);
1737 }
1738 
1739 static void __update_reg_bounds(struct bpf_reg_state *reg)
1740 {
1741 	__update_reg32_bounds(reg);
1742 	__update_reg64_bounds(reg);
1743 }
1744 
1745 /* Uses signed min/max values to inform unsigned, and vice-versa */
1746 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1747 {
1748 	/* Learn sign from signed bounds.
1749 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1750 	 * are the same, so combine.  This works even in the negative case, e.g.
1751 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1752 	 */
1753 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1754 		reg->s32_min_value = reg->u32_min_value =
1755 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1756 		reg->s32_max_value = reg->u32_max_value =
1757 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1758 		return;
1759 	}
1760 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1761 	 * boundary, so we must be careful.
1762 	 */
1763 	if ((s32)reg->u32_max_value >= 0) {
1764 		/* Positive.  We can't learn anything from the smin, but smax
1765 		 * is positive, hence safe.
1766 		 */
1767 		reg->s32_min_value = reg->u32_min_value;
1768 		reg->s32_max_value = reg->u32_max_value =
1769 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1770 	} else if ((s32)reg->u32_min_value < 0) {
1771 		/* Negative.  We can't learn anything from the smax, but smin
1772 		 * is negative, hence safe.
1773 		 */
1774 		reg->s32_min_value = reg->u32_min_value =
1775 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1776 		reg->s32_max_value = reg->u32_max_value;
1777 	}
1778 }
1779 
1780 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1781 {
1782 	/* Learn sign from signed bounds.
1783 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1784 	 * are the same, so combine.  This works even in the negative case, e.g.
1785 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1786 	 */
1787 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1788 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1789 							  reg->umin_value);
1790 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1791 							  reg->umax_value);
1792 		return;
1793 	}
1794 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1795 	 * boundary, so we must be careful.
1796 	 */
1797 	if ((s64)reg->umax_value >= 0) {
1798 		/* Positive.  We can't learn anything from the smin, but smax
1799 		 * is positive, hence safe.
1800 		 */
1801 		reg->smin_value = reg->umin_value;
1802 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1803 							  reg->umax_value);
1804 	} else if ((s64)reg->umin_value < 0) {
1805 		/* Negative.  We can't learn anything from the smax, but smin
1806 		 * is negative, hence safe.
1807 		 */
1808 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1809 							  reg->umin_value);
1810 		reg->smax_value = reg->umax_value;
1811 	}
1812 }
1813 
1814 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1815 {
1816 	__reg32_deduce_bounds(reg);
1817 	__reg64_deduce_bounds(reg);
1818 }
1819 
1820 /* Attempts to improve var_off based on unsigned min/max information */
1821 static void __reg_bound_offset(struct bpf_reg_state *reg)
1822 {
1823 	struct tnum var64_off = tnum_intersect(reg->var_off,
1824 					       tnum_range(reg->umin_value,
1825 							  reg->umax_value));
1826 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1827 						tnum_range(reg->u32_min_value,
1828 							   reg->u32_max_value));
1829 
1830 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1831 }
1832 
1833 static void reg_bounds_sync(struct bpf_reg_state *reg)
1834 {
1835 	/* We might have learned new bounds from the var_off. */
1836 	__update_reg_bounds(reg);
1837 	/* We might have learned something about the sign bit. */
1838 	__reg_deduce_bounds(reg);
1839 	/* We might have learned some bits from the bounds. */
1840 	__reg_bound_offset(reg);
1841 	/* Intersecting with the old var_off might have improved our bounds
1842 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1843 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1844 	 */
1845 	__update_reg_bounds(reg);
1846 }
1847 
1848 static bool __reg32_bound_s64(s32 a)
1849 {
1850 	return a >= 0 && a <= S32_MAX;
1851 }
1852 
1853 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1854 {
1855 	reg->umin_value = reg->u32_min_value;
1856 	reg->umax_value = reg->u32_max_value;
1857 
1858 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1859 	 * be positive otherwise set to worse case bounds and refine later
1860 	 * from tnum.
1861 	 */
1862 	if (__reg32_bound_s64(reg->s32_min_value) &&
1863 	    __reg32_bound_s64(reg->s32_max_value)) {
1864 		reg->smin_value = reg->s32_min_value;
1865 		reg->smax_value = reg->s32_max_value;
1866 	} else {
1867 		reg->smin_value = 0;
1868 		reg->smax_value = U32_MAX;
1869 	}
1870 }
1871 
1872 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1873 {
1874 	/* special case when 64-bit register has upper 32-bit register
1875 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1876 	 * allowing us to use 32-bit bounds directly,
1877 	 */
1878 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1879 		__reg_assign_32_into_64(reg);
1880 	} else {
1881 		/* Otherwise the best we can do is push lower 32bit known and
1882 		 * unknown bits into register (var_off set from jmp logic)
1883 		 * then learn as much as possible from the 64-bit tnum
1884 		 * known and unknown bits. The previous smin/smax bounds are
1885 		 * invalid here because of jmp32 compare so mark them unknown
1886 		 * so they do not impact tnum bounds calculation.
1887 		 */
1888 		__mark_reg64_unbounded(reg);
1889 	}
1890 	reg_bounds_sync(reg);
1891 }
1892 
1893 static bool __reg64_bound_s32(s64 a)
1894 {
1895 	return a >= S32_MIN && a <= S32_MAX;
1896 }
1897 
1898 static bool __reg64_bound_u32(u64 a)
1899 {
1900 	return a >= U32_MIN && a <= U32_MAX;
1901 }
1902 
1903 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1904 {
1905 	__mark_reg32_unbounded(reg);
1906 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1907 		reg->s32_min_value = (s32)reg->smin_value;
1908 		reg->s32_max_value = (s32)reg->smax_value;
1909 	}
1910 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1911 		reg->u32_min_value = (u32)reg->umin_value;
1912 		reg->u32_max_value = (u32)reg->umax_value;
1913 	}
1914 	reg_bounds_sync(reg);
1915 }
1916 
1917 /* Mark a register as having a completely unknown (scalar) value. */
1918 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1919 			       struct bpf_reg_state *reg)
1920 {
1921 	/*
1922 	 * Clear type, off, and union(map_ptr, range) and
1923 	 * padding between 'type' and union
1924 	 */
1925 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1926 	reg->type = SCALAR_VALUE;
1927 	reg->id = 0;
1928 	reg->ref_obj_id = 0;
1929 	reg->var_off = tnum_unknown;
1930 	reg->frameno = 0;
1931 	reg->precise = !env->bpf_capable;
1932 	__mark_reg_unbounded(reg);
1933 }
1934 
1935 static void mark_reg_unknown(struct bpf_verifier_env *env,
1936 			     struct bpf_reg_state *regs, u32 regno)
1937 {
1938 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1939 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1940 		/* Something bad happened, let's kill all regs except FP */
1941 		for (regno = 0; regno < BPF_REG_FP; regno++)
1942 			__mark_reg_not_init(env, regs + regno);
1943 		return;
1944 	}
1945 	__mark_reg_unknown(env, regs + regno);
1946 }
1947 
1948 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1949 				struct bpf_reg_state *reg)
1950 {
1951 	__mark_reg_unknown(env, reg);
1952 	reg->type = NOT_INIT;
1953 }
1954 
1955 static void mark_reg_not_init(struct bpf_verifier_env *env,
1956 			      struct bpf_reg_state *regs, u32 regno)
1957 {
1958 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1959 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1960 		/* Something bad happened, let's kill all regs except FP */
1961 		for (regno = 0; regno < BPF_REG_FP; regno++)
1962 			__mark_reg_not_init(env, regs + regno);
1963 		return;
1964 	}
1965 	__mark_reg_not_init(env, regs + regno);
1966 }
1967 
1968 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1969 			    struct bpf_reg_state *regs, u32 regno,
1970 			    enum bpf_reg_type reg_type,
1971 			    struct btf *btf, u32 btf_id,
1972 			    enum bpf_type_flag flag)
1973 {
1974 	if (reg_type == SCALAR_VALUE) {
1975 		mark_reg_unknown(env, regs, regno);
1976 		return;
1977 	}
1978 	mark_reg_known_zero(env, regs, regno);
1979 	regs[regno].type = PTR_TO_BTF_ID | flag;
1980 	regs[regno].btf = btf;
1981 	regs[regno].btf_id = btf_id;
1982 }
1983 
1984 #define DEF_NOT_SUBREG	(0)
1985 static void init_reg_state(struct bpf_verifier_env *env,
1986 			   struct bpf_func_state *state)
1987 {
1988 	struct bpf_reg_state *regs = state->regs;
1989 	int i;
1990 
1991 	for (i = 0; i < MAX_BPF_REG; i++) {
1992 		mark_reg_not_init(env, regs, i);
1993 		regs[i].live = REG_LIVE_NONE;
1994 		regs[i].parent = NULL;
1995 		regs[i].subreg_def = DEF_NOT_SUBREG;
1996 	}
1997 
1998 	/* frame pointer */
1999 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2000 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2001 	regs[BPF_REG_FP].frameno = state->frameno;
2002 }
2003 
2004 #define BPF_MAIN_FUNC (-1)
2005 static void init_func_state(struct bpf_verifier_env *env,
2006 			    struct bpf_func_state *state,
2007 			    int callsite, int frameno, int subprogno)
2008 {
2009 	state->callsite = callsite;
2010 	state->frameno = frameno;
2011 	state->subprogno = subprogno;
2012 	state->callback_ret_range = tnum_range(0, 0);
2013 	init_reg_state(env, state);
2014 	mark_verifier_state_scratched(env);
2015 }
2016 
2017 /* Similar to push_stack(), but for async callbacks */
2018 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2019 						int insn_idx, int prev_insn_idx,
2020 						int subprog)
2021 {
2022 	struct bpf_verifier_stack_elem *elem;
2023 	struct bpf_func_state *frame;
2024 
2025 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2026 	if (!elem)
2027 		goto err;
2028 
2029 	elem->insn_idx = insn_idx;
2030 	elem->prev_insn_idx = prev_insn_idx;
2031 	elem->next = env->head;
2032 	elem->log_pos = env->log.len_used;
2033 	env->head = elem;
2034 	env->stack_size++;
2035 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2036 		verbose(env,
2037 			"The sequence of %d jumps is too complex for async cb.\n",
2038 			env->stack_size);
2039 		goto err;
2040 	}
2041 	/* Unlike push_stack() do not copy_verifier_state().
2042 	 * The caller state doesn't matter.
2043 	 * This is async callback. It starts in a fresh stack.
2044 	 * Initialize it similar to do_check_common().
2045 	 */
2046 	elem->st.branches = 1;
2047 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2048 	if (!frame)
2049 		goto err;
2050 	init_func_state(env, frame,
2051 			BPF_MAIN_FUNC /* callsite */,
2052 			0 /* frameno within this callchain */,
2053 			subprog /* subprog number within this prog */);
2054 	elem->st.frame[0] = frame;
2055 	return &elem->st;
2056 err:
2057 	free_verifier_state(env->cur_state, true);
2058 	env->cur_state = NULL;
2059 	/* pop all elements and return */
2060 	while (!pop_stack(env, NULL, NULL, false));
2061 	return NULL;
2062 }
2063 
2064 
2065 enum reg_arg_type {
2066 	SRC_OP,		/* register is used as source operand */
2067 	DST_OP,		/* register is used as destination operand */
2068 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2069 };
2070 
2071 static int cmp_subprogs(const void *a, const void *b)
2072 {
2073 	return ((struct bpf_subprog_info *)a)->start -
2074 	       ((struct bpf_subprog_info *)b)->start;
2075 }
2076 
2077 static int find_subprog(struct bpf_verifier_env *env, int off)
2078 {
2079 	struct bpf_subprog_info *p;
2080 
2081 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2082 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2083 	if (!p)
2084 		return -ENOENT;
2085 	return p - env->subprog_info;
2086 
2087 }
2088 
2089 static int add_subprog(struct bpf_verifier_env *env, int off)
2090 {
2091 	int insn_cnt = env->prog->len;
2092 	int ret;
2093 
2094 	if (off >= insn_cnt || off < 0) {
2095 		verbose(env, "call to invalid destination\n");
2096 		return -EINVAL;
2097 	}
2098 	ret = find_subprog(env, off);
2099 	if (ret >= 0)
2100 		return ret;
2101 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2102 		verbose(env, "too many subprograms\n");
2103 		return -E2BIG;
2104 	}
2105 	/* determine subprog starts. The end is one before the next starts */
2106 	env->subprog_info[env->subprog_cnt++].start = off;
2107 	sort(env->subprog_info, env->subprog_cnt,
2108 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2109 	return env->subprog_cnt - 1;
2110 }
2111 
2112 #define MAX_KFUNC_DESCS 256
2113 #define MAX_KFUNC_BTFS	256
2114 
2115 struct bpf_kfunc_desc {
2116 	struct btf_func_model func_model;
2117 	u32 func_id;
2118 	s32 imm;
2119 	u16 offset;
2120 };
2121 
2122 struct bpf_kfunc_btf {
2123 	struct btf *btf;
2124 	struct module *module;
2125 	u16 offset;
2126 };
2127 
2128 struct bpf_kfunc_desc_tab {
2129 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2130 	u32 nr_descs;
2131 };
2132 
2133 struct bpf_kfunc_btf_tab {
2134 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2135 	u32 nr_descs;
2136 };
2137 
2138 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2139 {
2140 	const struct bpf_kfunc_desc *d0 = a;
2141 	const struct bpf_kfunc_desc *d1 = b;
2142 
2143 	/* func_id is not greater than BTF_MAX_TYPE */
2144 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2145 }
2146 
2147 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2148 {
2149 	const struct bpf_kfunc_btf *d0 = a;
2150 	const struct bpf_kfunc_btf *d1 = b;
2151 
2152 	return d0->offset - d1->offset;
2153 }
2154 
2155 static const struct bpf_kfunc_desc *
2156 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2157 {
2158 	struct bpf_kfunc_desc desc = {
2159 		.func_id = func_id,
2160 		.offset = offset,
2161 	};
2162 	struct bpf_kfunc_desc_tab *tab;
2163 
2164 	tab = prog->aux->kfunc_tab;
2165 	return bsearch(&desc, tab->descs, tab->nr_descs,
2166 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2167 }
2168 
2169 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2170 					 s16 offset)
2171 {
2172 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2173 	struct bpf_kfunc_btf_tab *tab;
2174 	struct bpf_kfunc_btf *b;
2175 	struct module *mod;
2176 	struct btf *btf;
2177 	int btf_fd;
2178 
2179 	tab = env->prog->aux->kfunc_btf_tab;
2180 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2181 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2182 	if (!b) {
2183 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2184 			verbose(env, "too many different module BTFs\n");
2185 			return ERR_PTR(-E2BIG);
2186 		}
2187 
2188 		if (bpfptr_is_null(env->fd_array)) {
2189 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2190 			return ERR_PTR(-EPROTO);
2191 		}
2192 
2193 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2194 					    offset * sizeof(btf_fd),
2195 					    sizeof(btf_fd)))
2196 			return ERR_PTR(-EFAULT);
2197 
2198 		btf = btf_get_by_fd(btf_fd);
2199 		if (IS_ERR(btf)) {
2200 			verbose(env, "invalid module BTF fd specified\n");
2201 			return btf;
2202 		}
2203 
2204 		if (!btf_is_module(btf)) {
2205 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2206 			btf_put(btf);
2207 			return ERR_PTR(-EINVAL);
2208 		}
2209 
2210 		mod = btf_try_get_module(btf);
2211 		if (!mod) {
2212 			btf_put(btf);
2213 			return ERR_PTR(-ENXIO);
2214 		}
2215 
2216 		b = &tab->descs[tab->nr_descs++];
2217 		b->btf = btf;
2218 		b->module = mod;
2219 		b->offset = offset;
2220 
2221 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2222 		     kfunc_btf_cmp_by_off, NULL);
2223 	}
2224 	return b->btf;
2225 }
2226 
2227 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2228 {
2229 	if (!tab)
2230 		return;
2231 
2232 	while (tab->nr_descs--) {
2233 		module_put(tab->descs[tab->nr_descs].module);
2234 		btf_put(tab->descs[tab->nr_descs].btf);
2235 	}
2236 	kfree(tab);
2237 }
2238 
2239 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2240 {
2241 	if (offset) {
2242 		if (offset < 0) {
2243 			/* In the future, this can be allowed to increase limit
2244 			 * of fd index into fd_array, interpreted as u16.
2245 			 */
2246 			verbose(env, "negative offset disallowed for kernel module function call\n");
2247 			return ERR_PTR(-EINVAL);
2248 		}
2249 
2250 		return __find_kfunc_desc_btf(env, offset);
2251 	}
2252 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2253 }
2254 
2255 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2256 {
2257 	const struct btf_type *func, *func_proto;
2258 	struct bpf_kfunc_btf_tab *btf_tab;
2259 	struct bpf_kfunc_desc_tab *tab;
2260 	struct bpf_prog_aux *prog_aux;
2261 	struct bpf_kfunc_desc *desc;
2262 	const char *func_name;
2263 	struct btf *desc_btf;
2264 	unsigned long call_imm;
2265 	unsigned long addr;
2266 	int err;
2267 
2268 	prog_aux = env->prog->aux;
2269 	tab = prog_aux->kfunc_tab;
2270 	btf_tab = prog_aux->kfunc_btf_tab;
2271 	if (!tab) {
2272 		if (!btf_vmlinux) {
2273 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2274 			return -ENOTSUPP;
2275 		}
2276 
2277 		if (!env->prog->jit_requested) {
2278 			verbose(env, "JIT is required for calling kernel function\n");
2279 			return -ENOTSUPP;
2280 		}
2281 
2282 		if (!bpf_jit_supports_kfunc_call()) {
2283 			verbose(env, "JIT does not support calling kernel function\n");
2284 			return -ENOTSUPP;
2285 		}
2286 
2287 		if (!env->prog->gpl_compatible) {
2288 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2289 			return -EINVAL;
2290 		}
2291 
2292 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2293 		if (!tab)
2294 			return -ENOMEM;
2295 		prog_aux->kfunc_tab = tab;
2296 	}
2297 
2298 	/* func_id == 0 is always invalid, but instead of returning an error, be
2299 	 * conservative and wait until the code elimination pass before returning
2300 	 * error, so that invalid calls that get pruned out can be in BPF programs
2301 	 * loaded from userspace.  It is also required that offset be untouched
2302 	 * for such calls.
2303 	 */
2304 	if (!func_id && !offset)
2305 		return 0;
2306 
2307 	if (!btf_tab && offset) {
2308 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2309 		if (!btf_tab)
2310 			return -ENOMEM;
2311 		prog_aux->kfunc_btf_tab = btf_tab;
2312 	}
2313 
2314 	desc_btf = find_kfunc_desc_btf(env, offset);
2315 	if (IS_ERR(desc_btf)) {
2316 		verbose(env, "failed to find BTF for kernel function\n");
2317 		return PTR_ERR(desc_btf);
2318 	}
2319 
2320 	if (find_kfunc_desc(env->prog, func_id, offset))
2321 		return 0;
2322 
2323 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2324 		verbose(env, "too many different kernel function calls\n");
2325 		return -E2BIG;
2326 	}
2327 
2328 	func = btf_type_by_id(desc_btf, func_id);
2329 	if (!func || !btf_type_is_func(func)) {
2330 		verbose(env, "kernel btf_id %u is not a function\n",
2331 			func_id);
2332 		return -EINVAL;
2333 	}
2334 	func_proto = btf_type_by_id(desc_btf, func->type);
2335 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2336 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2337 			func_id);
2338 		return -EINVAL;
2339 	}
2340 
2341 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2342 	addr = kallsyms_lookup_name(func_name);
2343 	if (!addr) {
2344 		verbose(env, "cannot find address for kernel function %s\n",
2345 			func_name);
2346 		return -EINVAL;
2347 	}
2348 
2349 	call_imm = BPF_CALL_IMM(addr);
2350 	/* Check whether or not the relative offset overflows desc->imm */
2351 	if ((unsigned long)(s32)call_imm != call_imm) {
2352 		verbose(env, "address of kernel function %s is out of range\n",
2353 			func_name);
2354 		return -EINVAL;
2355 	}
2356 
2357 	if (bpf_dev_bound_kfunc_id(func_id)) {
2358 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2359 		if (err)
2360 			return err;
2361 	}
2362 
2363 	desc = &tab->descs[tab->nr_descs++];
2364 	desc->func_id = func_id;
2365 	desc->imm = call_imm;
2366 	desc->offset = offset;
2367 	err = btf_distill_func_proto(&env->log, desc_btf,
2368 				     func_proto, func_name,
2369 				     &desc->func_model);
2370 	if (!err)
2371 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2372 		     kfunc_desc_cmp_by_id_off, NULL);
2373 	return err;
2374 }
2375 
2376 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2377 {
2378 	const struct bpf_kfunc_desc *d0 = a;
2379 	const struct bpf_kfunc_desc *d1 = b;
2380 
2381 	if (d0->imm > d1->imm)
2382 		return 1;
2383 	else if (d0->imm < d1->imm)
2384 		return -1;
2385 	return 0;
2386 }
2387 
2388 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2389 {
2390 	struct bpf_kfunc_desc_tab *tab;
2391 
2392 	tab = prog->aux->kfunc_tab;
2393 	if (!tab)
2394 		return;
2395 
2396 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2397 	     kfunc_desc_cmp_by_imm, NULL);
2398 }
2399 
2400 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2401 {
2402 	return !!prog->aux->kfunc_tab;
2403 }
2404 
2405 const struct btf_func_model *
2406 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2407 			 const struct bpf_insn *insn)
2408 {
2409 	const struct bpf_kfunc_desc desc = {
2410 		.imm = insn->imm,
2411 	};
2412 	const struct bpf_kfunc_desc *res;
2413 	struct bpf_kfunc_desc_tab *tab;
2414 
2415 	tab = prog->aux->kfunc_tab;
2416 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2417 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2418 
2419 	return res ? &res->func_model : NULL;
2420 }
2421 
2422 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2423 {
2424 	struct bpf_subprog_info *subprog = env->subprog_info;
2425 	struct bpf_insn *insn = env->prog->insnsi;
2426 	int i, ret, insn_cnt = env->prog->len;
2427 
2428 	/* Add entry function. */
2429 	ret = add_subprog(env, 0);
2430 	if (ret)
2431 		return ret;
2432 
2433 	for (i = 0; i < insn_cnt; i++, insn++) {
2434 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2435 		    !bpf_pseudo_kfunc_call(insn))
2436 			continue;
2437 
2438 		if (!env->bpf_capable) {
2439 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2440 			return -EPERM;
2441 		}
2442 
2443 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2444 			ret = add_subprog(env, i + insn->imm + 1);
2445 		else
2446 			ret = add_kfunc_call(env, insn->imm, insn->off);
2447 
2448 		if (ret < 0)
2449 			return ret;
2450 	}
2451 
2452 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2453 	 * logic. 'subprog_cnt' should not be increased.
2454 	 */
2455 	subprog[env->subprog_cnt].start = insn_cnt;
2456 
2457 	if (env->log.level & BPF_LOG_LEVEL2)
2458 		for (i = 0; i < env->subprog_cnt; i++)
2459 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2460 
2461 	return 0;
2462 }
2463 
2464 static int check_subprogs(struct bpf_verifier_env *env)
2465 {
2466 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2467 	struct bpf_subprog_info *subprog = env->subprog_info;
2468 	struct bpf_insn *insn = env->prog->insnsi;
2469 	int insn_cnt = env->prog->len;
2470 
2471 	/* now check that all jumps are within the same subprog */
2472 	subprog_start = subprog[cur_subprog].start;
2473 	subprog_end = subprog[cur_subprog + 1].start;
2474 	for (i = 0; i < insn_cnt; i++) {
2475 		u8 code = insn[i].code;
2476 
2477 		if (code == (BPF_JMP | BPF_CALL) &&
2478 		    insn[i].imm == BPF_FUNC_tail_call &&
2479 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2480 			subprog[cur_subprog].has_tail_call = true;
2481 		if (BPF_CLASS(code) == BPF_LD &&
2482 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2483 			subprog[cur_subprog].has_ld_abs = true;
2484 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2485 			goto next;
2486 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2487 			goto next;
2488 		off = i + insn[i].off + 1;
2489 		if (off < subprog_start || off >= subprog_end) {
2490 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2491 			return -EINVAL;
2492 		}
2493 next:
2494 		if (i == subprog_end - 1) {
2495 			/* to avoid fall-through from one subprog into another
2496 			 * the last insn of the subprog should be either exit
2497 			 * or unconditional jump back
2498 			 */
2499 			if (code != (BPF_JMP | BPF_EXIT) &&
2500 			    code != (BPF_JMP | BPF_JA)) {
2501 				verbose(env, "last insn is not an exit or jmp\n");
2502 				return -EINVAL;
2503 			}
2504 			subprog_start = subprog_end;
2505 			cur_subprog++;
2506 			if (cur_subprog < env->subprog_cnt)
2507 				subprog_end = subprog[cur_subprog + 1].start;
2508 		}
2509 	}
2510 	return 0;
2511 }
2512 
2513 /* Parentage chain of this register (or stack slot) should take care of all
2514  * issues like callee-saved registers, stack slot allocation time, etc.
2515  */
2516 static int mark_reg_read(struct bpf_verifier_env *env,
2517 			 const struct bpf_reg_state *state,
2518 			 struct bpf_reg_state *parent, u8 flag)
2519 {
2520 	bool writes = parent == state->parent; /* Observe write marks */
2521 	int cnt = 0;
2522 
2523 	while (parent) {
2524 		/* if read wasn't screened by an earlier write ... */
2525 		if (writes && state->live & REG_LIVE_WRITTEN)
2526 			break;
2527 		if (parent->live & REG_LIVE_DONE) {
2528 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2529 				reg_type_str(env, parent->type),
2530 				parent->var_off.value, parent->off);
2531 			return -EFAULT;
2532 		}
2533 		/* The first condition is more likely to be true than the
2534 		 * second, checked it first.
2535 		 */
2536 		if ((parent->live & REG_LIVE_READ) == flag ||
2537 		    parent->live & REG_LIVE_READ64)
2538 			/* The parentage chain never changes and
2539 			 * this parent was already marked as LIVE_READ.
2540 			 * There is no need to keep walking the chain again and
2541 			 * keep re-marking all parents as LIVE_READ.
2542 			 * This case happens when the same register is read
2543 			 * multiple times without writes into it in-between.
2544 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2545 			 * then no need to set the weak REG_LIVE_READ32.
2546 			 */
2547 			break;
2548 		/* ... then we depend on parent's value */
2549 		parent->live |= flag;
2550 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2551 		if (flag == REG_LIVE_READ64)
2552 			parent->live &= ~REG_LIVE_READ32;
2553 		state = parent;
2554 		parent = state->parent;
2555 		writes = true;
2556 		cnt++;
2557 	}
2558 
2559 	if (env->longest_mark_read_walk < cnt)
2560 		env->longest_mark_read_walk = cnt;
2561 	return 0;
2562 }
2563 
2564 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2565 {
2566 	struct bpf_func_state *state = func(env, reg);
2567 	int spi, ret;
2568 
2569 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2570 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2571 	 * check_kfunc_call.
2572 	 */
2573 	if (reg->type == CONST_PTR_TO_DYNPTR)
2574 		return 0;
2575 	spi = dynptr_get_spi(env, reg);
2576 	if (spi < 0)
2577 		return spi;
2578 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2579 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2580 	 * read.
2581 	 */
2582 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2583 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2584 	if (ret)
2585 		return ret;
2586 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2587 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2588 }
2589 
2590 /* This function is supposed to be used by the following 32-bit optimization
2591  * code only. It returns TRUE if the source or destination register operates
2592  * on 64-bit, otherwise return FALSE.
2593  */
2594 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2595 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2596 {
2597 	u8 code, class, op;
2598 
2599 	code = insn->code;
2600 	class = BPF_CLASS(code);
2601 	op = BPF_OP(code);
2602 	if (class == BPF_JMP) {
2603 		/* BPF_EXIT for "main" will reach here. Return TRUE
2604 		 * conservatively.
2605 		 */
2606 		if (op == BPF_EXIT)
2607 			return true;
2608 		if (op == BPF_CALL) {
2609 			/* BPF to BPF call will reach here because of marking
2610 			 * caller saved clobber with DST_OP_NO_MARK for which we
2611 			 * don't care the register def because they are anyway
2612 			 * marked as NOT_INIT already.
2613 			 */
2614 			if (insn->src_reg == BPF_PSEUDO_CALL)
2615 				return false;
2616 			/* Helper call will reach here because of arg type
2617 			 * check, conservatively return TRUE.
2618 			 */
2619 			if (t == SRC_OP)
2620 				return true;
2621 
2622 			return false;
2623 		}
2624 	}
2625 
2626 	if (class == BPF_ALU64 || class == BPF_JMP ||
2627 	    /* BPF_END always use BPF_ALU class. */
2628 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2629 		return true;
2630 
2631 	if (class == BPF_ALU || class == BPF_JMP32)
2632 		return false;
2633 
2634 	if (class == BPF_LDX) {
2635 		if (t != SRC_OP)
2636 			return BPF_SIZE(code) == BPF_DW;
2637 		/* LDX source must be ptr. */
2638 		return true;
2639 	}
2640 
2641 	if (class == BPF_STX) {
2642 		/* BPF_STX (including atomic variants) has multiple source
2643 		 * operands, one of which is a ptr. Check whether the caller is
2644 		 * asking about it.
2645 		 */
2646 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2647 			return true;
2648 		return BPF_SIZE(code) == BPF_DW;
2649 	}
2650 
2651 	if (class == BPF_LD) {
2652 		u8 mode = BPF_MODE(code);
2653 
2654 		/* LD_IMM64 */
2655 		if (mode == BPF_IMM)
2656 			return true;
2657 
2658 		/* Both LD_IND and LD_ABS return 32-bit data. */
2659 		if (t != SRC_OP)
2660 			return  false;
2661 
2662 		/* Implicit ctx ptr. */
2663 		if (regno == BPF_REG_6)
2664 			return true;
2665 
2666 		/* Explicit source could be any width. */
2667 		return true;
2668 	}
2669 
2670 	if (class == BPF_ST)
2671 		/* The only source register for BPF_ST is a ptr. */
2672 		return true;
2673 
2674 	/* Conservatively return true at default. */
2675 	return true;
2676 }
2677 
2678 /* Return the regno defined by the insn, or -1. */
2679 static int insn_def_regno(const struct bpf_insn *insn)
2680 {
2681 	switch (BPF_CLASS(insn->code)) {
2682 	case BPF_JMP:
2683 	case BPF_JMP32:
2684 	case BPF_ST:
2685 		return -1;
2686 	case BPF_STX:
2687 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2688 		    (insn->imm & BPF_FETCH)) {
2689 			if (insn->imm == BPF_CMPXCHG)
2690 				return BPF_REG_0;
2691 			else
2692 				return insn->src_reg;
2693 		} else {
2694 			return -1;
2695 		}
2696 	default:
2697 		return insn->dst_reg;
2698 	}
2699 }
2700 
2701 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2702 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2703 {
2704 	int dst_reg = insn_def_regno(insn);
2705 
2706 	if (dst_reg == -1)
2707 		return false;
2708 
2709 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2710 }
2711 
2712 static void mark_insn_zext(struct bpf_verifier_env *env,
2713 			   struct bpf_reg_state *reg)
2714 {
2715 	s32 def_idx = reg->subreg_def;
2716 
2717 	if (def_idx == DEF_NOT_SUBREG)
2718 		return;
2719 
2720 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2721 	/* The dst will be zero extended, so won't be sub-register anymore. */
2722 	reg->subreg_def = DEF_NOT_SUBREG;
2723 }
2724 
2725 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2726 			 enum reg_arg_type t)
2727 {
2728 	struct bpf_verifier_state *vstate = env->cur_state;
2729 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2730 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2731 	struct bpf_reg_state *reg, *regs = state->regs;
2732 	bool rw64;
2733 
2734 	if (regno >= MAX_BPF_REG) {
2735 		verbose(env, "R%d is invalid\n", regno);
2736 		return -EINVAL;
2737 	}
2738 
2739 	mark_reg_scratched(env, regno);
2740 
2741 	reg = &regs[regno];
2742 	rw64 = is_reg64(env, insn, regno, reg, t);
2743 	if (t == SRC_OP) {
2744 		/* check whether register used as source operand can be read */
2745 		if (reg->type == NOT_INIT) {
2746 			verbose(env, "R%d !read_ok\n", regno);
2747 			return -EACCES;
2748 		}
2749 		/* We don't need to worry about FP liveness because it's read-only */
2750 		if (regno == BPF_REG_FP)
2751 			return 0;
2752 
2753 		if (rw64)
2754 			mark_insn_zext(env, reg);
2755 
2756 		return mark_reg_read(env, reg, reg->parent,
2757 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2758 	} else {
2759 		/* check whether register used as dest operand can be written to */
2760 		if (regno == BPF_REG_FP) {
2761 			verbose(env, "frame pointer is read only\n");
2762 			return -EACCES;
2763 		}
2764 		reg->live |= REG_LIVE_WRITTEN;
2765 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2766 		if (t == DST_OP)
2767 			mark_reg_unknown(env, regs, regno);
2768 	}
2769 	return 0;
2770 }
2771 
2772 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2773 {
2774 	env->insn_aux_data[idx].jmp_point = true;
2775 }
2776 
2777 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2778 {
2779 	return env->insn_aux_data[insn_idx].jmp_point;
2780 }
2781 
2782 /* for any branch, call, exit record the history of jmps in the given state */
2783 static int push_jmp_history(struct bpf_verifier_env *env,
2784 			    struct bpf_verifier_state *cur)
2785 {
2786 	u32 cnt = cur->jmp_history_cnt;
2787 	struct bpf_idx_pair *p;
2788 	size_t alloc_size;
2789 
2790 	if (!is_jmp_point(env, env->insn_idx))
2791 		return 0;
2792 
2793 	cnt++;
2794 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2795 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2796 	if (!p)
2797 		return -ENOMEM;
2798 	p[cnt - 1].idx = env->insn_idx;
2799 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2800 	cur->jmp_history = p;
2801 	cur->jmp_history_cnt = cnt;
2802 	return 0;
2803 }
2804 
2805 /* Backtrack one insn at a time. If idx is not at the top of recorded
2806  * history then previous instruction came from straight line execution.
2807  */
2808 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2809 			     u32 *history)
2810 {
2811 	u32 cnt = *history;
2812 
2813 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2814 		i = st->jmp_history[cnt - 1].prev_idx;
2815 		(*history)--;
2816 	} else {
2817 		i--;
2818 	}
2819 	return i;
2820 }
2821 
2822 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2823 {
2824 	const struct btf_type *func;
2825 	struct btf *desc_btf;
2826 
2827 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2828 		return NULL;
2829 
2830 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2831 	if (IS_ERR(desc_btf))
2832 		return "<error>";
2833 
2834 	func = btf_type_by_id(desc_btf, insn->imm);
2835 	return btf_name_by_offset(desc_btf, func->name_off);
2836 }
2837 
2838 /* For given verifier state backtrack_insn() is called from the last insn to
2839  * the first insn. Its purpose is to compute a bitmask of registers and
2840  * stack slots that needs precision in the parent verifier state.
2841  */
2842 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2843 			  u32 *reg_mask, u64 *stack_mask)
2844 {
2845 	const struct bpf_insn_cbs cbs = {
2846 		.cb_call	= disasm_kfunc_name,
2847 		.cb_print	= verbose,
2848 		.private_data	= env,
2849 	};
2850 	struct bpf_insn *insn = env->prog->insnsi + idx;
2851 	u8 class = BPF_CLASS(insn->code);
2852 	u8 opcode = BPF_OP(insn->code);
2853 	u8 mode = BPF_MODE(insn->code);
2854 	u32 dreg = 1u << insn->dst_reg;
2855 	u32 sreg = 1u << insn->src_reg;
2856 	u32 spi;
2857 
2858 	if (insn->code == 0)
2859 		return 0;
2860 	if (env->log.level & BPF_LOG_LEVEL2) {
2861 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2862 		verbose(env, "%d: ", idx);
2863 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2864 	}
2865 
2866 	if (class == BPF_ALU || class == BPF_ALU64) {
2867 		if (!(*reg_mask & dreg))
2868 			return 0;
2869 		if (opcode == BPF_MOV) {
2870 			if (BPF_SRC(insn->code) == BPF_X) {
2871 				/* dreg = sreg
2872 				 * dreg needs precision after this insn
2873 				 * sreg needs precision before this insn
2874 				 */
2875 				*reg_mask &= ~dreg;
2876 				*reg_mask |= sreg;
2877 			} else {
2878 				/* dreg = K
2879 				 * dreg needs precision after this insn.
2880 				 * Corresponding register is already marked
2881 				 * as precise=true in this verifier state.
2882 				 * No further markings in parent are necessary
2883 				 */
2884 				*reg_mask &= ~dreg;
2885 			}
2886 		} else {
2887 			if (BPF_SRC(insn->code) == BPF_X) {
2888 				/* dreg += sreg
2889 				 * both dreg and sreg need precision
2890 				 * before this insn
2891 				 */
2892 				*reg_mask |= sreg;
2893 			} /* else dreg += K
2894 			   * dreg still needs precision before this insn
2895 			   */
2896 		}
2897 	} else if (class == BPF_LDX) {
2898 		if (!(*reg_mask & dreg))
2899 			return 0;
2900 		*reg_mask &= ~dreg;
2901 
2902 		/* scalars can only be spilled into stack w/o losing precision.
2903 		 * Load from any other memory can be zero extended.
2904 		 * The desire to keep that precision is already indicated
2905 		 * by 'precise' mark in corresponding register of this state.
2906 		 * No further tracking necessary.
2907 		 */
2908 		if (insn->src_reg != BPF_REG_FP)
2909 			return 0;
2910 
2911 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2912 		 * that [fp - off] slot contains scalar that needs to be
2913 		 * tracked with precision
2914 		 */
2915 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2916 		if (spi >= 64) {
2917 			verbose(env, "BUG spi %d\n", spi);
2918 			WARN_ONCE(1, "verifier backtracking bug");
2919 			return -EFAULT;
2920 		}
2921 		*stack_mask |= 1ull << spi;
2922 	} else if (class == BPF_STX || class == BPF_ST) {
2923 		if (*reg_mask & dreg)
2924 			/* stx & st shouldn't be using _scalar_ dst_reg
2925 			 * to access memory. It means backtracking
2926 			 * encountered a case of pointer subtraction.
2927 			 */
2928 			return -ENOTSUPP;
2929 		/* scalars can only be spilled into stack */
2930 		if (insn->dst_reg != BPF_REG_FP)
2931 			return 0;
2932 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2933 		if (spi >= 64) {
2934 			verbose(env, "BUG spi %d\n", spi);
2935 			WARN_ONCE(1, "verifier backtracking bug");
2936 			return -EFAULT;
2937 		}
2938 		if (!(*stack_mask & (1ull << spi)))
2939 			return 0;
2940 		*stack_mask &= ~(1ull << spi);
2941 		if (class == BPF_STX)
2942 			*reg_mask |= sreg;
2943 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2944 		if (opcode == BPF_CALL) {
2945 			if (insn->src_reg == BPF_PSEUDO_CALL)
2946 				return -ENOTSUPP;
2947 			/* BPF helpers that invoke callback subprogs are
2948 			 * equivalent to BPF_PSEUDO_CALL above
2949 			 */
2950 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2951 				return -ENOTSUPP;
2952 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2953 			 * catch this error later. Make backtracking conservative
2954 			 * with ENOTSUPP.
2955 			 */
2956 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2957 				return -ENOTSUPP;
2958 			/* regular helper call sets R0 */
2959 			*reg_mask &= ~1;
2960 			if (*reg_mask & 0x3f) {
2961 				/* if backtracing was looking for registers R1-R5
2962 				 * they should have been found already.
2963 				 */
2964 				verbose(env, "BUG regs %x\n", *reg_mask);
2965 				WARN_ONCE(1, "verifier backtracking bug");
2966 				return -EFAULT;
2967 			}
2968 		} else if (opcode == BPF_EXIT) {
2969 			return -ENOTSUPP;
2970 		}
2971 	} else if (class == BPF_LD) {
2972 		if (!(*reg_mask & dreg))
2973 			return 0;
2974 		*reg_mask &= ~dreg;
2975 		/* It's ld_imm64 or ld_abs or ld_ind.
2976 		 * For ld_imm64 no further tracking of precision
2977 		 * into parent is necessary
2978 		 */
2979 		if (mode == BPF_IND || mode == BPF_ABS)
2980 			/* to be analyzed */
2981 			return -ENOTSUPP;
2982 	}
2983 	return 0;
2984 }
2985 
2986 /* the scalar precision tracking algorithm:
2987  * . at the start all registers have precise=false.
2988  * . scalar ranges are tracked as normal through alu and jmp insns.
2989  * . once precise value of the scalar register is used in:
2990  *   .  ptr + scalar alu
2991  *   . if (scalar cond K|scalar)
2992  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2993  *   backtrack through the verifier states and mark all registers and
2994  *   stack slots with spilled constants that these scalar regisers
2995  *   should be precise.
2996  * . during state pruning two registers (or spilled stack slots)
2997  *   are equivalent if both are not precise.
2998  *
2999  * Note the verifier cannot simply walk register parentage chain,
3000  * since many different registers and stack slots could have been
3001  * used to compute single precise scalar.
3002  *
3003  * The approach of starting with precise=true for all registers and then
3004  * backtrack to mark a register as not precise when the verifier detects
3005  * that program doesn't care about specific value (e.g., when helper
3006  * takes register as ARG_ANYTHING parameter) is not safe.
3007  *
3008  * It's ok to walk single parentage chain of the verifier states.
3009  * It's possible that this backtracking will go all the way till 1st insn.
3010  * All other branches will be explored for needing precision later.
3011  *
3012  * The backtracking needs to deal with cases like:
3013  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3014  * r9 -= r8
3015  * r5 = r9
3016  * if r5 > 0x79f goto pc+7
3017  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3018  * r5 += 1
3019  * ...
3020  * call bpf_perf_event_output#25
3021  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3022  *
3023  * and this case:
3024  * r6 = 1
3025  * call foo // uses callee's r6 inside to compute r0
3026  * r0 += r6
3027  * if r0 == 0 goto
3028  *
3029  * to track above reg_mask/stack_mask needs to be independent for each frame.
3030  *
3031  * Also if parent's curframe > frame where backtracking started,
3032  * the verifier need to mark registers in both frames, otherwise callees
3033  * may incorrectly prune callers. This is similar to
3034  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3035  *
3036  * For now backtracking falls back into conservative marking.
3037  */
3038 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3039 				     struct bpf_verifier_state *st)
3040 {
3041 	struct bpf_func_state *func;
3042 	struct bpf_reg_state *reg;
3043 	int i, j;
3044 
3045 	/* big hammer: mark all scalars precise in this path.
3046 	 * pop_stack may still get !precise scalars.
3047 	 * We also skip current state and go straight to first parent state,
3048 	 * because precision markings in current non-checkpointed state are
3049 	 * not needed. See why in the comment in __mark_chain_precision below.
3050 	 */
3051 	for (st = st->parent; st; st = st->parent) {
3052 		for (i = 0; i <= st->curframe; i++) {
3053 			func = st->frame[i];
3054 			for (j = 0; j < BPF_REG_FP; j++) {
3055 				reg = &func->regs[j];
3056 				if (reg->type != SCALAR_VALUE)
3057 					continue;
3058 				reg->precise = true;
3059 			}
3060 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3061 				if (!is_spilled_reg(&func->stack[j]))
3062 					continue;
3063 				reg = &func->stack[j].spilled_ptr;
3064 				if (reg->type != SCALAR_VALUE)
3065 					continue;
3066 				reg->precise = true;
3067 			}
3068 		}
3069 	}
3070 }
3071 
3072 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3073 {
3074 	struct bpf_func_state *func;
3075 	struct bpf_reg_state *reg;
3076 	int i, j;
3077 
3078 	for (i = 0; i <= st->curframe; i++) {
3079 		func = st->frame[i];
3080 		for (j = 0; j < BPF_REG_FP; j++) {
3081 			reg = &func->regs[j];
3082 			if (reg->type != SCALAR_VALUE)
3083 				continue;
3084 			reg->precise = false;
3085 		}
3086 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3087 			if (!is_spilled_reg(&func->stack[j]))
3088 				continue;
3089 			reg = &func->stack[j].spilled_ptr;
3090 			if (reg->type != SCALAR_VALUE)
3091 				continue;
3092 			reg->precise = false;
3093 		}
3094 	}
3095 }
3096 
3097 /*
3098  * __mark_chain_precision() backtracks BPF program instruction sequence and
3099  * chain of verifier states making sure that register *regno* (if regno >= 0)
3100  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3101  * SCALARS, as well as any other registers and slots that contribute to
3102  * a tracked state of given registers/stack slots, depending on specific BPF
3103  * assembly instructions (see backtrack_insns() for exact instruction handling
3104  * logic). This backtracking relies on recorded jmp_history and is able to
3105  * traverse entire chain of parent states. This process ends only when all the
3106  * necessary registers/slots and their transitive dependencies are marked as
3107  * precise.
3108  *
3109  * One important and subtle aspect is that precise marks *do not matter* in
3110  * the currently verified state (current state). It is important to understand
3111  * why this is the case.
3112  *
3113  * First, note that current state is the state that is not yet "checkpointed",
3114  * i.e., it is not yet put into env->explored_states, and it has no children
3115  * states as well. It's ephemeral, and can end up either a) being discarded if
3116  * compatible explored state is found at some point or BPF_EXIT instruction is
3117  * reached or b) checkpointed and put into env->explored_states, branching out
3118  * into one or more children states.
3119  *
3120  * In the former case, precise markings in current state are completely
3121  * ignored by state comparison code (see regsafe() for details). Only
3122  * checkpointed ("old") state precise markings are important, and if old
3123  * state's register/slot is precise, regsafe() assumes current state's
3124  * register/slot as precise and checks value ranges exactly and precisely. If
3125  * states turn out to be compatible, current state's necessary precise
3126  * markings and any required parent states' precise markings are enforced
3127  * after the fact with propagate_precision() logic, after the fact. But it's
3128  * important to realize that in this case, even after marking current state
3129  * registers/slots as precise, we immediately discard current state. So what
3130  * actually matters is any of the precise markings propagated into current
3131  * state's parent states, which are always checkpointed (due to b) case above).
3132  * As such, for scenario a) it doesn't matter if current state has precise
3133  * markings set or not.
3134  *
3135  * Now, for the scenario b), checkpointing and forking into child(ren)
3136  * state(s). Note that before current state gets to checkpointing step, any
3137  * processed instruction always assumes precise SCALAR register/slot
3138  * knowledge: if precise value or range is useful to prune jump branch, BPF
3139  * verifier takes this opportunity enthusiastically. Similarly, when
3140  * register's value is used to calculate offset or memory address, exact
3141  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3142  * what we mentioned above about state comparison ignoring precise markings
3143  * during state comparison, BPF verifier ignores and also assumes precise
3144  * markings *at will* during instruction verification process. But as verifier
3145  * assumes precision, it also propagates any precision dependencies across
3146  * parent states, which are not yet finalized, so can be further restricted
3147  * based on new knowledge gained from restrictions enforced by their children
3148  * states. This is so that once those parent states are finalized, i.e., when
3149  * they have no more active children state, state comparison logic in
3150  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3151  * required for correctness.
3152  *
3153  * To build a bit more intuition, note also that once a state is checkpointed,
3154  * the path we took to get to that state is not important. This is crucial
3155  * property for state pruning. When state is checkpointed and finalized at
3156  * some instruction index, it can be correctly and safely used to "short
3157  * circuit" any *compatible* state that reaches exactly the same instruction
3158  * index. I.e., if we jumped to that instruction from a completely different
3159  * code path than original finalized state was derived from, it doesn't
3160  * matter, current state can be discarded because from that instruction
3161  * forward having a compatible state will ensure we will safely reach the
3162  * exit. States describe preconditions for further exploration, but completely
3163  * forget the history of how we got here.
3164  *
3165  * This also means that even if we needed precise SCALAR range to get to
3166  * finalized state, but from that point forward *that same* SCALAR register is
3167  * never used in a precise context (i.e., it's precise value is not needed for
3168  * correctness), it's correct and safe to mark such register as "imprecise"
3169  * (i.e., precise marking set to false). This is what we rely on when we do
3170  * not set precise marking in current state. If no child state requires
3171  * precision for any given SCALAR register, it's safe to dictate that it can
3172  * be imprecise. If any child state does require this register to be precise,
3173  * we'll mark it precise later retroactively during precise markings
3174  * propagation from child state to parent states.
3175  *
3176  * Skipping precise marking setting in current state is a mild version of
3177  * relying on the above observation. But we can utilize this property even
3178  * more aggressively by proactively forgetting any precise marking in the
3179  * current state (which we inherited from the parent state), right before we
3180  * checkpoint it and branch off into new child state. This is done by
3181  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3182  * finalized states which help in short circuiting more future states.
3183  */
3184 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3185 				  int spi)
3186 {
3187 	struct bpf_verifier_state *st = env->cur_state;
3188 	int first_idx = st->first_insn_idx;
3189 	int last_idx = env->insn_idx;
3190 	struct bpf_func_state *func;
3191 	struct bpf_reg_state *reg;
3192 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3193 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3194 	bool skip_first = true;
3195 	bool new_marks = false;
3196 	int i, err;
3197 
3198 	if (!env->bpf_capable)
3199 		return 0;
3200 
3201 	/* Do sanity checks against current state of register and/or stack
3202 	 * slot, but don't set precise flag in current state, as precision
3203 	 * tracking in the current state is unnecessary.
3204 	 */
3205 	func = st->frame[frame];
3206 	if (regno >= 0) {
3207 		reg = &func->regs[regno];
3208 		if (reg->type != SCALAR_VALUE) {
3209 			WARN_ONCE(1, "backtracing misuse");
3210 			return -EFAULT;
3211 		}
3212 		new_marks = true;
3213 	}
3214 
3215 	while (spi >= 0) {
3216 		if (!is_spilled_reg(&func->stack[spi])) {
3217 			stack_mask = 0;
3218 			break;
3219 		}
3220 		reg = &func->stack[spi].spilled_ptr;
3221 		if (reg->type != SCALAR_VALUE) {
3222 			stack_mask = 0;
3223 			break;
3224 		}
3225 		new_marks = true;
3226 		break;
3227 	}
3228 
3229 	if (!new_marks)
3230 		return 0;
3231 	if (!reg_mask && !stack_mask)
3232 		return 0;
3233 
3234 	for (;;) {
3235 		DECLARE_BITMAP(mask, 64);
3236 		u32 history = st->jmp_history_cnt;
3237 
3238 		if (env->log.level & BPF_LOG_LEVEL2)
3239 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3240 
3241 		if (last_idx < 0) {
3242 			/* we are at the entry into subprog, which
3243 			 * is expected for global funcs, but only if
3244 			 * requested precise registers are R1-R5
3245 			 * (which are global func's input arguments)
3246 			 */
3247 			if (st->curframe == 0 &&
3248 			    st->frame[0]->subprogno > 0 &&
3249 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3250 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3251 				bitmap_from_u64(mask, reg_mask);
3252 				for_each_set_bit(i, mask, 32) {
3253 					reg = &st->frame[0]->regs[i];
3254 					if (reg->type != SCALAR_VALUE) {
3255 						reg_mask &= ~(1u << i);
3256 						continue;
3257 					}
3258 					reg->precise = true;
3259 				}
3260 				return 0;
3261 			}
3262 
3263 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3264 				st->frame[0]->subprogno, reg_mask, stack_mask);
3265 			WARN_ONCE(1, "verifier backtracking bug");
3266 			return -EFAULT;
3267 		}
3268 
3269 		for (i = last_idx;;) {
3270 			if (skip_first) {
3271 				err = 0;
3272 				skip_first = false;
3273 			} else {
3274 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3275 			}
3276 			if (err == -ENOTSUPP) {
3277 				mark_all_scalars_precise(env, st);
3278 				return 0;
3279 			} else if (err) {
3280 				return err;
3281 			}
3282 			if (!reg_mask && !stack_mask)
3283 				/* Found assignment(s) into tracked register in this state.
3284 				 * Since this state is already marked, just return.
3285 				 * Nothing to be tracked further in the parent state.
3286 				 */
3287 				return 0;
3288 			if (i == first_idx)
3289 				break;
3290 			i = get_prev_insn_idx(st, i, &history);
3291 			if (i >= env->prog->len) {
3292 				/* This can happen if backtracking reached insn 0
3293 				 * and there are still reg_mask or stack_mask
3294 				 * to backtrack.
3295 				 * It means the backtracking missed the spot where
3296 				 * particular register was initialized with a constant.
3297 				 */
3298 				verbose(env, "BUG backtracking idx %d\n", i);
3299 				WARN_ONCE(1, "verifier backtracking bug");
3300 				return -EFAULT;
3301 			}
3302 		}
3303 		st = st->parent;
3304 		if (!st)
3305 			break;
3306 
3307 		new_marks = false;
3308 		func = st->frame[frame];
3309 		bitmap_from_u64(mask, reg_mask);
3310 		for_each_set_bit(i, mask, 32) {
3311 			reg = &func->regs[i];
3312 			if (reg->type != SCALAR_VALUE) {
3313 				reg_mask &= ~(1u << i);
3314 				continue;
3315 			}
3316 			if (!reg->precise)
3317 				new_marks = true;
3318 			reg->precise = true;
3319 		}
3320 
3321 		bitmap_from_u64(mask, stack_mask);
3322 		for_each_set_bit(i, mask, 64) {
3323 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3324 				/* the sequence of instructions:
3325 				 * 2: (bf) r3 = r10
3326 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3327 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3328 				 * doesn't contain jmps. It's backtracked
3329 				 * as a single block.
3330 				 * During backtracking insn 3 is not recognized as
3331 				 * stack access, so at the end of backtracking
3332 				 * stack slot fp-8 is still marked in stack_mask.
3333 				 * However the parent state may not have accessed
3334 				 * fp-8 and it's "unallocated" stack space.
3335 				 * In such case fallback to conservative.
3336 				 */
3337 				mark_all_scalars_precise(env, st);
3338 				return 0;
3339 			}
3340 
3341 			if (!is_spilled_reg(&func->stack[i])) {
3342 				stack_mask &= ~(1ull << i);
3343 				continue;
3344 			}
3345 			reg = &func->stack[i].spilled_ptr;
3346 			if (reg->type != SCALAR_VALUE) {
3347 				stack_mask &= ~(1ull << i);
3348 				continue;
3349 			}
3350 			if (!reg->precise)
3351 				new_marks = true;
3352 			reg->precise = true;
3353 		}
3354 		if (env->log.level & BPF_LOG_LEVEL2) {
3355 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3356 				new_marks ? "didn't have" : "already had",
3357 				reg_mask, stack_mask);
3358 			print_verifier_state(env, func, true);
3359 		}
3360 
3361 		if (!reg_mask && !stack_mask)
3362 			break;
3363 		if (!new_marks)
3364 			break;
3365 
3366 		last_idx = st->last_insn_idx;
3367 		first_idx = st->first_insn_idx;
3368 	}
3369 	return 0;
3370 }
3371 
3372 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3373 {
3374 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3375 }
3376 
3377 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3378 {
3379 	return __mark_chain_precision(env, frame, regno, -1);
3380 }
3381 
3382 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3383 {
3384 	return __mark_chain_precision(env, frame, -1, spi);
3385 }
3386 
3387 static bool is_spillable_regtype(enum bpf_reg_type type)
3388 {
3389 	switch (base_type(type)) {
3390 	case PTR_TO_MAP_VALUE:
3391 	case PTR_TO_STACK:
3392 	case PTR_TO_CTX:
3393 	case PTR_TO_PACKET:
3394 	case PTR_TO_PACKET_META:
3395 	case PTR_TO_PACKET_END:
3396 	case PTR_TO_FLOW_KEYS:
3397 	case CONST_PTR_TO_MAP:
3398 	case PTR_TO_SOCKET:
3399 	case PTR_TO_SOCK_COMMON:
3400 	case PTR_TO_TCP_SOCK:
3401 	case PTR_TO_XDP_SOCK:
3402 	case PTR_TO_BTF_ID:
3403 	case PTR_TO_BUF:
3404 	case PTR_TO_MEM:
3405 	case PTR_TO_FUNC:
3406 	case PTR_TO_MAP_KEY:
3407 		return true;
3408 	default:
3409 		return false;
3410 	}
3411 }
3412 
3413 /* Does this register contain a constant zero? */
3414 static bool register_is_null(struct bpf_reg_state *reg)
3415 {
3416 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3417 }
3418 
3419 static bool register_is_const(struct bpf_reg_state *reg)
3420 {
3421 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3422 }
3423 
3424 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3425 {
3426 	return tnum_is_unknown(reg->var_off) &&
3427 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3428 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3429 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3430 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3431 }
3432 
3433 static bool register_is_bounded(struct bpf_reg_state *reg)
3434 {
3435 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3436 }
3437 
3438 static bool __is_pointer_value(bool allow_ptr_leaks,
3439 			       const struct bpf_reg_state *reg)
3440 {
3441 	if (allow_ptr_leaks)
3442 		return false;
3443 
3444 	return reg->type != SCALAR_VALUE;
3445 }
3446 
3447 /* Copy src state preserving dst->parent and dst->live fields */
3448 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3449 {
3450 	struct bpf_reg_state *parent = dst->parent;
3451 	enum bpf_reg_liveness live = dst->live;
3452 
3453 	*dst = *src;
3454 	dst->parent = parent;
3455 	dst->live = live;
3456 }
3457 
3458 static void save_register_state(struct bpf_func_state *state,
3459 				int spi, struct bpf_reg_state *reg,
3460 				int size)
3461 {
3462 	int i;
3463 
3464 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
3465 	if (size == BPF_REG_SIZE)
3466 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3467 
3468 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3469 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3470 
3471 	/* size < 8 bytes spill */
3472 	for (; i; i--)
3473 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3474 }
3475 
3476 static bool is_bpf_st_mem(struct bpf_insn *insn)
3477 {
3478 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3479 }
3480 
3481 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3482  * stack boundary and alignment are checked in check_mem_access()
3483  */
3484 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3485 				       /* stack frame we're writing to */
3486 				       struct bpf_func_state *state,
3487 				       int off, int size, int value_regno,
3488 				       int insn_idx)
3489 {
3490 	struct bpf_func_state *cur; /* state of the current function */
3491 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3492 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3493 	struct bpf_reg_state *reg = NULL;
3494 	u32 dst_reg = insn->dst_reg;
3495 
3496 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3497 	if (err)
3498 		return err;
3499 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3500 	 * so it's aligned access and [off, off + size) are within stack limits
3501 	 */
3502 	if (!env->allow_ptr_leaks &&
3503 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3504 	    size != BPF_REG_SIZE) {
3505 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3506 		return -EACCES;
3507 	}
3508 
3509 	cur = env->cur_state->frame[env->cur_state->curframe];
3510 	if (value_regno >= 0)
3511 		reg = &cur->regs[value_regno];
3512 	if (!env->bypass_spec_v4) {
3513 		bool sanitize = reg && is_spillable_regtype(reg->type);
3514 
3515 		for (i = 0; i < size; i++) {
3516 			u8 type = state->stack[spi].slot_type[i];
3517 
3518 			if (type != STACK_MISC && type != STACK_ZERO) {
3519 				sanitize = true;
3520 				break;
3521 			}
3522 		}
3523 
3524 		if (sanitize)
3525 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3526 	}
3527 
3528 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3529 	if (err)
3530 		return err;
3531 
3532 	mark_stack_slot_scratched(env, spi);
3533 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3534 	    !register_is_null(reg) && env->bpf_capable) {
3535 		if (dst_reg != BPF_REG_FP) {
3536 			/* The backtracking logic can only recognize explicit
3537 			 * stack slot address like [fp - 8]. Other spill of
3538 			 * scalar via different register has to be conservative.
3539 			 * Backtrack from here and mark all registers as precise
3540 			 * that contributed into 'reg' being a constant.
3541 			 */
3542 			err = mark_chain_precision(env, value_regno);
3543 			if (err)
3544 				return err;
3545 		}
3546 		save_register_state(state, spi, reg, size);
3547 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3548 		   insn->imm != 0 && env->bpf_capable) {
3549 		struct bpf_reg_state fake_reg = {};
3550 
3551 		__mark_reg_known(&fake_reg, (u32)insn->imm);
3552 		fake_reg.type = SCALAR_VALUE;
3553 		save_register_state(state, spi, &fake_reg, size);
3554 	} else if (reg && is_spillable_regtype(reg->type)) {
3555 		/* register containing pointer is being spilled into stack */
3556 		if (size != BPF_REG_SIZE) {
3557 			verbose_linfo(env, insn_idx, "; ");
3558 			verbose(env, "invalid size of register spill\n");
3559 			return -EACCES;
3560 		}
3561 		if (state != cur && reg->type == PTR_TO_STACK) {
3562 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3563 			return -EINVAL;
3564 		}
3565 		save_register_state(state, spi, reg, size);
3566 	} else {
3567 		u8 type = STACK_MISC;
3568 
3569 		/* regular write of data into stack destroys any spilled ptr */
3570 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3571 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3572 		if (is_spilled_reg(&state->stack[spi]))
3573 			for (i = 0; i < BPF_REG_SIZE; i++)
3574 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3575 
3576 		/* only mark the slot as written if all 8 bytes were written
3577 		 * otherwise read propagation may incorrectly stop too soon
3578 		 * when stack slots are partially written.
3579 		 * This heuristic means that read propagation will be
3580 		 * conservative, since it will add reg_live_read marks
3581 		 * to stack slots all the way to first state when programs
3582 		 * writes+reads less than 8 bytes
3583 		 */
3584 		if (size == BPF_REG_SIZE)
3585 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3586 
3587 		/* when we zero initialize stack slots mark them as such */
3588 		if ((reg && register_is_null(reg)) ||
3589 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3590 			/* backtracking doesn't work for STACK_ZERO yet. */
3591 			err = mark_chain_precision(env, value_regno);
3592 			if (err)
3593 				return err;
3594 			type = STACK_ZERO;
3595 		}
3596 
3597 		/* Mark slots affected by this stack write. */
3598 		for (i = 0; i < size; i++)
3599 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3600 				type;
3601 	}
3602 	return 0;
3603 }
3604 
3605 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3606  * known to contain a variable offset.
3607  * This function checks whether the write is permitted and conservatively
3608  * tracks the effects of the write, considering that each stack slot in the
3609  * dynamic range is potentially written to.
3610  *
3611  * 'off' includes 'regno->off'.
3612  * 'value_regno' can be -1, meaning that an unknown value is being written to
3613  * the stack.
3614  *
3615  * Spilled pointers in range are not marked as written because we don't know
3616  * what's going to be actually written. This means that read propagation for
3617  * future reads cannot be terminated by this write.
3618  *
3619  * For privileged programs, uninitialized stack slots are considered
3620  * initialized by this write (even though we don't know exactly what offsets
3621  * are going to be written to). The idea is that we don't want the verifier to
3622  * reject future reads that access slots written to through variable offsets.
3623  */
3624 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3625 				     /* func where register points to */
3626 				     struct bpf_func_state *state,
3627 				     int ptr_regno, int off, int size,
3628 				     int value_regno, int insn_idx)
3629 {
3630 	struct bpf_func_state *cur; /* state of the current function */
3631 	int min_off, max_off;
3632 	int i, err;
3633 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3634 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3635 	bool writing_zero = false;
3636 	/* set if the fact that we're writing a zero is used to let any
3637 	 * stack slots remain STACK_ZERO
3638 	 */
3639 	bool zero_used = false;
3640 
3641 	cur = env->cur_state->frame[env->cur_state->curframe];
3642 	ptr_reg = &cur->regs[ptr_regno];
3643 	min_off = ptr_reg->smin_value + off;
3644 	max_off = ptr_reg->smax_value + off + size;
3645 	if (value_regno >= 0)
3646 		value_reg = &cur->regs[value_regno];
3647 	if ((value_reg && register_is_null(value_reg)) ||
3648 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3649 		writing_zero = true;
3650 
3651 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3652 	if (err)
3653 		return err;
3654 
3655 	for (i = min_off; i < max_off; i++) {
3656 		int spi;
3657 
3658 		spi = __get_spi(i);
3659 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3660 		if (err)
3661 			return err;
3662 	}
3663 
3664 	/* Variable offset writes destroy any spilled pointers in range. */
3665 	for (i = min_off; i < max_off; i++) {
3666 		u8 new_type, *stype;
3667 		int slot, spi;
3668 
3669 		slot = -i - 1;
3670 		spi = slot / BPF_REG_SIZE;
3671 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3672 		mark_stack_slot_scratched(env, spi);
3673 
3674 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3675 			/* Reject the write if range we may write to has not
3676 			 * been initialized beforehand. If we didn't reject
3677 			 * here, the ptr status would be erased below (even
3678 			 * though not all slots are actually overwritten),
3679 			 * possibly opening the door to leaks.
3680 			 *
3681 			 * We do however catch STACK_INVALID case below, and
3682 			 * only allow reading possibly uninitialized memory
3683 			 * later for CAP_PERFMON, as the write may not happen to
3684 			 * that slot.
3685 			 */
3686 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3687 				insn_idx, i);
3688 			return -EINVAL;
3689 		}
3690 
3691 		/* Erase all spilled pointers. */
3692 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3693 
3694 		/* Update the slot type. */
3695 		new_type = STACK_MISC;
3696 		if (writing_zero && *stype == STACK_ZERO) {
3697 			new_type = STACK_ZERO;
3698 			zero_used = true;
3699 		}
3700 		/* If the slot is STACK_INVALID, we check whether it's OK to
3701 		 * pretend that it will be initialized by this write. The slot
3702 		 * might not actually be written to, and so if we mark it as
3703 		 * initialized future reads might leak uninitialized memory.
3704 		 * For privileged programs, we will accept such reads to slots
3705 		 * that may or may not be written because, if we're reject
3706 		 * them, the error would be too confusing.
3707 		 */
3708 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3709 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3710 					insn_idx, i);
3711 			return -EINVAL;
3712 		}
3713 		*stype = new_type;
3714 	}
3715 	if (zero_used) {
3716 		/* backtracking doesn't work for STACK_ZERO yet. */
3717 		err = mark_chain_precision(env, value_regno);
3718 		if (err)
3719 			return err;
3720 	}
3721 	return 0;
3722 }
3723 
3724 /* When register 'dst_regno' is assigned some values from stack[min_off,
3725  * max_off), we set the register's type according to the types of the
3726  * respective stack slots. If all the stack values are known to be zeros, then
3727  * so is the destination reg. Otherwise, the register is considered to be
3728  * SCALAR. This function does not deal with register filling; the caller must
3729  * ensure that all spilled registers in the stack range have been marked as
3730  * read.
3731  */
3732 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3733 				/* func where src register points to */
3734 				struct bpf_func_state *ptr_state,
3735 				int min_off, int max_off, int dst_regno)
3736 {
3737 	struct bpf_verifier_state *vstate = env->cur_state;
3738 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3739 	int i, slot, spi;
3740 	u8 *stype;
3741 	int zeros = 0;
3742 
3743 	for (i = min_off; i < max_off; i++) {
3744 		slot = -i - 1;
3745 		spi = slot / BPF_REG_SIZE;
3746 		stype = ptr_state->stack[spi].slot_type;
3747 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3748 			break;
3749 		zeros++;
3750 	}
3751 	if (zeros == max_off - min_off) {
3752 		/* any access_size read into register is zero extended,
3753 		 * so the whole register == const_zero
3754 		 */
3755 		__mark_reg_const_zero(&state->regs[dst_regno]);
3756 		/* backtracking doesn't support STACK_ZERO yet,
3757 		 * so mark it precise here, so that later
3758 		 * backtracking can stop here.
3759 		 * Backtracking may not need this if this register
3760 		 * doesn't participate in pointer adjustment.
3761 		 * Forward propagation of precise flag is not
3762 		 * necessary either. This mark is only to stop
3763 		 * backtracking. Any register that contributed
3764 		 * to const 0 was marked precise before spill.
3765 		 */
3766 		state->regs[dst_regno].precise = true;
3767 	} else {
3768 		/* have read misc data from the stack */
3769 		mark_reg_unknown(env, state->regs, dst_regno);
3770 	}
3771 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3772 }
3773 
3774 /* Read the stack at 'off' and put the results into the register indicated by
3775  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3776  * spilled reg.
3777  *
3778  * 'dst_regno' can be -1, meaning that the read value is not going to a
3779  * register.
3780  *
3781  * The access is assumed to be within the current stack bounds.
3782  */
3783 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3784 				      /* func where src register points to */
3785 				      struct bpf_func_state *reg_state,
3786 				      int off, int size, int dst_regno)
3787 {
3788 	struct bpf_verifier_state *vstate = env->cur_state;
3789 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3790 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3791 	struct bpf_reg_state *reg;
3792 	u8 *stype, type;
3793 
3794 	stype = reg_state->stack[spi].slot_type;
3795 	reg = &reg_state->stack[spi].spilled_ptr;
3796 
3797 	if (is_spilled_reg(&reg_state->stack[spi])) {
3798 		u8 spill_size = 1;
3799 
3800 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3801 			spill_size++;
3802 
3803 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3804 			if (reg->type != SCALAR_VALUE) {
3805 				verbose_linfo(env, env->insn_idx, "; ");
3806 				verbose(env, "invalid size of register fill\n");
3807 				return -EACCES;
3808 			}
3809 
3810 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3811 			if (dst_regno < 0)
3812 				return 0;
3813 
3814 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3815 				/* The earlier check_reg_arg() has decided the
3816 				 * subreg_def for this insn.  Save it first.
3817 				 */
3818 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3819 
3820 				copy_register_state(&state->regs[dst_regno], reg);
3821 				state->regs[dst_regno].subreg_def = subreg_def;
3822 			} else {
3823 				for (i = 0; i < size; i++) {
3824 					type = stype[(slot - i) % BPF_REG_SIZE];
3825 					if (type == STACK_SPILL)
3826 						continue;
3827 					if (type == STACK_MISC)
3828 						continue;
3829 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3830 						off, i, size);
3831 					return -EACCES;
3832 				}
3833 				mark_reg_unknown(env, state->regs, dst_regno);
3834 			}
3835 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3836 			return 0;
3837 		}
3838 
3839 		if (dst_regno >= 0) {
3840 			/* restore register state from stack */
3841 			copy_register_state(&state->regs[dst_regno], reg);
3842 			/* mark reg as written since spilled pointer state likely
3843 			 * has its liveness marks cleared by is_state_visited()
3844 			 * which resets stack/reg liveness for state transitions
3845 			 */
3846 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3847 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3848 			/* If dst_regno==-1, the caller is asking us whether
3849 			 * it is acceptable to use this value as a SCALAR_VALUE
3850 			 * (e.g. for XADD).
3851 			 * We must not allow unprivileged callers to do that
3852 			 * with spilled pointers.
3853 			 */
3854 			verbose(env, "leaking pointer from stack off %d\n",
3855 				off);
3856 			return -EACCES;
3857 		}
3858 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3859 	} else {
3860 		for (i = 0; i < size; i++) {
3861 			type = stype[(slot - i) % BPF_REG_SIZE];
3862 			if (type == STACK_MISC)
3863 				continue;
3864 			if (type == STACK_ZERO)
3865 				continue;
3866 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3867 				off, i, size);
3868 			return -EACCES;
3869 		}
3870 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3871 		if (dst_regno >= 0)
3872 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3873 	}
3874 	return 0;
3875 }
3876 
3877 enum bpf_access_src {
3878 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3879 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3880 };
3881 
3882 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3883 					 int regno, int off, int access_size,
3884 					 bool zero_size_allowed,
3885 					 enum bpf_access_src type,
3886 					 struct bpf_call_arg_meta *meta);
3887 
3888 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3889 {
3890 	return cur_regs(env) + regno;
3891 }
3892 
3893 /* Read the stack at 'ptr_regno + off' and put the result into the register
3894  * 'dst_regno'.
3895  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3896  * but not its variable offset.
3897  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3898  *
3899  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3900  * filling registers (i.e. reads of spilled register cannot be detected when
3901  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3902  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3903  * offset; for a fixed offset check_stack_read_fixed_off should be used
3904  * instead.
3905  */
3906 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3907 				    int ptr_regno, int off, int size, int dst_regno)
3908 {
3909 	/* The state of the source register. */
3910 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3911 	struct bpf_func_state *ptr_state = func(env, reg);
3912 	int err;
3913 	int min_off, max_off;
3914 
3915 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3916 	 */
3917 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3918 					    false, ACCESS_DIRECT, NULL);
3919 	if (err)
3920 		return err;
3921 
3922 	min_off = reg->smin_value + off;
3923 	max_off = reg->smax_value + off;
3924 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3925 	return 0;
3926 }
3927 
3928 /* check_stack_read dispatches to check_stack_read_fixed_off or
3929  * check_stack_read_var_off.
3930  *
3931  * The caller must ensure that the offset falls within the allocated stack
3932  * bounds.
3933  *
3934  * 'dst_regno' is a register which will receive the value from the stack. It
3935  * can be -1, meaning that the read value is not going to a register.
3936  */
3937 static int check_stack_read(struct bpf_verifier_env *env,
3938 			    int ptr_regno, int off, int size,
3939 			    int dst_regno)
3940 {
3941 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3942 	struct bpf_func_state *state = func(env, reg);
3943 	int err;
3944 	/* Some accesses are only permitted with a static offset. */
3945 	bool var_off = !tnum_is_const(reg->var_off);
3946 
3947 	/* The offset is required to be static when reads don't go to a
3948 	 * register, in order to not leak pointers (see
3949 	 * check_stack_read_fixed_off).
3950 	 */
3951 	if (dst_regno < 0 && var_off) {
3952 		char tn_buf[48];
3953 
3954 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3955 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3956 			tn_buf, off, size);
3957 		return -EACCES;
3958 	}
3959 	/* Variable offset is prohibited for unprivileged mode for simplicity
3960 	 * since it requires corresponding support in Spectre masking for stack
3961 	 * ALU. See also retrieve_ptr_limit().
3962 	 */
3963 	if (!env->bypass_spec_v1 && var_off) {
3964 		char tn_buf[48];
3965 
3966 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3967 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3968 				ptr_regno, tn_buf);
3969 		return -EACCES;
3970 	}
3971 
3972 	if (!var_off) {
3973 		off += reg->var_off.value;
3974 		err = check_stack_read_fixed_off(env, state, off, size,
3975 						 dst_regno);
3976 	} else {
3977 		/* Variable offset stack reads need more conservative handling
3978 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3979 		 * branch.
3980 		 */
3981 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3982 					       dst_regno);
3983 	}
3984 	return err;
3985 }
3986 
3987 
3988 /* check_stack_write dispatches to check_stack_write_fixed_off or
3989  * check_stack_write_var_off.
3990  *
3991  * 'ptr_regno' is the register used as a pointer into the stack.
3992  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3993  * 'value_regno' is the register whose value we're writing to the stack. It can
3994  * be -1, meaning that we're not writing from a register.
3995  *
3996  * The caller must ensure that the offset falls within the maximum stack size.
3997  */
3998 static int check_stack_write(struct bpf_verifier_env *env,
3999 			     int ptr_regno, int off, int size,
4000 			     int value_regno, int insn_idx)
4001 {
4002 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4003 	struct bpf_func_state *state = func(env, reg);
4004 	int err;
4005 
4006 	if (tnum_is_const(reg->var_off)) {
4007 		off += reg->var_off.value;
4008 		err = check_stack_write_fixed_off(env, state, off, size,
4009 						  value_regno, insn_idx);
4010 	} else {
4011 		/* Variable offset stack reads need more conservative handling
4012 		 * than fixed offset ones.
4013 		 */
4014 		err = check_stack_write_var_off(env, state,
4015 						ptr_regno, off, size,
4016 						value_regno, insn_idx);
4017 	}
4018 	return err;
4019 }
4020 
4021 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4022 				 int off, int size, enum bpf_access_type type)
4023 {
4024 	struct bpf_reg_state *regs = cur_regs(env);
4025 	struct bpf_map *map = regs[regno].map_ptr;
4026 	u32 cap = bpf_map_flags_to_cap(map);
4027 
4028 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4029 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4030 			map->value_size, off, size);
4031 		return -EACCES;
4032 	}
4033 
4034 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4035 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4036 			map->value_size, off, size);
4037 		return -EACCES;
4038 	}
4039 
4040 	return 0;
4041 }
4042 
4043 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4044 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4045 			      int off, int size, u32 mem_size,
4046 			      bool zero_size_allowed)
4047 {
4048 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4049 	struct bpf_reg_state *reg;
4050 
4051 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4052 		return 0;
4053 
4054 	reg = &cur_regs(env)[regno];
4055 	switch (reg->type) {
4056 	case PTR_TO_MAP_KEY:
4057 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4058 			mem_size, off, size);
4059 		break;
4060 	case PTR_TO_MAP_VALUE:
4061 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4062 			mem_size, off, size);
4063 		break;
4064 	case PTR_TO_PACKET:
4065 	case PTR_TO_PACKET_META:
4066 	case PTR_TO_PACKET_END:
4067 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4068 			off, size, regno, reg->id, off, mem_size);
4069 		break;
4070 	case PTR_TO_MEM:
4071 	default:
4072 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4073 			mem_size, off, size);
4074 	}
4075 
4076 	return -EACCES;
4077 }
4078 
4079 /* check read/write into a memory region with possible variable offset */
4080 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4081 				   int off, int size, u32 mem_size,
4082 				   bool zero_size_allowed)
4083 {
4084 	struct bpf_verifier_state *vstate = env->cur_state;
4085 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4086 	struct bpf_reg_state *reg = &state->regs[regno];
4087 	int err;
4088 
4089 	/* We may have adjusted the register pointing to memory region, so we
4090 	 * need to try adding each of min_value and max_value to off
4091 	 * to make sure our theoretical access will be safe.
4092 	 *
4093 	 * The minimum value is only important with signed
4094 	 * comparisons where we can't assume the floor of a
4095 	 * value is 0.  If we are using signed variables for our
4096 	 * index'es we need to make sure that whatever we use
4097 	 * will have a set floor within our range.
4098 	 */
4099 	if (reg->smin_value < 0 &&
4100 	    (reg->smin_value == S64_MIN ||
4101 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4102 	      reg->smin_value + off < 0)) {
4103 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4104 			regno);
4105 		return -EACCES;
4106 	}
4107 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4108 				 mem_size, zero_size_allowed);
4109 	if (err) {
4110 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4111 			regno);
4112 		return err;
4113 	}
4114 
4115 	/* If we haven't set a max value then we need to bail since we can't be
4116 	 * sure we won't do bad things.
4117 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4118 	 */
4119 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4120 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4121 			regno);
4122 		return -EACCES;
4123 	}
4124 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4125 				 mem_size, zero_size_allowed);
4126 	if (err) {
4127 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4128 			regno);
4129 		return err;
4130 	}
4131 
4132 	return 0;
4133 }
4134 
4135 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4136 			       const struct bpf_reg_state *reg, int regno,
4137 			       bool fixed_off_ok)
4138 {
4139 	/* Access to this pointer-typed register or passing it to a helper
4140 	 * is only allowed in its original, unmodified form.
4141 	 */
4142 
4143 	if (reg->off < 0) {
4144 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4145 			reg_type_str(env, reg->type), regno, reg->off);
4146 		return -EACCES;
4147 	}
4148 
4149 	if (!fixed_off_ok && reg->off) {
4150 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4151 			reg_type_str(env, reg->type), regno, reg->off);
4152 		return -EACCES;
4153 	}
4154 
4155 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4156 		char tn_buf[48];
4157 
4158 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4159 		verbose(env, "variable %s access var_off=%s disallowed\n",
4160 			reg_type_str(env, reg->type), tn_buf);
4161 		return -EACCES;
4162 	}
4163 
4164 	return 0;
4165 }
4166 
4167 int check_ptr_off_reg(struct bpf_verifier_env *env,
4168 		      const struct bpf_reg_state *reg, int regno)
4169 {
4170 	return __check_ptr_off_reg(env, reg, regno, false);
4171 }
4172 
4173 static int map_kptr_match_type(struct bpf_verifier_env *env,
4174 			       struct btf_field *kptr_field,
4175 			       struct bpf_reg_state *reg, u32 regno)
4176 {
4177 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4178 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
4179 	const char *reg_name = "";
4180 
4181 	/* Only unreferenced case accepts untrusted pointers */
4182 	if (kptr_field->type == BPF_KPTR_UNREF)
4183 		perm_flags |= PTR_UNTRUSTED;
4184 
4185 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4186 		goto bad_type;
4187 
4188 	if (!btf_is_kernel(reg->btf)) {
4189 		verbose(env, "R%d must point to kernel BTF\n", regno);
4190 		return -EINVAL;
4191 	}
4192 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4193 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
4194 
4195 	/* For ref_ptr case, release function check should ensure we get one
4196 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4197 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4198 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4199 	 * reg->off and reg->ref_obj_id are not needed here.
4200 	 */
4201 	if (__check_ptr_off_reg(env, reg, regno, true))
4202 		return -EACCES;
4203 
4204 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4205 	 * we also need to take into account the reg->off.
4206 	 *
4207 	 * We want to support cases like:
4208 	 *
4209 	 * struct foo {
4210 	 *         struct bar br;
4211 	 *         struct baz bz;
4212 	 * };
4213 	 *
4214 	 * struct foo *v;
4215 	 * v = func();	      // PTR_TO_BTF_ID
4216 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4217 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4218 	 *                    // first member type of struct after comparison fails
4219 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4220 	 *                    // to match type
4221 	 *
4222 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4223 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4224 	 * the struct to match type against first member of struct, i.e. reject
4225 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4226 	 * strict mode to true for type match.
4227 	 */
4228 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4229 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4230 				  kptr_field->type == BPF_KPTR_REF))
4231 		goto bad_type;
4232 	return 0;
4233 bad_type:
4234 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4235 		reg_type_str(env, reg->type), reg_name);
4236 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4237 	if (kptr_field->type == BPF_KPTR_UNREF)
4238 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4239 			targ_name);
4240 	else
4241 		verbose(env, "\n");
4242 	return -EINVAL;
4243 }
4244 
4245 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4246 				 int value_regno, int insn_idx,
4247 				 struct btf_field *kptr_field)
4248 {
4249 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4250 	int class = BPF_CLASS(insn->code);
4251 	struct bpf_reg_state *val_reg;
4252 
4253 	/* Things we already checked for in check_map_access and caller:
4254 	 *  - Reject cases where variable offset may touch kptr
4255 	 *  - size of access (must be BPF_DW)
4256 	 *  - tnum_is_const(reg->var_off)
4257 	 *  - kptr_field->offset == off + reg->var_off.value
4258 	 */
4259 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4260 	if (BPF_MODE(insn->code) != BPF_MEM) {
4261 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4262 		return -EACCES;
4263 	}
4264 
4265 	/* We only allow loading referenced kptr, since it will be marked as
4266 	 * untrusted, similar to unreferenced kptr.
4267 	 */
4268 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4269 		verbose(env, "store to referenced kptr disallowed\n");
4270 		return -EACCES;
4271 	}
4272 
4273 	if (class == BPF_LDX) {
4274 		val_reg = reg_state(env, value_regno);
4275 		/* We can simply mark the value_regno receiving the pointer
4276 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4277 		 */
4278 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4279 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4280 		/* For mark_ptr_or_null_reg */
4281 		val_reg->id = ++env->id_gen;
4282 	} else if (class == BPF_STX) {
4283 		val_reg = reg_state(env, value_regno);
4284 		if (!register_is_null(val_reg) &&
4285 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4286 			return -EACCES;
4287 	} else if (class == BPF_ST) {
4288 		if (insn->imm) {
4289 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4290 				kptr_field->offset);
4291 			return -EACCES;
4292 		}
4293 	} else {
4294 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4295 		return -EACCES;
4296 	}
4297 	return 0;
4298 }
4299 
4300 /* check read/write into a map element with possible variable offset */
4301 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4302 			    int off, int size, bool zero_size_allowed,
4303 			    enum bpf_access_src src)
4304 {
4305 	struct bpf_verifier_state *vstate = env->cur_state;
4306 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4307 	struct bpf_reg_state *reg = &state->regs[regno];
4308 	struct bpf_map *map = reg->map_ptr;
4309 	struct btf_record *rec;
4310 	int err, i;
4311 
4312 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4313 				      zero_size_allowed);
4314 	if (err)
4315 		return err;
4316 
4317 	if (IS_ERR_OR_NULL(map->record))
4318 		return 0;
4319 	rec = map->record;
4320 	for (i = 0; i < rec->cnt; i++) {
4321 		struct btf_field *field = &rec->fields[i];
4322 		u32 p = field->offset;
4323 
4324 		/* If any part of a field  can be touched by load/store, reject
4325 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4326 		 * it is sufficient to check x1 < y2 && y1 < x2.
4327 		 */
4328 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4329 		    p < reg->umax_value + off + size) {
4330 			switch (field->type) {
4331 			case BPF_KPTR_UNREF:
4332 			case BPF_KPTR_REF:
4333 				if (src != ACCESS_DIRECT) {
4334 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4335 					return -EACCES;
4336 				}
4337 				if (!tnum_is_const(reg->var_off)) {
4338 					verbose(env, "kptr access cannot have variable offset\n");
4339 					return -EACCES;
4340 				}
4341 				if (p != off + reg->var_off.value) {
4342 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4343 						p, off + reg->var_off.value);
4344 					return -EACCES;
4345 				}
4346 				if (size != bpf_size_to_bytes(BPF_DW)) {
4347 					verbose(env, "kptr access size must be BPF_DW\n");
4348 					return -EACCES;
4349 				}
4350 				break;
4351 			default:
4352 				verbose(env, "%s cannot be accessed directly by load/store\n",
4353 					btf_field_type_name(field->type));
4354 				return -EACCES;
4355 			}
4356 		}
4357 	}
4358 	return 0;
4359 }
4360 
4361 #define MAX_PACKET_OFF 0xffff
4362 
4363 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4364 				       const struct bpf_call_arg_meta *meta,
4365 				       enum bpf_access_type t)
4366 {
4367 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4368 
4369 	switch (prog_type) {
4370 	/* Program types only with direct read access go here! */
4371 	case BPF_PROG_TYPE_LWT_IN:
4372 	case BPF_PROG_TYPE_LWT_OUT:
4373 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4374 	case BPF_PROG_TYPE_SK_REUSEPORT:
4375 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4376 	case BPF_PROG_TYPE_CGROUP_SKB:
4377 		if (t == BPF_WRITE)
4378 			return false;
4379 		fallthrough;
4380 
4381 	/* Program types with direct read + write access go here! */
4382 	case BPF_PROG_TYPE_SCHED_CLS:
4383 	case BPF_PROG_TYPE_SCHED_ACT:
4384 	case BPF_PROG_TYPE_XDP:
4385 	case BPF_PROG_TYPE_LWT_XMIT:
4386 	case BPF_PROG_TYPE_SK_SKB:
4387 	case BPF_PROG_TYPE_SK_MSG:
4388 		if (meta)
4389 			return meta->pkt_access;
4390 
4391 		env->seen_direct_write = true;
4392 		return true;
4393 
4394 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4395 		if (t == BPF_WRITE)
4396 			env->seen_direct_write = true;
4397 
4398 		return true;
4399 
4400 	default:
4401 		return false;
4402 	}
4403 }
4404 
4405 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4406 			       int size, bool zero_size_allowed)
4407 {
4408 	struct bpf_reg_state *regs = cur_regs(env);
4409 	struct bpf_reg_state *reg = &regs[regno];
4410 	int err;
4411 
4412 	/* We may have added a variable offset to the packet pointer; but any
4413 	 * reg->range we have comes after that.  We are only checking the fixed
4414 	 * offset.
4415 	 */
4416 
4417 	/* We don't allow negative numbers, because we aren't tracking enough
4418 	 * detail to prove they're safe.
4419 	 */
4420 	if (reg->smin_value < 0) {
4421 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4422 			regno);
4423 		return -EACCES;
4424 	}
4425 
4426 	err = reg->range < 0 ? -EINVAL :
4427 	      __check_mem_access(env, regno, off, size, reg->range,
4428 				 zero_size_allowed);
4429 	if (err) {
4430 		verbose(env, "R%d offset is outside of the packet\n", regno);
4431 		return err;
4432 	}
4433 
4434 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4435 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4436 	 * otherwise find_good_pkt_pointers would have refused to set range info
4437 	 * that __check_mem_access would have rejected this pkt access.
4438 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4439 	 */
4440 	env->prog->aux->max_pkt_offset =
4441 		max_t(u32, env->prog->aux->max_pkt_offset,
4442 		      off + reg->umax_value + size - 1);
4443 
4444 	return err;
4445 }
4446 
4447 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4448 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4449 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4450 			    struct btf **btf, u32 *btf_id)
4451 {
4452 	struct bpf_insn_access_aux info = {
4453 		.reg_type = *reg_type,
4454 		.log = &env->log,
4455 	};
4456 
4457 	if (env->ops->is_valid_access &&
4458 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4459 		/* A non zero info.ctx_field_size indicates that this field is a
4460 		 * candidate for later verifier transformation to load the whole
4461 		 * field and then apply a mask when accessed with a narrower
4462 		 * access than actual ctx access size. A zero info.ctx_field_size
4463 		 * will only allow for whole field access and rejects any other
4464 		 * type of narrower access.
4465 		 */
4466 		*reg_type = info.reg_type;
4467 
4468 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4469 			*btf = info.btf;
4470 			*btf_id = info.btf_id;
4471 		} else {
4472 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4473 		}
4474 		/* remember the offset of last byte accessed in ctx */
4475 		if (env->prog->aux->max_ctx_offset < off + size)
4476 			env->prog->aux->max_ctx_offset = off + size;
4477 		return 0;
4478 	}
4479 
4480 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4481 	return -EACCES;
4482 }
4483 
4484 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4485 				  int size)
4486 {
4487 	if (size < 0 || off < 0 ||
4488 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4489 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4490 			off, size);
4491 		return -EACCES;
4492 	}
4493 	return 0;
4494 }
4495 
4496 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4497 			     u32 regno, int off, int size,
4498 			     enum bpf_access_type t)
4499 {
4500 	struct bpf_reg_state *regs = cur_regs(env);
4501 	struct bpf_reg_state *reg = &regs[regno];
4502 	struct bpf_insn_access_aux info = {};
4503 	bool valid;
4504 
4505 	if (reg->smin_value < 0) {
4506 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4507 			regno);
4508 		return -EACCES;
4509 	}
4510 
4511 	switch (reg->type) {
4512 	case PTR_TO_SOCK_COMMON:
4513 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4514 		break;
4515 	case PTR_TO_SOCKET:
4516 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4517 		break;
4518 	case PTR_TO_TCP_SOCK:
4519 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4520 		break;
4521 	case PTR_TO_XDP_SOCK:
4522 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4523 		break;
4524 	default:
4525 		valid = false;
4526 	}
4527 
4528 
4529 	if (valid) {
4530 		env->insn_aux_data[insn_idx].ctx_field_size =
4531 			info.ctx_field_size;
4532 		return 0;
4533 	}
4534 
4535 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4536 		regno, reg_type_str(env, reg->type), off, size);
4537 
4538 	return -EACCES;
4539 }
4540 
4541 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4542 {
4543 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4544 }
4545 
4546 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4547 {
4548 	const struct bpf_reg_state *reg = reg_state(env, regno);
4549 
4550 	return reg->type == PTR_TO_CTX;
4551 }
4552 
4553 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4554 {
4555 	const struct bpf_reg_state *reg = reg_state(env, regno);
4556 
4557 	return type_is_sk_pointer(reg->type);
4558 }
4559 
4560 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4561 {
4562 	const struct bpf_reg_state *reg = reg_state(env, regno);
4563 
4564 	return type_is_pkt_pointer(reg->type);
4565 }
4566 
4567 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4568 {
4569 	const struct bpf_reg_state *reg = reg_state(env, regno);
4570 
4571 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4572 	return reg->type == PTR_TO_FLOW_KEYS;
4573 }
4574 
4575 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4576 {
4577 	/* A referenced register is always trusted. */
4578 	if (reg->ref_obj_id)
4579 		return true;
4580 
4581 	/* If a register is not referenced, it is trusted if it has the
4582 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4583 	 * other type modifiers may be safe, but we elect to take an opt-in
4584 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4585 	 * not.
4586 	 *
4587 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4588 	 * for whether a register is trusted.
4589 	 */
4590 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4591 	       !bpf_type_has_unsafe_modifiers(reg->type);
4592 }
4593 
4594 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4595 {
4596 	return reg->type & MEM_RCU;
4597 }
4598 
4599 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4600 				   const struct bpf_reg_state *reg,
4601 				   int off, int size, bool strict)
4602 {
4603 	struct tnum reg_off;
4604 	int ip_align;
4605 
4606 	/* Byte size accesses are always allowed. */
4607 	if (!strict || size == 1)
4608 		return 0;
4609 
4610 	/* For platforms that do not have a Kconfig enabling
4611 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4612 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4613 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4614 	 * to this code only in strict mode where we want to emulate
4615 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4616 	 * unconditional IP align value of '2'.
4617 	 */
4618 	ip_align = 2;
4619 
4620 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4621 	if (!tnum_is_aligned(reg_off, size)) {
4622 		char tn_buf[48];
4623 
4624 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4625 		verbose(env,
4626 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4627 			ip_align, tn_buf, reg->off, off, size);
4628 		return -EACCES;
4629 	}
4630 
4631 	return 0;
4632 }
4633 
4634 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4635 				       const struct bpf_reg_state *reg,
4636 				       const char *pointer_desc,
4637 				       int off, int size, bool strict)
4638 {
4639 	struct tnum reg_off;
4640 
4641 	/* Byte size accesses are always allowed. */
4642 	if (!strict || size == 1)
4643 		return 0;
4644 
4645 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4646 	if (!tnum_is_aligned(reg_off, size)) {
4647 		char tn_buf[48];
4648 
4649 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4650 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4651 			pointer_desc, tn_buf, reg->off, off, size);
4652 		return -EACCES;
4653 	}
4654 
4655 	return 0;
4656 }
4657 
4658 static int check_ptr_alignment(struct bpf_verifier_env *env,
4659 			       const struct bpf_reg_state *reg, int off,
4660 			       int size, bool strict_alignment_once)
4661 {
4662 	bool strict = env->strict_alignment || strict_alignment_once;
4663 	const char *pointer_desc = "";
4664 
4665 	switch (reg->type) {
4666 	case PTR_TO_PACKET:
4667 	case PTR_TO_PACKET_META:
4668 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4669 		 * right in front, treat it the very same way.
4670 		 */
4671 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4672 	case PTR_TO_FLOW_KEYS:
4673 		pointer_desc = "flow keys ";
4674 		break;
4675 	case PTR_TO_MAP_KEY:
4676 		pointer_desc = "key ";
4677 		break;
4678 	case PTR_TO_MAP_VALUE:
4679 		pointer_desc = "value ";
4680 		break;
4681 	case PTR_TO_CTX:
4682 		pointer_desc = "context ";
4683 		break;
4684 	case PTR_TO_STACK:
4685 		pointer_desc = "stack ";
4686 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4687 		 * and check_stack_read_fixed_off() relies on stack accesses being
4688 		 * aligned.
4689 		 */
4690 		strict = true;
4691 		break;
4692 	case PTR_TO_SOCKET:
4693 		pointer_desc = "sock ";
4694 		break;
4695 	case PTR_TO_SOCK_COMMON:
4696 		pointer_desc = "sock_common ";
4697 		break;
4698 	case PTR_TO_TCP_SOCK:
4699 		pointer_desc = "tcp_sock ";
4700 		break;
4701 	case PTR_TO_XDP_SOCK:
4702 		pointer_desc = "xdp_sock ";
4703 		break;
4704 	default:
4705 		break;
4706 	}
4707 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4708 					   strict);
4709 }
4710 
4711 static int update_stack_depth(struct bpf_verifier_env *env,
4712 			      const struct bpf_func_state *func,
4713 			      int off)
4714 {
4715 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4716 
4717 	if (stack >= -off)
4718 		return 0;
4719 
4720 	/* update known max for given subprogram */
4721 	env->subprog_info[func->subprogno].stack_depth = -off;
4722 	return 0;
4723 }
4724 
4725 /* starting from main bpf function walk all instructions of the function
4726  * and recursively walk all callees that given function can call.
4727  * Ignore jump and exit insns.
4728  * Since recursion is prevented by check_cfg() this algorithm
4729  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4730  */
4731 static int check_max_stack_depth(struct bpf_verifier_env *env)
4732 {
4733 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4734 	struct bpf_subprog_info *subprog = env->subprog_info;
4735 	struct bpf_insn *insn = env->prog->insnsi;
4736 	bool tail_call_reachable = false;
4737 	int ret_insn[MAX_CALL_FRAMES];
4738 	int ret_prog[MAX_CALL_FRAMES];
4739 	int j;
4740 
4741 process_func:
4742 	/* protect against potential stack overflow that might happen when
4743 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4744 	 * depth for such case down to 256 so that the worst case scenario
4745 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4746 	 * 8k).
4747 	 *
4748 	 * To get the idea what might happen, see an example:
4749 	 * func1 -> sub rsp, 128
4750 	 *  subfunc1 -> sub rsp, 256
4751 	 *  tailcall1 -> add rsp, 256
4752 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4753 	 *   subfunc2 -> sub rsp, 64
4754 	 *   subfunc22 -> sub rsp, 128
4755 	 *   tailcall2 -> add rsp, 128
4756 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4757 	 *
4758 	 * tailcall will unwind the current stack frame but it will not get rid
4759 	 * of caller's stack as shown on the example above.
4760 	 */
4761 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4762 		verbose(env,
4763 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4764 			depth);
4765 		return -EACCES;
4766 	}
4767 	/* round up to 32-bytes, since this is granularity
4768 	 * of interpreter stack size
4769 	 */
4770 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4771 	if (depth > MAX_BPF_STACK) {
4772 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4773 			frame + 1, depth);
4774 		return -EACCES;
4775 	}
4776 continue_func:
4777 	subprog_end = subprog[idx + 1].start;
4778 	for (; i < subprog_end; i++) {
4779 		int next_insn;
4780 
4781 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4782 			continue;
4783 		/* remember insn and function to return to */
4784 		ret_insn[frame] = i + 1;
4785 		ret_prog[frame] = idx;
4786 
4787 		/* find the callee */
4788 		next_insn = i + insn[i].imm + 1;
4789 		idx = find_subprog(env, next_insn);
4790 		if (idx < 0) {
4791 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4792 				  next_insn);
4793 			return -EFAULT;
4794 		}
4795 		if (subprog[idx].is_async_cb) {
4796 			if (subprog[idx].has_tail_call) {
4797 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4798 				return -EFAULT;
4799 			}
4800 			 /* async callbacks don't increase bpf prog stack size */
4801 			continue;
4802 		}
4803 		i = next_insn;
4804 
4805 		if (subprog[idx].has_tail_call)
4806 			tail_call_reachable = true;
4807 
4808 		frame++;
4809 		if (frame >= MAX_CALL_FRAMES) {
4810 			verbose(env, "the call stack of %d frames is too deep !\n",
4811 				frame);
4812 			return -E2BIG;
4813 		}
4814 		goto process_func;
4815 	}
4816 	/* if tail call got detected across bpf2bpf calls then mark each of the
4817 	 * currently present subprog frames as tail call reachable subprogs;
4818 	 * this info will be utilized by JIT so that we will be preserving the
4819 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4820 	 */
4821 	if (tail_call_reachable)
4822 		for (j = 0; j < frame; j++)
4823 			subprog[ret_prog[j]].tail_call_reachable = true;
4824 	if (subprog[0].tail_call_reachable)
4825 		env->prog->aux->tail_call_reachable = true;
4826 
4827 	/* end of for() loop means the last insn of the 'subprog'
4828 	 * was reached. Doesn't matter whether it was JA or EXIT
4829 	 */
4830 	if (frame == 0)
4831 		return 0;
4832 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4833 	frame--;
4834 	i = ret_insn[frame];
4835 	idx = ret_prog[frame];
4836 	goto continue_func;
4837 }
4838 
4839 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4840 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4841 				  const struct bpf_insn *insn, int idx)
4842 {
4843 	int start = idx + insn->imm + 1, subprog;
4844 
4845 	subprog = find_subprog(env, start);
4846 	if (subprog < 0) {
4847 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4848 			  start);
4849 		return -EFAULT;
4850 	}
4851 	return env->subprog_info[subprog].stack_depth;
4852 }
4853 #endif
4854 
4855 static int __check_buffer_access(struct bpf_verifier_env *env,
4856 				 const char *buf_info,
4857 				 const struct bpf_reg_state *reg,
4858 				 int regno, int off, int size)
4859 {
4860 	if (off < 0) {
4861 		verbose(env,
4862 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4863 			regno, buf_info, off, size);
4864 		return -EACCES;
4865 	}
4866 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4867 		char tn_buf[48];
4868 
4869 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4870 		verbose(env,
4871 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4872 			regno, off, tn_buf);
4873 		return -EACCES;
4874 	}
4875 
4876 	return 0;
4877 }
4878 
4879 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4880 				  const struct bpf_reg_state *reg,
4881 				  int regno, int off, int size)
4882 {
4883 	int err;
4884 
4885 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4886 	if (err)
4887 		return err;
4888 
4889 	if (off + size > env->prog->aux->max_tp_access)
4890 		env->prog->aux->max_tp_access = off + size;
4891 
4892 	return 0;
4893 }
4894 
4895 static int check_buffer_access(struct bpf_verifier_env *env,
4896 			       const struct bpf_reg_state *reg,
4897 			       int regno, int off, int size,
4898 			       bool zero_size_allowed,
4899 			       u32 *max_access)
4900 {
4901 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4902 	int err;
4903 
4904 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4905 	if (err)
4906 		return err;
4907 
4908 	if (off + size > *max_access)
4909 		*max_access = off + size;
4910 
4911 	return 0;
4912 }
4913 
4914 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4915 static void zext_32_to_64(struct bpf_reg_state *reg)
4916 {
4917 	reg->var_off = tnum_subreg(reg->var_off);
4918 	__reg_assign_32_into_64(reg);
4919 }
4920 
4921 /* truncate register to smaller size (in bytes)
4922  * must be called with size < BPF_REG_SIZE
4923  */
4924 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4925 {
4926 	u64 mask;
4927 
4928 	/* clear high bits in bit representation */
4929 	reg->var_off = tnum_cast(reg->var_off, size);
4930 
4931 	/* fix arithmetic bounds */
4932 	mask = ((u64)1 << (size * 8)) - 1;
4933 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4934 		reg->umin_value &= mask;
4935 		reg->umax_value &= mask;
4936 	} else {
4937 		reg->umin_value = 0;
4938 		reg->umax_value = mask;
4939 	}
4940 	reg->smin_value = reg->umin_value;
4941 	reg->smax_value = reg->umax_value;
4942 
4943 	/* If size is smaller than 32bit register the 32bit register
4944 	 * values are also truncated so we push 64-bit bounds into
4945 	 * 32-bit bounds. Above were truncated < 32-bits already.
4946 	 */
4947 	if (size >= 4)
4948 		return;
4949 	__reg_combine_64_into_32(reg);
4950 }
4951 
4952 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4953 {
4954 	/* A map is considered read-only if the following condition are true:
4955 	 *
4956 	 * 1) BPF program side cannot change any of the map content. The
4957 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4958 	 *    and was set at map creation time.
4959 	 * 2) The map value(s) have been initialized from user space by a
4960 	 *    loader and then "frozen", such that no new map update/delete
4961 	 *    operations from syscall side are possible for the rest of
4962 	 *    the map's lifetime from that point onwards.
4963 	 * 3) Any parallel/pending map update/delete operations from syscall
4964 	 *    side have been completed. Only after that point, it's safe to
4965 	 *    assume that map value(s) are immutable.
4966 	 */
4967 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4968 	       READ_ONCE(map->frozen) &&
4969 	       !bpf_map_write_active(map);
4970 }
4971 
4972 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4973 {
4974 	void *ptr;
4975 	u64 addr;
4976 	int err;
4977 
4978 	err = map->ops->map_direct_value_addr(map, &addr, off);
4979 	if (err)
4980 		return err;
4981 	ptr = (void *)(long)addr + off;
4982 
4983 	switch (size) {
4984 	case sizeof(u8):
4985 		*val = (u64)*(u8 *)ptr;
4986 		break;
4987 	case sizeof(u16):
4988 		*val = (u64)*(u16 *)ptr;
4989 		break;
4990 	case sizeof(u32):
4991 		*val = (u64)*(u32 *)ptr;
4992 		break;
4993 	case sizeof(u64):
4994 		*val = *(u64 *)ptr;
4995 		break;
4996 	default:
4997 		return -EINVAL;
4998 	}
4999 	return 0;
5000 }
5001 
5002 #define BTF_TYPE_SAFE_NESTED(__type)  __PASTE(__type, __safe_fields)
5003 
5004 BTF_TYPE_SAFE_NESTED(struct task_struct) {
5005 	const cpumask_t *cpus_ptr;
5006 };
5007 
5008 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env,
5009 				  struct bpf_reg_state *reg,
5010 				  int off)
5011 {
5012 	/* If its parent is not trusted, it can't regain its trusted status. */
5013 	if (!is_trusted_reg(reg))
5014 		return false;
5015 
5016 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct));
5017 
5018 	return btf_nested_type_is_trusted(&env->log, reg, off);
5019 }
5020 
5021 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5022 				   struct bpf_reg_state *regs,
5023 				   int regno, int off, int size,
5024 				   enum bpf_access_type atype,
5025 				   int value_regno)
5026 {
5027 	struct bpf_reg_state *reg = regs + regno;
5028 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5029 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5030 	enum bpf_type_flag flag = 0;
5031 	u32 btf_id;
5032 	int ret;
5033 
5034 	if (!env->allow_ptr_leaks) {
5035 		verbose(env,
5036 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5037 			tname);
5038 		return -EPERM;
5039 	}
5040 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5041 		verbose(env,
5042 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5043 			tname);
5044 		return -EINVAL;
5045 	}
5046 	if (off < 0) {
5047 		verbose(env,
5048 			"R%d is ptr_%s invalid negative access: off=%d\n",
5049 			regno, tname, off);
5050 		return -EACCES;
5051 	}
5052 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5053 		char tn_buf[48];
5054 
5055 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5056 		verbose(env,
5057 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5058 			regno, tname, off, tn_buf);
5059 		return -EACCES;
5060 	}
5061 
5062 	if (reg->type & MEM_USER) {
5063 		verbose(env,
5064 			"R%d is ptr_%s access user memory: off=%d\n",
5065 			regno, tname, off);
5066 		return -EACCES;
5067 	}
5068 
5069 	if (reg->type & MEM_PERCPU) {
5070 		verbose(env,
5071 			"R%d is ptr_%s access percpu memory: off=%d\n",
5072 			regno, tname, off);
5073 		return -EACCES;
5074 	}
5075 
5076 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5077 		if (!btf_is_kernel(reg->btf)) {
5078 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5079 			return -EFAULT;
5080 		}
5081 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5082 	} else {
5083 		/* Writes are permitted with default btf_struct_access for
5084 		 * program allocated objects (which always have ref_obj_id > 0),
5085 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5086 		 */
5087 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5088 			verbose(env, "only read is supported\n");
5089 			return -EACCES;
5090 		}
5091 
5092 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5093 		    !reg->ref_obj_id) {
5094 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5095 			return -EFAULT;
5096 		}
5097 
5098 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5099 	}
5100 
5101 	if (ret < 0)
5102 		return ret;
5103 
5104 	/* If this is an untrusted pointer, all pointers formed by walking it
5105 	 * also inherit the untrusted flag.
5106 	 */
5107 	if (type_flag(reg->type) & PTR_UNTRUSTED)
5108 		flag |= PTR_UNTRUSTED;
5109 
5110 	/* By default any pointer obtained from walking a trusted pointer is no
5111 	 * longer trusted, unless the field being accessed has explicitly been
5112 	 * marked as inheriting its parent's state of trust.
5113 	 *
5114 	 * An RCU-protected pointer can also be deemed trusted if we are in an
5115 	 * RCU read region. This case is handled below.
5116 	 */
5117 	if (nested_ptr_is_trusted(env, reg, off))
5118 		flag |= PTR_TRUSTED;
5119 	else
5120 		flag &= ~PTR_TRUSTED;
5121 
5122 	if (flag & MEM_RCU) {
5123 		/* Mark value register as MEM_RCU only if it is protected by
5124 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
5125 		 * itself can already indicate trustedness inside the rcu
5126 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
5127 		 * it could be null in some cases.
5128 		 */
5129 		if (!env->cur_state->active_rcu_lock ||
5130 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
5131 			flag &= ~MEM_RCU;
5132 		else
5133 			flag |= PTR_MAYBE_NULL;
5134 	} else if (reg->type & MEM_RCU) {
5135 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
5136 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
5137 		 */
5138 		flag |= PTR_UNTRUSTED;
5139 	}
5140 
5141 	if (atype == BPF_READ && value_regno >= 0)
5142 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5143 
5144 	return 0;
5145 }
5146 
5147 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5148 				   struct bpf_reg_state *regs,
5149 				   int regno, int off, int size,
5150 				   enum bpf_access_type atype,
5151 				   int value_regno)
5152 {
5153 	struct bpf_reg_state *reg = regs + regno;
5154 	struct bpf_map *map = reg->map_ptr;
5155 	struct bpf_reg_state map_reg;
5156 	enum bpf_type_flag flag = 0;
5157 	const struct btf_type *t;
5158 	const char *tname;
5159 	u32 btf_id;
5160 	int ret;
5161 
5162 	if (!btf_vmlinux) {
5163 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5164 		return -ENOTSUPP;
5165 	}
5166 
5167 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5168 		verbose(env, "map_ptr access not supported for map type %d\n",
5169 			map->map_type);
5170 		return -ENOTSUPP;
5171 	}
5172 
5173 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5174 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5175 
5176 	if (!env->allow_ptr_leaks) {
5177 		verbose(env,
5178 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5179 			tname);
5180 		return -EPERM;
5181 	}
5182 
5183 	if (off < 0) {
5184 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5185 			regno, tname, off);
5186 		return -EACCES;
5187 	}
5188 
5189 	if (atype != BPF_READ) {
5190 		verbose(env, "only read from %s is supported\n", tname);
5191 		return -EACCES;
5192 	}
5193 
5194 	/* Simulate access to a PTR_TO_BTF_ID */
5195 	memset(&map_reg, 0, sizeof(map_reg));
5196 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5197 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5198 	if (ret < 0)
5199 		return ret;
5200 
5201 	if (value_regno >= 0)
5202 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5203 
5204 	return 0;
5205 }
5206 
5207 /* Check that the stack access at the given offset is within bounds. The
5208  * maximum valid offset is -1.
5209  *
5210  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5211  * -state->allocated_stack for reads.
5212  */
5213 static int check_stack_slot_within_bounds(int off,
5214 					  struct bpf_func_state *state,
5215 					  enum bpf_access_type t)
5216 {
5217 	int min_valid_off;
5218 
5219 	if (t == BPF_WRITE)
5220 		min_valid_off = -MAX_BPF_STACK;
5221 	else
5222 		min_valid_off = -state->allocated_stack;
5223 
5224 	if (off < min_valid_off || off > -1)
5225 		return -EACCES;
5226 	return 0;
5227 }
5228 
5229 /* Check that the stack access at 'regno + off' falls within the maximum stack
5230  * bounds.
5231  *
5232  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5233  */
5234 static int check_stack_access_within_bounds(
5235 		struct bpf_verifier_env *env,
5236 		int regno, int off, int access_size,
5237 		enum bpf_access_src src, enum bpf_access_type type)
5238 {
5239 	struct bpf_reg_state *regs = cur_regs(env);
5240 	struct bpf_reg_state *reg = regs + regno;
5241 	struct bpf_func_state *state = func(env, reg);
5242 	int min_off, max_off;
5243 	int err;
5244 	char *err_extra;
5245 
5246 	if (src == ACCESS_HELPER)
5247 		/* We don't know if helpers are reading or writing (or both). */
5248 		err_extra = " indirect access to";
5249 	else if (type == BPF_READ)
5250 		err_extra = " read from";
5251 	else
5252 		err_extra = " write to";
5253 
5254 	if (tnum_is_const(reg->var_off)) {
5255 		min_off = reg->var_off.value + off;
5256 		if (access_size > 0)
5257 			max_off = min_off + access_size - 1;
5258 		else
5259 			max_off = min_off;
5260 	} else {
5261 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5262 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5263 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5264 				err_extra, regno);
5265 			return -EACCES;
5266 		}
5267 		min_off = reg->smin_value + off;
5268 		if (access_size > 0)
5269 			max_off = reg->smax_value + off + access_size - 1;
5270 		else
5271 			max_off = min_off;
5272 	}
5273 
5274 	err = check_stack_slot_within_bounds(min_off, state, type);
5275 	if (!err)
5276 		err = check_stack_slot_within_bounds(max_off, state, type);
5277 
5278 	if (err) {
5279 		if (tnum_is_const(reg->var_off)) {
5280 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5281 				err_extra, regno, off, access_size);
5282 		} else {
5283 			char tn_buf[48];
5284 
5285 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5286 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5287 				err_extra, regno, tn_buf, access_size);
5288 		}
5289 	}
5290 	return err;
5291 }
5292 
5293 /* check whether memory at (regno + off) is accessible for t = (read | write)
5294  * if t==write, value_regno is a register which value is stored into memory
5295  * if t==read, value_regno is a register which will receive the value from memory
5296  * if t==write && value_regno==-1, some unknown value is stored into memory
5297  * if t==read && value_regno==-1, don't care what we read from memory
5298  */
5299 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5300 			    int off, int bpf_size, enum bpf_access_type t,
5301 			    int value_regno, bool strict_alignment_once)
5302 {
5303 	struct bpf_reg_state *regs = cur_regs(env);
5304 	struct bpf_reg_state *reg = regs + regno;
5305 	struct bpf_func_state *state;
5306 	int size, err = 0;
5307 
5308 	size = bpf_size_to_bytes(bpf_size);
5309 	if (size < 0)
5310 		return size;
5311 
5312 	/* alignment checks will add in reg->off themselves */
5313 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5314 	if (err)
5315 		return err;
5316 
5317 	/* for access checks, reg->off is just part of off */
5318 	off += reg->off;
5319 
5320 	if (reg->type == PTR_TO_MAP_KEY) {
5321 		if (t == BPF_WRITE) {
5322 			verbose(env, "write to change key R%d not allowed\n", regno);
5323 			return -EACCES;
5324 		}
5325 
5326 		err = check_mem_region_access(env, regno, off, size,
5327 					      reg->map_ptr->key_size, false);
5328 		if (err)
5329 			return err;
5330 		if (value_regno >= 0)
5331 			mark_reg_unknown(env, regs, value_regno);
5332 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5333 		struct btf_field *kptr_field = NULL;
5334 
5335 		if (t == BPF_WRITE && value_regno >= 0 &&
5336 		    is_pointer_value(env, value_regno)) {
5337 			verbose(env, "R%d leaks addr into map\n", value_regno);
5338 			return -EACCES;
5339 		}
5340 		err = check_map_access_type(env, regno, off, size, t);
5341 		if (err)
5342 			return err;
5343 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5344 		if (err)
5345 			return err;
5346 		if (tnum_is_const(reg->var_off))
5347 			kptr_field = btf_record_find(reg->map_ptr->record,
5348 						     off + reg->var_off.value, BPF_KPTR);
5349 		if (kptr_field) {
5350 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5351 		} else if (t == BPF_READ && value_regno >= 0) {
5352 			struct bpf_map *map = reg->map_ptr;
5353 
5354 			/* if map is read-only, track its contents as scalars */
5355 			if (tnum_is_const(reg->var_off) &&
5356 			    bpf_map_is_rdonly(map) &&
5357 			    map->ops->map_direct_value_addr) {
5358 				int map_off = off + reg->var_off.value;
5359 				u64 val = 0;
5360 
5361 				err = bpf_map_direct_read(map, map_off, size,
5362 							  &val);
5363 				if (err)
5364 					return err;
5365 
5366 				regs[value_regno].type = SCALAR_VALUE;
5367 				__mark_reg_known(&regs[value_regno], val);
5368 			} else {
5369 				mark_reg_unknown(env, regs, value_regno);
5370 			}
5371 		}
5372 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5373 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5374 
5375 		if (type_may_be_null(reg->type)) {
5376 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5377 				reg_type_str(env, reg->type));
5378 			return -EACCES;
5379 		}
5380 
5381 		if (t == BPF_WRITE && rdonly_mem) {
5382 			verbose(env, "R%d cannot write into %s\n",
5383 				regno, reg_type_str(env, reg->type));
5384 			return -EACCES;
5385 		}
5386 
5387 		if (t == BPF_WRITE && value_regno >= 0 &&
5388 		    is_pointer_value(env, value_regno)) {
5389 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5390 			return -EACCES;
5391 		}
5392 
5393 		err = check_mem_region_access(env, regno, off, size,
5394 					      reg->mem_size, false);
5395 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5396 			mark_reg_unknown(env, regs, value_regno);
5397 	} else if (reg->type == PTR_TO_CTX) {
5398 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5399 		struct btf *btf = NULL;
5400 		u32 btf_id = 0;
5401 
5402 		if (t == BPF_WRITE && value_regno >= 0 &&
5403 		    is_pointer_value(env, value_regno)) {
5404 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5405 			return -EACCES;
5406 		}
5407 
5408 		err = check_ptr_off_reg(env, reg, regno);
5409 		if (err < 0)
5410 			return err;
5411 
5412 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5413 				       &btf_id);
5414 		if (err)
5415 			verbose_linfo(env, insn_idx, "; ");
5416 		if (!err && t == BPF_READ && value_regno >= 0) {
5417 			/* ctx access returns either a scalar, or a
5418 			 * PTR_TO_PACKET[_META,_END]. In the latter
5419 			 * case, we know the offset is zero.
5420 			 */
5421 			if (reg_type == SCALAR_VALUE) {
5422 				mark_reg_unknown(env, regs, value_regno);
5423 			} else {
5424 				mark_reg_known_zero(env, regs,
5425 						    value_regno);
5426 				if (type_may_be_null(reg_type))
5427 					regs[value_regno].id = ++env->id_gen;
5428 				/* A load of ctx field could have different
5429 				 * actual load size with the one encoded in the
5430 				 * insn. When the dst is PTR, it is for sure not
5431 				 * a sub-register.
5432 				 */
5433 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5434 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5435 					regs[value_regno].btf = btf;
5436 					regs[value_regno].btf_id = btf_id;
5437 				}
5438 			}
5439 			regs[value_regno].type = reg_type;
5440 		}
5441 
5442 	} else if (reg->type == PTR_TO_STACK) {
5443 		/* Basic bounds checks. */
5444 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5445 		if (err)
5446 			return err;
5447 
5448 		state = func(env, reg);
5449 		err = update_stack_depth(env, state, off);
5450 		if (err)
5451 			return err;
5452 
5453 		if (t == BPF_READ)
5454 			err = check_stack_read(env, regno, off, size,
5455 					       value_regno);
5456 		else
5457 			err = check_stack_write(env, regno, off, size,
5458 						value_regno, insn_idx);
5459 	} else if (reg_is_pkt_pointer(reg)) {
5460 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5461 			verbose(env, "cannot write into packet\n");
5462 			return -EACCES;
5463 		}
5464 		if (t == BPF_WRITE && value_regno >= 0 &&
5465 		    is_pointer_value(env, value_regno)) {
5466 			verbose(env, "R%d leaks addr into packet\n",
5467 				value_regno);
5468 			return -EACCES;
5469 		}
5470 		err = check_packet_access(env, regno, off, size, false);
5471 		if (!err && t == BPF_READ && value_regno >= 0)
5472 			mark_reg_unknown(env, regs, value_regno);
5473 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5474 		if (t == BPF_WRITE && value_regno >= 0 &&
5475 		    is_pointer_value(env, value_regno)) {
5476 			verbose(env, "R%d leaks addr into flow keys\n",
5477 				value_regno);
5478 			return -EACCES;
5479 		}
5480 
5481 		err = check_flow_keys_access(env, off, size);
5482 		if (!err && t == BPF_READ && value_regno >= 0)
5483 			mark_reg_unknown(env, regs, value_regno);
5484 	} else if (type_is_sk_pointer(reg->type)) {
5485 		if (t == BPF_WRITE) {
5486 			verbose(env, "R%d cannot write into %s\n",
5487 				regno, reg_type_str(env, reg->type));
5488 			return -EACCES;
5489 		}
5490 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5491 		if (!err && value_regno >= 0)
5492 			mark_reg_unknown(env, regs, value_regno);
5493 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5494 		err = check_tp_buffer_access(env, reg, regno, off, size);
5495 		if (!err && t == BPF_READ && value_regno >= 0)
5496 			mark_reg_unknown(env, regs, value_regno);
5497 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5498 		   !type_may_be_null(reg->type)) {
5499 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5500 					      value_regno);
5501 	} else if (reg->type == CONST_PTR_TO_MAP) {
5502 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5503 					      value_regno);
5504 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5505 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5506 		u32 *max_access;
5507 
5508 		if (rdonly_mem) {
5509 			if (t == BPF_WRITE) {
5510 				verbose(env, "R%d cannot write into %s\n",
5511 					regno, reg_type_str(env, reg->type));
5512 				return -EACCES;
5513 			}
5514 			max_access = &env->prog->aux->max_rdonly_access;
5515 		} else {
5516 			max_access = &env->prog->aux->max_rdwr_access;
5517 		}
5518 
5519 		err = check_buffer_access(env, reg, regno, off, size, false,
5520 					  max_access);
5521 
5522 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5523 			mark_reg_unknown(env, regs, value_regno);
5524 	} else {
5525 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5526 			reg_type_str(env, reg->type));
5527 		return -EACCES;
5528 	}
5529 
5530 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5531 	    regs[value_regno].type == SCALAR_VALUE) {
5532 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5533 		coerce_reg_to_size(&regs[value_regno], size);
5534 	}
5535 	return err;
5536 }
5537 
5538 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5539 {
5540 	int load_reg;
5541 	int err;
5542 
5543 	switch (insn->imm) {
5544 	case BPF_ADD:
5545 	case BPF_ADD | BPF_FETCH:
5546 	case BPF_AND:
5547 	case BPF_AND | BPF_FETCH:
5548 	case BPF_OR:
5549 	case BPF_OR | BPF_FETCH:
5550 	case BPF_XOR:
5551 	case BPF_XOR | BPF_FETCH:
5552 	case BPF_XCHG:
5553 	case BPF_CMPXCHG:
5554 		break;
5555 	default:
5556 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5557 		return -EINVAL;
5558 	}
5559 
5560 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5561 		verbose(env, "invalid atomic operand size\n");
5562 		return -EINVAL;
5563 	}
5564 
5565 	/* check src1 operand */
5566 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5567 	if (err)
5568 		return err;
5569 
5570 	/* check src2 operand */
5571 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5572 	if (err)
5573 		return err;
5574 
5575 	if (insn->imm == BPF_CMPXCHG) {
5576 		/* Check comparison of R0 with memory location */
5577 		const u32 aux_reg = BPF_REG_0;
5578 
5579 		err = check_reg_arg(env, aux_reg, SRC_OP);
5580 		if (err)
5581 			return err;
5582 
5583 		if (is_pointer_value(env, aux_reg)) {
5584 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5585 			return -EACCES;
5586 		}
5587 	}
5588 
5589 	if (is_pointer_value(env, insn->src_reg)) {
5590 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5591 		return -EACCES;
5592 	}
5593 
5594 	if (is_ctx_reg(env, insn->dst_reg) ||
5595 	    is_pkt_reg(env, insn->dst_reg) ||
5596 	    is_flow_key_reg(env, insn->dst_reg) ||
5597 	    is_sk_reg(env, insn->dst_reg)) {
5598 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5599 			insn->dst_reg,
5600 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5601 		return -EACCES;
5602 	}
5603 
5604 	if (insn->imm & BPF_FETCH) {
5605 		if (insn->imm == BPF_CMPXCHG)
5606 			load_reg = BPF_REG_0;
5607 		else
5608 			load_reg = insn->src_reg;
5609 
5610 		/* check and record load of old value */
5611 		err = check_reg_arg(env, load_reg, DST_OP);
5612 		if (err)
5613 			return err;
5614 	} else {
5615 		/* This instruction accesses a memory location but doesn't
5616 		 * actually load it into a register.
5617 		 */
5618 		load_reg = -1;
5619 	}
5620 
5621 	/* Check whether we can read the memory, with second call for fetch
5622 	 * case to simulate the register fill.
5623 	 */
5624 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5625 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5626 	if (!err && load_reg >= 0)
5627 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5628 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5629 				       true);
5630 	if (err)
5631 		return err;
5632 
5633 	/* Check whether we can write into the same memory. */
5634 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5635 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5636 	if (err)
5637 		return err;
5638 
5639 	return 0;
5640 }
5641 
5642 /* When register 'regno' is used to read the stack (either directly or through
5643  * a helper function) make sure that it's within stack boundary and, depending
5644  * on the access type, that all elements of the stack are initialized.
5645  *
5646  * 'off' includes 'regno->off', but not its dynamic part (if any).
5647  *
5648  * All registers that have been spilled on the stack in the slots within the
5649  * read offsets are marked as read.
5650  */
5651 static int check_stack_range_initialized(
5652 		struct bpf_verifier_env *env, int regno, int off,
5653 		int access_size, bool zero_size_allowed,
5654 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5655 {
5656 	struct bpf_reg_state *reg = reg_state(env, regno);
5657 	struct bpf_func_state *state = func(env, reg);
5658 	int err, min_off, max_off, i, j, slot, spi;
5659 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5660 	enum bpf_access_type bounds_check_type;
5661 	/* Some accesses can write anything into the stack, others are
5662 	 * read-only.
5663 	 */
5664 	bool clobber = false;
5665 
5666 	if (access_size == 0 && !zero_size_allowed) {
5667 		verbose(env, "invalid zero-sized read\n");
5668 		return -EACCES;
5669 	}
5670 
5671 	if (type == ACCESS_HELPER) {
5672 		/* The bounds checks for writes are more permissive than for
5673 		 * reads. However, if raw_mode is not set, we'll do extra
5674 		 * checks below.
5675 		 */
5676 		bounds_check_type = BPF_WRITE;
5677 		clobber = true;
5678 	} else {
5679 		bounds_check_type = BPF_READ;
5680 	}
5681 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5682 					       type, bounds_check_type);
5683 	if (err)
5684 		return err;
5685 
5686 
5687 	if (tnum_is_const(reg->var_off)) {
5688 		min_off = max_off = reg->var_off.value + off;
5689 	} else {
5690 		/* Variable offset is prohibited for unprivileged mode for
5691 		 * simplicity since it requires corresponding support in
5692 		 * Spectre masking for stack ALU.
5693 		 * See also retrieve_ptr_limit().
5694 		 */
5695 		if (!env->bypass_spec_v1) {
5696 			char tn_buf[48];
5697 
5698 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5699 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5700 				regno, err_extra, tn_buf);
5701 			return -EACCES;
5702 		}
5703 		/* Only initialized buffer on stack is allowed to be accessed
5704 		 * with variable offset. With uninitialized buffer it's hard to
5705 		 * guarantee that whole memory is marked as initialized on
5706 		 * helper return since specific bounds are unknown what may
5707 		 * cause uninitialized stack leaking.
5708 		 */
5709 		if (meta && meta->raw_mode)
5710 			meta = NULL;
5711 
5712 		min_off = reg->smin_value + off;
5713 		max_off = reg->smax_value + off;
5714 	}
5715 
5716 	if (meta && meta->raw_mode) {
5717 		/* Ensure we won't be overwriting dynptrs when simulating byte
5718 		 * by byte access in check_helper_call using meta.access_size.
5719 		 * This would be a problem if we have a helper in the future
5720 		 * which takes:
5721 		 *
5722 		 *	helper(uninit_mem, len, dynptr)
5723 		 *
5724 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5725 		 * may end up writing to dynptr itself when touching memory from
5726 		 * arg 1. This can be relaxed on a case by case basis for known
5727 		 * safe cases, but reject due to the possibilitiy of aliasing by
5728 		 * default.
5729 		 */
5730 		for (i = min_off; i < max_off + access_size; i++) {
5731 			int stack_off = -i - 1;
5732 
5733 			spi = __get_spi(i);
5734 			/* raw_mode may write past allocated_stack */
5735 			if (state->allocated_stack <= stack_off)
5736 				continue;
5737 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5738 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5739 				return -EACCES;
5740 			}
5741 		}
5742 		meta->access_size = access_size;
5743 		meta->regno = regno;
5744 		return 0;
5745 	}
5746 
5747 	for (i = min_off; i < max_off + access_size; i++) {
5748 		u8 *stype;
5749 
5750 		slot = -i - 1;
5751 		spi = slot / BPF_REG_SIZE;
5752 		if (state->allocated_stack <= slot)
5753 			goto err;
5754 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5755 		if (*stype == STACK_MISC)
5756 			goto mark;
5757 		if (*stype == STACK_ZERO) {
5758 			if (clobber) {
5759 				/* helper can write anything into the stack */
5760 				*stype = STACK_MISC;
5761 			}
5762 			goto mark;
5763 		}
5764 
5765 		if (is_spilled_reg(&state->stack[spi]) &&
5766 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5767 		     env->allow_ptr_leaks)) {
5768 			if (clobber) {
5769 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5770 				for (j = 0; j < BPF_REG_SIZE; j++)
5771 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5772 			}
5773 			goto mark;
5774 		}
5775 
5776 err:
5777 		if (tnum_is_const(reg->var_off)) {
5778 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5779 				err_extra, regno, min_off, i - min_off, access_size);
5780 		} else {
5781 			char tn_buf[48];
5782 
5783 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5784 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5785 				err_extra, regno, tn_buf, i - min_off, access_size);
5786 		}
5787 		return -EACCES;
5788 mark:
5789 		/* reading any byte out of 8-byte 'spill_slot' will cause
5790 		 * the whole slot to be marked as 'read'
5791 		 */
5792 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5793 			      state->stack[spi].spilled_ptr.parent,
5794 			      REG_LIVE_READ64);
5795 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5796 		 * be sure that whether stack slot is written to or not. Hence,
5797 		 * we must still conservatively propagate reads upwards even if
5798 		 * helper may write to the entire memory range.
5799 		 */
5800 	}
5801 	return update_stack_depth(env, state, min_off);
5802 }
5803 
5804 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5805 				   int access_size, bool zero_size_allowed,
5806 				   struct bpf_call_arg_meta *meta)
5807 {
5808 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5809 	u32 *max_access;
5810 
5811 	switch (base_type(reg->type)) {
5812 	case PTR_TO_PACKET:
5813 	case PTR_TO_PACKET_META:
5814 		return check_packet_access(env, regno, reg->off, access_size,
5815 					   zero_size_allowed);
5816 	case PTR_TO_MAP_KEY:
5817 		if (meta && meta->raw_mode) {
5818 			verbose(env, "R%d cannot write into %s\n", regno,
5819 				reg_type_str(env, reg->type));
5820 			return -EACCES;
5821 		}
5822 		return check_mem_region_access(env, regno, reg->off, access_size,
5823 					       reg->map_ptr->key_size, false);
5824 	case PTR_TO_MAP_VALUE:
5825 		if (check_map_access_type(env, regno, reg->off, access_size,
5826 					  meta && meta->raw_mode ? BPF_WRITE :
5827 					  BPF_READ))
5828 			return -EACCES;
5829 		return check_map_access(env, regno, reg->off, access_size,
5830 					zero_size_allowed, ACCESS_HELPER);
5831 	case PTR_TO_MEM:
5832 		if (type_is_rdonly_mem(reg->type)) {
5833 			if (meta && meta->raw_mode) {
5834 				verbose(env, "R%d cannot write into %s\n", regno,
5835 					reg_type_str(env, reg->type));
5836 				return -EACCES;
5837 			}
5838 		}
5839 		return check_mem_region_access(env, regno, reg->off,
5840 					       access_size, reg->mem_size,
5841 					       zero_size_allowed);
5842 	case PTR_TO_BUF:
5843 		if (type_is_rdonly_mem(reg->type)) {
5844 			if (meta && meta->raw_mode) {
5845 				verbose(env, "R%d cannot write into %s\n", regno,
5846 					reg_type_str(env, reg->type));
5847 				return -EACCES;
5848 			}
5849 
5850 			max_access = &env->prog->aux->max_rdonly_access;
5851 		} else {
5852 			max_access = &env->prog->aux->max_rdwr_access;
5853 		}
5854 		return check_buffer_access(env, reg, regno, reg->off,
5855 					   access_size, zero_size_allowed,
5856 					   max_access);
5857 	case PTR_TO_STACK:
5858 		return check_stack_range_initialized(
5859 				env,
5860 				regno, reg->off, access_size,
5861 				zero_size_allowed, ACCESS_HELPER, meta);
5862 	case PTR_TO_CTX:
5863 		/* in case the function doesn't know how to access the context,
5864 		 * (because we are in a program of type SYSCALL for example), we
5865 		 * can not statically check its size.
5866 		 * Dynamically check it now.
5867 		 */
5868 		if (!env->ops->convert_ctx_access) {
5869 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5870 			int offset = access_size - 1;
5871 
5872 			/* Allow zero-byte read from PTR_TO_CTX */
5873 			if (access_size == 0)
5874 				return zero_size_allowed ? 0 : -EACCES;
5875 
5876 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5877 						atype, -1, false);
5878 		}
5879 
5880 		fallthrough;
5881 	default: /* scalar_value or invalid ptr */
5882 		/* Allow zero-byte read from NULL, regardless of pointer type */
5883 		if (zero_size_allowed && access_size == 0 &&
5884 		    register_is_null(reg))
5885 			return 0;
5886 
5887 		verbose(env, "R%d type=%s ", regno,
5888 			reg_type_str(env, reg->type));
5889 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5890 		return -EACCES;
5891 	}
5892 }
5893 
5894 static int check_mem_size_reg(struct bpf_verifier_env *env,
5895 			      struct bpf_reg_state *reg, u32 regno,
5896 			      bool zero_size_allowed,
5897 			      struct bpf_call_arg_meta *meta)
5898 {
5899 	int err;
5900 
5901 	/* This is used to refine r0 return value bounds for helpers
5902 	 * that enforce this value as an upper bound on return values.
5903 	 * See do_refine_retval_range() for helpers that can refine
5904 	 * the return value. C type of helper is u32 so we pull register
5905 	 * bound from umax_value however, if negative verifier errors
5906 	 * out. Only upper bounds can be learned because retval is an
5907 	 * int type and negative retvals are allowed.
5908 	 */
5909 	meta->msize_max_value = reg->umax_value;
5910 
5911 	/* The register is SCALAR_VALUE; the access check
5912 	 * happens using its boundaries.
5913 	 */
5914 	if (!tnum_is_const(reg->var_off))
5915 		/* For unprivileged variable accesses, disable raw
5916 		 * mode so that the program is required to
5917 		 * initialize all the memory that the helper could
5918 		 * just partially fill up.
5919 		 */
5920 		meta = NULL;
5921 
5922 	if (reg->smin_value < 0) {
5923 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5924 			regno);
5925 		return -EACCES;
5926 	}
5927 
5928 	if (reg->umin_value == 0) {
5929 		err = check_helper_mem_access(env, regno - 1, 0,
5930 					      zero_size_allowed,
5931 					      meta);
5932 		if (err)
5933 			return err;
5934 	}
5935 
5936 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5937 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5938 			regno);
5939 		return -EACCES;
5940 	}
5941 	err = check_helper_mem_access(env, regno - 1,
5942 				      reg->umax_value,
5943 				      zero_size_allowed, meta);
5944 	if (!err)
5945 		err = mark_chain_precision(env, regno);
5946 	return err;
5947 }
5948 
5949 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5950 		   u32 regno, u32 mem_size)
5951 {
5952 	bool may_be_null = type_may_be_null(reg->type);
5953 	struct bpf_reg_state saved_reg;
5954 	struct bpf_call_arg_meta meta;
5955 	int err;
5956 
5957 	if (register_is_null(reg))
5958 		return 0;
5959 
5960 	memset(&meta, 0, sizeof(meta));
5961 	/* Assuming that the register contains a value check if the memory
5962 	 * access is safe. Temporarily save and restore the register's state as
5963 	 * the conversion shouldn't be visible to a caller.
5964 	 */
5965 	if (may_be_null) {
5966 		saved_reg = *reg;
5967 		mark_ptr_not_null_reg(reg);
5968 	}
5969 
5970 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5971 	/* Check access for BPF_WRITE */
5972 	meta.raw_mode = true;
5973 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5974 
5975 	if (may_be_null)
5976 		*reg = saved_reg;
5977 
5978 	return err;
5979 }
5980 
5981 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5982 				    u32 regno)
5983 {
5984 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5985 	bool may_be_null = type_may_be_null(mem_reg->type);
5986 	struct bpf_reg_state saved_reg;
5987 	struct bpf_call_arg_meta meta;
5988 	int err;
5989 
5990 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5991 
5992 	memset(&meta, 0, sizeof(meta));
5993 
5994 	if (may_be_null) {
5995 		saved_reg = *mem_reg;
5996 		mark_ptr_not_null_reg(mem_reg);
5997 	}
5998 
5999 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6000 	/* Check access for BPF_WRITE */
6001 	meta.raw_mode = true;
6002 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6003 
6004 	if (may_be_null)
6005 		*mem_reg = saved_reg;
6006 	return err;
6007 }
6008 
6009 /* Implementation details:
6010  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6011  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6012  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6013  * Two separate bpf_obj_new will also have different reg->id.
6014  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6015  * clears reg->id after value_or_null->value transition, since the verifier only
6016  * cares about the range of access to valid map value pointer and doesn't care
6017  * about actual address of the map element.
6018  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6019  * reg->id > 0 after value_or_null->value transition. By doing so
6020  * two bpf_map_lookups will be considered two different pointers that
6021  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6022  * returned from bpf_obj_new.
6023  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6024  * dead-locks.
6025  * Since only one bpf_spin_lock is allowed the checks are simpler than
6026  * reg_is_refcounted() logic. The verifier needs to remember only
6027  * one spin_lock instead of array of acquired_refs.
6028  * cur_state->active_lock remembers which map value element or allocated
6029  * object got locked and clears it after bpf_spin_unlock.
6030  */
6031 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6032 			     bool is_lock)
6033 {
6034 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6035 	struct bpf_verifier_state *cur = env->cur_state;
6036 	bool is_const = tnum_is_const(reg->var_off);
6037 	u64 val = reg->var_off.value;
6038 	struct bpf_map *map = NULL;
6039 	struct btf *btf = NULL;
6040 	struct btf_record *rec;
6041 
6042 	if (!is_const) {
6043 		verbose(env,
6044 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6045 			regno);
6046 		return -EINVAL;
6047 	}
6048 	if (reg->type == PTR_TO_MAP_VALUE) {
6049 		map = reg->map_ptr;
6050 		if (!map->btf) {
6051 			verbose(env,
6052 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6053 				map->name);
6054 			return -EINVAL;
6055 		}
6056 	} else {
6057 		btf = reg->btf;
6058 	}
6059 
6060 	rec = reg_btf_record(reg);
6061 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6062 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6063 			map ? map->name : "kptr");
6064 		return -EINVAL;
6065 	}
6066 	if (rec->spin_lock_off != val + reg->off) {
6067 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6068 			val + reg->off, rec->spin_lock_off);
6069 		return -EINVAL;
6070 	}
6071 	if (is_lock) {
6072 		if (cur->active_lock.ptr) {
6073 			verbose(env,
6074 				"Locking two bpf_spin_locks are not allowed\n");
6075 			return -EINVAL;
6076 		}
6077 		if (map)
6078 			cur->active_lock.ptr = map;
6079 		else
6080 			cur->active_lock.ptr = btf;
6081 		cur->active_lock.id = reg->id;
6082 	} else {
6083 		void *ptr;
6084 
6085 		if (map)
6086 			ptr = map;
6087 		else
6088 			ptr = btf;
6089 
6090 		if (!cur->active_lock.ptr) {
6091 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6092 			return -EINVAL;
6093 		}
6094 		if (cur->active_lock.ptr != ptr ||
6095 		    cur->active_lock.id != reg->id) {
6096 			verbose(env, "bpf_spin_unlock of different lock\n");
6097 			return -EINVAL;
6098 		}
6099 
6100 		invalidate_non_owning_refs(env);
6101 
6102 		cur->active_lock.ptr = NULL;
6103 		cur->active_lock.id = 0;
6104 	}
6105 	return 0;
6106 }
6107 
6108 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6109 			      struct bpf_call_arg_meta *meta)
6110 {
6111 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6112 	bool is_const = tnum_is_const(reg->var_off);
6113 	struct bpf_map *map = reg->map_ptr;
6114 	u64 val = reg->var_off.value;
6115 
6116 	if (!is_const) {
6117 		verbose(env,
6118 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6119 			regno);
6120 		return -EINVAL;
6121 	}
6122 	if (!map->btf) {
6123 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6124 			map->name);
6125 		return -EINVAL;
6126 	}
6127 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6128 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6129 		return -EINVAL;
6130 	}
6131 	if (map->record->timer_off != val + reg->off) {
6132 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6133 			val + reg->off, map->record->timer_off);
6134 		return -EINVAL;
6135 	}
6136 	if (meta->map_ptr) {
6137 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6138 		return -EFAULT;
6139 	}
6140 	meta->map_uid = reg->map_uid;
6141 	meta->map_ptr = map;
6142 	return 0;
6143 }
6144 
6145 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6146 			     struct bpf_call_arg_meta *meta)
6147 {
6148 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6149 	struct bpf_map *map_ptr = reg->map_ptr;
6150 	struct btf_field *kptr_field;
6151 	u32 kptr_off;
6152 
6153 	if (!tnum_is_const(reg->var_off)) {
6154 		verbose(env,
6155 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6156 			regno);
6157 		return -EINVAL;
6158 	}
6159 	if (!map_ptr->btf) {
6160 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6161 			map_ptr->name);
6162 		return -EINVAL;
6163 	}
6164 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6165 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6166 		return -EINVAL;
6167 	}
6168 
6169 	meta->map_ptr = map_ptr;
6170 	kptr_off = reg->off + reg->var_off.value;
6171 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6172 	if (!kptr_field) {
6173 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6174 		return -EACCES;
6175 	}
6176 	if (kptr_field->type != BPF_KPTR_REF) {
6177 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6178 		return -EACCES;
6179 	}
6180 	meta->kptr_field = kptr_field;
6181 	return 0;
6182 }
6183 
6184 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6185  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6186  *
6187  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6188  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6189  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6190  *
6191  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6192  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6193  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6194  * mutate the view of the dynptr and also possibly destroy it. In the latter
6195  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6196  * memory that dynptr points to.
6197  *
6198  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6199  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6200  * readonly dynptr view yet, hence only the first case is tracked and checked.
6201  *
6202  * This is consistent with how C applies the const modifier to a struct object,
6203  * where the pointer itself inside bpf_dynptr becomes const but not what it
6204  * points to.
6205  *
6206  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6207  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6208  */
6209 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
6210 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
6211 {
6212 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6213 	int spi = 0;
6214 
6215 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6216 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6217 	 */
6218 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6219 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6220 		return -EFAULT;
6221 	}
6222 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
6223 	 * check_func_arg_reg_off's logic. We only need to check offset
6224 	 * and its alignment for PTR_TO_STACK.
6225 	 */
6226 	if (reg->type == PTR_TO_STACK) {
6227 		spi = dynptr_get_spi(env, reg);
6228 		if (spi < 0 && spi != -ERANGE)
6229 			return spi;
6230 	}
6231 
6232 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6233 	 *		 constructing a mutable bpf_dynptr object.
6234 	 *
6235 	 *		 Currently, this is only possible with PTR_TO_STACK
6236 	 *		 pointing to a region of at least 16 bytes which doesn't
6237 	 *		 contain an existing bpf_dynptr.
6238 	 *
6239 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6240 	 *		 mutated or destroyed. However, the memory it points to
6241 	 *		 may be mutated.
6242 	 *
6243 	 *  None       - Points to a initialized dynptr that can be mutated and
6244 	 *		 destroyed, including mutation of the memory it points
6245 	 *		 to.
6246 	 */
6247 	if (arg_type & MEM_UNINIT) {
6248 		if (!is_dynptr_reg_valid_uninit(env, reg, spi)) {
6249 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6250 			return -EINVAL;
6251 		}
6252 
6253 		/* We only support one dynptr being uninitialized at the moment,
6254 		 * which is sufficient for the helper functions we have right now.
6255 		 */
6256 		if (meta->uninit_dynptr_regno) {
6257 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6258 			return -EFAULT;
6259 		}
6260 
6261 		meta->uninit_dynptr_regno = regno;
6262 	} else /* MEM_RDONLY and None case from above */ {
6263 		int err;
6264 
6265 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6266 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6267 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6268 			return -EINVAL;
6269 		}
6270 
6271 		if (!is_dynptr_reg_valid_init(env, reg, spi)) {
6272 			verbose(env,
6273 				"Expected an initialized dynptr as arg #%d\n",
6274 				regno);
6275 			return -EINVAL;
6276 		}
6277 
6278 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6279 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6280 			const char *err_extra = "";
6281 
6282 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6283 			case DYNPTR_TYPE_LOCAL:
6284 				err_extra = "local";
6285 				break;
6286 			case DYNPTR_TYPE_RINGBUF:
6287 				err_extra = "ringbuf";
6288 				break;
6289 			default:
6290 				err_extra = "<unknown>";
6291 				break;
6292 			}
6293 			verbose(env,
6294 				"Expected a dynptr of type %s as arg #%d\n",
6295 				err_extra, regno);
6296 			return -EINVAL;
6297 		}
6298 
6299 		err = mark_dynptr_read(env, reg);
6300 		if (err)
6301 			return err;
6302 	}
6303 	return 0;
6304 }
6305 
6306 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6307 {
6308 	return type == ARG_CONST_SIZE ||
6309 	       type == ARG_CONST_SIZE_OR_ZERO;
6310 }
6311 
6312 static bool arg_type_is_release(enum bpf_arg_type type)
6313 {
6314 	return type & OBJ_RELEASE;
6315 }
6316 
6317 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6318 {
6319 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6320 }
6321 
6322 static int int_ptr_type_to_size(enum bpf_arg_type type)
6323 {
6324 	if (type == ARG_PTR_TO_INT)
6325 		return sizeof(u32);
6326 	else if (type == ARG_PTR_TO_LONG)
6327 		return sizeof(u64);
6328 
6329 	return -EINVAL;
6330 }
6331 
6332 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6333 				 const struct bpf_call_arg_meta *meta,
6334 				 enum bpf_arg_type *arg_type)
6335 {
6336 	if (!meta->map_ptr) {
6337 		/* kernel subsystem misconfigured verifier */
6338 		verbose(env, "invalid map_ptr to access map->type\n");
6339 		return -EACCES;
6340 	}
6341 
6342 	switch (meta->map_ptr->map_type) {
6343 	case BPF_MAP_TYPE_SOCKMAP:
6344 	case BPF_MAP_TYPE_SOCKHASH:
6345 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6346 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6347 		} else {
6348 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6349 			return -EINVAL;
6350 		}
6351 		break;
6352 	case BPF_MAP_TYPE_BLOOM_FILTER:
6353 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6354 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6355 		break;
6356 	default:
6357 		break;
6358 	}
6359 	return 0;
6360 }
6361 
6362 struct bpf_reg_types {
6363 	const enum bpf_reg_type types[10];
6364 	u32 *btf_id;
6365 };
6366 
6367 static const struct bpf_reg_types sock_types = {
6368 	.types = {
6369 		PTR_TO_SOCK_COMMON,
6370 		PTR_TO_SOCKET,
6371 		PTR_TO_TCP_SOCK,
6372 		PTR_TO_XDP_SOCK,
6373 	},
6374 };
6375 
6376 #ifdef CONFIG_NET
6377 static const struct bpf_reg_types btf_id_sock_common_types = {
6378 	.types = {
6379 		PTR_TO_SOCK_COMMON,
6380 		PTR_TO_SOCKET,
6381 		PTR_TO_TCP_SOCK,
6382 		PTR_TO_XDP_SOCK,
6383 		PTR_TO_BTF_ID,
6384 		PTR_TO_BTF_ID | PTR_TRUSTED,
6385 	},
6386 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6387 };
6388 #endif
6389 
6390 static const struct bpf_reg_types mem_types = {
6391 	.types = {
6392 		PTR_TO_STACK,
6393 		PTR_TO_PACKET,
6394 		PTR_TO_PACKET_META,
6395 		PTR_TO_MAP_KEY,
6396 		PTR_TO_MAP_VALUE,
6397 		PTR_TO_MEM,
6398 		PTR_TO_MEM | MEM_RINGBUF,
6399 		PTR_TO_BUF,
6400 	},
6401 };
6402 
6403 static const struct bpf_reg_types int_ptr_types = {
6404 	.types = {
6405 		PTR_TO_STACK,
6406 		PTR_TO_PACKET,
6407 		PTR_TO_PACKET_META,
6408 		PTR_TO_MAP_KEY,
6409 		PTR_TO_MAP_VALUE,
6410 	},
6411 };
6412 
6413 static const struct bpf_reg_types spin_lock_types = {
6414 	.types = {
6415 		PTR_TO_MAP_VALUE,
6416 		PTR_TO_BTF_ID | MEM_ALLOC,
6417 	}
6418 };
6419 
6420 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6421 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6422 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6423 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6424 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6425 static const struct bpf_reg_types btf_ptr_types = {
6426 	.types = {
6427 		PTR_TO_BTF_ID,
6428 		PTR_TO_BTF_ID | PTR_TRUSTED,
6429 		PTR_TO_BTF_ID | MEM_RCU,
6430 	},
6431 };
6432 static const struct bpf_reg_types percpu_btf_ptr_types = {
6433 	.types = {
6434 		PTR_TO_BTF_ID | MEM_PERCPU,
6435 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6436 	}
6437 };
6438 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6439 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6440 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6441 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6442 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6443 static const struct bpf_reg_types dynptr_types = {
6444 	.types = {
6445 		PTR_TO_STACK,
6446 		CONST_PTR_TO_DYNPTR,
6447 	}
6448 };
6449 
6450 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6451 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6452 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6453 	[ARG_CONST_SIZE]		= &scalar_types,
6454 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6455 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6456 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6457 	[ARG_PTR_TO_CTX]		= &context_types,
6458 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6459 #ifdef CONFIG_NET
6460 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6461 #endif
6462 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6463 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6464 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6465 	[ARG_PTR_TO_MEM]		= &mem_types,
6466 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6467 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6468 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6469 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6470 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6471 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6472 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6473 	[ARG_PTR_TO_TIMER]		= &timer_types,
6474 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6475 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6476 };
6477 
6478 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6479 			  enum bpf_arg_type arg_type,
6480 			  const u32 *arg_btf_id,
6481 			  struct bpf_call_arg_meta *meta)
6482 {
6483 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6484 	enum bpf_reg_type expected, type = reg->type;
6485 	const struct bpf_reg_types *compatible;
6486 	int i, j;
6487 
6488 	compatible = compatible_reg_types[base_type(arg_type)];
6489 	if (!compatible) {
6490 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6491 		return -EFAULT;
6492 	}
6493 
6494 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6495 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6496 	 *
6497 	 * Same for MAYBE_NULL:
6498 	 *
6499 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6500 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6501 	 *
6502 	 * Therefore we fold these flags depending on the arg_type before comparison.
6503 	 */
6504 	if (arg_type & MEM_RDONLY)
6505 		type &= ~MEM_RDONLY;
6506 	if (arg_type & PTR_MAYBE_NULL)
6507 		type &= ~PTR_MAYBE_NULL;
6508 
6509 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6510 		expected = compatible->types[i];
6511 		if (expected == NOT_INIT)
6512 			break;
6513 
6514 		if (type == expected)
6515 			goto found;
6516 	}
6517 
6518 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6519 	for (j = 0; j + 1 < i; j++)
6520 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6521 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6522 	return -EACCES;
6523 
6524 found:
6525 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6526 		/* For bpf_sk_release, it needs to match against first member
6527 		 * 'struct sock_common', hence make an exception for it. This
6528 		 * allows bpf_sk_release to work for multiple socket types.
6529 		 */
6530 		bool strict_type_match = arg_type_is_release(arg_type) &&
6531 					 meta->func_id != BPF_FUNC_sk_release;
6532 
6533 		if (!arg_btf_id) {
6534 			if (!compatible->btf_id) {
6535 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6536 				return -EFAULT;
6537 			}
6538 			arg_btf_id = compatible->btf_id;
6539 		}
6540 
6541 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6542 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6543 				return -EACCES;
6544 		} else {
6545 			if (arg_btf_id == BPF_PTR_POISON) {
6546 				verbose(env, "verifier internal error:");
6547 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6548 					regno);
6549 				return -EACCES;
6550 			}
6551 
6552 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6553 						  btf_vmlinux, *arg_btf_id,
6554 						  strict_type_match)) {
6555 				verbose(env, "R%d is of type %s but %s is expected\n",
6556 					regno, kernel_type_name(reg->btf, reg->btf_id),
6557 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6558 				return -EACCES;
6559 			}
6560 		}
6561 	} else if (type_is_alloc(reg->type)) {
6562 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6563 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6564 			return -EFAULT;
6565 		}
6566 	}
6567 
6568 	return 0;
6569 }
6570 
6571 static struct btf_field *
6572 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6573 {
6574 	struct btf_field *field;
6575 	struct btf_record *rec;
6576 
6577 	rec = reg_btf_record(reg);
6578 	if (!rec)
6579 		return NULL;
6580 
6581 	field = btf_record_find(rec, off, fields);
6582 	if (!field)
6583 		return NULL;
6584 
6585 	return field;
6586 }
6587 
6588 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6589 			   const struct bpf_reg_state *reg, int regno,
6590 			   enum bpf_arg_type arg_type)
6591 {
6592 	u32 type = reg->type;
6593 
6594 	/* When referenced register is passed to release function, its fixed
6595 	 * offset must be 0.
6596 	 *
6597 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6598 	 * meta->release_regno.
6599 	 */
6600 	if (arg_type_is_release(arg_type)) {
6601 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6602 		 * may not directly point to the object being released, but to
6603 		 * dynptr pointing to such object, which might be at some offset
6604 		 * on the stack. In that case, we simply to fallback to the
6605 		 * default handling.
6606 		 */
6607 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6608 			return 0;
6609 
6610 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6611 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6612 				return __check_ptr_off_reg(env, reg, regno, true);
6613 
6614 			verbose(env, "R%d must have zero offset when passed to release func\n",
6615 				regno);
6616 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6617 				kernel_type_name(reg->btf, reg->btf_id), reg->off);
6618 			return -EINVAL;
6619 		}
6620 
6621 		/* Doing check_ptr_off_reg check for the offset will catch this
6622 		 * because fixed_off_ok is false, but checking here allows us
6623 		 * to give the user a better error message.
6624 		 */
6625 		if (reg->off) {
6626 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6627 				regno);
6628 			return -EINVAL;
6629 		}
6630 		return __check_ptr_off_reg(env, reg, regno, false);
6631 	}
6632 
6633 	switch (type) {
6634 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6635 	case PTR_TO_STACK:
6636 	case PTR_TO_PACKET:
6637 	case PTR_TO_PACKET_META:
6638 	case PTR_TO_MAP_KEY:
6639 	case PTR_TO_MAP_VALUE:
6640 	case PTR_TO_MEM:
6641 	case PTR_TO_MEM | MEM_RDONLY:
6642 	case PTR_TO_MEM | MEM_RINGBUF:
6643 	case PTR_TO_BUF:
6644 	case PTR_TO_BUF | MEM_RDONLY:
6645 	case SCALAR_VALUE:
6646 		return 0;
6647 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6648 	 * fixed offset.
6649 	 */
6650 	case PTR_TO_BTF_ID:
6651 	case PTR_TO_BTF_ID | MEM_ALLOC:
6652 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6653 	case PTR_TO_BTF_ID | MEM_RCU:
6654 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6655 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6656 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6657 		 * its fixed offset must be 0. In the other cases, fixed offset
6658 		 * can be non-zero. This was already checked above. So pass
6659 		 * fixed_off_ok as true to allow fixed offset for all other
6660 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6661 		 * still need to do checks instead of returning.
6662 		 */
6663 		return __check_ptr_off_reg(env, reg, regno, true);
6664 	default:
6665 		return __check_ptr_off_reg(env, reg, regno, false);
6666 	}
6667 }
6668 
6669 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6670 {
6671 	struct bpf_func_state *state = func(env, reg);
6672 	int spi;
6673 
6674 	if (reg->type == CONST_PTR_TO_DYNPTR)
6675 		return reg->id;
6676 	spi = dynptr_get_spi(env, reg);
6677 	if (spi < 0)
6678 		return spi;
6679 	return state->stack[spi].spilled_ptr.id;
6680 }
6681 
6682 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6683 {
6684 	struct bpf_func_state *state = func(env, reg);
6685 	int spi;
6686 
6687 	if (reg->type == CONST_PTR_TO_DYNPTR)
6688 		return reg->ref_obj_id;
6689 	spi = dynptr_get_spi(env, reg);
6690 	if (spi < 0)
6691 		return spi;
6692 	return state->stack[spi].spilled_ptr.ref_obj_id;
6693 }
6694 
6695 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6696 			  struct bpf_call_arg_meta *meta,
6697 			  const struct bpf_func_proto *fn)
6698 {
6699 	u32 regno = BPF_REG_1 + arg;
6700 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6701 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6702 	enum bpf_reg_type type = reg->type;
6703 	u32 *arg_btf_id = NULL;
6704 	int err = 0;
6705 
6706 	if (arg_type == ARG_DONTCARE)
6707 		return 0;
6708 
6709 	err = check_reg_arg(env, regno, SRC_OP);
6710 	if (err)
6711 		return err;
6712 
6713 	if (arg_type == ARG_ANYTHING) {
6714 		if (is_pointer_value(env, regno)) {
6715 			verbose(env, "R%d leaks addr into helper function\n",
6716 				regno);
6717 			return -EACCES;
6718 		}
6719 		return 0;
6720 	}
6721 
6722 	if (type_is_pkt_pointer(type) &&
6723 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6724 		verbose(env, "helper access to the packet is not allowed\n");
6725 		return -EACCES;
6726 	}
6727 
6728 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6729 		err = resolve_map_arg_type(env, meta, &arg_type);
6730 		if (err)
6731 			return err;
6732 	}
6733 
6734 	if (register_is_null(reg) && type_may_be_null(arg_type))
6735 		/* A NULL register has a SCALAR_VALUE type, so skip
6736 		 * type checking.
6737 		 */
6738 		goto skip_type_check;
6739 
6740 	/* arg_btf_id and arg_size are in a union. */
6741 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6742 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6743 		arg_btf_id = fn->arg_btf_id[arg];
6744 
6745 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6746 	if (err)
6747 		return err;
6748 
6749 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6750 	if (err)
6751 		return err;
6752 
6753 skip_type_check:
6754 	if (arg_type_is_release(arg_type)) {
6755 		if (arg_type_is_dynptr(arg_type)) {
6756 			struct bpf_func_state *state = func(env, reg);
6757 			int spi;
6758 
6759 			/* Only dynptr created on stack can be released, thus
6760 			 * the get_spi and stack state checks for spilled_ptr
6761 			 * should only be done before process_dynptr_func for
6762 			 * PTR_TO_STACK.
6763 			 */
6764 			if (reg->type == PTR_TO_STACK) {
6765 				spi = dynptr_get_spi(env, reg);
6766 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
6767 					verbose(env, "arg %d is an unacquired reference\n", regno);
6768 					return -EINVAL;
6769 				}
6770 			} else {
6771 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6772 				return -EINVAL;
6773 			}
6774 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6775 			verbose(env, "R%d must be referenced when passed to release function\n",
6776 				regno);
6777 			return -EINVAL;
6778 		}
6779 		if (meta->release_regno) {
6780 			verbose(env, "verifier internal error: more than one release argument\n");
6781 			return -EFAULT;
6782 		}
6783 		meta->release_regno = regno;
6784 	}
6785 
6786 	if (reg->ref_obj_id) {
6787 		if (meta->ref_obj_id) {
6788 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6789 				regno, reg->ref_obj_id,
6790 				meta->ref_obj_id);
6791 			return -EFAULT;
6792 		}
6793 		meta->ref_obj_id = reg->ref_obj_id;
6794 	}
6795 
6796 	switch (base_type(arg_type)) {
6797 	case ARG_CONST_MAP_PTR:
6798 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6799 		if (meta->map_ptr) {
6800 			/* Use map_uid (which is unique id of inner map) to reject:
6801 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6802 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6803 			 * if (inner_map1 && inner_map2) {
6804 			 *     timer = bpf_map_lookup_elem(inner_map1);
6805 			 *     if (timer)
6806 			 *         // mismatch would have been allowed
6807 			 *         bpf_timer_init(timer, inner_map2);
6808 			 * }
6809 			 *
6810 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6811 			 */
6812 			if (meta->map_ptr != reg->map_ptr ||
6813 			    meta->map_uid != reg->map_uid) {
6814 				verbose(env,
6815 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6816 					meta->map_uid, reg->map_uid);
6817 				return -EINVAL;
6818 			}
6819 		}
6820 		meta->map_ptr = reg->map_ptr;
6821 		meta->map_uid = reg->map_uid;
6822 		break;
6823 	case ARG_PTR_TO_MAP_KEY:
6824 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6825 		 * check that [key, key + map->key_size) are within
6826 		 * stack limits and initialized
6827 		 */
6828 		if (!meta->map_ptr) {
6829 			/* in function declaration map_ptr must come before
6830 			 * map_key, so that it's verified and known before
6831 			 * we have to check map_key here. Otherwise it means
6832 			 * that kernel subsystem misconfigured verifier
6833 			 */
6834 			verbose(env, "invalid map_ptr to access map->key\n");
6835 			return -EACCES;
6836 		}
6837 		err = check_helper_mem_access(env, regno,
6838 					      meta->map_ptr->key_size, false,
6839 					      NULL);
6840 		break;
6841 	case ARG_PTR_TO_MAP_VALUE:
6842 		if (type_may_be_null(arg_type) && register_is_null(reg))
6843 			return 0;
6844 
6845 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6846 		 * check [value, value + map->value_size) validity
6847 		 */
6848 		if (!meta->map_ptr) {
6849 			/* kernel subsystem misconfigured verifier */
6850 			verbose(env, "invalid map_ptr to access map->value\n");
6851 			return -EACCES;
6852 		}
6853 		meta->raw_mode = arg_type & MEM_UNINIT;
6854 		err = check_helper_mem_access(env, regno,
6855 					      meta->map_ptr->value_size, false,
6856 					      meta);
6857 		break;
6858 	case ARG_PTR_TO_PERCPU_BTF_ID:
6859 		if (!reg->btf_id) {
6860 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6861 			return -EACCES;
6862 		}
6863 		meta->ret_btf = reg->btf;
6864 		meta->ret_btf_id = reg->btf_id;
6865 		break;
6866 	case ARG_PTR_TO_SPIN_LOCK:
6867 		if (in_rbtree_lock_required_cb(env)) {
6868 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
6869 			return -EACCES;
6870 		}
6871 		if (meta->func_id == BPF_FUNC_spin_lock) {
6872 			err = process_spin_lock(env, regno, true);
6873 			if (err)
6874 				return err;
6875 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6876 			err = process_spin_lock(env, regno, false);
6877 			if (err)
6878 				return err;
6879 		} else {
6880 			verbose(env, "verifier internal error\n");
6881 			return -EFAULT;
6882 		}
6883 		break;
6884 	case ARG_PTR_TO_TIMER:
6885 		err = process_timer_func(env, regno, meta);
6886 		if (err)
6887 			return err;
6888 		break;
6889 	case ARG_PTR_TO_FUNC:
6890 		meta->subprogno = reg->subprogno;
6891 		break;
6892 	case ARG_PTR_TO_MEM:
6893 		/* The access to this pointer is only checked when we hit the
6894 		 * next is_mem_size argument below.
6895 		 */
6896 		meta->raw_mode = arg_type & MEM_UNINIT;
6897 		if (arg_type & MEM_FIXED_SIZE) {
6898 			err = check_helper_mem_access(env, regno,
6899 						      fn->arg_size[arg], false,
6900 						      meta);
6901 		}
6902 		break;
6903 	case ARG_CONST_SIZE:
6904 		err = check_mem_size_reg(env, reg, regno, false, meta);
6905 		break;
6906 	case ARG_CONST_SIZE_OR_ZERO:
6907 		err = check_mem_size_reg(env, reg, regno, true, meta);
6908 		break;
6909 	case ARG_PTR_TO_DYNPTR:
6910 		err = process_dynptr_func(env, regno, arg_type, meta);
6911 		if (err)
6912 			return err;
6913 		break;
6914 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6915 		if (!tnum_is_const(reg->var_off)) {
6916 			verbose(env, "R%d is not a known constant'\n",
6917 				regno);
6918 			return -EACCES;
6919 		}
6920 		meta->mem_size = reg->var_off.value;
6921 		err = mark_chain_precision(env, regno);
6922 		if (err)
6923 			return err;
6924 		break;
6925 	case ARG_PTR_TO_INT:
6926 	case ARG_PTR_TO_LONG:
6927 	{
6928 		int size = int_ptr_type_to_size(arg_type);
6929 
6930 		err = check_helper_mem_access(env, regno, size, false, meta);
6931 		if (err)
6932 			return err;
6933 		err = check_ptr_alignment(env, reg, 0, size, true);
6934 		break;
6935 	}
6936 	case ARG_PTR_TO_CONST_STR:
6937 	{
6938 		struct bpf_map *map = reg->map_ptr;
6939 		int map_off;
6940 		u64 map_addr;
6941 		char *str_ptr;
6942 
6943 		if (!bpf_map_is_rdonly(map)) {
6944 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6945 			return -EACCES;
6946 		}
6947 
6948 		if (!tnum_is_const(reg->var_off)) {
6949 			verbose(env, "R%d is not a constant address'\n", regno);
6950 			return -EACCES;
6951 		}
6952 
6953 		if (!map->ops->map_direct_value_addr) {
6954 			verbose(env, "no direct value access support for this map type\n");
6955 			return -EACCES;
6956 		}
6957 
6958 		err = check_map_access(env, regno, reg->off,
6959 				       map->value_size - reg->off, false,
6960 				       ACCESS_HELPER);
6961 		if (err)
6962 			return err;
6963 
6964 		map_off = reg->off + reg->var_off.value;
6965 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6966 		if (err) {
6967 			verbose(env, "direct value access on string failed\n");
6968 			return err;
6969 		}
6970 
6971 		str_ptr = (char *)(long)(map_addr);
6972 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6973 			verbose(env, "string is not zero-terminated\n");
6974 			return -EINVAL;
6975 		}
6976 		break;
6977 	}
6978 	case ARG_PTR_TO_KPTR:
6979 		err = process_kptr_func(env, regno, meta);
6980 		if (err)
6981 			return err;
6982 		break;
6983 	}
6984 
6985 	return err;
6986 }
6987 
6988 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6989 {
6990 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6991 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6992 
6993 	if (func_id != BPF_FUNC_map_update_elem)
6994 		return false;
6995 
6996 	/* It's not possible to get access to a locked struct sock in these
6997 	 * contexts, so updating is safe.
6998 	 */
6999 	switch (type) {
7000 	case BPF_PROG_TYPE_TRACING:
7001 		if (eatype == BPF_TRACE_ITER)
7002 			return true;
7003 		break;
7004 	case BPF_PROG_TYPE_SOCKET_FILTER:
7005 	case BPF_PROG_TYPE_SCHED_CLS:
7006 	case BPF_PROG_TYPE_SCHED_ACT:
7007 	case BPF_PROG_TYPE_XDP:
7008 	case BPF_PROG_TYPE_SK_REUSEPORT:
7009 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
7010 	case BPF_PROG_TYPE_SK_LOOKUP:
7011 		return true;
7012 	default:
7013 		break;
7014 	}
7015 
7016 	verbose(env, "cannot update sockmap in this context\n");
7017 	return false;
7018 }
7019 
7020 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7021 {
7022 	return env->prog->jit_requested &&
7023 	       bpf_jit_supports_subprog_tailcalls();
7024 }
7025 
7026 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7027 					struct bpf_map *map, int func_id)
7028 {
7029 	if (!map)
7030 		return 0;
7031 
7032 	/* We need a two way check, first is from map perspective ... */
7033 	switch (map->map_type) {
7034 	case BPF_MAP_TYPE_PROG_ARRAY:
7035 		if (func_id != BPF_FUNC_tail_call)
7036 			goto error;
7037 		break;
7038 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7039 		if (func_id != BPF_FUNC_perf_event_read &&
7040 		    func_id != BPF_FUNC_perf_event_output &&
7041 		    func_id != BPF_FUNC_skb_output &&
7042 		    func_id != BPF_FUNC_perf_event_read_value &&
7043 		    func_id != BPF_FUNC_xdp_output)
7044 			goto error;
7045 		break;
7046 	case BPF_MAP_TYPE_RINGBUF:
7047 		if (func_id != BPF_FUNC_ringbuf_output &&
7048 		    func_id != BPF_FUNC_ringbuf_reserve &&
7049 		    func_id != BPF_FUNC_ringbuf_query &&
7050 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7051 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7052 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
7053 			goto error;
7054 		break;
7055 	case BPF_MAP_TYPE_USER_RINGBUF:
7056 		if (func_id != BPF_FUNC_user_ringbuf_drain)
7057 			goto error;
7058 		break;
7059 	case BPF_MAP_TYPE_STACK_TRACE:
7060 		if (func_id != BPF_FUNC_get_stackid)
7061 			goto error;
7062 		break;
7063 	case BPF_MAP_TYPE_CGROUP_ARRAY:
7064 		if (func_id != BPF_FUNC_skb_under_cgroup &&
7065 		    func_id != BPF_FUNC_current_task_under_cgroup)
7066 			goto error;
7067 		break;
7068 	case BPF_MAP_TYPE_CGROUP_STORAGE:
7069 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7070 		if (func_id != BPF_FUNC_get_local_storage)
7071 			goto error;
7072 		break;
7073 	case BPF_MAP_TYPE_DEVMAP:
7074 	case BPF_MAP_TYPE_DEVMAP_HASH:
7075 		if (func_id != BPF_FUNC_redirect_map &&
7076 		    func_id != BPF_FUNC_map_lookup_elem)
7077 			goto error;
7078 		break;
7079 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
7080 	 * appear.
7081 	 */
7082 	case BPF_MAP_TYPE_CPUMAP:
7083 		if (func_id != BPF_FUNC_redirect_map)
7084 			goto error;
7085 		break;
7086 	case BPF_MAP_TYPE_XSKMAP:
7087 		if (func_id != BPF_FUNC_redirect_map &&
7088 		    func_id != BPF_FUNC_map_lookup_elem)
7089 			goto error;
7090 		break;
7091 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7092 	case BPF_MAP_TYPE_HASH_OF_MAPS:
7093 		if (func_id != BPF_FUNC_map_lookup_elem)
7094 			goto error;
7095 		break;
7096 	case BPF_MAP_TYPE_SOCKMAP:
7097 		if (func_id != BPF_FUNC_sk_redirect_map &&
7098 		    func_id != BPF_FUNC_sock_map_update &&
7099 		    func_id != BPF_FUNC_map_delete_elem &&
7100 		    func_id != BPF_FUNC_msg_redirect_map &&
7101 		    func_id != BPF_FUNC_sk_select_reuseport &&
7102 		    func_id != BPF_FUNC_map_lookup_elem &&
7103 		    !may_update_sockmap(env, func_id))
7104 			goto error;
7105 		break;
7106 	case BPF_MAP_TYPE_SOCKHASH:
7107 		if (func_id != BPF_FUNC_sk_redirect_hash &&
7108 		    func_id != BPF_FUNC_sock_hash_update &&
7109 		    func_id != BPF_FUNC_map_delete_elem &&
7110 		    func_id != BPF_FUNC_msg_redirect_hash &&
7111 		    func_id != BPF_FUNC_sk_select_reuseport &&
7112 		    func_id != BPF_FUNC_map_lookup_elem &&
7113 		    !may_update_sockmap(env, func_id))
7114 			goto error;
7115 		break;
7116 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7117 		if (func_id != BPF_FUNC_sk_select_reuseport)
7118 			goto error;
7119 		break;
7120 	case BPF_MAP_TYPE_QUEUE:
7121 	case BPF_MAP_TYPE_STACK:
7122 		if (func_id != BPF_FUNC_map_peek_elem &&
7123 		    func_id != BPF_FUNC_map_pop_elem &&
7124 		    func_id != BPF_FUNC_map_push_elem)
7125 			goto error;
7126 		break;
7127 	case BPF_MAP_TYPE_SK_STORAGE:
7128 		if (func_id != BPF_FUNC_sk_storage_get &&
7129 		    func_id != BPF_FUNC_sk_storage_delete)
7130 			goto error;
7131 		break;
7132 	case BPF_MAP_TYPE_INODE_STORAGE:
7133 		if (func_id != BPF_FUNC_inode_storage_get &&
7134 		    func_id != BPF_FUNC_inode_storage_delete)
7135 			goto error;
7136 		break;
7137 	case BPF_MAP_TYPE_TASK_STORAGE:
7138 		if (func_id != BPF_FUNC_task_storage_get &&
7139 		    func_id != BPF_FUNC_task_storage_delete)
7140 			goto error;
7141 		break;
7142 	case BPF_MAP_TYPE_CGRP_STORAGE:
7143 		if (func_id != BPF_FUNC_cgrp_storage_get &&
7144 		    func_id != BPF_FUNC_cgrp_storage_delete)
7145 			goto error;
7146 		break;
7147 	case BPF_MAP_TYPE_BLOOM_FILTER:
7148 		if (func_id != BPF_FUNC_map_peek_elem &&
7149 		    func_id != BPF_FUNC_map_push_elem)
7150 			goto error;
7151 		break;
7152 	default:
7153 		break;
7154 	}
7155 
7156 	/* ... and second from the function itself. */
7157 	switch (func_id) {
7158 	case BPF_FUNC_tail_call:
7159 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7160 			goto error;
7161 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7162 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7163 			return -EINVAL;
7164 		}
7165 		break;
7166 	case BPF_FUNC_perf_event_read:
7167 	case BPF_FUNC_perf_event_output:
7168 	case BPF_FUNC_perf_event_read_value:
7169 	case BPF_FUNC_skb_output:
7170 	case BPF_FUNC_xdp_output:
7171 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7172 			goto error;
7173 		break;
7174 	case BPF_FUNC_ringbuf_output:
7175 	case BPF_FUNC_ringbuf_reserve:
7176 	case BPF_FUNC_ringbuf_query:
7177 	case BPF_FUNC_ringbuf_reserve_dynptr:
7178 	case BPF_FUNC_ringbuf_submit_dynptr:
7179 	case BPF_FUNC_ringbuf_discard_dynptr:
7180 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7181 			goto error;
7182 		break;
7183 	case BPF_FUNC_user_ringbuf_drain:
7184 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7185 			goto error;
7186 		break;
7187 	case BPF_FUNC_get_stackid:
7188 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7189 			goto error;
7190 		break;
7191 	case BPF_FUNC_current_task_under_cgroup:
7192 	case BPF_FUNC_skb_under_cgroup:
7193 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7194 			goto error;
7195 		break;
7196 	case BPF_FUNC_redirect_map:
7197 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7198 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7199 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
7200 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
7201 			goto error;
7202 		break;
7203 	case BPF_FUNC_sk_redirect_map:
7204 	case BPF_FUNC_msg_redirect_map:
7205 	case BPF_FUNC_sock_map_update:
7206 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7207 			goto error;
7208 		break;
7209 	case BPF_FUNC_sk_redirect_hash:
7210 	case BPF_FUNC_msg_redirect_hash:
7211 	case BPF_FUNC_sock_hash_update:
7212 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7213 			goto error;
7214 		break;
7215 	case BPF_FUNC_get_local_storage:
7216 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7217 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7218 			goto error;
7219 		break;
7220 	case BPF_FUNC_sk_select_reuseport:
7221 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7222 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7223 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
7224 			goto error;
7225 		break;
7226 	case BPF_FUNC_map_pop_elem:
7227 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7228 		    map->map_type != BPF_MAP_TYPE_STACK)
7229 			goto error;
7230 		break;
7231 	case BPF_FUNC_map_peek_elem:
7232 	case BPF_FUNC_map_push_elem:
7233 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7234 		    map->map_type != BPF_MAP_TYPE_STACK &&
7235 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7236 			goto error;
7237 		break;
7238 	case BPF_FUNC_map_lookup_percpu_elem:
7239 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7240 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7241 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7242 			goto error;
7243 		break;
7244 	case BPF_FUNC_sk_storage_get:
7245 	case BPF_FUNC_sk_storage_delete:
7246 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7247 			goto error;
7248 		break;
7249 	case BPF_FUNC_inode_storage_get:
7250 	case BPF_FUNC_inode_storage_delete:
7251 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7252 			goto error;
7253 		break;
7254 	case BPF_FUNC_task_storage_get:
7255 	case BPF_FUNC_task_storage_delete:
7256 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7257 			goto error;
7258 		break;
7259 	case BPF_FUNC_cgrp_storage_get:
7260 	case BPF_FUNC_cgrp_storage_delete:
7261 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7262 			goto error;
7263 		break;
7264 	default:
7265 		break;
7266 	}
7267 
7268 	return 0;
7269 error:
7270 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
7271 		map->map_type, func_id_name(func_id), func_id);
7272 	return -EINVAL;
7273 }
7274 
7275 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7276 {
7277 	int count = 0;
7278 
7279 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7280 		count++;
7281 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7282 		count++;
7283 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7284 		count++;
7285 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7286 		count++;
7287 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7288 		count++;
7289 
7290 	/* We only support one arg being in raw mode at the moment,
7291 	 * which is sufficient for the helper functions we have
7292 	 * right now.
7293 	 */
7294 	return count <= 1;
7295 }
7296 
7297 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7298 {
7299 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7300 	bool has_size = fn->arg_size[arg] != 0;
7301 	bool is_next_size = false;
7302 
7303 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7304 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7305 
7306 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7307 		return is_next_size;
7308 
7309 	return has_size == is_next_size || is_next_size == is_fixed;
7310 }
7311 
7312 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7313 {
7314 	/* bpf_xxx(..., buf, len) call will access 'len'
7315 	 * bytes from memory 'buf'. Both arg types need
7316 	 * to be paired, so make sure there's no buggy
7317 	 * helper function specification.
7318 	 */
7319 	if (arg_type_is_mem_size(fn->arg1_type) ||
7320 	    check_args_pair_invalid(fn, 0) ||
7321 	    check_args_pair_invalid(fn, 1) ||
7322 	    check_args_pair_invalid(fn, 2) ||
7323 	    check_args_pair_invalid(fn, 3) ||
7324 	    check_args_pair_invalid(fn, 4))
7325 		return false;
7326 
7327 	return true;
7328 }
7329 
7330 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7331 {
7332 	int i;
7333 
7334 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7335 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7336 			return !!fn->arg_btf_id[i];
7337 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7338 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7339 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7340 		    /* arg_btf_id and arg_size are in a union. */
7341 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7342 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7343 			return false;
7344 	}
7345 
7346 	return true;
7347 }
7348 
7349 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7350 {
7351 	return check_raw_mode_ok(fn) &&
7352 	       check_arg_pair_ok(fn) &&
7353 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7354 }
7355 
7356 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7357  * are now invalid, so turn them into unknown SCALAR_VALUE.
7358  */
7359 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7360 {
7361 	struct bpf_func_state *state;
7362 	struct bpf_reg_state *reg;
7363 
7364 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7365 		if (reg_is_pkt_pointer_any(reg))
7366 			__mark_reg_unknown(env, reg);
7367 	}));
7368 }
7369 
7370 enum {
7371 	AT_PKT_END = -1,
7372 	BEYOND_PKT_END = -2,
7373 };
7374 
7375 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7376 {
7377 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7378 	struct bpf_reg_state *reg = &state->regs[regn];
7379 
7380 	if (reg->type != PTR_TO_PACKET)
7381 		/* PTR_TO_PACKET_META is not supported yet */
7382 		return;
7383 
7384 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7385 	 * How far beyond pkt_end it goes is unknown.
7386 	 * if (!range_open) it's the case of pkt >= pkt_end
7387 	 * if (range_open) it's the case of pkt > pkt_end
7388 	 * hence this pointer is at least 1 byte bigger than pkt_end
7389 	 */
7390 	if (range_open)
7391 		reg->range = BEYOND_PKT_END;
7392 	else
7393 		reg->range = AT_PKT_END;
7394 }
7395 
7396 /* The pointer with the specified id has released its reference to kernel
7397  * resources. Identify all copies of the same pointer and clear the reference.
7398  */
7399 static int release_reference(struct bpf_verifier_env *env,
7400 			     int ref_obj_id)
7401 {
7402 	struct bpf_func_state *state;
7403 	struct bpf_reg_state *reg;
7404 	int err;
7405 
7406 	err = release_reference_state(cur_func(env), ref_obj_id);
7407 	if (err)
7408 		return err;
7409 
7410 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7411 		if (reg->ref_obj_id == ref_obj_id) {
7412 			if (!env->allow_ptr_leaks)
7413 				__mark_reg_not_init(env, reg);
7414 			else
7415 				__mark_reg_unknown(env, reg);
7416 		}
7417 	}));
7418 
7419 	return 0;
7420 }
7421 
7422 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7423 {
7424 	struct bpf_func_state *unused;
7425 	struct bpf_reg_state *reg;
7426 
7427 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7428 		if (type_is_non_owning_ref(reg->type))
7429 			__mark_reg_unknown(env, reg);
7430 	}));
7431 }
7432 
7433 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7434 				    struct bpf_reg_state *regs)
7435 {
7436 	int i;
7437 
7438 	/* after the call registers r0 - r5 were scratched */
7439 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7440 		mark_reg_not_init(env, regs, caller_saved[i]);
7441 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7442 	}
7443 }
7444 
7445 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7446 				   struct bpf_func_state *caller,
7447 				   struct bpf_func_state *callee,
7448 				   int insn_idx);
7449 
7450 static int set_callee_state(struct bpf_verifier_env *env,
7451 			    struct bpf_func_state *caller,
7452 			    struct bpf_func_state *callee, int insn_idx);
7453 
7454 static bool is_callback_calling_kfunc(u32 btf_id);
7455 
7456 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7457 			     int *insn_idx, int subprog,
7458 			     set_callee_state_fn set_callee_state_cb)
7459 {
7460 	struct bpf_verifier_state *state = env->cur_state;
7461 	struct bpf_func_info_aux *func_info_aux;
7462 	struct bpf_func_state *caller, *callee;
7463 	int err;
7464 	bool is_global = false;
7465 
7466 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7467 		verbose(env, "the call stack of %d frames is too deep\n",
7468 			state->curframe + 2);
7469 		return -E2BIG;
7470 	}
7471 
7472 	caller = state->frame[state->curframe];
7473 	if (state->frame[state->curframe + 1]) {
7474 		verbose(env, "verifier bug. Frame %d already allocated\n",
7475 			state->curframe + 1);
7476 		return -EFAULT;
7477 	}
7478 
7479 	func_info_aux = env->prog->aux->func_info_aux;
7480 	if (func_info_aux)
7481 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7482 	err = btf_check_subprog_call(env, subprog, caller->regs);
7483 	if (err == -EFAULT)
7484 		return err;
7485 	if (is_global) {
7486 		if (err) {
7487 			verbose(env, "Caller passes invalid args into func#%d\n",
7488 				subprog);
7489 			return err;
7490 		} else {
7491 			if (env->log.level & BPF_LOG_LEVEL)
7492 				verbose(env,
7493 					"Func#%d is global and valid. Skipping.\n",
7494 					subprog);
7495 			clear_caller_saved_regs(env, caller->regs);
7496 
7497 			/* All global functions return a 64-bit SCALAR_VALUE */
7498 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7499 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7500 
7501 			/* continue with next insn after call */
7502 			return 0;
7503 		}
7504 	}
7505 
7506 	/* set_callee_state is used for direct subprog calls, but we are
7507 	 * interested in validating only BPF helpers that can call subprogs as
7508 	 * callbacks
7509 	 */
7510 	if (set_callee_state_cb != set_callee_state) {
7511 		if (bpf_pseudo_kfunc_call(insn) &&
7512 		    !is_callback_calling_kfunc(insn->imm)) {
7513 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7514 				func_id_name(insn->imm), insn->imm);
7515 			return -EFAULT;
7516 		} else if (!bpf_pseudo_kfunc_call(insn) &&
7517 			   !is_callback_calling_function(insn->imm)) { /* helper */
7518 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7519 				func_id_name(insn->imm), insn->imm);
7520 			return -EFAULT;
7521 		}
7522 	}
7523 
7524 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7525 	    insn->src_reg == 0 &&
7526 	    insn->imm == BPF_FUNC_timer_set_callback) {
7527 		struct bpf_verifier_state *async_cb;
7528 
7529 		/* there is no real recursion here. timer callbacks are async */
7530 		env->subprog_info[subprog].is_async_cb = true;
7531 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7532 					 *insn_idx, subprog);
7533 		if (!async_cb)
7534 			return -EFAULT;
7535 		callee = async_cb->frame[0];
7536 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7537 
7538 		/* Convert bpf_timer_set_callback() args into timer callback args */
7539 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7540 		if (err)
7541 			return err;
7542 
7543 		clear_caller_saved_regs(env, caller->regs);
7544 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7545 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7546 		/* continue with next insn after call */
7547 		return 0;
7548 	}
7549 
7550 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7551 	if (!callee)
7552 		return -ENOMEM;
7553 	state->frame[state->curframe + 1] = callee;
7554 
7555 	/* callee cannot access r0, r6 - r9 for reading and has to write
7556 	 * into its own stack before reading from it.
7557 	 * callee can read/write into caller's stack
7558 	 */
7559 	init_func_state(env, callee,
7560 			/* remember the callsite, it will be used by bpf_exit */
7561 			*insn_idx /* callsite */,
7562 			state->curframe + 1 /* frameno within this callchain */,
7563 			subprog /* subprog number within this prog */);
7564 
7565 	/* Transfer references to the callee */
7566 	err = copy_reference_state(callee, caller);
7567 	if (err)
7568 		goto err_out;
7569 
7570 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7571 	if (err)
7572 		goto err_out;
7573 
7574 	clear_caller_saved_regs(env, caller->regs);
7575 
7576 	/* only increment it after check_reg_arg() finished */
7577 	state->curframe++;
7578 
7579 	/* and go analyze first insn of the callee */
7580 	*insn_idx = env->subprog_info[subprog].start - 1;
7581 
7582 	if (env->log.level & BPF_LOG_LEVEL) {
7583 		verbose(env, "caller:\n");
7584 		print_verifier_state(env, caller, true);
7585 		verbose(env, "callee:\n");
7586 		print_verifier_state(env, callee, true);
7587 	}
7588 	return 0;
7589 
7590 err_out:
7591 	free_func_state(callee);
7592 	state->frame[state->curframe + 1] = NULL;
7593 	return err;
7594 }
7595 
7596 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7597 				   struct bpf_func_state *caller,
7598 				   struct bpf_func_state *callee)
7599 {
7600 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7601 	 *      void *callback_ctx, u64 flags);
7602 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7603 	 *      void *callback_ctx);
7604 	 */
7605 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7606 
7607 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7608 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7609 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7610 
7611 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7612 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7613 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7614 
7615 	/* pointer to stack or null */
7616 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7617 
7618 	/* unused */
7619 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7620 	return 0;
7621 }
7622 
7623 static int set_callee_state(struct bpf_verifier_env *env,
7624 			    struct bpf_func_state *caller,
7625 			    struct bpf_func_state *callee, int insn_idx)
7626 {
7627 	int i;
7628 
7629 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7630 	 * pointers, which connects us up to the liveness chain
7631 	 */
7632 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7633 		callee->regs[i] = caller->regs[i];
7634 	return 0;
7635 }
7636 
7637 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7638 			   int *insn_idx)
7639 {
7640 	int subprog, target_insn;
7641 
7642 	target_insn = *insn_idx + insn->imm + 1;
7643 	subprog = find_subprog(env, target_insn);
7644 	if (subprog < 0) {
7645 		verbose(env, "verifier bug. No program starts at insn %d\n",
7646 			target_insn);
7647 		return -EFAULT;
7648 	}
7649 
7650 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7651 }
7652 
7653 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7654 				       struct bpf_func_state *caller,
7655 				       struct bpf_func_state *callee,
7656 				       int insn_idx)
7657 {
7658 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7659 	struct bpf_map *map;
7660 	int err;
7661 
7662 	if (bpf_map_ptr_poisoned(insn_aux)) {
7663 		verbose(env, "tail_call abusing map_ptr\n");
7664 		return -EINVAL;
7665 	}
7666 
7667 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7668 	if (!map->ops->map_set_for_each_callback_args ||
7669 	    !map->ops->map_for_each_callback) {
7670 		verbose(env, "callback function not allowed for map\n");
7671 		return -ENOTSUPP;
7672 	}
7673 
7674 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7675 	if (err)
7676 		return err;
7677 
7678 	callee->in_callback_fn = true;
7679 	callee->callback_ret_range = tnum_range(0, 1);
7680 	return 0;
7681 }
7682 
7683 static int set_loop_callback_state(struct bpf_verifier_env *env,
7684 				   struct bpf_func_state *caller,
7685 				   struct bpf_func_state *callee,
7686 				   int insn_idx)
7687 {
7688 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7689 	 *	    u64 flags);
7690 	 * callback_fn(u32 index, void *callback_ctx);
7691 	 */
7692 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7693 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7694 
7695 	/* unused */
7696 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7697 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7698 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7699 
7700 	callee->in_callback_fn = true;
7701 	callee->callback_ret_range = tnum_range(0, 1);
7702 	return 0;
7703 }
7704 
7705 static int set_timer_callback_state(struct bpf_verifier_env *env,
7706 				    struct bpf_func_state *caller,
7707 				    struct bpf_func_state *callee,
7708 				    int insn_idx)
7709 {
7710 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7711 
7712 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7713 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7714 	 */
7715 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7716 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7717 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7718 
7719 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7720 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7721 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7722 
7723 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7724 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7725 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7726 
7727 	/* unused */
7728 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7729 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7730 	callee->in_async_callback_fn = true;
7731 	callee->callback_ret_range = tnum_range(0, 1);
7732 	return 0;
7733 }
7734 
7735 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7736 				       struct bpf_func_state *caller,
7737 				       struct bpf_func_state *callee,
7738 				       int insn_idx)
7739 {
7740 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7741 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7742 	 * (callback_fn)(struct task_struct *task,
7743 	 *               struct vm_area_struct *vma, void *callback_ctx);
7744 	 */
7745 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7746 
7747 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7748 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7749 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7750 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7751 
7752 	/* pointer to stack or null */
7753 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7754 
7755 	/* unused */
7756 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7757 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7758 	callee->in_callback_fn = true;
7759 	callee->callback_ret_range = tnum_range(0, 1);
7760 	return 0;
7761 }
7762 
7763 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7764 					   struct bpf_func_state *caller,
7765 					   struct bpf_func_state *callee,
7766 					   int insn_idx)
7767 {
7768 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7769 	 *			  callback_ctx, u64 flags);
7770 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7771 	 */
7772 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7773 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7774 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7775 
7776 	/* unused */
7777 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7778 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7779 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7780 
7781 	callee->in_callback_fn = true;
7782 	callee->callback_ret_range = tnum_range(0, 1);
7783 	return 0;
7784 }
7785 
7786 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
7787 					 struct bpf_func_state *caller,
7788 					 struct bpf_func_state *callee,
7789 					 int insn_idx)
7790 {
7791 	/* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
7792 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
7793 	 *
7794 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
7795 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
7796 	 * by this point, so look at 'root'
7797 	 */
7798 	struct btf_field *field;
7799 
7800 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
7801 				      BPF_RB_ROOT);
7802 	if (!field || !field->graph_root.value_btf_id)
7803 		return -EFAULT;
7804 
7805 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
7806 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
7807 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
7808 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
7809 
7810 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7811 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7812 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7813 	callee->in_callback_fn = true;
7814 	callee->callback_ret_range = tnum_range(0, 1);
7815 	return 0;
7816 }
7817 
7818 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
7819 
7820 /* Are we currently verifying the callback for a rbtree helper that must
7821  * be called with lock held? If so, no need to complain about unreleased
7822  * lock
7823  */
7824 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
7825 {
7826 	struct bpf_verifier_state *state = env->cur_state;
7827 	struct bpf_insn *insn = env->prog->insnsi;
7828 	struct bpf_func_state *callee;
7829 	int kfunc_btf_id;
7830 
7831 	if (!state->curframe)
7832 		return false;
7833 
7834 	callee = state->frame[state->curframe];
7835 
7836 	if (!callee->in_callback_fn)
7837 		return false;
7838 
7839 	kfunc_btf_id = insn[callee->callsite].imm;
7840 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
7841 }
7842 
7843 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7844 {
7845 	struct bpf_verifier_state *state = env->cur_state;
7846 	struct bpf_func_state *caller, *callee;
7847 	struct bpf_reg_state *r0;
7848 	int err;
7849 
7850 	callee = state->frame[state->curframe];
7851 	r0 = &callee->regs[BPF_REG_0];
7852 	if (r0->type == PTR_TO_STACK) {
7853 		/* technically it's ok to return caller's stack pointer
7854 		 * (or caller's caller's pointer) back to the caller,
7855 		 * since these pointers are valid. Only current stack
7856 		 * pointer will be invalid as soon as function exits,
7857 		 * but let's be conservative
7858 		 */
7859 		verbose(env, "cannot return stack pointer to the caller\n");
7860 		return -EINVAL;
7861 	}
7862 
7863 	caller = state->frame[state->curframe - 1];
7864 	if (callee->in_callback_fn) {
7865 		/* enforce R0 return value range [0, 1]. */
7866 		struct tnum range = callee->callback_ret_range;
7867 
7868 		if (r0->type != SCALAR_VALUE) {
7869 			verbose(env, "R0 not a scalar value\n");
7870 			return -EACCES;
7871 		}
7872 		if (!tnum_in(range, r0->var_off)) {
7873 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7874 			return -EINVAL;
7875 		}
7876 	} else {
7877 		/* return to the caller whatever r0 had in the callee */
7878 		caller->regs[BPF_REG_0] = *r0;
7879 	}
7880 
7881 	/* callback_fn frame should have released its own additions to parent's
7882 	 * reference state at this point, or check_reference_leak would
7883 	 * complain, hence it must be the same as the caller. There is no need
7884 	 * to copy it back.
7885 	 */
7886 	if (!callee->in_callback_fn) {
7887 		/* Transfer references to the caller */
7888 		err = copy_reference_state(caller, callee);
7889 		if (err)
7890 			return err;
7891 	}
7892 
7893 	*insn_idx = callee->callsite + 1;
7894 	if (env->log.level & BPF_LOG_LEVEL) {
7895 		verbose(env, "returning from callee:\n");
7896 		print_verifier_state(env, callee, true);
7897 		verbose(env, "to caller at %d:\n", *insn_idx);
7898 		print_verifier_state(env, caller, true);
7899 	}
7900 	/* clear everything in the callee */
7901 	free_func_state(callee);
7902 	state->frame[state->curframe--] = NULL;
7903 	return 0;
7904 }
7905 
7906 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7907 				   int func_id,
7908 				   struct bpf_call_arg_meta *meta)
7909 {
7910 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7911 
7912 	if (ret_type != RET_INTEGER ||
7913 	    (func_id != BPF_FUNC_get_stack &&
7914 	     func_id != BPF_FUNC_get_task_stack &&
7915 	     func_id != BPF_FUNC_probe_read_str &&
7916 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7917 	     func_id != BPF_FUNC_probe_read_user_str))
7918 		return;
7919 
7920 	ret_reg->smax_value = meta->msize_max_value;
7921 	ret_reg->s32_max_value = meta->msize_max_value;
7922 	ret_reg->smin_value = -MAX_ERRNO;
7923 	ret_reg->s32_min_value = -MAX_ERRNO;
7924 	reg_bounds_sync(ret_reg);
7925 }
7926 
7927 static int
7928 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7929 		int func_id, int insn_idx)
7930 {
7931 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7932 	struct bpf_map *map = meta->map_ptr;
7933 
7934 	if (func_id != BPF_FUNC_tail_call &&
7935 	    func_id != BPF_FUNC_map_lookup_elem &&
7936 	    func_id != BPF_FUNC_map_update_elem &&
7937 	    func_id != BPF_FUNC_map_delete_elem &&
7938 	    func_id != BPF_FUNC_map_push_elem &&
7939 	    func_id != BPF_FUNC_map_pop_elem &&
7940 	    func_id != BPF_FUNC_map_peek_elem &&
7941 	    func_id != BPF_FUNC_for_each_map_elem &&
7942 	    func_id != BPF_FUNC_redirect_map &&
7943 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7944 		return 0;
7945 
7946 	if (map == NULL) {
7947 		verbose(env, "kernel subsystem misconfigured verifier\n");
7948 		return -EINVAL;
7949 	}
7950 
7951 	/* In case of read-only, some additional restrictions
7952 	 * need to be applied in order to prevent altering the
7953 	 * state of the map from program side.
7954 	 */
7955 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7956 	    (func_id == BPF_FUNC_map_delete_elem ||
7957 	     func_id == BPF_FUNC_map_update_elem ||
7958 	     func_id == BPF_FUNC_map_push_elem ||
7959 	     func_id == BPF_FUNC_map_pop_elem)) {
7960 		verbose(env, "write into map forbidden\n");
7961 		return -EACCES;
7962 	}
7963 
7964 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7965 		bpf_map_ptr_store(aux, meta->map_ptr,
7966 				  !meta->map_ptr->bypass_spec_v1);
7967 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7968 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7969 				  !meta->map_ptr->bypass_spec_v1);
7970 	return 0;
7971 }
7972 
7973 static int
7974 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7975 		int func_id, int insn_idx)
7976 {
7977 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7978 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7979 	struct bpf_map *map = meta->map_ptr;
7980 	u64 val, max;
7981 	int err;
7982 
7983 	if (func_id != BPF_FUNC_tail_call)
7984 		return 0;
7985 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7986 		verbose(env, "kernel subsystem misconfigured verifier\n");
7987 		return -EINVAL;
7988 	}
7989 
7990 	reg = &regs[BPF_REG_3];
7991 	val = reg->var_off.value;
7992 	max = map->max_entries;
7993 
7994 	if (!(register_is_const(reg) && val < max)) {
7995 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7996 		return 0;
7997 	}
7998 
7999 	err = mark_chain_precision(env, BPF_REG_3);
8000 	if (err)
8001 		return err;
8002 	if (bpf_map_key_unseen(aux))
8003 		bpf_map_key_store(aux, val);
8004 	else if (!bpf_map_key_poisoned(aux) &&
8005 		  bpf_map_key_immediate(aux) != val)
8006 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8007 	return 0;
8008 }
8009 
8010 static int check_reference_leak(struct bpf_verifier_env *env)
8011 {
8012 	struct bpf_func_state *state = cur_func(env);
8013 	bool refs_lingering = false;
8014 	int i;
8015 
8016 	if (state->frameno && !state->in_callback_fn)
8017 		return 0;
8018 
8019 	for (i = 0; i < state->acquired_refs; i++) {
8020 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8021 			continue;
8022 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8023 			state->refs[i].id, state->refs[i].insn_idx);
8024 		refs_lingering = true;
8025 	}
8026 	return refs_lingering ? -EINVAL : 0;
8027 }
8028 
8029 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8030 				   struct bpf_reg_state *regs)
8031 {
8032 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8033 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8034 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
8035 	struct bpf_bprintf_data data = {};
8036 	int err, fmt_map_off, num_args;
8037 	u64 fmt_addr;
8038 	char *fmt;
8039 
8040 	/* data must be an array of u64 */
8041 	if (data_len_reg->var_off.value % 8)
8042 		return -EINVAL;
8043 	num_args = data_len_reg->var_off.value / 8;
8044 
8045 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8046 	 * and map_direct_value_addr is set.
8047 	 */
8048 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8049 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8050 						  fmt_map_off);
8051 	if (err) {
8052 		verbose(env, "verifier bug\n");
8053 		return -EFAULT;
8054 	}
8055 	fmt = (char *)(long)fmt_addr + fmt_map_off;
8056 
8057 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8058 	 * can focus on validating the format specifiers.
8059 	 */
8060 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8061 	if (err < 0)
8062 		verbose(env, "Invalid format string\n");
8063 
8064 	return err;
8065 }
8066 
8067 static int check_get_func_ip(struct bpf_verifier_env *env)
8068 {
8069 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8070 	int func_id = BPF_FUNC_get_func_ip;
8071 
8072 	if (type == BPF_PROG_TYPE_TRACING) {
8073 		if (!bpf_prog_has_trampoline(env->prog)) {
8074 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8075 				func_id_name(func_id), func_id);
8076 			return -ENOTSUPP;
8077 		}
8078 		return 0;
8079 	} else if (type == BPF_PROG_TYPE_KPROBE) {
8080 		return 0;
8081 	}
8082 
8083 	verbose(env, "func %s#%d not supported for program type %d\n",
8084 		func_id_name(func_id), func_id, type);
8085 	return -ENOTSUPP;
8086 }
8087 
8088 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8089 {
8090 	return &env->insn_aux_data[env->insn_idx];
8091 }
8092 
8093 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8094 {
8095 	struct bpf_reg_state *regs = cur_regs(env);
8096 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
8097 	bool reg_is_null = register_is_null(reg);
8098 
8099 	if (reg_is_null)
8100 		mark_chain_precision(env, BPF_REG_4);
8101 
8102 	return reg_is_null;
8103 }
8104 
8105 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8106 {
8107 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8108 
8109 	if (!state->initialized) {
8110 		state->initialized = 1;
8111 		state->fit_for_inline = loop_flag_is_zero(env);
8112 		state->callback_subprogno = subprogno;
8113 		return;
8114 	}
8115 
8116 	if (!state->fit_for_inline)
8117 		return;
8118 
8119 	state->fit_for_inline = (loop_flag_is_zero(env) &&
8120 				 state->callback_subprogno == subprogno);
8121 }
8122 
8123 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8124 			     int *insn_idx_p)
8125 {
8126 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8127 	const struct bpf_func_proto *fn = NULL;
8128 	enum bpf_return_type ret_type;
8129 	enum bpf_type_flag ret_flag;
8130 	struct bpf_reg_state *regs;
8131 	struct bpf_call_arg_meta meta;
8132 	int insn_idx = *insn_idx_p;
8133 	bool changes_data;
8134 	int i, err, func_id;
8135 
8136 	/* find function prototype */
8137 	func_id = insn->imm;
8138 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8139 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8140 			func_id);
8141 		return -EINVAL;
8142 	}
8143 
8144 	if (env->ops->get_func_proto)
8145 		fn = env->ops->get_func_proto(func_id, env->prog);
8146 	if (!fn) {
8147 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8148 			func_id);
8149 		return -EINVAL;
8150 	}
8151 
8152 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
8153 	if (!env->prog->gpl_compatible && fn->gpl_only) {
8154 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8155 		return -EINVAL;
8156 	}
8157 
8158 	if (fn->allowed && !fn->allowed(env->prog)) {
8159 		verbose(env, "helper call is not allowed in probe\n");
8160 		return -EINVAL;
8161 	}
8162 
8163 	if (!env->prog->aux->sleepable && fn->might_sleep) {
8164 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
8165 		return -EINVAL;
8166 	}
8167 
8168 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
8169 	changes_data = bpf_helper_changes_pkt_data(fn->func);
8170 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8171 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8172 			func_id_name(func_id), func_id);
8173 		return -EINVAL;
8174 	}
8175 
8176 	memset(&meta, 0, sizeof(meta));
8177 	meta.pkt_access = fn->pkt_access;
8178 
8179 	err = check_func_proto(fn, func_id);
8180 	if (err) {
8181 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8182 			func_id_name(func_id), func_id);
8183 		return err;
8184 	}
8185 
8186 	if (env->cur_state->active_rcu_lock) {
8187 		if (fn->might_sleep) {
8188 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8189 				func_id_name(func_id), func_id);
8190 			return -EINVAL;
8191 		}
8192 
8193 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8194 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8195 	}
8196 
8197 	meta.func_id = func_id;
8198 	/* check args */
8199 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8200 		err = check_func_arg(env, i, &meta, fn);
8201 		if (err)
8202 			return err;
8203 	}
8204 
8205 	err = record_func_map(env, &meta, func_id, insn_idx);
8206 	if (err)
8207 		return err;
8208 
8209 	err = record_func_key(env, &meta, func_id, insn_idx);
8210 	if (err)
8211 		return err;
8212 
8213 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
8214 	 * is inferred from register state.
8215 	 */
8216 	for (i = 0; i < meta.access_size; i++) {
8217 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8218 				       BPF_WRITE, -1, false);
8219 		if (err)
8220 			return err;
8221 	}
8222 
8223 	regs = cur_regs(env);
8224 
8225 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8226 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
8227 	 * is safe to do directly.
8228 	 */
8229 	if (meta.uninit_dynptr_regno) {
8230 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
8231 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
8232 			return -EFAULT;
8233 		}
8234 		/* we write BPF_DW bits (8 bytes) at a time */
8235 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8236 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
8237 					       i, BPF_DW, BPF_WRITE, -1, false);
8238 			if (err)
8239 				return err;
8240 		}
8241 
8242 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
8243 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
8244 					      insn_idx);
8245 		if (err)
8246 			return err;
8247 	}
8248 
8249 	if (meta.release_regno) {
8250 		err = -EINVAL;
8251 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8252 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8253 		 * is safe to do directly.
8254 		 */
8255 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8256 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8257 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8258 				return -EFAULT;
8259 			}
8260 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8261 		} else if (meta.ref_obj_id) {
8262 			err = release_reference(env, meta.ref_obj_id);
8263 		} else if (register_is_null(&regs[meta.release_regno])) {
8264 			/* meta.ref_obj_id can only be 0 if register that is meant to be
8265 			 * released is NULL, which must be > R0.
8266 			 */
8267 			err = 0;
8268 		}
8269 		if (err) {
8270 			verbose(env, "func %s#%d reference has not been acquired before\n",
8271 				func_id_name(func_id), func_id);
8272 			return err;
8273 		}
8274 	}
8275 
8276 	switch (func_id) {
8277 	case BPF_FUNC_tail_call:
8278 		err = check_reference_leak(env);
8279 		if (err) {
8280 			verbose(env, "tail_call would lead to reference leak\n");
8281 			return err;
8282 		}
8283 		break;
8284 	case BPF_FUNC_get_local_storage:
8285 		/* check that flags argument in get_local_storage(map, flags) is 0,
8286 		 * this is required because get_local_storage() can't return an error.
8287 		 */
8288 		if (!register_is_null(&regs[BPF_REG_2])) {
8289 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8290 			return -EINVAL;
8291 		}
8292 		break;
8293 	case BPF_FUNC_for_each_map_elem:
8294 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8295 					set_map_elem_callback_state);
8296 		break;
8297 	case BPF_FUNC_timer_set_callback:
8298 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8299 					set_timer_callback_state);
8300 		break;
8301 	case BPF_FUNC_find_vma:
8302 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8303 					set_find_vma_callback_state);
8304 		break;
8305 	case BPF_FUNC_snprintf:
8306 		err = check_bpf_snprintf_call(env, regs);
8307 		break;
8308 	case BPF_FUNC_loop:
8309 		update_loop_inline_state(env, meta.subprogno);
8310 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8311 					set_loop_callback_state);
8312 		break;
8313 	case BPF_FUNC_dynptr_from_mem:
8314 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8315 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8316 				reg_type_str(env, regs[BPF_REG_1].type));
8317 			return -EACCES;
8318 		}
8319 		break;
8320 	case BPF_FUNC_set_retval:
8321 		if (prog_type == BPF_PROG_TYPE_LSM &&
8322 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8323 			if (!env->prog->aux->attach_func_proto->type) {
8324 				/* Make sure programs that attach to void
8325 				 * hooks don't try to modify return value.
8326 				 */
8327 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8328 				return -EINVAL;
8329 			}
8330 		}
8331 		break;
8332 	case BPF_FUNC_dynptr_data:
8333 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8334 			if (arg_type_is_dynptr(fn->arg_type[i])) {
8335 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
8336 				int id, ref_obj_id;
8337 
8338 				if (meta.dynptr_id) {
8339 					verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8340 					return -EFAULT;
8341 				}
8342 
8343 				if (meta.ref_obj_id) {
8344 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8345 					return -EFAULT;
8346 				}
8347 
8348 				id = dynptr_id(env, reg);
8349 				if (id < 0) {
8350 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8351 					return id;
8352 				}
8353 
8354 				ref_obj_id = dynptr_ref_obj_id(env, reg);
8355 				if (ref_obj_id < 0) {
8356 					verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8357 					return ref_obj_id;
8358 				}
8359 
8360 				meta.dynptr_id = id;
8361 				meta.ref_obj_id = ref_obj_id;
8362 				break;
8363 			}
8364 		}
8365 		if (i == MAX_BPF_FUNC_REG_ARGS) {
8366 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
8367 			return -EFAULT;
8368 		}
8369 		break;
8370 	case BPF_FUNC_user_ringbuf_drain:
8371 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8372 					set_user_ringbuf_callback_state);
8373 		break;
8374 	}
8375 
8376 	if (err)
8377 		return err;
8378 
8379 	/* reset caller saved regs */
8380 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8381 		mark_reg_not_init(env, regs, caller_saved[i]);
8382 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8383 	}
8384 
8385 	/* helper call returns 64-bit value. */
8386 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8387 
8388 	/* update return register (already marked as written above) */
8389 	ret_type = fn->ret_type;
8390 	ret_flag = type_flag(ret_type);
8391 
8392 	switch (base_type(ret_type)) {
8393 	case RET_INTEGER:
8394 		/* sets type to SCALAR_VALUE */
8395 		mark_reg_unknown(env, regs, BPF_REG_0);
8396 		break;
8397 	case RET_VOID:
8398 		regs[BPF_REG_0].type = NOT_INIT;
8399 		break;
8400 	case RET_PTR_TO_MAP_VALUE:
8401 		/* There is no offset yet applied, variable or fixed */
8402 		mark_reg_known_zero(env, regs, BPF_REG_0);
8403 		/* remember map_ptr, so that check_map_access()
8404 		 * can check 'value_size' boundary of memory access
8405 		 * to map element returned from bpf_map_lookup_elem()
8406 		 */
8407 		if (meta.map_ptr == NULL) {
8408 			verbose(env,
8409 				"kernel subsystem misconfigured verifier\n");
8410 			return -EINVAL;
8411 		}
8412 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
8413 		regs[BPF_REG_0].map_uid = meta.map_uid;
8414 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8415 		if (!type_may_be_null(ret_type) &&
8416 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8417 			regs[BPF_REG_0].id = ++env->id_gen;
8418 		}
8419 		break;
8420 	case RET_PTR_TO_SOCKET:
8421 		mark_reg_known_zero(env, regs, BPF_REG_0);
8422 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8423 		break;
8424 	case RET_PTR_TO_SOCK_COMMON:
8425 		mark_reg_known_zero(env, regs, BPF_REG_0);
8426 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8427 		break;
8428 	case RET_PTR_TO_TCP_SOCK:
8429 		mark_reg_known_zero(env, regs, BPF_REG_0);
8430 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8431 		break;
8432 	case RET_PTR_TO_MEM:
8433 		mark_reg_known_zero(env, regs, BPF_REG_0);
8434 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8435 		regs[BPF_REG_0].mem_size = meta.mem_size;
8436 		break;
8437 	case RET_PTR_TO_MEM_OR_BTF_ID:
8438 	{
8439 		const struct btf_type *t;
8440 
8441 		mark_reg_known_zero(env, regs, BPF_REG_0);
8442 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8443 		if (!btf_type_is_struct(t)) {
8444 			u32 tsize;
8445 			const struct btf_type *ret;
8446 			const char *tname;
8447 
8448 			/* resolve the type size of ksym. */
8449 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8450 			if (IS_ERR(ret)) {
8451 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8452 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8453 					tname, PTR_ERR(ret));
8454 				return -EINVAL;
8455 			}
8456 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8457 			regs[BPF_REG_0].mem_size = tsize;
8458 		} else {
8459 			/* MEM_RDONLY may be carried from ret_flag, but it
8460 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8461 			 * it will confuse the check of PTR_TO_BTF_ID in
8462 			 * check_mem_access().
8463 			 */
8464 			ret_flag &= ~MEM_RDONLY;
8465 
8466 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8467 			regs[BPF_REG_0].btf = meta.ret_btf;
8468 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8469 		}
8470 		break;
8471 	}
8472 	case RET_PTR_TO_BTF_ID:
8473 	{
8474 		struct btf *ret_btf;
8475 		int ret_btf_id;
8476 
8477 		mark_reg_known_zero(env, regs, BPF_REG_0);
8478 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8479 		if (func_id == BPF_FUNC_kptr_xchg) {
8480 			ret_btf = meta.kptr_field->kptr.btf;
8481 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8482 		} else {
8483 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8484 				verbose(env, "verifier internal error:");
8485 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8486 					func_id_name(func_id));
8487 				return -EINVAL;
8488 			}
8489 			ret_btf = btf_vmlinux;
8490 			ret_btf_id = *fn->ret_btf_id;
8491 		}
8492 		if (ret_btf_id == 0) {
8493 			verbose(env, "invalid return type %u of func %s#%d\n",
8494 				base_type(ret_type), func_id_name(func_id),
8495 				func_id);
8496 			return -EINVAL;
8497 		}
8498 		regs[BPF_REG_0].btf = ret_btf;
8499 		regs[BPF_REG_0].btf_id = ret_btf_id;
8500 		break;
8501 	}
8502 	default:
8503 		verbose(env, "unknown return type %u of func %s#%d\n",
8504 			base_type(ret_type), func_id_name(func_id), func_id);
8505 		return -EINVAL;
8506 	}
8507 
8508 	if (type_may_be_null(regs[BPF_REG_0].type))
8509 		regs[BPF_REG_0].id = ++env->id_gen;
8510 
8511 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8512 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8513 			func_id_name(func_id), func_id);
8514 		return -EFAULT;
8515 	}
8516 
8517 	if (is_dynptr_ref_function(func_id))
8518 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8519 
8520 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8521 		/* For release_reference() */
8522 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8523 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8524 		int id = acquire_reference_state(env, insn_idx);
8525 
8526 		if (id < 0)
8527 			return id;
8528 		/* For mark_ptr_or_null_reg() */
8529 		regs[BPF_REG_0].id = id;
8530 		/* For release_reference() */
8531 		regs[BPF_REG_0].ref_obj_id = id;
8532 	}
8533 
8534 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8535 
8536 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8537 	if (err)
8538 		return err;
8539 
8540 	if ((func_id == BPF_FUNC_get_stack ||
8541 	     func_id == BPF_FUNC_get_task_stack) &&
8542 	    !env->prog->has_callchain_buf) {
8543 		const char *err_str;
8544 
8545 #ifdef CONFIG_PERF_EVENTS
8546 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8547 		err_str = "cannot get callchain buffer for func %s#%d\n";
8548 #else
8549 		err = -ENOTSUPP;
8550 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8551 #endif
8552 		if (err) {
8553 			verbose(env, err_str, func_id_name(func_id), func_id);
8554 			return err;
8555 		}
8556 
8557 		env->prog->has_callchain_buf = true;
8558 	}
8559 
8560 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8561 		env->prog->call_get_stack = true;
8562 
8563 	if (func_id == BPF_FUNC_get_func_ip) {
8564 		if (check_get_func_ip(env))
8565 			return -ENOTSUPP;
8566 		env->prog->call_get_func_ip = true;
8567 	}
8568 
8569 	if (changes_data)
8570 		clear_all_pkt_pointers(env);
8571 	return 0;
8572 }
8573 
8574 /* mark_btf_func_reg_size() is used when the reg size is determined by
8575  * the BTF func_proto's return value size and argument.
8576  */
8577 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8578 				   size_t reg_size)
8579 {
8580 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8581 
8582 	if (regno == BPF_REG_0) {
8583 		/* Function return value */
8584 		reg->live |= REG_LIVE_WRITTEN;
8585 		reg->subreg_def = reg_size == sizeof(u64) ?
8586 			DEF_NOT_SUBREG : env->insn_idx + 1;
8587 	} else {
8588 		/* Function argument */
8589 		if (reg_size == sizeof(u64)) {
8590 			mark_insn_zext(env, reg);
8591 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8592 		} else {
8593 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8594 		}
8595 	}
8596 }
8597 
8598 struct bpf_kfunc_call_arg_meta {
8599 	/* In parameters */
8600 	struct btf *btf;
8601 	u32 func_id;
8602 	u32 kfunc_flags;
8603 	const struct btf_type *func_proto;
8604 	const char *func_name;
8605 	/* Out parameters */
8606 	u32 ref_obj_id;
8607 	u8 release_regno;
8608 	bool r0_rdonly;
8609 	u32 ret_btf_id;
8610 	u64 r0_size;
8611 	u32 subprogno;
8612 	struct {
8613 		u64 value;
8614 		bool found;
8615 	} arg_constant;
8616 	struct {
8617 		struct btf *btf;
8618 		u32 btf_id;
8619 	} arg_obj_drop;
8620 	struct {
8621 		struct btf_field *field;
8622 	} arg_list_head;
8623 	struct {
8624 		struct btf_field *field;
8625 	} arg_rbtree_root;
8626 };
8627 
8628 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8629 {
8630 	return meta->kfunc_flags & KF_ACQUIRE;
8631 }
8632 
8633 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8634 {
8635 	return meta->kfunc_flags & KF_RET_NULL;
8636 }
8637 
8638 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8639 {
8640 	return meta->kfunc_flags & KF_RELEASE;
8641 }
8642 
8643 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8644 {
8645 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8646 }
8647 
8648 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8649 {
8650 	return meta->kfunc_flags & KF_SLEEPABLE;
8651 }
8652 
8653 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8654 {
8655 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8656 }
8657 
8658 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8659 {
8660 	return meta->kfunc_flags & KF_RCU;
8661 }
8662 
8663 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8664 {
8665 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8666 }
8667 
8668 static bool __kfunc_param_match_suffix(const struct btf *btf,
8669 				       const struct btf_param *arg,
8670 				       const char *suffix)
8671 {
8672 	int suffix_len = strlen(suffix), len;
8673 	const char *param_name;
8674 
8675 	/* In the future, this can be ported to use BTF tagging */
8676 	param_name = btf_name_by_offset(btf, arg->name_off);
8677 	if (str_is_empty(param_name))
8678 		return false;
8679 	len = strlen(param_name);
8680 	if (len < suffix_len)
8681 		return false;
8682 	param_name += len - suffix_len;
8683 	return !strncmp(param_name, suffix, suffix_len);
8684 }
8685 
8686 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8687 				  const struct btf_param *arg,
8688 				  const struct bpf_reg_state *reg)
8689 {
8690 	const struct btf_type *t;
8691 
8692 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8693 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8694 		return false;
8695 
8696 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8697 }
8698 
8699 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8700 {
8701 	return __kfunc_param_match_suffix(btf, arg, "__k");
8702 }
8703 
8704 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8705 {
8706 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8707 }
8708 
8709 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8710 {
8711 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8712 }
8713 
8714 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8715 					  const struct btf_param *arg,
8716 					  const char *name)
8717 {
8718 	int len, target_len = strlen(name);
8719 	const char *param_name;
8720 
8721 	param_name = btf_name_by_offset(btf, arg->name_off);
8722 	if (str_is_empty(param_name))
8723 		return false;
8724 	len = strlen(param_name);
8725 	if (len != target_len)
8726 		return false;
8727 	if (strcmp(param_name, name))
8728 		return false;
8729 
8730 	return true;
8731 }
8732 
8733 enum {
8734 	KF_ARG_DYNPTR_ID,
8735 	KF_ARG_LIST_HEAD_ID,
8736 	KF_ARG_LIST_NODE_ID,
8737 	KF_ARG_RB_ROOT_ID,
8738 	KF_ARG_RB_NODE_ID,
8739 };
8740 
8741 BTF_ID_LIST(kf_arg_btf_ids)
8742 BTF_ID(struct, bpf_dynptr_kern)
8743 BTF_ID(struct, bpf_list_head)
8744 BTF_ID(struct, bpf_list_node)
8745 BTF_ID(struct, bpf_rb_root)
8746 BTF_ID(struct, bpf_rb_node)
8747 
8748 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8749 				    const struct btf_param *arg, int type)
8750 {
8751 	const struct btf_type *t;
8752 	u32 res_id;
8753 
8754 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8755 	if (!t)
8756 		return false;
8757 	if (!btf_type_is_ptr(t))
8758 		return false;
8759 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8760 	if (!t)
8761 		return false;
8762 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8763 }
8764 
8765 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8766 {
8767 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8768 }
8769 
8770 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8771 {
8772 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8773 }
8774 
8775 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8776 {
8777 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8778 }
8779 
8780 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
8781 {
8782 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
8783 }
8784 
8785 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
8786 {
8787 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
8788 }
8789 
8790 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
8791 				  const struct btf_param *arg)
8792 {
8793 	const struct btf_type *t;
8794 
8795 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
8796 	if (!t)
8797 		return false;
8798 
8799 	return true;
8800 }
8801 
8802 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8803 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8804 					const struct btf *btf,
8805 					const struct btf_type *t, int rec)
8806 {
8807 	const struct btf_type *member_type;
8808 	const struct btf_member *member;
8809 	u32 i;
8810 
8811 	if (!btf_type_is_struct(t))
8812 		return false;
8813 
8814 	for_each_member(i, t, member) {
8815 		const struct btf_array *array;
8816 
8817 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8818 		if (btf_type_is_struct(member_type)) {
8819 			if (rec >= 3) {
8820 				verbose(env, "max struct nesting depth exceeded\n");
8821 				return false;
8822 			}
8823 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8824 				return false;
8825 			continue;
8826 		}
8827 		if (btf_type_is_array(member_type)) {
8828 			array = btf_array(member_type);
8829 			if (!array->nelems)
8830 				return false;
8831 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8832 			if (!btf_type_is_scalar(member_type))
8833 				return false;
8834 			continue;
8835 		}
8836 		if (!btf_type_is_scalar(member_type))
8837 			return false;
8838 	}
8839 	return true;
8840 }
8841 
8842 
8843 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8844 #ifdef CONFIG_NET
8845 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8846 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8847 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8848 #endif
8849 };
8850 
8851 enum kfunc_ptr_arg_type {
8852 	KF_ARG_PTR_TO_CTX,
8853 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8854 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8855 	KF_ARG_PTR_TO_DYNPTR,
8856 	KF_ARG_PTR_TO_LIST_HEAD,
8857 	KF_ARG_PTR_TO_LIST_NODE,
8858 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8859 	KF_ARG_PTR_TO_MEM,
8860 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8861 	KF_ARG_PTR_TO_CALLBACK,
8862 	KF_ARG_PTR_TO_RB_ROOT,
8863 	KF_ARG_PTR_TO_RB_NODE,
8864 };
8865 
8866 enum special_kfunc_type {
8867 	KF_bpf_obj_new_impl,
8868 	KF_bpf_obj_drop_impl,
8869 	KF_bpf_list_push_front,
8870 	KF_bpf_list_push_back,
8871 	KF_bpf_list_pop_front,
8872 	KF_bpf_list_pop_back,
8873 	KF_bpf_cast_to_kern_ctx,
8874 	KF_bpf_rdonly_cast,
8875 	KF_bpf_rcu_read_lock,
8876 	KF_bpf_rcu_read_unlock,
8877 	KF_bpf_rbtree_remove,
8878 	KF_bpf_rbtree_add,
8879 	KF_bpf_rbtree_first,
8880 };
8881 
8882 BTF_SET_START(special_kfunc_set)
8883 BTF_ID(func, bpf_obj_new_impl)
8884 BTF_ID(func, bpf_obj_drop_impl)
8885 BTF_ID(func, bpf_list_push_front)
8886 BTF_ID(func, bpf_list_push_back)
8887 BTF_ID(func, bpf_list_pop_front)
8888 BTF_ID(func, bpf_list_pop_back)
8889 BTF_ID(func, bpf_cast_to_kern_ctx)
8890 BTF_ID(func, bpf_rdonly_cast)
8891 BTF_ID(func, bpf_rbtree_remove)
8892 BTF_ID(func, bpf_rbtree_add)
8893 BTF_ID(func, bpf_rbtree_first)
8894 BTF_SET_END(special_kfunc_set)
8895 
8896 BTF_ID_LIST(special_kfunc_list)
8897 BTF_ID(func, bpf_obj_new_impl)
8898 BTF_ID(func, bpf_obj_drop_impl)
8899 BTF_ID(func, bpf_list_push_front)
8900 BTF_ID(func, bpf_list_push_back)
8901 BTF_ID(func, bpf_list_pop_front)
8902 BTF_ID(func, bpf_list_pop_back)
8903 BTF_ID(func, bpf_cast_to_kern_ctx)
8904 BTF_ID(func, bpf_rdonly_cast)
8905 BTF_ID(func, bpf_rcu_read_lock)
8906 BTF_ID(func, bpf_rcu_read_unlock)
8907 BTF_ID(func, bpf_rbtree_remove)
8908 BTF_ID(func, bpf_rbtree_add)
8909 BTF_ID(func, bpf_rbtree_first)
8910 
8911 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8912 {
8913 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8914 }
8915 
8916 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8917 {
8918 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8919 }
8920 
8921 static enum kfunc_ptr_arg_type
8922 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8923 		       struct bpf_kfunc_call_arg_meta *meta,
8924 		       const struct btf_type *t, const struct btf_type *ref_t,
8925 		       const char *ref_tname, const struct btf_param *args,
8926 		       int argno, int nargs)
8927 {
8928 	u32 regno = argno + 1;
8929 	struct bpf_reg_state *regs = cur_regs(env);
8930 	struct bpf_reg_state *reg = &regs[regno];
8931 	bool arg_mem_size = false;
8932 
8933 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8934 		return KF_ARG_PTR_TO_CTX;
8935 
8936 	/* In this function, we verify the kfunc's BTF as per the argument type,
8937 	 * leaving the rest of the verification with respect to the register
8938 	 * type to our caller. When a set of conditions hold in the BTF type of
8939 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8940 	 */
8941 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8942 		return KF_ARG_PTR_TO_CTX;
8943 
8944 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8945 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8946 
8947 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8948 		if (!btf_type_is_ptr(ref_t)) {
8949 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8950 			return -EINVAL;
8951 		}
8952 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8953 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8954 		if (!btf_type_is_struct(ref_t)) {
8955 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8956 				meta->func_name, btf_type_str(ref_t), ref_tname);
8957 			return -EINVAL;
8958 		}
8959 		return KF_ARG_PTR_TO_KPTR;
8960 	}
8961 
8962 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8963 		return KF_ARG_PTR_TO_DYNPTR;
8964 
8965 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8966 		return KF_ARG_PTR_TO_LIST_HEAD;
8967 
8968 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8969 		return KF_ARG_PTR_TO_LIST_NODE;
8970 
8971 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
8972 		return KF_ARG_PTR_TO_RB_ROOT;
8973 
8974 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
8975 		return KF_ARG_PTR_TO_RB_NODE;
8976 
8977 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8978 		if (!btf_type_is_struct(ref_t)) {
8979 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8980 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8981 			return -EINVAL;
8982 		}
8983 		return KF_ARG_PTR_TO_BTF_ID;
8984 	}
8985 
8986 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
8987 		return KF_ARG_PTR_TO_CALLBACK;
8988 
8989 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8990 		arg_mem_size = true;
8991 
8992 	/* This is the catch all argument type of register types supported by
8993 	 * check_helper_mem_access. However, we only allow when argument type is
8994 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8995 	 * arg_mem_size is true, the pointer can be void *.
8996 	 */
8997 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8998 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8999 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9000 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9001 		return -EINVAL;
9002 	}
9003 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9004 }
9005 
9006 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9007 					struct bpf_reg_state *reg,
9008 					const struct btf_type *ref_t,
9009 					const char *ref_tname, u32 ref_id,
9010 					struct bpf_kfunc_call_arg_meta *meta,
9011 					int argno)
9012 {
9013 	const struct btf_type *reg_ref_t;
9014 	bool strict_type_match = false;
9015 	const struct btf *reg_btf;
9016 	const char *reg_ref_tname;
9017 	u32 reg_ref_id;
9018 
9019 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
9020 		reg_btf = reg->btf;
9021 		reg_ref_id = reg->btf_id;
9022 	} else {
9023 		reg_btf = btf_vmlinux;
9024 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9025 	}
9026 
9027 	/* Enforce strict type matching for calls to kfuncs that are acquiring
9028 	 * or releasing a reference, or are no-cast aliases. We do _not_
9029 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9030 	 * as we want to enable BPF programs to pass types that are bitwise
9031 	 * equivalent without forcing them to explicitly cast with something
9032 	 * like bpf_cast_to_kern_ctx().
9033 	 *
9034 	 * For example, say we had a type like the following:
9035 	 *
9036 	 * struct bpf_cpumask {
9037 	 *	cpumask_t cpumask;
9038 	 *	refcount_t usage;
9039 	 * };
9040 	 *
9041 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9042 	 * to a struct cpumask, so it would be safe to pass a struct
9043 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9044 	 *
9045 	 * The philosophy here is similar to how we allow scalars of different
9046 	 * types to be passed to kfuncs as long as the size is the same. The
9047 	 * only difference here is that we're simply allowing
9048 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9049 	 * resolve types.
9050 	 */
9051 	if (is_kfunc_acquire(meta) ||
9052 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
9053 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9054 		strict_type_match = true;
9055 
9056 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9057 
9058 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9059 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9060 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9061 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9062 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9063 			btf_type_str(reg_ref_t), reg_ref_tname);
9064 		return -EINVAL;
9065 	}
9066 	return 0;
9067 }
9068 
9069 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9070 				      struct bpf_reg_state *reg,
9071 				      const struct btf_type *ref_t,
9072 				      const char *ref_tname,
9073 				      struct bpf_kfunc_call_arg_meta *meta,
9074 				      int argno)
9075 {
9076 	struct btf_field *kptr_field;
9077 
9078 	/* check_func_arg_reg_off allows var_off for
9079 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9080 	 * off_desc.
9081 	 */
9082 	if (!tnum_is_const(reg->var_off)) {
9083 		verbose(env, "arg#0 must have constant offset\n");
9084 		return -EINVAL;
9085 	}
9086 
9087 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9088 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9089 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9090 			reg->off + reg->var_off.value);
9091 		return -EINVAL;
9092 	}
9093 
9094 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9095 				  kptr_field->kptr.btf_id, true)) {
9096 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9097 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9098 		return -EINVAL;
9099 	}
9100 	return 0;
9101 }
9102 
9103 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9104 {
9105 	struct bpf_verifier_state *state = env->cur_state;
9106 
9107 	if (!state->active_lock.ptr) {
9108 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9109 		return -EFAULT;
9110 	}
9111 
9112 	if (type_flag(reg->type) & NON_OWN_REF) {
9113 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9114 		return -EFAULT;
9115 	}
9116 
9117 	reg->type |= NON_OWN_REF;
9118 	return 0;
9119 }
9120 
9121 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9122 {
9123 	struct bpf_func_state *state, *unused;
9124 	struct bpf_reg_state *reg;
9125 	int i;
9126 
9127 	state = cur_func(env);
9128 
9129 	if (!ref_obj_id) {
9130 		verbose(env, "verifier internal error: ref_obj_id is zero for "
9131 			     "owning -> non-owning conversion\n");
9132 		return -EFAULT;
9133 	}
9134 
9135 	for (i = 0; i < state->acquired_refs; i++) {
9136 		if (state->refs[i].id != ref_obj_id)
9137 			continue;
9138 
9139 		/* Clear ref_obj_id here so release_reference doesn't clobber
9140 		 * the whole reg
9141 		 */
9142 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9143 			if (reg->ref_obj_id == ref_obj_id) {
9144 				reg->ref_obj_id = 0;
9145 				ref_set_non_owning(env, reg);
9146 			}
9147 		}));
9148 		return 0;
9149 	}
9150 
9151 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9152 	return -EFAULT;
9153 }
9154 
9155 /* Implementation details:
9156  *
9157  * Each register points to some region of memory, which we define as an
9158  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9159  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9160  * allocation. The lock and the data it protects are colocated in the same
9161  * memory region.
9162  *
9163  * Hence, everytime a register holds a pointer value pointing to such
9164  * allocation, the verifier preserves a unique reg->id for it.
9165  *
9166  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9167  * bpf_spin_lock is called.
9168  *
9169  * To enable this, lock state in the verifier captures two values:
9170  *	active_lock.ptr = Register's type specific pointer
9171  *	active_lock.id  = A unique ID for each register pointer value
9172  *
9173  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9174  * supported register types.
9175  *
9176  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9177  * allocated objects is the reg->btf pointer.
9178  *
9179  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9180  * can establish the provenance of the map value statically for each distinct
9181  * lookup into such maps. They always contain a single map value hence unique
9182  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9183  *
9184  * So, in case of global variables, they use array maps with max_entries = 1,
9185  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9186  * into the same map value as max_entries is 1, as described above).
9187  *
9188  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9189  * outer map pointer (in verifier context), but each lookup into an inner map
9190  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9191  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9192  * will get different reg->id assigned to each lookup, hence different
9193  * active_lock.id.
9194  *
9195  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9196  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9197  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9198  */
9199 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9200 {
9201 	void *ptr;
9202 	u32 id;
9203 
9204 	switch ((int)reg->type) {
9205 	case PTR_TO_MAP_VALUE:
9206 		ptr = reg->map_ptr;
9207 		break;
9208 	case PTR_TO_BTF_ID | MEM_ALLOC:
9209 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
9210 		ptr = reg->btf;
9211 		break;
9212 	default:
9213 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
9214 		return -EFAULT;
9215 	}
9216 	id = reg->id;
9217 
9218 	if (!env->cur_state->active_lock.ptr)
9219 		return -EINVAL;
9220 	if (env->cur_state->active_lock.ptr != ptr ||
9221 	    env->cur_state->active_lock.id != id) {
9222 		verbose(env, "held lock and object are not in the same allocation\n");
9223 		return -EINVAL;
9224 	}
9225 	return 0;
9226 }
9227 
9228 static bool is_bpf_list_api_kfunc(u32 btf_id)
9229 {
9230 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9231 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9232 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9233 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9234 }
9235 
9236 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9237 {
9238 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9239 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9240 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9241 }
9242 
9243 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9244 {
9245 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9246 }
9247 
9248 static bool is_callback_calling_kfunc(u32 btf_id)
9249 {
9250 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9251 }
9252 
9253 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9254 {
9255 	return is_bpf_rbtree_api_kfunc(btf_id);
9256 }
9257 
9258 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9259 					  enum btf_field_type head_field_type,
9260 					  u32 kfunc_btf_id)
9261 {
9262 	bool ret;
9263 
9264 	switch (head_field_type) {
9265 	case BPF_LIST_HEAD:
9266 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9267 		break;
9268 	case BPF_RB_ROOT:
9269 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9270 		break;
9271 	default:
9272 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9273 			btf_field_type_name(head_field_type));
9274 		return false;
9275 	}
9276 
9277 	if (!ret)
9278 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9279 			btf_field_type_name(head_field_type));
9280 	return ret;
9281 }
9282 
9283 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9284 					  enum btf_field_type node_field_type,
9285 					  u32 kfunc_btf_id)
9286 {
9287 	bool ret;
9288 
9289 	switch (node_field_type) {
9290 	case BPF_LIST_NODE:
9291 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9292 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9293 		break;
9294 	case BPF_RB_NODE:
9295 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9296 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9297 		break;
9298 	default:
9299 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9300 			btf_field_type_name(node_field_type));
9301 		return false;
9302 	}
9303 
9304 	if (!ret)
9305 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9306 			btf_field_type_name(node_field_type));
9307 	return ret;
9308 }
9309 
9310 static int
9311 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9312 				   struct bpf_reg_state *reg, u32 regno,
9313 				   struct bpf_kfunc_call_arg_meta *meta,
9314 				   enum btf_field_type head_field_type,
9315 				   struct btf_field **head_field)
9316 {
9317 	const char *head_type_name;
9318 	struct btf_field *field;
9319 	struct btf_record *rec;
9320 	u32 head_off;
9321 
9322 	if (meta->btf != btf_vmlinux) {
9323 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9324 		return -EFAULT;
9325 	}
9326 
9327 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9328 		return -EFAULT;
9329 
9330 	head_type_name = btf_field_type_name(head_field_type);
9331 	if (!tnum_is_const(reg->var_off)) {
9332 		verbose(env,
9333 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9334 			regno, head_type_name);
9335 		return -EINVAL;
9336 	}
9337 
9338 	rec = reg_btf_record(reg);
9339 	head_off = reg->off + reg->var_off.value;
9340 	field = btf_record_find(rec, head_off, head_field_type);
9341 	if (!field) {
9342 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9343 		return -EINVAL;
9344 	}
9345 
9346 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9347 	if (check_reg_allocation_locked(env, reg)) {
9348 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9349 			rec->spin_lock_off, head_type_name);
9350 		return -EINVAL;
9351 	}
9352 
9353 	if (*head_field) {
9354 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9355 		return -EFAULT;
9356 	}
9357 	*head_field = field;
9358 	return 0;
9359 }
9360 
9361 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9362 					   struct bpf_reg_state *reg, u32 regno,
9363 					   struct bpf_kfunc_call_arg_meta *meta)
9364 {
9365 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9366 							  &meta->arg_list_head.field);
9367 }
9368 
9369 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9370 					     struct bpf_reg_state *reg, u32 regno,
9371 					     struct bpf_kfunc_call_arg_meta *meta)
9372 {
9373 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9374 							  &meta->arg_rbtree_root.field);
9375 }
9376 
9377 static int
9378 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9379 				   struct bpf_reg_state *reg, u32 regno,
9380 				   struct bpf_kfunc_call_arg_meta *meta,
9381 				   enum btf_field_type head_field_type,
9382 				   enum btf_field_type node_field_type,
9383 				   struct btf_field **node_field)
9384 {
9385 	const char *node_type_name;
9386 	const struct btf_type *et, *t;
9387 	struct btf_field *field;
9388 	u32 node_off;
9389 
9390 	if (meta->btf != btf_vmlinux) {
9391 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9392 		return -EFAULT;
9393 	}
9394 
9395 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9396 		return -EFAULT;
9397 
9398 	node_type_name = btf_field_type_name(node_field_type);
9399 	if (!tnum_is_const(reg->var_off)) {
9400 		verbose(env,
9401 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9402 			regno, node_type_name);
9403 		return -EINVAL;
9404 	}
9405 
9406 	node_off = reg->off + reg->var_off.value;
9407 	field = reg_find_field_offset(reg, node_off, node_field_type);
9408 	if (!field || field->offset != node_off) {
9409 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9410 		return -EINVAL;
9411 	}
9412 
9413 	field = *node_field;
9414 
9415 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9416 	t = btf_type_by_id(reg->btf, reg->btf_id);
9417 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9418 				  field->graph_root.value_btf_id, true)) {
9419 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9420 			"in struct %s, but arg is at offset=%d in struct %s\n",
9421 			btf_field_type_name(head_field_type),
9422 			btf_field_type_name(node_field_type),
9423 			field->graph_root.node_offset,
9424 			btf_name_by_offset(field->graph_root.btf, et->name_off),
9425 			node_off, btf_name_by_offset(reg->btf, t->name_off));
9426 		return -EINVAL;
9427 	}
9428 
9429 	if (node_off != field->graph_root.node_offset) {
9430 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9431 			node_off, btf_field_type_name(node_field_type),
9432 			field->graph_root.node_offset,
9433 			btf_name_by_offset(field->graph_root.btf, et->name_off));
9434 		return -EINVAL;
9435 	}
9436 
9437 	return 0;
9438 }
9439 
9440 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9441 					   struct bpf_reg_state *reg, u32 regno,
9442 					   struct bpf_kfunc_call_arg_meta *meta)
9443 {
9444 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9445 						  BPF_LIST_HEAD, BPF_LIST_NODE,
9446 						  &meta->arg_list_head.field);
9447 }
9448 
9449 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9450 					     struct bpf_reg_state *reg, u32 regno,
9451 					     struct bpf_kfunc_call_arg_meta *meta)
9452 {
9453 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9454 						  BPF_RB_ROOT, BPF_RB_NODE,
9455 						  &meta->arg_rbtree_root.field);
9456 }
9457 
9458 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
9459 {
9460 	const char *func_name = meta->func_name, *ref_tname;
9461 	const struct btf *btf = meta->btf;
9462 	const struct btf_param *args;
9463 	u32 i, nargs;
9464 	int ret;
9465 
9466 	args = (const struct btf_param *)(meta->func_proto + 1);
9467 	nargs = btf_type_vlen(meta->func_proto);
9468 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9469 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9470 			MAX_BPF_FUNC_REG_ARGS);
9471 		return -EINVAL;
9472 	}
9473 
9474 	/* Check that BTF function arguments match actual types that the
9475 	 * verifier sees.
9476 	 */
9477 	for (i = 0; i < nargs; i++) {
9478 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9479 		const struct btf_type *t, *ref_t, *resolve_ret;
9480 		enum bpf_arg_type arg_type = ARG_DONTCARE;
9481 		u32 regno = i + 1, ref_id, type_size;
9482 		bool is_ret_buf_sz = false;
9483 		int kf_arg_type;
9484 
9485 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9486 
9487 		if (is_kfunc_arg_ignore(btf, &args[i]))
9488 			continue;
9489 
9490 		if (btf_type_is_scalar(t)) {
9491 			if (reg->type != SCALAR_VALUE) {
9492 				verbose(env, "R%d is not a scalar\n", regno);
9493 				return -EINVAL;
9494 			}
9495 
9496 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9497 				if (meta->arg_constant.found) {
9498 					verbose(env, "verifier internal error: only one constant argument permitted\n");
9499 					return -EFAULT;
9500 				}
9501 				if (!tnum_is_const(reg->var_off)) {
9502 					verbose(env, "R%d must be a known constant\n", regno);
9503 					return -EINVAL;
9504 				}
9505 				ret = mark_chain_precision(env, regno);
9506 				if (ret < 0)
9507 					return ret;
9508 				meta->arg_constant.found = true;
9509 				meta->arg_constant.value = reg->var_off.value;
9510 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9511 				meta->r0_rdonly = true;
9512 				is_ret_buf_sz = true;
9513 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9514 				is_ret_buf_sz = true;
9515 			}
9516 
9517 			if (is_ret_buf_sz) {
9518 				if (meta->r0_size) {
9519 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9520 					return -EINVAL;
9521 				}
9522 
9523 				if (!tnum_is_const(reg->var_off)) {
9524 					verbose(env, "R%d is not a const\n", regno);
9525 					return -EINVAL;
9526 				}
9527 
9528 				meta->r0_size = reg->var_off.value;
9529 				ret = mark_chain_precision(env, regno);
9530 				if (ret)
9531 					return ret;
9532 			}
9533 			continue;
9534 		}
9535 
9536 		if (!btf_type_is_ptr(t)) {
9537 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9538 			return -EINVAL;
9539 		}
9540 
9541 		if (is_kfunc_trusted_args(meta) &&
9542 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
9543 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9544 			return -EACCES;
9545 		}
9546 
9547 		if (reg->ref_obj_id) {
9548 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
9549 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9550 					regno, reg->ref_obj_id,
9551 					meta->ref_obj_id);
9552 				return -EFAULT;
9553 			}
9554 			meta->ref_obj_id = reg->ref_obj_id;
9555 			if (is_kfunc_release(meta))
9556 				meta->release_regno = regno;
9557 		}
9558 
9559 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9560 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9561 
9562 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9563 		if (kf_arg_type < 0)
9564 			return kf_arg_type;
9565 
9566 		switch (kf_arg_type) {
9567 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9568 		case KF_ARG_PTR_TO_BTF_ID:
9569 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9570 				break;
9571 
9572 			if (!is_trusted_reg(reg)) {
9573 				if (!is_kfunc_rcu(meta)) {
9574 					verbose(env, "R%d must be referenced or trusted\n", regno);
9575 					return -EINVAL;
9576 				}
9577 				if (!is_rcu_reg(reg)) {
9578 					verbose(env, "R%d must be a rcu pointer\n", regno);
9579 					return -EINVAL;
9580 				}
9581 			}
9582 
9583 			fallthrough;
9584 		case KF_ARG_PTR_TO_CTX:
9585 			/* Trusted arguments have the same offset checks as release arguments */
9586 			arg_type |= OBJ_RELEASE;
9587 			break;
9588 		case KF_ARG_PTR_TO_KPTR:
9589 		case KF_ARG_PTR_TO_DYNPTR:
9590 		case KF_ARG_PTR_TO_LIST_HEAD:
9591 		case KF_ARG_PTR_TO_LIST_NODE:
9592 		case KF_ARG_PTR_TO_RB_ROOT:
9593 		case KF_ARG_PTR_TO_RB_NODE:
9594 		case KF_ARG_PTR_TO_MEM:
9595 		case KF_ARG_PTR_TO_MEM_SIZE:
9596 		case KF_ARG_PTR_TO_CALLBACK:
9597 			/* Trusted by default */
9598 			break;
9599 		default:
9600 			WARN_ON_ONCE(1);
9601 			return -EFAULT;
9602 		}
9603 
9604 		if (is_kfunc_release(meta) && reg->ref_obj_id)
9605 			arg_type |= OBJ_RELEASE;
9606 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9607 		if (ret < 0)
9608 			return ret;
9609 
9610 		switch (kf_arg_type) {
9611 		case KF_ARG_PTR_TO_CTX:
9612 			if (reg->type != PTR_TO_CTX) {
9613 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9614 				return -EINVAL;
9615 			}
9616 
9617 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9618 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9619 				if (ret < 0)
9620 					return -EINVAL;
9621 				meta->ret_btf_id  = ret;
9622 			}
9623 			break;
9624 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9625 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9626 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9627 				return -EINVAL;
9628 			}
9629 			if (!reg->ref_obj_id) {
9630 				verbose(env, "allocated object must be referenced\n");
9631 				return -EINVAL;
9632 			}
9633 			if (meta->btf == btf_vmlinux &&
9634 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9635 				meta->arg_obj_drop.btf = reg->btf;
9636 				meta->arg_obj_drop.btf_id = reg->btf_id;
9637 			}
9638 			break;
9639 		case KF_ARG_PTR_TO_KPTR:
9640 			if (reg->type != PTR_TO_MAP_VALUE) {
9641 				verbose(env, "arg#0 expected pointer to map value\n");
9642 				return -EINVAL;
9643 			}
9644 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9645 			if (ret < 0)
9646 				return ret;
9647 			break;
9648 		case KF_ARG_PTR_TO_DYNPTR:
9649 			if (reg->type != PTR_TO_STACK &&
9650 			    reg->type != CONST_PTR_TO_DYNPTR) {
9651 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9652 				return -EINVAL;
9653 			}
9654 
9655 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
9656 			if (ret < 0)
9657 				return ret;
9658 			break;
9659 		case KF_ARG_PTR_TO_LIST_HEAD:
9660 			if (reg->type != PTR_TO_MAP_VALUE &&
9661 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9662 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9663 				return -EINVAL;
9664 			}
9665 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9666 				verbose(env, "allocated object must be referenced\n");
9667 				return -EINVAL;
9668 			}
9669 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9670 			if (ret < 0)
9671 				return ret;
9672 			break;
9673 		case KF_ARG_PTR_TO_RB_ROOT:
9674 			if (reg->type != PTR_TO_MAP_VALUE &&
9675 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9676 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9677 				return -EINVAL;
9678 			}
9679 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9680 				verbose(env, "allocated object must be referenced\n");
9681 				return -EINVAL;
9682 			}
9683 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9684 			if (ret < 0)
9685 				return ret;
9686 			break;
9687 		case KF_ARG_PTR_TO_LIST_NODE:
9688 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9689 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9690 				return -EINVAL;
9691 			}
9692 			if (!reg->ref_obj_id) {
9693 				verbose(env, "allocated object must be referenced\n");
9694 				return -EINVAL;
9695 			}
9696 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9697 			if (ret < 0)
9698 				return ret;
9699 			break;
9700 		case KF_ARG_PTR_TO_RB_NODE:
9701 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9702 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9703 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
9704 					return -EINVAL;
9705 				}
9706 				if (in_rbtree_lock_required_cb(env)) {
9707 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9708 					return -EINVAL;
9709 				}
9710 			} else {
9711 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9712 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
9713 					return -EINVAL;
9714 				}
9715 				if (!reg->ref_obj_id) {
9716 					verbose(env, "allocated object must be referenced\n");
9717 					return -EINVAL;
9718 				}
9719 			}
9720 
9721 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
9722 			if (ret < 0)
9723 				return ret;
9724 			break;
9725 		case KF_ARG_PTR_TO_BTF_ID:
9726 			/* Only base_type is checked, further checks are done here */
9727 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9728 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9729 			    !reg2btf_ids[base_type(reg->type)]) {
9730 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9731 				verbose(env, "expected %s or socket\n",
9732 					reg_type_str(env, base_type(reg->type) |
9733 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9734 				return -EINVAL;
9735 			}
9736 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9737 			if (ret < 0)
9738 				return ret;
9739 			break;
9740 		case KF_ARG_PTR_TO_MEM:
9741 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9742 			if (IS_ERR(resolve_ret)) {
9743 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9744 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9745 				return -EINVAL;
9746 			}
9747 			ret = check_mem_reg(env, reg, regno, type_size);
9748 			if (ret < 0)
9749 				return ret;
9750 			break;
9751 		case KF_ARG_PTR_TO_MEM_SIZE:
9752 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9753 			if (ret < 0) {
9754 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9755 				return ret;
9756 			}
9757 			/* Skip next '__sz' argument */
9758 			i++;
9759 			break;
9760 		case KF_ARG_PTR_TO_CALLBACK:
9761 			meta->subprogno = reg->subprogno;
9762 			break;
9763 		}
9764 	}
9765 
9766 	if (is_kfunc_release(meta) && !meta->release_regno) {
9767 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9768 			func_name);
9769 		return -EINVAL;
9770 	}
9771 
9772 	return 0;
9773 }
9774 
9775 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9776 			    int *insn_idx_p)
9777 {
9778 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9779 	u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
9780 	struct bpf_reg_state *regs = cur_regs(env);
9781 	const char *func_name, *ptr_type_name;
9782 	bool sleepable, rcu_lock, rcu_unlock;
9783 	struct bpf_kfunc_call_arg_meta meta;
9784 	int err, insn_idx = *insn_idx_p;
9785 	const struct btf_param *args;
9786 	const struct btf_type *ret_t;
9787 	struct btf *desc_btf;
9788 	u32 *kfunc_flags;
9789 
9790 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9791 	if (!insn->imm)
9792 		return 0;
9793 
9794 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9795 	if (IS_ERR(desc_btf))
9796 		return PTR_ERR(desc_btf);
9797 
9798 	func_id = insn->imm;
9799 	func = btf_type_by_id(desc_btf, func_id);
9800 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9801 	func_proto = btf_type_by_id(desc_btf, func->type);
9802 
9803 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9804 	if (!kfunc_flags) {
9805 		verbose(env, "calling kernel function %s is not allowed\n",
9806 			func_name);
9807 		return -EACCES;
9808 	}
9809 
9810 	/* Prepare kfunc call metadata */
9811 	memset(&meta, 0, sizeof(meta));
9812 	meta.btf = desc_btf;
9813 	meta.func_id = func_id;
9814 	meta.kfunc_flags = *kfunc_flags;
9815 	meta.func_proto = func_proto;
9816 	meta.func_name = func_name;
9817 
9818 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9819 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9820 		return -EACCES;
9821 	}
9822 
9823 	sleepable = is_kfunc_sleepable(&meta);
9824 	if (sleepable && !env->prog->aux->sleepable) {
9825 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9826 		return -EACCES;
9827 	}
9828 
9829 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9830 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9831 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9832 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9833 		return -EACCES;
9834 	}
9835 
9836 	if (env->cur_state->active_rcu_lock) {
9837 		struct bpf_func_state *state;
9838 		struct bpf_reg_state *reg;
9839 
9840 		if (rcu_lock) {
9841 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9842 			return -EINVAL;
9843 		} else if (rcu_unlock) {
9844 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9845 				if (reg->type & MEM_RCU) {
9846 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9847 					reg->type |= PTR_UNTRUSTED;
9848 				}
9849 			}));
9850 			env->cur_state->active_rcu_lock = false;
9851 		} else if (sleepable) {
9852 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9853 			return -EACCES;
9854 		}
9855 	} else if (rcu_lock) {
9856 		env->cur_state->active_rcu_lock = true;
9857 	} else if (rcu_unlock) {
9858 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9859 		return -EINVAL;
9860 	}
9861 
9862 	/* Check the arguments */
9863 	err = check_kfunc_args(env, &meta);
9864 	if (err < 0)
9865 		return err;
9866 	/* In case of release function, we get register number of refcounted
9867 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9868 	 */
9869 	if (meta.release_regno) {
9870 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9871 		if (err) {
9872 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9873 				func_name, func_id);
9874 			return err;
9875 		}
9876 	}
9877 
9878 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
9879 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
9880 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9881 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
9882 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
9883 		if (err) {
9884 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
9885 				func_name, func_id);
9886 			return err;
9887 		}
9888 
9889 		err = release_reference(env, release_ref_obj_id);
9890 		if (err) {
9891 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9892 				func_name, func_id);
9893 			return err;
9894 		}
9895 	}
9896 
9897 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
9898 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9899 					set_rbtree_add_callback_state);
9900 		if (err) {
9901 			verbose(env, "kfunc %s#%d failed callback verification\n",
9902 				func_name, func_id);
9903 			return err;
9904 		}
9905 	}
9906 
9907 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9908 		mark_reg_not_init(env, regs, caller_saved[i]);
9909 
9910 	/* Check return type */
9911 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9912 
9913 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9914 		/* Only exception is bpf_obj_new_impl */
9915 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9916 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9917 			return -EINVAL;
9918 		}
9919 	}
9920 
9921 	if (btf_type_is_scalar(t)) {
9922 		mark_reg_unknown(env, regs, BPF_REG_0);
9923 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9924 	} else if (btf_type_is_ptr(t)) {
9925 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9926 
9927 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9928 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9929 				struct btf *ret_btf;
9930 				u32 ret_btf_id;
9931 
9932 				if (unlikely(!bpf_global_ma_set))
9933 					return -ENOMEM;
9934 
9935 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9936 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9937 					return -EINVAL;
9938 				}
9939 
9940 				ret_btf = env->prog->aux->btf;
9941 				ret_btf_id = meta.arg_constant.value;
9942 
9943 				/* This may be NULL due to user not supplying a BTF */
9944 				if (!ret_btf) {
9945 					verbose(env, "bpf_obj_new requires prog BTF\n");
9946 					return -EINVAL;
9947 				}
9948 
9949 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9950 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9951 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9952 					return -EINVAL;
9953 				}
9954 
9955 				mark_reg_known_zero(env, regs, BPF_REG_0);
9956 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9957 				regs[BPF_REG_0].btf = ret_btf;
9958 				regs[BPF_REG_0].btf_id = ret_btf_id;
9959 
9960 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9961 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9962 					btf_find_struct_meta(ret_btf, ret_btf_id);
9963 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9964 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9965 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9966 							     meta.arg_obj_drop.btf_id);
9967 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9968 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9969 				struct btf_field *field = meta.arg_list_head.field;
9970 
9971 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9972 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9973 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
9974 				struct btf_field *field = meta.arg_rbtree_root.field;
9975 
9976 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
9977 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9978 				mark_reg_known_zero(env, regs, BPF_REG_0);
9979 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9980 				regs[BPF_REG_0].btf = desc_btf;
9981 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9982 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9983 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9984 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9985 					verbose(env,
9986 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9987 					return -EINVAL;
9988 				}
9989 
9990 				mark_reg_known_zero(env, regs, BPF_REG_0);
9991 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9992 				regs[BPF_REG_0].btf = desc_btf;
9993 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9994 			} else {
9995 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9996 					meta.func_name);
9997 				return -EFAULT;
9998 			}
9999 		} else if (!__btf_type_is_struct(ptr_type)) {
10000 			if (!meta.r0_size) {
10001 				ptr_type_name = btf_name_by_offset(desc_btf,
10002 								   ptr_type->name_off);
10003 				verbose(env,
10004 					"kernel function %s returns pointer type %s %s is not supported\n",
10005 					func_name,
10006 					btf_type_str(ptr_type),
10007 					ptr_type_name);
10008 				return -EINVAL;
10009 			}
10010 
10011 			mark_reg_known_zero(env, regs, BPF_REG_0);
10012 			regs[BPF_REG_0].type = PTR_TO_MEM;
10013 			regs[BPF_REG_0].mem_size = meta.r0_size;
10014 
10015 			if (meta.r0_rdonly)
10016 				regs[BPF_REG_0].type |= MEM_RDONLY;
10017 
10018 			/* Ensures we don't access the memory after a release_reference() */
10019 			if (meta.ref_obj_id)
10020 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10021 		} else {
10022 			mark_reg_known_zero(env, regs, BPF_REG_0);
10023 			regs[BPF_REG_0].btf = desc_btf;
10024 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10025 			regs[BPF_REG_0].btf_id = ptr_type_id;
10026 		}
10027 
10028 		if (is_kfunc_ret_null(&meta)) {
10029 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10030 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10031 			regs[BPF_REG_0].id = ++env->id_gen;
10032 		}
10033 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10034 		if (is_kfunc_acquire(&meta)) {
10035 			int id = acquire_reference_state(env, insn_idx);
10036 
10037 			if (id < 0)
10038 				return id;
10039 			if (is_kfunc_ret_null(&meta))
10040 				regs[BPF_REG_0].id = id;
10041 			regs[BPF_REG_0].ref_obj_id = id;
10042 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10043 			ref_set_non_owning(env, &regs[BPF_REG_0]);
10044 		}
10045 
10046 		if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10047 			invalidate_non_owning_refs(env);
10048 
10049 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10050 			regs[BPF_REG_0].id = ++env->id_gen;
10051 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10052 
10053 	nargs = btf_type_vlen(func_proto);
10054 	args = (const struct btf_param *)(func_proto + 1);
10055 	for (i = 0; i < nargs; i++) {
10056 		u32 regno = i + 1;
10057 
10058 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10059 		if (btf_type_is_ptr(t))
10060 			mark_btf_func_reg_size(env, regno, sizeof(void *));
10061 		else
10062 			/* scalar. ensured by btf_check_kfunc_arg_match() */
10063 			mark_btf_func_reg_size(env, regno, t->size);
10064 	}
10065 
10066 	return 0;
10067 }
10068 
10069 static bool signed_add_overflows(s64 a, s64 b)
10070 {
10071 	/* Do the add in u64, where overflow is well-defined */
10072 	s64 res = (s64)((u64)a + (u64)b);
10073 
10074 	if (b < 0)
10075 		return res > a;
10076 	return res < a;
10077 }
10078 
10079 static bool signed_add32_overflows(s32 a, s32 b)
10080 {
10081 	/* Do the add in u32, where overflow is well-defined */
10082 	s32 res = (s32)((u32)a + (u32)b);
10083 
10084 	if (b < 0)
10085 		return res > a;
10086 	return res < a;
10087 }
10088 
10089 static bool signed_sub_overflows(s64 a, s64 b)
10090 {
10091 	/* Do the sub in u64, where overflow is well-defined */
10092 	s64 res = (s64)((u64)a - (u64)b);
10093 
10094 	if (b < 0)
10095 		return res < a;
10096 	return res > a;
10097 }
10098 
10099 static bool signed_sub32_overflows(s32 a, s32 b)
10100 {
10101 	/* Do the sub in u32, where overflow is well-defined */
10102 	s32 res = (s32)((u32)a - (u32)b);
10103 
10104 	if (b < 0)
10105 		return res < a;
10106 	return res > a;
10107 }
10108 
10109 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10110 				  const struct bpf_reg_state *reg,
10111 				  enum bpf_reg_type type)
10112 {
10113 	bool known = tnum_is_const(reg->var_off);
10114 	s64 val = reg->var_off.value;
10115 	s64 smin = reg->smin_value;
10116 
10117 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10118 		verbose(env, "math between %s pointer and %lld is not allowed\n",
10119 			reg_type_str(env, type), val);
10120 		return false;
10121 	}
10122 
10123 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10124 		verbose(env, "%s pointer offset %d is not allowed\n",
10125 			reg_type_str(env, type), reg->off);
10126 		return false;
10127 	}
10128 
10129 	if (smin == S64_MIN) {
10130 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10131 			reg_type_str(env, type));
10132 		return false;
10133 	}
10134 
10135 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10136 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
10137 			smin, reg_type_str(env, type));
10138 		return false;
10139 	}
10140 
10141 	return true;
10142 }
10143 
10144 enum {
10145 	REASON_BOUNDS	= -1,
10146 	REASON_TYPE	= -2,
10147 	REASON_PATHS	= -3,
10148 	REASON_LIMIT	= -4,
10149 	REASON_STACK	= -5,
10150 };
10151 
10152 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10153 			      u32 *alu_limit, bool mask_to_left)
10154 {
10155 	u32 max = 0, ptr_limit = 0;
10156 
10157 	switch (ptr_reg->type) {
10158 	case PTR_TO_STACK:
10159 		/* Offset 0 is out-of-bounds, but acceptable start for the
10160 		 * left direction, see BPF_REG_FP. Also, unknown scalar
10161 		 * offset where we would need to deal with min/max bounds is
10162 		 * currently prohibited for unprivileged.
10163 		 */
10164 		max = MAX_BPF_STACK + mask_to_left;
10165 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10166 		break;
10167 	case PTR_TO_MAP_VALUE:
10168 		max = ptr_reg->map_ptr->value_size;
10169 		ptr_limit = (mask_to_left ?
10170 			     ptr_reg->smin_value :
10171 			     ptr_reg->umax_value) + ptr_reg->off;
10172 		break;
10173 	default:
10174 		return REASON_TYPE;
10175 	}
10176 
10177 	if (ptr_limit >= max)
10178 		return REASON_LIMIT;
10179 	*alu_limit = ptr_limit;
10180 	return 0;
10181 }
10182 
10183 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10184 				    const struct bpf_insn *insn)
10185 {
10186 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10187 }
10188 
10189 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10190 				       u32 alu_state, u32 alu_limit)
10191 {
10192 	/* If we arrived here from different branches with different
10193 	 * state or limits to sanitize, then this won't work.
10194 	 */
10195 	if (aux->alu_state &&
10196 	    (aux->alu_state != alu_state ||
10197 	     aux->alu_limit != alu_limit))
10198 		return REASON_PATHS;
10199 
10200 	/* Corresponding fixup done in do_misc_fixups(). */
10201 	aux->alu_state = alu_state;
10202 	aux->alu_limit = alu_limit;
10203 	return 0;
10204 }
10205 
10206 static int sanitize_val_alu(struct bpf_verifier_env *env,
10207 			    struct bpf_insn *insn)
10208 {
10209 	struct bpf_insn_aux_data *aux = cur_aux(env);
10210 
10211 	if (can_skip_alu_sanitation(env, insn))
10212 		return 0;
10213 
10214 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10215 }
10216 
10217 static bool sanitize_needed(u8 opcode)
10218 {
10219 	return opcode == BPF_ADD || opcode == BPF_SUB;
10220 }
10221 
10222 struct bpf_sanitize_info {
10223 	struct bpf_insn_aux_data aux;
10224 	bool mask_to_left;
10225 };
10226 
10227 static struct bpf_verifier_state *
10228 sanitize_speculative_path(struct bpf_verifier_env *env,
10229 			  const struct bpf_insn *insn,
10230 			  u32 next_idx, u32 curr_idx)
10231 {
10232 	struct bpf_verifier_state *branch;
10233 	struct bpf_reg_state *regs;
10234 
10235 	branch = push_stack(env, next_idx, curr_idx, true);
10236 	if (branch && insn) {
10237 		regs = branch->frame[branch->curframe]->regs;
10238 		if (BPF_SRC(insn->code) == BPF_K) {
10239 			mark_reg_unknown(env, regs, insn->dst_reg);
10240 		} else if (BPF_SRC(insn->code) == BPF_X) {
10241 			mark_reg_unknown(env, regs, insn->dst_reg);
10242 			mark_reg_unknown(env, regs, insn->src_reg);
10243 		}
10244 	}
10245 	return branch;
10246 }
10247 
10248 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10249 			    struct bpf_insn *insn,
10250 			    const struct bpf_reg_state *ptr_reg,
10251 			    const struct bpf_reg_state *off_reg,
10252 			    struct bpf_reg_state *dst_reg,
10253 			    struct bpf_sanitize_info *info,
10254 			    const bool commit_window)
10255 {
10256 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10257 	struct bpf_verifier_state *vstate = env->cur_state;
10258 	bool off_is_imm = tnum_is_const(off_reg->var_off);
10259 	bool off_is_neg = off_reg->smin_value < 0;
10260 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
10261 	u8 opcode = BPF_OP(insn->code);
10262 	u32 alu_state, alu_limit;
10263 	struct bpf_reg_state tmp;
10264 	bool ret;
10265 	int err;
10266 
10267 	if (can_skip_alu_sanitation(env, insn))
10268 		return 0;
10269 
10270 	/* We already marked aux for masking from non-speculative
10271 	 * paths, thus we got here in the first place. We only care
10272 	 * to explore bad access from here.
10273 	 */
10274 	if (vstate->speculative)
10275 		goto do_sim;
10276 
10277 	if (!commit_window) {
10278 		if (!tnum_is_const(off_reg->var_off) &&
10279 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10280 			return REASON_BOUNDS;
10281 
10282 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
10283 				     (opcode == BPF_SUB && !off_is_neg);
10284 	}
10285 
10286 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10287 	if (err < 0)
10288 		return err;
10289 
10290 	if (commit_window) {
10291 		/* In commit phase we narrow the masking window based on
10292 		 * the observed pointer move after the simulated operation.
10293 		 */
10294 		alu_state = info->aux.alu_state;
10295 		alu_limit = abs(info->aux.alu_limit - alu_limit);
10296 	} else {
10297 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10298 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10299 		alu_state |= ptr_is_dst_reg ?
10300 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10301 
10302 		/* Limit pruning on unknown scalars to enable deep search for
10303 		 * potential masking differences from other program paths.
10304 		 */
10305 		if (!off_is_imm)
10306 			env->explore_alu_limits = true;
10307 	}
10308 
10309 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10310 	if (err < 0)
10311 		return err;
10312 do_sim:
10313 	/* If we're in commit phase, we're done here given we already
10314 	 * pushed the truncated dst_reg into the speculative verification
10315 	 * stack.
10316 	 *
10317 	 * Also, when register is a known constant, we rewrite register-based
10318 	 * operation to immediate-based, and thus do not need masking (and as
10319 	 * a consequence, do not need to simulate the zero-truncation either).
10320 	 */
10321 	if (commit_window || off_is_imm)
10322 		return 0;
10323 
10324 	/* Simulate and find potential out-of-bounds access under
10325 	 * speculative execution from truncation as a result of
10326 	 * masking when off was not within expected range. If off
10327 	 * sits in dst, then we temporarily need to move ptr there
10328 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
10329 	 * for cases where we use K-based arithmetic in one direction
10330 	 * and truncated reg-based in the other in order to explore
10331 	 * bad access.
10332 	 */
10333 	if (!ptr_is_dst_reg) {
10334 		tmp = *dst_reg;
10335 		copy_register_state(dst_reg, ptr_reg);
10336 	}
10337 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10338 					env->insn_idx);
10339 	if (!ptr_is_dst_reg && ret)
10340 		*dst_reg = tmp;
10341 	return !ret ? REASON_STACK : 0;
10342 }
10343 
10344 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10345 {
10346 	struct bpf_verifier_state *vstate = env->cur_state;
10347 
10348 	/* If we simulate paths under speculation, we don't update the
10349 	 * insn as 'seen' such that when we verify unreachable paths in
10350 	 * the non-speculative domain, sanitize_dead_code() can still
10351 	 * rewrite/sanitize them.
10352 	 */
10353 	if (!vstate->speculative)
10354 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10355 }
10356 
10357 static int sanitize_err(struct bpf_verifier_env *env,
10358 			const struct bpf_insn *insn, int reason,
10359 			const struct bpf_reg_state *off_reg,
10360 			const struct bpf_reg_state *dst_reg)
10361 {
10362 	static const char *err = "pointer arithmetic with it prohibited for !root";
10363 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10364 	u32 dst = insn->dst_reg, src = insn->src_reg;
10365 
10366 	switch (reason) {
10367 	case REASON_BOUNDS:
10368 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10369 			off_reg == dst_reg ? dst : src, err);
10370 		break;
10371 	case REASON_TYPE:
10372 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10373 			off_reg == dst_reg ? src : dst, err);
10374 		break;
10375 	case REASON_PATHS:
10376 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10377 			dst, op, err);
10378 		break;
10379 	case REASON_LIMIT:
10380 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10381 			dst, op, err);
10382 		break;
10383 	case REASON_STACK:
10384 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10385 			dst, err);
10386 		break;
10387 	default:
10388 		verbose(env, "verifier internal error: unknown reason (%d)\n",
10389 			reason);
10390 		break;
10391 	}
10392 
10393 	return -EACCES;
10394 }
10395 
10396 /* check that stack access falls within stack limits and that 'reg' doesn't
10397  * have a variable offset.
10398  *
10399  * Variable offset is prohibited for unprivileged mode for simplicity since it
10400  * requires corresponding support in Spectre masking for stack ALU.  See also
10401  * retrieve_ptr_limit().
10402  *
10403  *
10404  * 'off' includes 'reg->off'.
10405  */
10406 static int check_stack_access_for_ptr_arithmetic(
10407 				struct bpf_verifier_env *env,
10408 				int regno,
10409 				const struct bpf_reg_state *reg,
10410 				int off)
10411 {
10412 	if (!tnum_is_const(reg->var_off)) {
10413 		char tn_buf[48];
10414 
10415 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10416 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10417 			regno, tn_buf, off);
10418 		return -EACCES;
10419 	}
10420 
10421 	if (off >= 0 || off < -MAX_BPF_STACK) {
10422 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
10423 			"prohibited for !root; off=%d\n", regno, off);
10424 		return -EACCES;
10425 	}
10426 
10427 	return 0;
10428 }
10429 
10430 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10431 				 const struct bpf_insn *insn,
10432 				 const struct bpf_reg_state *dst_reg)
10433 {
10434 	u32 dst = insn->dst_reg;
10435 
10436 	/* For unprivileged we require that resulting offset must be in bounds
10437 	 * in order to be able to sanitize access later on.
10438 	 */
10439 	if (env->bypass_spec_v1)
10440 		return 0;
10441 
10442 	switch (dst_reg->type) {
10443 	case PTR_TO_STACK:
10444 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10445 					dst_reg->off + dst_reg->var_off.value))
10446 			return -EACCES;
10447 		break;
10448 	case PTR_TO_MAP_VALUE:
10449 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10450 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10451 				"prohibited for !root\n", dst);
10452 			return -EACCES;
10453 		}
10454 		break;
10455 	default:
10456 		break;
10457 	}
10458 
10459 	return 0;
10460 }
10461 
10462 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10463  * Caller should also handle BPF_MOV case separately.
10464  * If we return -EACCES, caller may want to try again treating pointer as a
10465  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10466  */
10467 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10468 				   struct bpf_insn *insn,
10469 				   const struct bpf_reg_state *ptr_reg,
10470 				   const struct bpf_reg_state *off_reg)
10471 {
10472 	struct bpf_verifier_state *vstate = env->cur_state;
10473 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10474 	struct bpf_reg_state *regs = state->regs, *dst_reg;
10475 	bool known = tnum_is_const(off_reg->var_off);
10476 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10477 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10478 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10479 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10480 	struct bpf_sanitize_info info = {};
10481 	u8 opcode = BPF_OP(insn->code);
10482 	u32 dst = insn->dst_reg;
10483 	int ret;
10484 
10485 	dst_reg = &regs[dst];
10486 
10487 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10488 	    smin_val > smax_val || umin_val > umax_val) {
10489 		/* Taint dst register if offset had invalid bounds derived from
10490 		 * e.g. dead branches.
10491 		 */
10492 		__mark_reg_unknown(env, dst_reg);
10493 		return 0;
10494 	}
10495 
10496 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
10497 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
10498 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10499 			__mark_reg_unknown(env, dst_reg);
10500 			return 0;
10501 		}
10502 
10503 		verbose(env,
10504 			"R%d 32-bit pointer arithmetic prohibited\n",
10505 			dst);
10506 		return -EACCES;
10507 	}
10508 
10509 	if (ptr_reg->type & PTR_MAYBE_NULL) {
10510 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10511 			dst, reg_type_str(env, ptr_reg->type));
10512 		return -EACCES;
10513 	}
10514 
10515 	switch (base_type(ptr_reg->type)) {
10516 	case CONST_PTR_TO_MAP:
10517 		/* smin_val represents the known value */
10518 		if (known && smin_val == 0 && opcode == BPF_ADD)
10519 			break;
10520 		fallthrough;
10521 	case PTR_TO_PACKET_END:
10522 	case PTR_TO_SOCKET:
10523 	case PTR_TO_SOCK_COMMON:
10524 	case PTR_TO_TCP_SOCK:
10525 	case PTR_TO_XDP_SOCK:
10526 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10527 			dst, reg_type_str(env, ptr_reg->type));
10528 		return -EACCES;
10529 	default:
10530 		break;
10531 	}
10532 
10533 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10534 	 * The id may be overwritten later if we create a new variable offset.
10535 	 */
10536 	dst_reg->type = ptr_reg->type;
10537 	dst_reg->id = ptr_reg->id;
10538 
10539 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10540 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10541 		return -EINVAL;
10542 
10543 	/* pointer types do not carry 32-bit bounds at the moment. */
10544 	__mark_reg32_unbounded(dst_reg);
10545 
10546 	if (sanitize_needed(opcode)) {
10547 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10548 				       &info, false);
10549 		if (ret < 0)
10550 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10551 	}
10552 
10553 	switch (opcode) {
10554 	case BPF_ADD:
10555 		/* We can take a fixed offset as long as it doesn't overflow
10556 		 * the s32 'off' field
10557 		 */
10558 		if (known && (ptr_reg->off + smin_val ==
10559 			      (s64)(s32)(ptr_reg->off + smin_val))) {
10560 			/* pointer += K.  Accumulate it into fixed offset */
10561 			dst_reg->smin_value = smin_ptr;
10562 			dst_reg->smax_value = smax_ptr;
10563 			dst_reg->umin_value = umin_ptr;
10564 			dst_reg->umax_value = umax_ptr;
10565 			dst_reg->var_off = ptr_reg->var_off;
10566 			dst_reg->off = ptr_reg->off + smin_val;
10567 			dst_reg->raw = ptr_reg->raw;
10568 			break;
10569 		}
10570 		/* A new variable offset is created.  Note that off_reg->off
10571 		 * == 0, since it's a scalar.
10572 		 * dst_reg gets the pointer type and since some positive
10573 		 * integer value was added to the pointer, give it a new 'id'
10574 		 * if it's a PTR_TO_PACKET.
10575 		 * this creates a new 'base' pointer, off_reg (variable) gets
10576 		 * added into the variable offset, and we copy the fixed offset
10577 		 * from ptr_reg.
10578 		 */
10579 		if (signed_add_overflows(smin_ptr, smin_val) ||
10580 		    signed_add_overflows(smax_ptr, smax_val)) {
10581 			dst_reg->smin_value = S64_MIN;
10582 			dst_reg->smax_value = S64_MAX;
10583 		} else {
10584 			dst_reg->smin_value = smin_ptr + smin_val;
10585 			dst_reg->smax_value = smax_ptr + smax_val;
10586 		}
10587 		if (umin_ptr + umin_val < umin_ptr ||
10588 		    umax_ptr + umax_val < umax_ptr) {
10589 			dst_reg->umin_value = 0;
10590 			dst_reg->umax_value = U64_MAX;
10591 		} else {
10592 			dst_reg->umin_value = umin_ptr + umin_val;
10593 			dst_reg->umax_value = umax_ptr + umax_val;
10594 		}
10595 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10596 		dst_reg->off = ptr_reg->off;
10597 		dst_reg->raw = ptr_reg->raw;
10598 		if (reg_is_pkt_pointer(ptr_reg)) {
10599 			dst_reg->id = ++env->id_gen;
10600 			/* something was added to pkt_ptr, set range to zero */
10601 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10602 		}
10603 		break;
10604 	case BPF_SUB:
10605 		if (dst_reg == off_reg) {
10606 			/* scalar -= pointer.  Creates an unknown scalar */
10607 			verbose(env, "R%d tried to subtract pointer from scalar\n",
10608 				dst);
10609 			return -EACCES;
10610 		}
10611 		/* We don't allow subtraction from FP, because (according to
10612 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
10613 		 * be able to deal with it.
10614 		 */
10615 		if (ptr_reg->type == PTR_TO_STACK) {
10616 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
10617 				dst);
10618 			return -EACCES;
10619 		}
10620 		if (known && (ptr_reg->off - smin_val ==
10621 			      (s64)(s32)(ptr_reg->off - smin_val))) {
10622 			/* pointer -= K.  Subtract it from fixed offset */
10623 			dst_reg->smin_value = smin_ptr;
10624 			dst_reg->smax_value = smax_ptr;
10625 			dst_reg->umin_value = umin_ptr;
10626 			dst_reg->umax_value = umax_ptr;
10627 			dst_reg->var_off = ptr_reg->var_off;
10628 			dst_reg->id = ptr_reg->id;
10629 			dst_reg->off = ptr_reg->off - smin_val;
10630 			dst_reg->raw = ptr_reg->raw;
10631 			break;
10632 		}
10633 		/* A new variable offset is created.  If the subtrahend is known
10634 		 * nonnegative, then any reg->range we had before is still good.
10635 		 */
10636 		if (signed_sub_overflows(smin_ptr, smax_val) ||
10637 		    signed_sub_overflows(smax_ptr, smin_val)) {
10638 			/* Overflow possible, we know nothing */
10639 			dst_reg->smin_value = S64_MIN;
10640 			dst_reg->smax_value = S64_MAX;
10641 		} else {
10642 			dst_reg->smin_value = smin_ptr - smax_val;
10643 			dst_reg->smax_value = smax_ptr - smin_val;
10644 		}
10645 		if (umin_ptr < umax_val) {
10646 			/* Overflow possible, we know nothing */
10647 			dst_reg->umin_value = 0;
10648 			dst_reg->umax_value = U64_MAX;
10649 		} else {
10650 			/* Cannot overflow (as long as bounds are consistent) */
10651 			dst_reg->umin_value = umin_ptr - umax_val;
10652 			dst_reg->umax_value = umax_ptr - umin_val;
10653 		}
10654 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10655 		dst_reg->off = ptr_reg->off;
10656 		dst_reg->raw = ptr_reg->raw;
10657 		if (reg_is_pkt_pointer(ptr_reg)) {
10658 			dst_reg->id = ++env->id_gen;
10659 			/* something was added to pkt_ptr, set range to zero */
10660 			if (smin_val < 0)
10661 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10662 		}
10663 		break;
10664 	case BPF_AND:
10665 	case BPF_OR:
10666 	case BPF_XOR:
10667 		/* bitwise ops on pointers are troublesome, prohibit. */
10668 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
10669 			dst, bpf_alu_string[opcode >> 4]);
10670 		return -EACCES;
10671 	default:
10672 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
10673 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
10674 			dst, bpf_alu_string[opcode >> 4]);
10675 		return -EACCES;
10676 	}
10677 
10678 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
10679 		return -EINVAL;
10680 	reg_bounds_sync(dst_reg);
10681 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
10682 		return -EACCES;
10683 	if (sanitize_needed(opcode)) {
10684 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
10685 				       &info, true);
10686 		if (ret < 0)
10687 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10688 	}
10689 
10690 	return 0;
10691 }
10692 
10693 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
10694 				 struct bpf_reg_state *src_reg)
10695 {
10696 	s32 smin_val = src_reg->s32_min_value;
10697 	s32 smax_val = src_reg->s32_max_value;
10698 	u32 umin_val = src_reg->u32_min_value;
10699 	u32 umax_val = src_reg->u32_max_value;
10700 
10701 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
10702 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
10703 		dst_reg->s32_min_value = S32_MIN;
10704 		dst_reg->s32_max_value = S32_MAX;
10705 	} else {
10706 		dst_reg->s32_min_value += smin_val;
10707 		dst_reg->s32_max_value += smax_val;
10708 	}
10709 	if (dst_reg->u32_min_value + umin_val < umin_val ||
10710 	    dst_reg->u32_max_value + umax_val < umax_val) {
10711 		dst_reg->u32_min_value = 0;
10712 		dst_reg->u32_max_value = U32_MAX;
10713 	} else {
10714 		dst_reg->u32_min_value += umin_val;
10715 		dst_reg->u32_max_value += umax_val;
10716 	}
10717 }
10718 
10719 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
10720 			       struct bpf_reg_state *src_reg)
10721 {
10722 	s64 smin_val = src_reg->smin_value;
10723 	s64 smax_val = src_reg->smax_value;
10724 	u64 umin_val = src_reg->umin_value;
10725 	u64 umax_val = src_reg->umax_value;
10726 
10727 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
10728 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
10729 		dst_reg->smin_value = S64_MIN;
10730 		dst_reg->smax_value = S64_MAX;
10731 	} else {
10732 		dst_reg->smin_value += smin_val;
10733 		dst_reg->smax_value += smax_val;
10734 	}
10735 	if (dst_reg->umin_value + umin_val < umin_val ||
10736 	    dst_reg->umax_value + umax_val < umax_val) {
10737 		dst_reg->umin_value = 0;
10738 		dst_reg->umax_value = U64_MAX;
10739 	} else {
10740 		dst_reg->umin_value += umin_val;
10741 		dst_reg->umax_value += umax_val;
10742 	}
10743 }
10744 
10745 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10746 				 struct bpf_reg_state *src_reg)
10747 {
10748 	s32 smin_val = src_reg->s32_min_value;
10749 	s32 smax_val = src_reg->s32_max_value;
10750 	u32 umin_val = src_reg->u32_min_value;
10751 	u32 umax_val = src_reg->u32_max_value;
10752 
10753 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10754 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10755 		/* Overflow possible, we know nothing */
10756 		dst_reg->s32_min_value = S32_MIN;
10757 		dst_reg->s32_max_value = S32_MAX;
10758 	} else {
10759 		dst_reg->s32_min_value -= smax_val;
10760 		dst_reg->s32_max_value -= smin_val;
10761 	}
10762 	if (dst_reg->u32_min_value < umax_val) {
10763 		/* Overflow possible, we know nothing */
10764 		dst_reg->u32_min_value = 0;
10765 		dst_reg->u32_max_value = U32_MAX;
10766 	} else {
10767 		/* Cannot overflow (as long as bounds are consistent) */
10768 		dst_reg->u32_min_value -= umax_val;
10769 		dst_reg->u32_max_value -= umin_val;
10770 	}
10771 }
10772 
10773 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10774 			       struct bpf_reg_state *src_reg)
10775 {
10776 	s64 smin_val = src_reg->smin_value;
10777 	s64 smax_val = src_reg->smax_value;
10778 	u64 umin_val = src_reg->umin_value;
10779 	u64 umax_val = src_reg->umax_value;
10780 
10781 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10782 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10783 		/* Overflow possible, we know nothing */
10784 		dst_reg->smin_value = S64_MIN;
10785 		dst_reg->smax_value = S64_MAX;
10786 	} else {
10787 		dst_reg->smin_value -= smax_val;
10788 		dst_reg->smax_value -= smin_val;
10789 	}
10790 	if (dst_reg->umin_value < umax_val) {
10791 		/* Overflow possible, we know nothing */
10792 		dst_reg->umin_value = 0;
10793 		dst_reg->umax_value = U64_MAX;
10794 	} else {
10795 		/* Cannot overflow (as long as bounds are consistent) */
10796 		dst_reg->umin_value -= umax_val;
10797 		dst_reg->umax_value -= umin_val;
10798 	}
10799 }
10800 
10801 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10802 				 struct bpf_reg_state *src_reg)
10803 {
10804 	s32 smin_val = src_reg->s32_min_value;
10805 	u32 umin_val = src_reg->u32_min_value;
10806 	u32 umax_val = src_reg->u32_max_value;
10807 
10808 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10809 		/* Ain't nobody got time to multiply that sign */
10810 		__mark_reg32_unbounded(dst_reg);
10811 		return;
10812 	}
10813 	/* Both values are positive, so we can work with unsigned and
10814 	 * copy the result to signed (unless it exceeds S32_MAX).
10815 	 */
10816 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10817 		/* Potential overflow, we know nothing */
10818 		__mark_reg32_unbounded(dst_reg);
10819 		return;
10820 	}
10821 	dst_reg->u32_min_value *= umin_val;
10822 	dst_reg->u32_max_value *= umax_val;
10823 	if (dst_reg->u32_max_value > S32_MAX) {
10824 		/* Overflow possible, we know nothing */
10825 		dst_reg->s32_min_value = S32_MIN;
10826 		dst_reg->s32_max_value = S32_MAX;
10827 	} else {
10828 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10829 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10830 	}
10831 }
10832 
10833 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10834 			       struct bpf_reg_state *src_reg)
10835 {
10836 	s64 smin_val = src_reg->smin_value;
10837 	u64 umin_val = src_reg->umin_value;
10838 	u64 umax_val = src_reg->umax_value;
10839 
10840 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10841 		/* Ain't nobody got time to multiply that sign */
10842 		__mark_reg64_unbounded(dst_reg);
10843 		return;
10844 	}
10845 	/* Both values are positive, so we can work with unsigned and
10846 	 * copy the result to signed (unless it exceeds S64_MAX).
10847 	 */
10848 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10849 		/* Potential overflow, we know nothing */
10850 		__mark_reg64_unbounded(dst_reg);
10851 		return;
10852 	}
10853 	dst_reg->umin_value *= umin_val;
10854 	dst_reg->umax_value *= umax_val;
10855 	if (dst_reg->umax_value > S64_MAX) {
10856 		/* Overflow possible, we know nothing */
10857 		dst_reg->smin_value = S64_MIN;
10858 		dst_reg->smax_value = S64_MAX;
10859 	} else {
10860 		dst_reg->smin_value = dst_reg->umin_value;
10861 		dst_reg->smax_value = dst_reg->umax_value;
10862 	}
10863 }
10864 
10865 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10866 				 struct bpf_reg_state *src_reg)
10867 {
10868 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10869 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10870 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10871 	s32 smin_val = src_reg->s32_min_value;
10872 	u32 umax_val = src_reg->u32_max_value;
10873 
10874 	if (src_known && dst_known) {
10875 		__mark_reg32_known(dst_reg, var32_off.value);
10876 		return;
10877 	}
10878 
10879 	/* We get our minimum from the var_off, since that's inherently
10880 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10881 	 */
10882 	dst_reg->u32_min_value = var32_off.value;
10883 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10884 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10885 		/* Lose signed bounds when ANDing negative numbers,
10886 		 * ain't nobody got time for that.
10887 		 */
10888 		dst_reg->s32_min_value = S32_MIN;
10889 		dst_reg->s32_max_value = S32_MAX;
10890 	} else {
10891 		/* ANDing two positives gives a positive, so safe to
10892 		 * cast result into s64.
10893 		 */
10894 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10895 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10896 	}
10897 }
10898 
10899 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10900 			       struct bpf_reg_state *src_reg)
10901 {
10902 	bool src_known = tnum_is_const(src_reg->var_off);
10903 	bool dst_known = tnum_is_const(dst_reg->var_off);
10904 	s64 smin_val = src_reg->smin_value;
10905 	u64 umax_val = src_reg->umax_value;
10906 
10907 	if (src_known && dst_known) {
10908 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10909 		return;
10910 	}
10911 
10912 	/* We get our minimum from the var_off, since that's inherently
10913 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10914 	 */
10915 	dst_reg->umin_value = dst_reg->var_off.value;
10916 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10917 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10918 		/* Lose signed bounds when ANDing negative numbers,
10919 		 * ain't nobody got time for that.
10920 		 */
10921 		dst_reg->smin_value = S64_MIN;
10922 		dst_reg->smax_value = S64_MAX;
10923 	} else {
10924 		/* ANDing two positives gives a positive, so safe to
10925 		 * cast result into s64.
10926 		 */
10927 		dst_reg->smin_value = dst_reg->umin_value;
10928 		dst_reg->smax_value = dst_reg->umax_value;
10929 	}
10930 	/* We may learn something more from the var_off */
10931 	__update_reg_bounds(dst_reg);
10932 }
10933 
10934 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10935 				struct bpf_reg_state *src_reg)
10936 {
10937 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10938 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10939 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10940 	s32 smin_val = src_reg->s32_min_value;
10941 	u32 umin_val = src_reg->u32_min_value;
10942 
10943 	if (src_known && dst_known) {
10944 		__mark_reg32_known(dst_reg, var32_off.value);
10945 		return;
10946 	}
10947 
10948 	/* We get our maximum from the var_off, and our minimum is the
10949 	 * maximum of the operands' minima
10950 	 */
10951 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10952 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10953 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10954 		/* Lose signed bounds when ORing negative numbers,
10955 		 * ain't nobody got time for that.
10956 		 */
10957 		dst_reg->s32_min_value = S32_MIN;
10958 		dst_reg->s32_max_value = S32_MAX;
10959 	} else {
10960 		/* ORing two positives gives a positive, so safe to
10961 		 * cast result into s64.
10962 		 */
10963 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10964 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10965 	}
10966 }
10967 
10968 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10969 			      struct bpf_reg_state *src_reg)
10970 {
10971 	bool src_known = tnum_is_const(src_reg->var_off);
10972 	bool dst_known = tnum_is_const(dst_reg->var_off);
10973 	s64 smin_val = src_reg->smin_value;
10974 	u64 umin_val = src_reg->umin_value;
10975 
10976 	if (src_known && dst_known) {
10977 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10978 		return;
10979 	}
10980 
10981 	/* We get our maximum from the var_off, and our minimum is the
10982 	 * maximum of the operands' minima
10983 	 */
10984 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10985 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10986 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10987 		/* Lose signed bounds when ORing negative numbers,
10988 		 * ain't nobody got time for that.
10989 		 */
10990 		dst_reg->smin_value = S64_MIN;
10991 		dst_reg->smax_value = S64_MAX;
10992 	} else {
10993 		/* ORing two positives gives a positive, so safe to
10994 		 * cast result into s64.
10995 		 */
10996 		dst_reg->smin_value = dst_reg->umin_value;
10997 		dst_reg->smax_value = dst_reg->umax_value;
10998 	}
10999 	/* We may learn something more from the var_off */
11000 	__update_reg_bounds(dst_reg);
11001 }
11002 
11003 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11004 				 struct bpf_reg_state *src_reg)
11005 {
11006 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11007 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11008 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11009 	s32 smin_val = src_reg->s32_min_value;
11010 
11011 	if (src_known && dst_known) {
11012 		__mark_reg32_known(dst_reg, var32_off.value);
11013 		return;
11014 	}
11015 
11016 	/* We get both minimum and maximum from the var32_off. */
11017 	dst_reg->u32_min_value = var32_off.value;
11018 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11019 
11020 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11021 		/* XORing two positive sign numbers gives a positive,
11022 		 * so safe to cast u32 result into s32.
11023 		 */
11024 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11025 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11026 	} else {
11027 		dst_reg->s32_min_value = S32_MIN;
11028 		dst_reg->s32_max_value = S32_MAX;
11029 	}
11030 }
11031 
11032 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11033 			       struct bpf_reg_state *src_reg)
11034 {
11035 	bool src_known = tnum_is_const(src_reg->var_off);
11036 	bool dst_known = tnum_is_const(dst_reg->var_off);
11037 	s64 smin_val = src_reg->smin_value;
11038 
11039 	if (src_known && dst_known) {
11040 		/* dst_reg->var_off.value has been updated earlier */
11041 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11042 		return;
11043 	}
11044 
11045 	/* We get both minimum and maximum from the var_off. */
11046 	dst_reg->umin_value = dst_reg->var_off.value;
11047 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11048 
11049 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11050 		/* XORing two positive sign numbers gives a positive,
11051 		 * so safe to cast u64 result into s64.
11052 		 */
11053 		dst_reg->smin_value = dst_reg->umin_value;
11054 		dst_reg->smax_value = dst_reg->umax_value;
11055 	} else {
11056 		dst_reg->smin_value = S64_MIN;
11057 		dst_reg->smax_value = S64_MAX;
11058 	}
11059 
11060 	__update_reg_bounds(dst_reg);
11061 }
11062 
11063 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11064 				   u64 umin_val, u64 umax_val)
11065 {
11066 	/* We lose all sign bit information (except what we can pick
11067 	 * up from var_off)
11068 	 */
11069 	dst_reg->s32_min_value = S32_MIN;
11070 	dst_reg->s32_max_value = S32_MAX;
11071 	/* If we might shift our top bit out, then we know nothing */
11072 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11073 		dst_reg->u32_min_value = 0;
11074 		dst_reg->u32_max_value = U32_MAX;
11075 	} else {
11076 		dst_reg->u32_min_value <<= umin_val;
11077 		dst_reg->u32_max_value <<= umax_val;
11078 	}
11079 }
11080 
11081 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11082 				 struct bpf_reg_state *src_reg)
11083 {
11084 	u32 umax_val = src_reg->u32_max_value;
11085 	u32 umin_val = src_reg->u32_min_value;
11086 	/* u32 alu operation will zext upper bits */
11087 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11088 
11089 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11090 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11091 	/* Not required but being careful mark reg64 bounds as unknown so
11092 	 * that we are forced to pick them up from tnum and zext later and
11093 	 * if some path skips this step we are still safe.
11094 	 */
11095 	__mark_reg64_unbounded(dst_reg);
11096 	__update_reg32_bounds(dst_reg);
11097 }
11098 
11099 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11100 				   u64 umin_val, u64 umax_val)
11101 {
11102 	/* Special case <<32 because it is a common compiler pattern to sign
11103 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11104 	 * positive we know this shift will also be positive so we can track
11105 	 * bounds correctly. Otherwise we lose all sign bit information except
11106 	 * what we can pick up from var_off. Perhaps we can generalize this
11107 	 * later to shifts of any length.
11108 	 */
11109 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11110 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11111 	else
11112 		dst_reg->smax_value = S64_MAX;
11113 
11114 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11115 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11116 	else
11117 		dst_reg->smin_value = S64_MIN;
11118 
11119 	/* If we might shift our top bit out, then we know nothing */
11120 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11121 		dst_reg->umin_value = 0;
11122 		dst_reg->umax_value = U64_MAX;
11123 	} else {
11124 		dst_reg->umin_value <<= umin_val;
11125 		dst_reg->umax_value <<= umax_val;
11126 	}
11127 }
11128 
11129 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11130 			       struct bpf_reg_state *src_reg)
11131 {
11132 	u64 umax_val = src_reg->umax_value;
11133 	u64 umin_val = src_reg->umin_value;
11134 
11135 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
11136 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11137 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11138 
11139 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11140 	/* We may learn something more from the var_off */
11141 	__update_reg_bounds(dst_reg);
11142 }
11143 
11144 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11145 				 struct bpf_reg_state *src_reg)
11146 {
11147 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11148 	u32 umax_val = src_reg->u32_max_value;
11149 	u32 umin_val = src_reg->u32_min_value;
11150 
11151 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11152 	 * be negative, then either:
11153 	 * 1) src_reg might be zero, so the sign bit of the result is
11154 	 *    unknown, so we lose our signed bounds
11155 	 * 2) it's known negative, thus the unsigned bounds capture the
11156 	 *    signed bounds
11157 	 * 3) the signed bounds cross zero, so they tell us nothing
11158 	 *    about the result
11159 	 * If the value in dst_reg is known nonnegative, then again the
11160 	 * unsigned bounds capture the signed bounds.
11161 	 * Thus, in all cases it suffices to blow away our signed bounds
11162 	 * and rely on inferring new ones from the unsigned bounds and
11163 	 * var_off of the result.
11164 	 */
11165 	dst_reg->s32_min_value = S32_MIN;
11166 	dst_reg->s32_max_value = S32_MAX;
11167 
11168 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
11169 	dst_reg->u32_min_value >>= umax_val;
11170 	dst_reg->u32_max_value >>= umin_val;
11171 
11172 	__mark_reg64_unbounded(dst_reg);
11173 	__update_reg32_bounds(dst_reg);
11174 }
11175 
11176 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11177 			       struct bpf_reg_state *src_reg)
11178 {
11179 	u64 umax_val = src_reg->umax_value;
11180 	u64 umin_val = src_reg->umin_value;
11181 
11182 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11183 	 * be negative, then either:
11184 	 * 1) src_reg might be zero, so the sign bit of the result is
11185 	 *    unknown, so we lose our signed bounds
11186 	 * 2) it's known negative, thus the unsigned bounds capture the
11187 	 *    signed bounds
11188 	 * 3) the signed bounds cross zero, so they tell us nothing
11189 	 *    about the result
11190 	 * If the value in dst_reg is known nonnegative, then again the
11191 	 * unsigned bounds capture the signed bounds.
11192 	 * Thus, in all cases it suffices to blow away our signed bounds
11193 	 * and rely on inferring new ones from the unsigned bounds and
11194 	 * var_off of the result.
11195 	 */
11196 	dst_reg->smin_value = S64_MIN;
11197 	dst_reg->smax_value = S64_MAX;
11198 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11199 	dst_reg->umin_value >>= umax_val;
11200 	dst_reg->umax_value >>= umin_val;
11201 
11202 	/* Its not easy to operate on alu32 bounds here because it depends
11203 	 * on bits being shifted in. Take easy way out and mark unbounded
11204 	 * so we can recalculate later from tnum.
11205 	 */
11206 	__mark_reg32_unbounded(dst_reg);
11207 	__update_reg_bounds(dst_reg);
11208 }
11209 
11210 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11211 				  struct bpf_reg_state *src_reg)
11212 {
11213 	u64 umin_val = src_reg->u32_min_value;
11214 
11215 	/* Upon reaching here, src_known is true and
11216 	 * umax_val is equal to umin_val.
11217 	 */
11218 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11219 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11220 
11221 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11222 
11223 	/* blow away the dst_reg umin_value/umax_value and rely on
11224 	 * dst_reg var_off to refine the result.
11225 	 */
11226 	dst_reg->u32_min_value = 0;
11227 	dst_reg->u32_max_value = U32_MAX;
11228 
11229 	__mark_reg64_unbounded(dst_reg);
11230 	__update_reg32_bounds(dst_reg);
11231 }
11232 
11233 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11234 				struct bpf_reg_state *src_reg)
11235 {
11236 	u64 umin_val = src_reg->umin_value;
11237 
11238 	/* Upon reaching here, src_known is true and umax_val is equal
11239 	 * to umin_val.
11240 	 */
11241 	dst_reg->smin_value >>= umin_val;
11242 	dst_reg->smax_value >>= umin_val;
11243 
11244 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11245 
11246 	/* blow away the dst_reg umin_value/umax_value and rely on
11247 	 * dst_reg var_off to refine the result.
11248 	 */
11249 	dst_reg->umin_value = 0;
11250 	dst_reg->umax_value = U64_MAX;
11251 
11252 	/* Its not easy to operate on alu32 bounds here because it depends
11253 	 * on bits being shifted in from upper 32-bits. Take easy way out
11254 	 * and mark unbounded so we can recalculate later from tnum.
11255 	 */
11256 	__mark_reg32_unbounded(dst_reg);
11257 	__update_reg_bounds(dst_reg);
11258 }
11259 
11260 /* WARNING: This function does calculations on 64-bit values, but the actual
11261  * execution may occur on 32-bit values. Therefore, things like bitshifts
11262  * need extra checks in the 32-bit case.
11263  */
11264 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11265 				      struct bpf_insn *insn,
11266 				      struct bpf_reg_state *dst_reg,
11267 				      struct bpf_reg_state src_reg)
11268 {
11269 	struct bpf_reg_state *regs = cur_regs(env);
11270 	u8 opcode = BPF_OP(insn->code);
11271 	bool src_known;
11272 	s64 smin_val, smax_val;
11273 	u64 umin_val, umax_val;
11274 	s32 s32_min_val, s32_max_val;
11275 	u32 u32_min_val, u32_max_val;
11276 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11277 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11278 	int ret;
11279 
11280 	smin_val = src_reg.smin_value;
11281 	smax_val = src_reg.smax_value;
11282 	umin_val = src_reg.umin_value;
11283 	umax_val = src_reg.umax_value;
11284 
11285 	s32_min_val = src_reg.s32_min_value;
11286 	s32_max_val = src_reg.s32_max_value;
11287 	u32_min_val = src_reg.u32_min_value;
11288 	u32_max_val = src_reg.u32_max_value;
11289 
11290 	if (alu32) {
11291 		src_known = tnum_subreg_is_const(src_reg.var_off);
11292 		if ((src_known &&
11293 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11294 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11295 			/* Taint dst register if offset had invalid bounds
11296 			 * derived from e.g. dead branches.
11297 			 */
11298 			__mark_reg_unknown(env, dst_reg);
11299 			return 0;
11300 		}
11301 	} else {
11302 		src_known = tnum_is_const(src_reg.var_off);
11303 		if ((src_known &&
11304 		     (smin_val != smax_val || umin_val != umax_val)) ||
11305 		    smin_val > smax_val || umin_val > umax_val) {
11306 			/* Taint dst register if offset had invalid bounds
11307 			 * derived from e.g. dead branches.
11308 			 */
11309 			__mark_reg_unknown(env, dst_reg);
11310 			return 0;
11311 		}
11312 	}
11313 
11314 	if (!src_known &&
11315 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11316 		__mark_reg_unknown(env, dst_reg);
11317 		return 0;
11318 	}
11319 
11320 	if (sanitize_needed(opcode)) {
11321 		ret = sanitize_val_alu(env, insn);
11322 		if (ret < 0)
11323 			return sanitize_err(env, insn, ret, NULL, NULL);
11324 	}
11325 
11326 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11327 	 * There are two classes of instructions: The first class we track both
11328 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
11329 	 * greatest amount of precision when alu operations are mixed with jmp32
11330 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11331 	 * and BPF_OR. This is possible because these ops have fairly easy to
11332 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11333 	 * See alu32 verifier tests for examples. The second class of
11334 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11335 	 * with regards to tracking sign/unsigned bounds because the bits may
11336 	 * cross subreg boundaries in the alu64 case. When this happens we mark
11337 	 * the reg unbounded in the subreg bound space and use the resulting
11338 	 * tnum to calculate an approximation of the sign/unsigned bounds.
11339 	 */
11340 	switch (opcode) {
11341 	case BPF_ADD:
11342 		scalar32_min_max_add(dst_reg, &src_reg);
11343 		scalar_min_max_add(dst_reg, &src_reg);
11344 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11345 		break;
11346 	case BPF_SUB:
11347 		scalar32_min_max_sub(dst_reg, &src_reg);
11348 		scalar_min_max_sub(dst_reg, &src_reg);
11349 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11350 		break;
11351 	case BPF_MUL:
11352 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11353 		scalar32_min_max_mul(dst_reg, &src_reg);
11354 		scalar_min_max_mul(dst_reg, &src_reg);
11355 		break;
11356 	case BPF_AND:
11357 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11358 		scalar32_min_max_and(dst_reg, &src_reg);
11359 		scalar_min_max_and(dst_reg, &src_reg);
11360 		break;
11361 	case BPF_OR:
11362 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11363 		scalar32_min_max_or(dst_reg, &src_reg);
11364 		scalar_min_max_or(dst_reg, &src_reg);
11365 		break;
11366 	case BPF_XOR:
11367 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11368 		scalar32_min_max_xor(dst_reg, &src_reg);
11369 		scalar_min_max_xor(dst_reg, &src_reg);
11370 		break;
11371 	case BPF_LSH:
11372 		if (umax_val >= insn_bitness) {
11373 			/* Shifts greater than 31 or 63 are undefined.
11374 			 * This includes shifts by a negative number.
11375 			 */
11376 			mark_reg_unknown(env, regs, insn->dst_reg);
11377 			break;
11378 		}
11379 		if (alu32)
11380 			scalar32_min_max_lsh(dst_reg, &src_reg);
11381 		else
11382 			scalar_min_max_lsh(dst_reg, &src_reg);
11383 		break;
11384 	case BPF_RSH:
11385 		if (umax_val >= insn_bitness) {
11386 			/* Shifts greater than 31 or 63 are undefined.
11387 			 * This includes shifts by a negative number.
11388 			 */
11389 			mark_reg_unknown(env, regs, insn->dst_reg);
11390 			break;
11391 		}
11392 		if (alu32)
11393 			scalar32_min_max_rsh(dst_reg, &src_reg);
11394 		else
11395 			scalar_min_max_rsh(dst_reg, &src_reg);
11396 		break;
11397 	case BPF_ARSH:
11398 		if (umax_val >= insn_bitness) {
11399 			/* Shifts greater than 31 or 63 are undefined.
11400 			 * This includes shifts by a negative number.
11401 			 */
11402 			mark_reg_unknown(env, regs, insn->dst_reg);
11403 			break;
11404 		}
11405 		if (alu32)
11406 			scalar32_min_max_arsh(dst_reg, &src_reg);
11407 		else
11408 			scalar_min_max_arsh(dst_reg, &src_reg);
11409 		break;
11410 	default:
11411 		mark_reg_unknown(env, regs, insn->dst_reg);
11412 		break;
11413 	}
11414 
11415 	/* ALU32 ops are zero extended into 64bit register */
11416 	if (alu32)
11417 		zext_32_to_64(dst_reg);
11418 	reg_bounds_sync(dst_reg);
11419 	return 0;
11420 }
11421 
11422 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11423  * and var_off.
11424  */
11425 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11426 				   struct bpf_insn *insn)
11427 {
11428 	struct bpf_verifier_state *vstate = env->cur_state;
11429 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11430 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11431 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11432 	u8 opcode = BPF_OP(insn->code);
11433 	int err;
11434 
11435 	dst_reg = &regs[insn->dst_reg];
11436 	src_reg = NULL;
11437 	if (dst_reg->type != SCALAR_VALUE)
11438 		ptr_reg = dst_reg;
11439 	else
11440 		/* Make sure ID is cleared otherwise dst_reg min/max could be
11441 		 * incorrectly propagated into other registers by find_equal_scalars()
11442 		 */
11443 		dst_reg->id = 0;
11444 	if (BPF_SRC(insn->code) == BPF_X) {
11445 		src_reg = &regs[insn->src_reg];
11446 		if (src_reg->type != SCALAR_VALUE) {
11447 			if (dst_reg->type != SCALAR_VALUE) {
11448 				/* Combining two pointers by any ALU op yields
11449 				 * an arbitrary scalar. Disallow all math except
11450 				 * pointer subtraction
11451 				 */
11452 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11453 					mark_reg_unknown(env, regs, insn->dst_reg);
11454 					return 0;
11455 				}
11456 				verbose(env, "R%d pointer %s pointer prohibited\n",
11457 					insn->dst_reg,
11458 					bpf_alu_string[opcode >> 4]);
11459 				return -EACCES;
11460 			} else {
11461 				/* scalar += pointer
11462 				 * This is legal, but we have to reverse our
11463 				 * src/dest handling in computing the range
11464 				 */
11465 				err = mark_chain_precision(env, insn->dst_reg);
11466 				if (err)
11467 					return err;
11468 				return adjust_ptr_min_max_vals(env, insn,
11469 							       src_reg, dst_reg);
11470 			}
11471 		} else if (ptr_reg) {
11472 			/* pointer += scalar */
11473 			err = mark_chain_precision(env, insn->src_reg);
11474 			if (err)
11475 				return err;
11476 			return adjust_ptr_min_max_vals(env, insn,
11477 						       dst_reg, src_reg);
11478 		} else if (dst_reg->precise) {
11479 			/* if dst_reg is precise, src_reg should be precise as well */
11480 			err = mark_chain_precision(env, insn->src_reg);
11481 			if (err)
11482 				return err;
11483 		}
11484 	} else {
11485 		/* Pretend the src is a reg with a known value, since we only
11486 		 * need to be able to read from this state.
11487 		 */
11488 		off_reg.type = SCALAR_VALUE;
11489 		__mark_reg_known(&off_reg, insn->imm);
11490 		src_reg = &off_reg;
11491 		if (ptr_reg) /* pointer += K */
11492 			return adjust_ptr_min_max_vals(env, insn,
11493 						       ptr_reg, src_reg);
11494 	}
11495 
11496 	/* Got here implies adding two SCALAR_VALUEs */
11497 	if (WARN_ON_ONCE(ptr_reg)) {
11498 		print_verifier_state(env, state, true);
11499 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
11500 		return -EINVAL;
11501 	}
11502 	if (WARN_ON(!src_reg)) {
11503 		print_verifier_state(env, state, true);
11504 		verbose(env, "verifier internal error: no src_reg\n");
11505 		return -EINVAL;
11506 	}
11507 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11508 }
11509 
11510 /* check validity of 32-bit and 64-bit arithmetic operations */
11511 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11512 {
11513 	struct bpf_reg_state *regs = cur_regs(env);
11514 	u8 opcode = BPF_OP(insn->code);
11515 	int err;
11516 
11517 	if (opcode == BPF_END || opcode == BPF_NEG) {
11518 		if (opcode == BPF_NEG) {
11519 			if (BPF_SRC(insn->code) != BPF_K ||
11520 			    insn->src_reg != BPF_REG_0 ||
11521 			    insn->off != 0 || insn->imm != 0) {
11522 				verbose(env, "BPF_NEG uses reserved fields\n");
11523 				return -EINVAL;
11524 			}
11525 		} else {
11526 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11527 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11528 			    BPF_CLASS(insn->code) == BPF_ALU64) {
11529 				verbose(env, "BPF_END uses reserved fields\n");
11530 				return -EINVAL;
11531 			}
11532 		}
11533 
11534 		/* check src operand */
11535 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11536 		if (err)
11537 			return err;
11538 
11539 		if (is_pointer_value(env, insn->dst_reg)) {
11540 			verbose(env, "R%d pointer arithmetic prohibited\n",
11541 				insn->dst_reg);
11542 			return -EACCES;
11543 		}
11544 
11545 		/* check dest operand */
11546 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
11547 		if (err)
11548 			return err;
11549 
11550 	} else if (opcode == BPF_MOV) {
11551 
11552 		if (BPF_SRC(insn->code) == BPF_X) {
11553 			if (insn->imm != 0 || insn->off != 0) {
11554 				verbose(env, "BPF_MOV uses reserved fields\n");
11555 				return -EINVAL;
11556 			}
11557 
11558 			/* check src operand */
11559 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11560 			if (err)
11561 				return err;
11562 		} else {
11563 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11564 				verbose(env, "BPF_MOV uses reserved fields\n");
11565 				return -EINVAL;
11566 			}
11567 		}
11568 
11569 		/* check dest operand, mark as required later */
11570 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11571 		if (err)
11572 			return err;
11573 
11574 		if (BPF_SRC(insn->code) == BPF_X) {
11575 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
11576 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11577 
11578 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11579 				/* case: R1 = R2
11580 				 * copy register state to dest reg
11581 				 */
11582 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11583 					/* Assign src and dst registers the same ID
11584 					 * that will be used by find_equal_scalars()
11585 					 * to propagate min/max range.
11586 					 */
11587 					src_reg->id = ++env->id_gen;
11588 				copy_register_state(dst_reg, src_reg);
11589 				dst_reg->live |= REG_LIVE_WRITTEN;
11590 				dst_reg->subreg_def = DEF_NOT_SUBREG;
11591 			} else {
11592 				/* R1 = (u32) R2 */
11593 				if (is_pointer_value(env, insn->src_reg)) {
11594 					verbose(env,
11595 						"R%d partial copy of pointer\n",
11596 						insn->src_reg);
11597 					return -EACCES;
11598 				} else if (src_reg->type == SCALAR_VALUE) {
11599 					copy_register_state(dst_reg, src_reg);
11600 					/* Make sure ID is cleared otherwise
11601 					 * dst_reg min/max could be incorrectly
11602 					 * propagated into src_reg by find_equal_scalars()
11603 					 */
11604 					dst_reg->id = 0;
11605 					dst_reg->live |= REG_LIVE_WRITTEN;
11606 					dst_reg->subreg_def = env->insn_idx + 1;
11607 				} else {
11608 					mark_reg_unknown(env, regs,
11609 							 insn->dst_reg);
11610 				}
11611 				zext_32_to_64(dst_reg);
11612 				reg_bounds_sync(dst_reg);
11613 			}
11614 		} else {
11615 			/* case: R = imm
11616 			 * remember the value we stored into this reg
11617 			 */
11618 			/* clear any state __mark_reg_known doesn't set */
11619 			mark_reg_unknown(env, regs, insn->dst_reg);
11620 			regs[insn->dst_reg].type = SCALAR_VALUE;
11621 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11622 				__mark_reg_known(regs + insn->dst_reg,
11623 						 insn->imm);
11624 			} else {
11625 				__mark_reg_known(regs + insn->dst_reg,
11626 						 (u32)insn->imm);
11627 			}
11628 		}
11629 
11630 	} else if (opcode > BPF_END) {
11631 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11632 		return -EINVAL;
11633 
11634 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
11635 
11636 		if (BPF_SRC(insn->code) == BPF_X) {
11637 			if (insn->imm != 0 || insn->off != 0) {
11638 				verbose(env, "BPF_ALU uses reserved fields\n");
11639 				return -EINVAL;
11640 			}
11641 			/* check src1 operand */
11642 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11643 			if (err)
11644 				return err;
11645 		} else {
11646 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11647 				verbose(env, "BPF_ALU uses reserved fields\n");
11648 				return -EINVAL;
11649 			}
11650 		}
11651 
11652 		/* check src2 operand */
11653 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11654 		if (err)
11655 			return err;
11656 
11657 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11658 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11659 			verbose(env, "div by zero\n");
11660 			return -EINVAL;
11661 		}
11662 
11663 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11664 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11665 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11666 
11667 			if (insn->imm < 0 || insn->imm >= size) {
11668 				verbose(env, "invalid shift %d\n", insn->imm);
11669 				return -EINVAL;
11670 			}
11671 		}
11672 
11673 		/* check dest operand */
11674 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11675 		if (err)
11676 			return err;
11677 
11678 		return adjust_reg_min_max_vals(env, insn);
11679 	}
11680 
11681 	return 0;
11682 }
11683 
11684 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
11685 				   struct bpf_reg_state *dst_reg,
11686 				   enum bpf_reg_type type,
11687 				   bool range_right_open)
11688 {
11689 	struct bpf_func_state *state;
11690 	struct bpf_reg_state *reg;
11691 	int new_range;
11692 
11693 	if (dst_reg->off < 0 ||
11694 	    (dst_reg->off == 0 && range_right_open))
11695 		/* This doesn't give us any range */
11696 		return;
11697 
11698 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
11699 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
11700 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
11701 		 * than pkt_end, but that's because it's also less than pkt.
11702 		 */
11703 		return;
11704 
11705 	new_range = dst_reg->off;
11706 	if (range_right_open)
11707 		new_range++;
11708 
11709 	/* Examples for register markings:
11710 	 *
11711 	 * pkt_data in dst register:
11712 	 *
11713 	 *   r2 = r3;
11714 	 *   r2 += 8;
11715 	 *   if (r2 > pkt_end) goto <handle exception>
11716 	 *   <access okay>
11717 	 *
11718 	 *   r2 = r3;
11719 	 *   r2 += 8;
11720 	 *   if (r2 < pkt_end) goto <access okay>
11721 	 *   <handle exception>
11722 	 *
11723 	 *   Where:
11724 	 *     r2 == dst_reg, pkt_end == src_reg
11725 	 *     r2=pkt(id=n,off=8,r=0)
11726 	 *     r3=pkt(id=n,off=0,r=0)
11727 	 *
11728 	 * pkt_data in src register:
11729 	 *
11730 	 *   r2 = r3;
11731 	 *   r2 += 8;
11732 	 *   if (pkt_end >= r2) goto <access okay>
11733 	 *   <handle exception>
11734 	 *
11735 	 *   r2 = r3;
11736 	 *   r2 += 8;
11737 	 *   if (pkt_end <= r2) goto <handle exception>
11738 	 *   <access okay>
11739 	 *
11740 	 *   Where:
11741 	 *     pkt_end == dst_reg, r2 == src_reg
11742 	 *     r2=pkt(id=n,off=8,r=0)
11743 	 *     r3=pkt(id=n,off=0,r=0)
11744 	 *
11745 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11746 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11747 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
11748 	 * the check.
11749 	 */
11750 
11751 	/* If our ids match, then we must have the same max_value.  And we
11752 	 * don't care about the other reg's fixed offset, since if it's too big
11753 	 * the range won't allow anything.
11754 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11755 	 */
11756 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11757 		if (reg->type == type && reg->id == dst_reg->id)
11758 			/* keep the maximum range already checked */
11759 			reg->range = max(reg->range, new_range);
11760 	}));
11761 }
11762 
11763 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11764 {
11765 	struct tnum subreg = tnum_subreg(reg->var_off);
11766 	s32 sval = (s32)val;
11767 
11768 	switch (opcode) {
11769 	case BPF_JEQ:
11770 		if (tnum_is_const(subreg))
11771 			return !!tnum_equals_const(subreg, val);
11772 		break;
11773 	case BPF_JNE:
11774 		if (tnum_is_const(subreg))
11775 			return !tnum_equals_const(subreg, val);
11776 		break;
11777 	case BPF_JSET:
11778 		if ((~subreg.mask & subreg.value) & val)
11779 			return 1;
11780 		if (!((subreg.mask | subreg.value) & val))
11781 			return 0;
11782 		break;
11783 	case BPF_JGT:
11784 		if (reg->u32_min_value > val)
11785 			return 1;
11786 		else if (reg->u32_max_value <= val)
11787 			return 0;
11788 		break;
11789 	case BPF_JSGT:
11790 		if (reg->s32_min_value > sval)
11791 			return 1;
11792 		else if (reg->s32_max_value <= sval)
11793 			return 0;
11794 		break;
11795 	case BPF_JLT:
11796 		if (reg->u32_max_value < val)
11797 			return 1;
11798 		else if (reg->u32_min_value >= val)
11799 			return 0;
11800 		break;
11801 	case BPF_JSLT:
11802 		if (reg->s32_max_value < sval)
11803 			return 1;
11804 		else if (reg->s32_min_value >= sval)
11805 			return 0;
11806 		break;
11807 	case BPF_JGE:
11808 		if (reg->u32_min_value >= val)
11809 			return 1;
11810 		else if (reg->u32_max_value < val)
11811 			return 0;
11812 		break;
11813 	case BPF_JSGE:
11814 		if (reg->s32_min_value >= sval)
11815 			return 1;
11816 		else if (reg->s32_max_value < sval)
11817 			return 0;
11818 		break;
11819 	case BPF_JLE:
11820 		if (reg->u32_max_value <= val)
11821 			return 1;
11822 		else if (reg->u32_min_value > val)
11823 			return 0;
11824 		break;
11825 	case BPF_JSLE:
11826 		if (reg->s32_max_value <= sval)
11827 			return 1;
11828 		else if (reg->s32_min_value > sval)
11829 			return 0;
11830 		break;
11831 	}
11832 
11833 	return -1;
11834 }
11835 
11836 
11837 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11838 {
11839 	s64 sval = (s64)val;
11840 
11841 	switch (opcode) {
11842 	case BPF_JEQ:
11843 		if (tnum_is_const(reg->var_off))
11844 			return !!tnum_equals_const(reg->var_off, val);
11845 		break;
11846 	case BPF_JNE:
11847 		if (tnum_is_const(reg->var_off))
11848 			return !tnum_equals_const(reg->var_off, val);
11849 		break;
11850 	case BPF_JSET:
11851 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11852 			return 1;
11853 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11854 			return 0;
11855 		break;
11856 	case BPF_JGT:
11857 		if (reg->umin_value > val)
11858 			return 1;
11859 		else if (reg->umax_value <= val)
11860 			return 0;
11861 		break;
11862 	case BPF_JSGT:
11863 		if (reg->smin_value > sval)
11864 			return 1;
11865 		else if (reg->smax_value <= sval)
11866 			return 0;
11867 		break;
11868 	case BPF_JLT:
11869 		if (reg->umax_value < val)
11870 			return 1;
11871 		else if (reg->umin_value >= val)
11872 			return 0;
11873 		break;
11874 	case BPF_JSLT:
11875 		if (reg->smax_value < sval)
11876 			return 1;
11877 		else if (reg->smin_value >= sval)
11878 			return 0;
11879 		break;
11880 	case BPF_JGE:
11881 		if (reg->umin_value >= val)
11882 			return 1;
11883 		else if (reg->umax_value < val)
11884 			return 0;
11885 		break;
11886 	case BPF_JSGE:
11887 		if (reg->smin_value >= sval)
11888 			return 1;
11889 		else if (reg->smax_value < sval)
11890 			return 0;
11891 		break;
11892 	case BPF_JLE:
11893 		if (reg->umax_value <= val)
11894 			return 1;
11895 		else if (reg->umin_value > val)
11896 			return 0;
11897 		break;
11898 	case BPF_JSLE:
11899 		if (reg->smax_value <= sval)
11900 			return 1;
11901 		else if (reg->smin_value > sval)
11902 			return 0;
11903 		break;
11904 	}
11905 
11906 	return -1;
11907 }
11908 
11909 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11910  * and return:
11911  *  1 - branch will be taken and "goto target" will be executed
11912  *  0 - branch will not be taken and fall-through to next insn
11913  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11914  *      range [0,10]
11915  */
11916 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11917 			   bool is_jmp32)
11918 {
11919 	if (__is_pointer_value(false, reg)) {
11920 		if (!reg_type_not_null(reg->type))
11921 			return -1;
11922 
11923 		/* If pointer is valid tests against zero will fail so we can
11924 		 * use this to direct branch taken.
11925 		 */
11926 		if (val != 0)
11927 			return -1;
11928 
11929 		switch (opcode) {
11930 		case BPF_JEQ:
11931 			return 0;
11932 		case BPF_JNE:
11933 			return 1;
11934 		default:
11935 			return -1;
11936 		}
11937 	}
11938 
11939 	if (is_jmp32)
11940 		return is_branch32_taken(reg, val, opcode);
11941 	return is_branch64_taken(reg, val, opcode);
11942 }
11943 
11944 static int flip_opcode(u32 opcode)
11945 {
11946 	/* How can we transform "a <op> b" into "b <op> a"? */
11947 	static const u8 opcode_flip[16] = {
11948 		/* these stay the same */
11949 		[BPF_JEQ  >> 4] = BPF_JEQ,
11950 		[BPF_JNE  >> 4] = BPF_JNE,
11951 		[BPF_JSET >> 4] = BPF_JSET,
11952 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11953 		[BPF_JGE  >> 4] = BPF_JLE,
11954 		[BPF_JGT  >> 4] = BPF_JLT,
11955 		[BPF_JLE  >> 4] = BPF_JGE,
11956 		[BPF_JLT  >> 4] = BPF_JGT,
11957 		[BPF_JSGE >> 4] = BPF_JSLE,
11958 		[BPF_JSGT >> 4] = BPF_JSLT,
11959 		[BPF_JSLE >> 4] = BPF_JSGE,
11960 		[BPF_JSLT >> 4] = BPF_JSGT
11961 	};
11962 	return opcode_flip[opcode >> 4];
11963 }
11964 
11965 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11966 				   struct bpf_reg_state *src_reg,
11967 				   u8 opcode)
11968 {
11969 	struct bpf_reg_state *pkt;
11970 
11971 	if (src_reg->type == PTR_TO_PACKET_END) {
11972 		pkt = dst_reg;
11973 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11974 		pkt = src_reg;
11975 		opcode = flip_opcode(opcode);
11976 	} else {
11977 		return -1;
11978 	}
11979 
11980 	if (pkt->range >= 0)
11981 		return -1;
11982 
11983 	switch (opcode) {
11984 	case BPF_JLE:
11985 		/* pkt <= pkt_end */
11986 		fallthrough;
11987 	case BPF_JGT:
11988 		/* pkt > pkt_end */
11989 		if (pkt->range == BEYOND_PKT_END)
11990 			/* pkt has at last one extra byte beyond pkt_end */
11991 			return opcode == BPF_JGT;
11992 		break;
11993 	case BPF_JLT:
11994 		/* pkt < pkt_end */
11995 		fallthrough;
11996 	case BPF_JGE:
11997 		/* pkt >= pkt_end */
11998 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11999 			return opcode == BPF_JGE;
12000 		break;
12001 	}
12002 	return -1;
12003 }
12004 
12005 /* Adjusts the register min/max values in the case that the dst_reg is the
12006  * variable register that we are working on, and src_reg is a constant or we're
12007  * simply doing a BPF_K check.
12008  * In JEQ/JNE cases we also adjust the var_off values.
12009  */
12010 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12011 			    struct bpf_reg_state *false_reg,
12012 			    u64 val, u32 val32,
12013 			    u8 opcode, bool is_jmp32)
12014 {
12015 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
12016 	struct tnum false_64off = false_reg->var_off;
12017 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
12018 	struct tnum true_64off = true_reg->var_off;
12019 	s64 sval = (s64)val;
12020 	s32 sval32 = (s32)val32;
12021 
12022 	/* If the dst_reg is a pointer, we can't learn anything about its
12023 	 * variable offset from the compare (unless src_reg were a pointer into
12024 	 * the same object, but we don't bother with that.
12025 	 * Since false_reg and true_reg have the same type by construction, we
12026 	 * only need to check one of them for pointerness.
12027 	 */
12028 	if (__is_pointer_value(false, false_reg))
12029 		return;
12030 
12031 	switch (opcode) {
12032 	/* JEQ/JNE comparison doesn't change the register equivalence.
12033 	 *
12034 	 * r1 = r2;
12035 	 * if (r1 == 42) goto label;
12036 	 * ...
12037 	 * label: // here both r1 and r2 are known to be 42.
12038 	 *
12039 	 * Hence when marking register as known preserve it's ID.
12040 	 */
12041 	case BPF_JEQ:
12042 		if (is_jmp32) {
12043 			__mark_reg32_known(true_reg, val32);
12044 			true_32off = tnum_subreg(true_reg->var_off);
12045 		} else {
12046 			___mark_reg_known(true_reg, val);
12047 			true_64off = true_reg->var_off;
12048 		}
12049 		break;
12050 	case BPF_JNE:
12051 		if (is_jmp32) {
12052 			__mark_reg32_known(false_reg, val32);
12053 			false_32off = tnum_subreg(false_reg->var_off);
12054 		} else {
12055 			___mark_reg_known(false_reg, val);
12056 			false_64off = false_reg->var_off;
12057 		}
12058 		break;
12059 	case BPF_JSET:
12060 		if (is_jmp32) {
12061 			false_32off = tnum_and(false_32off, tnum_const(~val32));
12062 			if (is_power_of_2(val32))
12063 				true_32off = tnum_or(true_32off,
12064 						     tnum_const(val32));
12065 		} else {
12066 			false_64off = tnum_and(false_64off, tnum_const(~val));
12067 			if (is_power_of_2(val))
12068 				true_64off = tnum_or(true_64off,
12069 						     tnum_const(val));
12070 		}
12071 		break;
12072 	case BPF_JGE:
12073 	case BPF_JGT:
12074 	{
12075 		if (is_jmp32) {
12076 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12077 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12078 
12079 			false_reg->u32_max_value = min(false_reg->u32_max_value,
12080 						       false_umax);
12081 			true_reg->u32_min_value = max(true_reg->u32_min_value,
12082 						      true_umin);
12083 		} else {
12084 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12085 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12086 
12087 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
12088 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
12089 		}
12090 		break;
12091 	}
12092 	case BPF_JSGE:
12093 	case BPF_JSGT:
12094 	{
12095 		if (is_jmp32) {
12096 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12097 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12098 
12099 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12100 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12101 		} else {
12102 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12103 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12104 
12105 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
12106 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
12107 		}
12108 		break;
12109 	}
12110 	case BPF_JLE:
12111 	case BPF_JLT:
12112 	{
12113 		if (is_jmp32) {
12114 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12115 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12116 
12117 			false_reg->u32_min_value = max(false_reg->u32_min_value,
12118 						       false_umin);
12119 			true_reg->u32_max_value = min(true_reg->u32_max_value,
12120 						      true_umax);
12121 		} else {
12122 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12123 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12124 
12125 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
12126 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
12127 		}
12128 		break;
12129 	}
12130 	case BPF_JSLE:
12131 	case BPF_JSLT:
12132 	{
12133 		if (is_jmp32) {
12134 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12135 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12136 
12137 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12138 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12139 		} else {
12140 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12141 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12142 
12143 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
12144 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
12145 		}
12146 		break;
12147 	}
12148 	default:
12149 		return;
12150 	}
12151 
12152 	if (is_jmp32) {
12153 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12154 					     tnum_subreg(false_32off));
12155 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12156 					    tnum_subreg(true_32off));
12157 		__reg_combine_32_into_64(false_reg);
12158 		__reg_combine_32_into_64(true_reg);
12159 	} else {
12160 		false_reg->var_off = false_64off;
12161 		true_reg->var_off = true_64off;
12162 		__reg_combine_64_into_32(false_reg);
12163 		__reg_combine_64_into_32(true_reg);
12164 	}
12165 }
12166 
12167 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12168  * the variable reg.
12169  */
12170 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12171 				struct bpf_reg_state *false_reg,
12172 				u64 val, u32 val32,
12173 				u8 opcode, bool is_jmp32)
12174 {
12175 	opcode = flip_opcode(opcode);
12176 	/* This uses zero as "not present in table"; luckily the zero opcode,
12177 	 * BPF_JA, can't get here.
12178 	 */
12179 	if (opcode)
12180 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12181 }
12182 
12183 /* Regs are known to be equal, so intersect their min/max/var_off */
12184 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12185 				  struct bpf_reg_state *dst_reg)
12186 {
12187 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12188 							dst_reg->umin_value);
12189 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12190 							dst_reg->umax_value);
12191 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12192 							dst_reg->smin_value);
12193 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12194 							dst_reg->smax_value);
12195 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12196 							     dst_reg->var_off);
12197 	reg_bounds_sync(src_reg);
12198 	reg_bounds_sync(dst_reg);
12199 }
12200 
12201 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12202 				struct bpf_reg_state *true_dst,
12203 				struct bpf_reg_state *false_src,
12204 				struct bpf_reg_state *false_dst,
12205 				u8 opcode)
12206 {
12207 	switch (opcode) {
12208 	case BPF_JEQ:
12209 		__reg_combine_min_max(true_src, true_dst);
12210 		break;
12211 	case BPF_JNE:
12212 		__reg_combine_min_max(false_src, false_dst);
12213 		break;
12214 	}
12215 }
12216 
12217 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12218 				 struct bpf_reg_state *reg, u32 id,
12219 				 bool is_null)
12220 {
12221 	if (type_may_be_null(reg->type) && reg->id == id &&
12222 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12223 		/* Old offset (both fixed and variable parts) should have been
12224 		 * known-zero, because we don't allow pointer arithmetic on
12225 		 * pointers that might be NULL. If we see this happening, don't
12226 		 * convert the register.
12227 		 *
12228 		 * But in some cases, some helpers that return local kptrs
12229 		 * advance offset for the returned pointer. In those cases, it
12230 		 * is fine to expect to see reg->off.
12231 		 */
12232 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12233 			return;
12234 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12235 		    WARN_ON_ONCE(reg->off))
12236 			return;
12237 
12238 		if (is_null) {
12239 			reg->type = SCALAR_VALUE;
12240 			/* We don't need id and ref_obj_id from this point
12241 			 * onwards anymore, thus we should better reset it,
12242 			 * so that state pruning has chances to take effect.
12243 			 */
12244 			reg->id = 0;
12245 			reg->ref_obj_id = 0;
12246 
12247 			return;
12248 		}
12249 
12250 		mark_ptr_not_null_reg(reg);
12251 
12252 		if (!reg_may_point_to_spin_lock(reg)) {
12253 			/* For not-NULL ptr, reg->ref_obj_id will be reset
12254 			 * in release_reference().
12255 			 *
12256 			 * reg->id is still used by spin_lock ptr. Other
12257 			 * than spin_lock ptr type, reg->id can be reset.
12258 			 */
12259 			reg->id = 0;
12260 		}
12261 	}
12262 }
12263 
12264 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12265  * be folded together at some point.
12266  */
12267 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12268 				  bool is_null)
12269 {
12270 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12271 	struct bpf_reg_state *regs = state->regs, *reg;
12272 	u32 ref_obj_id = regs[regno].ref_obj_id;
12273 	u32 id = regs[regno].id;
12274 
12275 	if (ref_obj_id && ref_obj_id == id && is_null)
12276 		/* regs[regno] is in the " == NULL" branch.
12277 		 * No one could have freed the reference state before
12278 		 * doing the NULL check.
12279 		 */
12280 		WARN_ON_ONCE(release_reference_state(state, id));
12281 
12282 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12283 		mark_ptr_or_null_reg(state, reg, id, is_null);
12284 	}));
12285 }
12286 
12287 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12288 				   struct bpf_reg_state *dst_reg,
12289 				   struct bpf_reg_state *src_reg,
12290 				   struct bpf_verifier_state *this_branch,
12291 				   struct bpf_verifier_state *other_branch)
12292 {
12293 	if (BPF_SRC(insn->code) != BPF_X)
12294 		return false;
12295 
12296 	/* Pointers are always 64-bit. */
12297 	if (BPF_CLASS(insn->code) == BPF_JMP32)
12298 		return false;
12299 
12300 	switch (BPF_OP(insn->code)) {
12301 	case BPF_JGT:
12302 		if ((dst_reg->type == PTR_TO_PACKET &&
12303 		     src_reg->type == PTR_TO_PACKET_END) ||
12304 		    (dst_reg->type == PTR_TO_PACKET_META &&
12305 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12306 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12307 			find_good_pkt_pointers(this_branch, dst_reg,
12308 					       dst_reg->type, false);
12309 			mark_pkt_end(other_branch, insn->dst_reg, true);
12310 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12311 			    src_reg->type == PTR_TO_PACKET) ||
12312 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12313 			    src_reg->type == PTR_TO_PACKET_META)) {
12314 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
12315 			find_good_pkt_pointers(other_branch, src_reg,
12316 					       src_reg->type, true);
12317 			mark_pkt_end(this_branch, insn->src_reg, false);
12318 		} else {
12319 			return false;
12320 		}
12321 		break;
12322 	case BPF_JLT:
12323 		if ((dst_reg->type == PTR_TO_PACKET &&
12324 		     src_reg->type == PTR_TO_PACKET_END) ||
12325 		    (dst_reg->type == PTR_TO_PACKET_META &&
12326 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12327 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
12328 			find_good_pkt_pointers(other_branch, dst_reg,
12329 					       dst_reg->type, true);
12330 			mark_pkt_end(this_branch, insn->dst_reg, false);
12331 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12332 			    src_reg->type == PTR_TO_PACKET) ||
12333 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12334 			    src_reg->type == PTR_TO_PACKET_META)) {
12335 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
12336 			find_good_pkt_pointers(this_branch, src_reg,
12337 					       src_reg->type, false);
12338 			mark_pkt_end(other_branch, insn->src_reg, true);
12339 		} else {
12340 			return false;
12341 		}
12342 		break;
12343 	case BPF_JGE:
12344 		if ((dst_reg->type == PTR_TO_PACKET &&
12345 		     src_reg->type == PTR_TO_PACKET_END) ||
12346 		    (dst_reg->type == PTR_TO_PACKET_META &&
12347 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12348 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
12349 			find_good_pkt_pointers(this_branch, dst_reg,
12350 					       dst_reg->type, true);
12351 			mark_pkt_end(other_branch, insn->dst_reg, false);
12352 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12353 			    src_reg->type == PTR_TO_PACKET) ||
12354 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12355 			    src_reg->type == PTR_TO_PACKET_META)) {
12356 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
12357 			find_good_pkt_pointers(other_branch, src_reg,
12358 					       src_reg->type, false);
12359 			mark_pkt_end(this_branch, insn->src_reg, true);
12360 		} else {
12361 			return false;
12362 		}
12363 		break;
12364 	case BPF_JLE:
12365 		if ((dst_reg->type == PTR_TO_PACKET &&
12366 		     src_reg->type == PTR_TO_PACKET_END) ||
12367 		    (dst_reg->type == PTR_TO_PACKET_META &&
12368 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12369 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
12370 			find_good_pkt_pointers(other_branch, dst_reg,
12371 					       dst_reg->type, false);
12372 			mark_pkt_end(this_branch, insn->dst_reg, true);
12373 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12374 			    src_reg->type == PTR_TO_PACKET) ||
12375 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12376 			    src_reg->type == PTR_TO_PACKET_META)) {
12377 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
12378 			find_good_pkt_pointers(this_branch, src_reg,
12379 					       src_reg->type, true);
12380 			mark_pkt_end(other_branch, insn->src_reg, false);
12381 		} else {
12382 			return false;
12383 		}
12384 		break;
12385 	default:
12386 		return false;
12387 	}
12388 
12389 	return true;
12390 }
12391 
12392 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12393 			       struct bpf_reg_state *known_reg)
12394 {
12395 	struct bpf_func_state *state;
12396 	struct bpf_reg_state *reg;
12397 
12398 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12399 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12400 			copy_register_state(reg, known_reg);
12401 	}));
12402 }
12403 
12404 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12405 			     struct bpf_insn *insn, int *insn_idx)
12406 {
12407 	struct bpf_verifier_state *this_branch = env->cur_state;
12408 	struct bpf_verifier_state *other_branch;
12409 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12410 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12411 	struct bpf_reg_state *eq_branch_regs;
12412 	u8 opcode = BPF_OP(insn->code);
12413 	bool is_jmp32;
12414 	int pred = -1;
12415 	int err;
12416 
12417 	/* Only conditional jumps are expected to reach here. */
12418 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
12419 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12420 		return -EINVAL;
12421 	}
12422 
12423 	if (BPF_SRC(insn->code) == BPF_X) {
12424 		if (insn->imm != 0) {
12425 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12426 			return -EINVAL;
12427 		}
12428 
12429 		/* check src1 operand */
12430 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12431 		if (err)
12432 			return err;
12433 
12434 		if (is_pointer_value(env, insn->src_reg)) {
12435 			verbose(env, "R%d pointer comparison prohibited\n",
12436 				insn->src_reg);
12437 			return -EACCES;
12438 		}
12439 		src_reg = &regs[insn->src_reg];
12440 	} else {
12441 		if (insn->src_reg != BPF_REG_0) {
12442 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12443 			return -EINVAL;
12444 		}
12445 	}
12446 
12447 	/* check src2 operand */
12448 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12449 	if (err)
12450 		return err;
12451 
12452 	dst_reg = &regs[insn->dst_reg];
12453 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12454 
12455 	if (BPF_SRC(insn->code) == BPF_K) {
12456 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12457 	} else if (src_reg->type == SCALAR_VALUE &&
12458 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12459 		pred = is_branch_taken(dst_reg,
12460 				       tnum_subreg(src_reg->var_off).value,
12461 				       opcode,
12462 				       is_jmp32);
12463 	} else if (src_reg->type == SCALAR_VALUE &&
12464 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12465 		pred = is_branch_taken(dst_reg,
12466 				       src_reg->var_off.value,
12467 				       opcode,
12468 				       is_jmp32);
12469 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
12470 		   reg_is_pkt_pointer_any(src_reg) &&
12471 		   !is_jmp32) {
12472 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12473 	}
12474 
12475 	if (pred >= 0) {
12476 		/* If we get here with a dst_reg pointer type it is because
12477 		 * above is_branch_taken() special cased the 0 comparison.
12478 		 */
12479 		if (!__is_pointer_value(false, dst_reg))
12480 			err = mark_chain_precision(env, insn->dst_reg);
12481 		if (BPF_SRC(insn->code) == BPF_X && !err &&
12482 		    !__is_pointer_value(false, src_reg))
12483 			err = mark_chain_precision(env, insn->src_reg);
12484 		if (err)
12485 			return err;
12486 	}
12487 
12488 	if (pred == 1) {
12489 		/* Only follow the goto, ignore fall-through. If needed, push
12490 		 * the fall-through branch for simulation under speculative
12491 		 * execution.
12492 		 */
12493 		if (!env->bypass_spec_v1 &&
12494 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
12495 					       *insn_idx))
12496 			return -EFAULT;
12497 		*insn_idx += insn->off;
12498 		return 0;
12499 	} else if (pred == 0) {
12500 		/* Only follow the fall-through branch, since that's where the
12501 		 * program will go. If needed, push the goto branch for
12502 		 * simulation under speculative execution.
12503 		 */
12504 		if (!env->bypass_spec_v1 &&
12505 		    !sanitize_speculative_path(env, insn,
12506 					       *insn_idx + insn->off + 1,
12507 					       *insn_idx))
12508 			return -EFAULT;
12509 		return 0;
12510 	}
12511 
12512 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12513 				  false);
12514 	if (!other_branch)
12515 		return -EFAULT;
12516 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12517 
12518 	/* detect if we are comparing against a constant value so we can adjust
12519 	 * our min/max values for our dst register.
12520 	 * this is only legit if both are scalars (or pointers to the same
12521 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12522 	 * because otherwise the different base pointers mean the offsets aren't
12523 	 * comparable.
12524 	 */
12525 	if (BPF_SRC(insn->code) == BPF_X) {
12526 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12527 
12528 		if (dst_reg->type == SCALAR_VALUE &&
12529 		    src_reg->type == SCALAR_VALUE) {
12530 			if (tnum_is_const(src_reg->var_off) ||
12531 			    (is_jmp32 &&
12532 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
12533 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
12534 						dst_reg,
12535 						src_reg->var_off.value,
12536 						tnum_subreg(src_reg->var_off).value,
12537 						opcode, is_jmp32);
12538 			else if (tnum_is_const(dst_reg->var_off) ||
12539 				 (is_jmp32 &&
12540 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
12541 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12542 						    src_reg,
12543 						    dst_reg->var_off.value,
12544 						    tnum_subreg(dst_reg->var_off).value,
12545 						    opcode, is_jmp32);
12546 			else if (!is_jmp32 &&
12547 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
12548 				/* Comparing for equality, we can combine knowledge */
12549 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
12550 						    &other_branch_regs[insn->dst_reg],
12551 						    src_reg, dst_reg, opcode);
12552 			if (src_reg->id &&
12553 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12554 				find_equal_scalars(this_branch, src_reg);
12555 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12556 			}
12557 
12558 		}
12559 	} else if (dst_reg->type == SCALAR_VALUE) {
12560 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
12561 					dst_reg, insn->imm, (u32)insn->imm,
12562 					opcode, is_jmp32);
12563 	}
12564 
12565 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12566 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12567 		find_equal_scalars(this_branch, dst_reg);
12568 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12569 	}
12570 
12571 	/* if one pointer register is compared to another pointer
12572 	 * register check if PTR_MAYBE_NULL could be lifted.
12573 	 * E.g. register A - maybe null
12574 	 *      register B - not null
12575 	 * for JNE A, B, ... - A is not null in the false branch;
12576 	 * for JEQ A, B, ... - A is not null in the true branch.
12577 	 *
12578 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
12579 	 * not need to be null checked by the BPF program, i.e.,
12580 	 * could be null even without PTR_MAYBE_NULL marking, so
12581 	 * only propagate nullness when neither reg is that type.
12582 	 */
12583 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12584 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12585 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12586 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
12587 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12588 		eq_branch_regs = NULL;
12589 		switch (opcode) {
12590 		case BPF_JEQ:
12591 			eq_branch_regs = other_branch_regs;
12592 			break;
12593 		case BPF_JNE:
12594 			eq_branch_regs = regs;
12595 			break;
12596 		default:
12597 			/* do nothing */
12598 			break;
12599 		}
12600 		if (eq_branch_regs) {
12601 			if (type_may_be_null(src_reg->type))
12602 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12603 			else
12604 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12605 		}
12606 	}
12607 
12608 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12609 	 * NOTE: these optimizations below are related with pointer comparison
12610 	 *       which will never be JMP32.
12611 	 */
12612 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12613 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12614 	    type_may_be_null(dst_reg->type)) {
12615 		/* Mark all identical registers in each branch as either
12616 		 * safe or unknown depending R == 0 or R != 0 conditional.
12617 		 */
12618 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12619 				      opcode == BPF_JNE);
12620 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12621 				      opcode == BPF_JEQ);
12622 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12623 					   this_branch, other_branch) &&
12624 		   is_pointer_value(env, insn->dst_reg)) {
12625 		verbose(env, "R%d pointer comparison prohibited\n",
12626 			insn->dst_reg);
12627 		return -EACCES;
12628 	}
12629 	if (env->log.level & BPF_LOG_LEVEL)
12630 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
12631 	return 0;
12632 }
12633 
12634 /* verify BPF_LD_IMM64 instruction */
12635 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12636 {
12637 	struct bpf_insn_aux_data *aux = cur_aux(env);
12638 	struct bpf_reg_state *regs = cur_regs(env);
12639 	struct bpf_reg_state *dst_reg;
12640 	struct bpf_map *map;
12641 	int err;
12642 
12643 	if (BPF_SIZE(insn->code) != BPF_DW) {
12644 		verbose(env, "invalid BPF_LD_IMM insn\n");
12645 		return -EINVAL;
12646 	}
12647 	if (insn->off != 0) {
12648 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12649 		return -EINVAL;
12650 	}
12651 
12652 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
12653 	if (err)
12654 		return err;
12655 
12656 	dst_reg = &regs[insn->dst_reg];
12657 	if (insn->src_reg == 0) {
12658 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12659 
12660 		dst_reg->type = SCALAR_VALUE;
12661 		__mark_reg_known(&regs[insn->dst_reg], imm);
12662 		return 0;
12663 	}
12664 
12665 	/* All special src_reg cases are listed below. From this point onwards
12666 	 * we either succeed and assign a corresponding dst_reg->type after
12667 	 * zeroing the offset, or fail and reject the program.
12668 	 */
12669 	mark_reg_known_zero(env, regs, insn->dst_reg);
12670 
12671 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
12672 		dst_reg->type = aux->btf_var.reg_type;
12673 		switch (base_type(dst_reg->type)) {
12674 		case PTR_TO_MEM:
12675 			dst_reg->mem_size = aux->btf_var.mem_size;
12676 			break;
12677 		case PTR_TO_BTF_ID:
12678 			dst_reg->btf = aux->btf_var.btf;
12679 			dst_reg->btf_id = aux->btf_var.btf_id;
12680 			break;
12681 		default:
12682 			verbose(env, "bpf verifier is misconfigured\n");
12683 			return -EFAULT;
12684 		}
12685 		return 0;
12686 	}
12687 
12688 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
12689 		struct bpf_prog_aux *aux = env->prog->aux;
12690 		u32 subprogno = find_subprog(env,
12691 					     env->insn_idx + insn->imm + 1);
12692 
12693 		if (!aux->func_info) {
12694 			verbose(env, "missing btf func_info\n");
12695 			return -EINVAL;
12696 		}
12697 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
12698 			verbose(env, "callback function not static\n");
12699 			return -EINVAL;
12700 		}
12701 
12702 		dst_reg->type = PTR_TO_FUNC;
12703 		dst_reg->subprogno = subprogno;
12704 		return 0;
12705 	}
12706 
12707 	map = env->used_maps[aux->map_index];
12708 	dst_reg->map_ptr = map;
12709 
12710 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
12711 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
12712 		dst_reg->type = PTR_TO_MAP_VALUE;
12713 		dst_reg->off = aux->map_off;
12714 		WARN_ON_ONCE(map->max_entries != 1);
12715 		/* We want reg->id to be same (0) as map_value is not distinct */
12716 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
12717 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
12718 		dst_reg->type = CONST_PTR_TO_MAP;
12719 	} else {
12720 		verbose(env, "bpf verifier is misconfigured\n");
12721 		return -EINVAL;
12722 	}
12723 
12724 	return 0;
12725 }
12726 
12727 static bool may_access_skb(enum bpf_prog_type type)
12728 {
12729 	switch (type) {
12730 	case BPF_PROG_TYPE_SOCKET_FILTER:
12731 	case BPF_PROG_TYPE_SCHED_CLS:
12732 	case BPF_PROG_TYPE_SCHED_ACT:
12733 		return true;
12734 	default:
12735 		return false;
12736 	}
12737 }
12738 
12739 /* verify safety of LD_ABS|LD_IND instructions:
12740  * - they can only appear in the programs where ctx == skb
12741  * - since they are wrappers of function calls, they scratch R1-R5 registers,
12742  *   preserve R6-R9, and store return value into R0
12743  *
12744  * Implicit input:
12745  *   ctx == skb == R6 == CTX
12746  *
12747  * Explicit input:
12748  *   SRC == any register
12749  *   IMM == 32-bit immediate
12750  *
12751  * Output:
12752  *   R0 - 8/16/32-bit skb data converted to cpu endianness
12753  */
12754 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12755 {
12756 	struct bpf_reg_state *regs = cur_regs(env);
12757 	static const int ctx_reg = BPF_REG_6;
12758 	u8 mode = BPF_MODE(insn->code);
12759 	int i, err;
12760 
12761 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12762 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12763 		return -EINVAL;
12764 	}
12765 
12766 	if (!env->ops->gen_ld_abs) {
12767 		verbose(env, "bpf verifier is misconfigured\n");
12768 		return -EINVAL;
12769 	}
12770 
12771 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12772 	    BPF_SIZE(insn->code) == BPF_DW ||
12773 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12774 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12775 		return -EINVAL;
12776 	}
12777 
12778 	/* check whether implicit source operand (register R6) is readable */
12779 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12780 	if (err)
12781 		return err;
12782 
12783 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12784 	 * gen_ld_abs() may terminate the program at runtime, leading to
12785 	 * reference leak.
12786 	 */
12787 	err = check_reference_leak(env);
12788 	if (err) {
12789 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12790 		return err;
12791 	}
12792 
12793 	if (env->cur_state->active_lock.ptr) {
12794 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12795 		return -EINVAL;
12796 	}
12797 
12798 	if (env->cur_state->active_rcu_lock) {
12799 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12800 		return -EINVAL;
12801 	}
12802 
12803 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12804 		verbose(env,
12805 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12806 		return -EINVAL;
12807 	}
12808 
12809 	if (mode == BPF_IND) {
12810 		/* check explicit source operand */
12811 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12812 		if (err)
12813 			return err;
12814 	}
12815 
12816 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12817 	if (err < 0)
12818 		return err;
12819 
12820 	/* reset caller saved regs to unreadable */
12821 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12822 		mark_reg_not_init(env, regs, caller_saved[i]);
12823 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12824 	}
12825 
12826 	/* mark destination R0 register as readable, since it contains
12827 	 * the value fetched from the packet.
12828 	 * Already marked as written above.
12829 	 */
12830 	mark_reg_unknown(env, regs, BPF_REG_0);
12831 	/* ld_abs load up to 32-bit skb data. */
12832 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12833 	return 0;
12834 }
12835 
12836 static int check_return_code(struct bpf_verifier_env *env)
12837 {
12838 	struct tnum enforce_attach_type_range = tnum_unknown;
12839 	const struct bpf_prog *prog = env->prog;
12840 	struct bpf_reg_state *reg;
12841 	struct tnum range = tnum_range(0, 1);
12842 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12843 	int err;
12844 	struct bpf_func_state *frame = env->cur_state->frame[0];
12845 	const bool is_subprog = frame->subprogno;
12846 
12847 	/* LSM and struct_ops func-ptr's return type could be "void" */
12848 	if (!is_subprog) {
12849 		switch (prog_type) {
12850 		case BPF_PROG_TYPE_LSM:
12851 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12852 				/* See below, can be 0 or 0-1 depending on hook. */
12853 				break;
12854 			fallthrough;
12855 		case BPF_PROG_TYPE_STRUCT_OPS:
12856 			if (!prog->aux->attach_func_proto->type)
12857 				return 0;
12858 			break;
12859 		default:
12860 			break;
12861 		}
12862 	}
12863 
12864 	/* eBPF calling convention is such that R0 is used
12865 	 * to return the value from eBPF program.
12866 	 * Make sure that it's readable at this time
12867 	 * of bpf_exit, which means that program wrote
12868 	 * something into it earlier
12869 	 */
12870 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12871 	if (err)
12872 		return err;
12873 
12874 	if (is_pointer_value(env, BPF_REG_0)) {
12875 		verbose(env, "R0 leaks addr as return value\n");
12876 		return -EACCES;
12877 	}
12878 
12879 	reg = cur_regs(env) + BPF_REG_0;
12880 
12881 	if (frame->in_async_callback_fn) {
12882 		/* enforce return zero from async callbacks like timer */
12883 		if (reg->type != SCALAR_VALUE) {
12884 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12885 				reg_type_str(env, reg->type));
12886 			return -EINVAL;
12887 		}
12888 
12889 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12890 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12891 			return -EINVAL;
12892 		}
12893 		return 0;
12894 	}
12895 
12896 	if (is_subprog) {
12897 		if (reg->type != SCALAR_VALUE) {
12898 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12899 				reg_type_str(env, reg->type));
12900 			return -EINVAL;
12901 		}
12902 		return 0;
12903 	}
12904 
12905 	switch (prog_type) {
12906 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12907 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12908 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12909 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12910 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12911 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12912 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12913 			range = tnum_range(1, 1);
12914 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12915 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12916 			range = tnum_range(0, 3);
12917 		break;
12918 	case BPF_PROG_TYPE_CGROUP_SKB:
12919 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12920 			range = tnum_range(0, 3);
12921 			enforce_attach_type_range = tnum_range(2, 3);
12922 		}
12923 		break;
12924 	case BPF_PROG_TYPE_CGROUP_SOCK:
12925 	case BPF_PROG_TYPE_SOCK_OPS:
12926 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12927 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12928 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12929 		break;
12930 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12931 		if (!env->prog->aux->attach_btf_id)
12932 			return 0;
12933 		range = tnum_const(0);
12934 		break;
12935 	case BPF_PROG_TYPE_TRACING:
12936 		switch (env->prog->expected_attach_type) {
12937 		case BPF_TRACE_FENTRY:
12938 		case BPF_TRACE_FEXIT:
12939 			range = tnum_const(0);
12940 			break;
12941 		case BPF_TRACE_RAW_TP:
12942 		case BPF_MODIFY_RETURN:
12943 			return 0;
12944 		case BPF_TRACE_ITER:
12945 			break;
12946 		default:
12947 			return -ENOTSUPP;
12948 		}
12949 		break;
12950 	case BPF_PROG_TYPE_SK_LOOKUP:
12951 		range = tnum_range(SK_DROP, SK_PASS);
12952 		break;
12953 
12954 	case BPF_PROG_TYPE_LSM:
12955 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12956 			/* Regular BPF_PROG_TYPE_LSM programs can return
12957 			 * any value.
12958 			 */
12959 			return 0;
12960 		}
12961 		if (!env->prog->aux->attach_func_proto->type) {
12962 			/* Make sure programs that attach to void
12963 			 * hooks don't try to modify return value.
12964 			 */
12965 			range = tnum_range(1, 1);
12966 		}
12967 		break;
12968 
12969 	case BPF_PROG_TYPE_EXT:
12970 		/* freplace program can return anything as its return value
12971 		 * depends on the to-be-replaced kernel func or bpf program.
12972 		 */
12973 	default:
12974 		return 0;
12975 	}
12976 
12977 	if (reg->type != SCALAR_VALUE) {
12978 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12979 			reg_type_str(env, reg->type));
12980 		return -EINVAL;
12981 	}
12982 
12983 	if (!tnum_in(range, reg->var_off)) {
12984 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12985 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12986 		    prog_type == BPF_PROG_TYPE_LSM &&
12987 		    !prog->aux->attach_func_proto->type)
12988 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12989 		return -EINVAL;
12990 	}
12991 
12992 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12993 	    tnum_in(enforce_attach_type_range, reg->var_off))
12994 		env->prog->enforce_expected_attach_type = 1;
12995 	return 0;
12996 }
12997 
12998 /* non-recursive DFS pseudo code
12999  * 1  procedure DFS-iterative(G,v):
13000  * 2      label v as discovered
13001  * 3      let S be a stack
13002  * 4      S.push(v)
13003  * 5      while S is not empty
13004  * 6            t <- S.peek()
13005  * 7            if t is what we're looking for:
13006  * 8                return t
13007  * 9            for all edges e in G.adjacentEdges(t) do
13008  * 10               if edge e is already labelled
13009  * 11                   continue with the next edge
13010  * 12               w <- G.adjacentVertex(t,e)
13011  * 13               if vertex w is not discovered and not explored
13012  * 14                   label e as tree-edge
13013  * 15                   label w as discovered
13014  * 16                   S.push(w)
13015  * 17                   continue at 5
13016  * 18               else if vertex w is discovered
13017  * 19                   label e as back-edge
13018  * 20               else
13019  * 21                   // vertex w is explored
13020  * 22                   label e as forward- or cross-edge
13021  * 23           label t as explored
13022  * 24           S.pop()
13023  *
13024  * convention:
13025  * 0x10 - discovered
13026  * 0x11 - discovered and fall-through edge labelled
13027  * 0x12 - discovered and fall-through and branch edges labelled
13028  * 0x20 - explored
13029  */
13030 
13031 enum {
13032 	DISCOVERED = 0x10,
13033 	EXPLORED = 0x20,
13034 	FALLTHROUGH = 1,
13035 	BRANCH = 2,
13036 };
13037 
13038 static u32 state_htab_size(struct bpf_verifier_env *env)
13039 {
13040 	return env->prog->len;
13041 }
13042 
13043 static struct bpf_verifier_state_list **explored_state(
13044 					struct bpf_verifier_env *env,
13045 					int idx)
13046 {
13047 	struct bpf_verifier_state *cur = env->cur_state;
13048 	struct bpf_func_state *state = cur->frame[cur->curframe];
13049 
13050 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13051 }
13052 
13053 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13054 {
13055 	env->insn_aux_data[idx].prune_point = true;
13056 }
13057 
13058 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13059 {
13060 	return env->insn_aux_data[insn_idx].prune_point;
13061 }
13062 
13063 enum {
13064 	DONE_EXPLORING = 0,
13065 	KEEP_EXPLORING = 1,
13066 };
13067 
13068 /* t, w, e - match pseudo-code above:
13069  * t - index of current instruction
13070  * w - next instruction
13071  * e - edge
13072  */
13073 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13074 		     bool loop_ok)
13075 {
13076 	int *insn_stack = env->cfg.insn_stack;
13077 	int *insn_state = env->cfg.insn_state;
13078 
13079 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13080 		return DONE_EXPLORING;
13081 
13082 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13083 		return DONE_EXPLORING;
13084 
13085 	if (w < 0 || w >= env->prog->len) {
13086 		verbose_linfo(env, t, "%d: ", t);
13087 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
13088 		return -EINVAL;
13089 	}
13090 
13091 	if (e == BRANCH) {
13092 		/* mark branch target for state pruning */
13093 		mark_prune_point(env, w);
13094 		mark_jmp_point(env, w);
13095 	}
13096 
13097 	if (insn_state[w] == 0) {
13098 		/* tree-edge */
13099 		insn_state[t] = DISCOVERED | e;
13100 		insn_state[w] = DISCOVERED;
13101 		if (env->cfg.cur_stack >= env->prog->len)
13102 			return -E2BIG;
13103 		insn_stack[env->cfg.cur_stack++] = w;
13104 		return KEEP_EXPLORING;
13105 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13106 		if (loop_ok && env->bpf_capable)
13107 			return DONE_EXPLORING;
13108 		verbose_linfo(env, t, "%d: ", t);
13109 		verbose_linfo(env, w, "%d: ", w);
13110 		verbose(env, "back-edge from insn %d to %d\n", t, w);
13111 		return -EINVAL;
13112 	} else if (insn_state[w] == EXPLORED) {
13113 		/* forward- or cross-edge */
13114 		insn_state[t] = DISCOVERED | e;
13115 	} else {
13116 		verbose(env, "insn state internal bug\n");
13117 		return -EFAULT;
13118 	}
13119 	return DONE_EXPLORING;
13120 }
13121 
13122 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13123 				struct bpf_verifier_env *env,
13124 				bool visit_callee)
13125 {
13126 	int ret;
13127 
13128 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13129 	if (ret)
13130 		return ret;
13131 
13132 	mark_prune_point(env, t + 1);
13133 	/* when we exit from subprog, we need to record non-linear history */
13134 	mark_jmp_point(env, t + 1);
13135 
13136 	if (visit_callee) {
13137 		mark_prune_point(env, t);
13138 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13139 				/* It's ok to allow recursion from CFG point of
13140 				 * view. __check_func_call() will do the actual
13141 				 * check.
13142 				 */
13143 				bpf_pseudo_func(insns + t));
13144 	}
13145 	return ret;
13146 }
13147 
13148 /* Visits the instruction at index t and returns one of the following:
13149  *  < 0 - an error occurred
13150  *  DONE_EXPLORING - the instruction was fully explored
13151  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
13152  */
13153 static int visit_insn(int t, struct bpf_verifier_env *env)
13154 {
13155 	struct bpf_insn *insns = env->prog->insnsi;
13156 	int ret;
13157 
13158 	if (bpf_pseudo_func(insns + t))
13159 		return visit_func_call_insn(t, insns, env, true);
13160 
13161 	/* All non-branch instructions have a single fall-through edge. */
13162 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
13163 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
13164 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
13165 
13166 	switch (BPF_OP(insns[t].code)) {
13167 	case BPF_EXIT:
13168 		return DONE_EXPLORING;
13169 
13170 	case BPF_CALL:
13171 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
13172 			/* Mark this call insn as a prune point to trigger
13173 			 * is_state_visited() check before call itself is
13174 			 * processed by __check_func_call(). Otherwise new
13175 			 * async state will be pushed for further exploration.
13176 			 */
13177 			mark_prune_point(env, t);
13178 		return visit_func_call_insn(t, insns, env,
13179 					    insns[t].src_reg == BPF_PSEUDO_CALL);
13180 
13181 	case BPF_JA:
13182 		if (BPF_SRC(insns[t].code) != BPF_K)
13183 			return -EINVAL;
13184 
13185 		/* unconditional jump with single edge */
13186 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
13187 				true);
13188 		if (ret)
13189 			return ret;
13190 
13191 		mark_prune_point(env, t + insns[t].off + 1);
13192 		mark_jmp_point(env, t + insns[t].off + 1);
13193 
13194 		return ret;
13195 
13196 	default:
13197 		/* conditional jump with two edges */
13198 		mark_prune_point(env, t);
13199 
13200 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13201 		if (ret)
13202 			return ret;
13203 
13204 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
13205 	}
13206 }
13207 
13208 /* non-recursive depth-first-search to detect loops in BPF program
13209  * loop == back-edge in directed graph
13210  */
13211 static int check_cfg(struct bpf_verifier_env *env)
13212 {
13213 	int insn_cnt = env->prog->len;
13214 	int *insn_stack, *insn_state;
13215 	int ret = 0;
13216 	int i;
13217 
13218 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13219 	if (!insn_state)
13220 		return -ENOMEM;
13221 
13222 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13223 	if (!insn_stack) {
13224 		kvfree(insn_state);
13225 		return -ENOMEM;
13226 	}
13227 
13228 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13229 	insn_stack[0] = 0; /* 0 is the first instruction */
13230 	env->cfg.cur_stack = 1;
13231 
13232 	while (env->cfg.cur_stack > 0) {
13233 		int t = insn_stack[env->cfg.cur_stack - 1];
13234 
13235 		ret = visit_insn(t, env);
13236 		switch (ret) {
13237 		case DONE_EXPLORING:
13238 			insn_state[t] = EXPLORED;
13239 			env->cfg.cur_stack--;
13240 			break;
13241 		case KEEP_EXPLORING:
13242 			break;
13243 		default:
13244 			if (ret > 0) {
13245 				verbose(env, "visit_insn internal bug\n");
13246 				ret = -EFAULT;
13247 			}
13248 			goto err_free;
13249 		}
13250 	}
13251 
13252 	if (env->cfg.cur_stack < 0) {
13253 		verbose(env, "pop stack internal bug\n");
13254 		ret = -EFAULT;
13255 		goto err_free;
13256 	}
13257 
13258 	for (i = 0; i < insn_cnt; i++) {
13259 		if (insn_state[i] != EXPLORED) {
13260 			verbose(env, "unreachable insn %d\n", i);
13261 			ret = -EINVAL;
13262 			goto err_free;
13263 		}
13264 	}
13265 	ret = 0; /* cfg looks good */
13266 
13267 err_free:
13268 	kvfree(insn_state);
13269 	kvfree(insn_stack);
13270 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
13271 	return ret;
13272 }
13273 
13274 static int check_abnormal_return(struct bpf_verifier_env *env)
13275 {
13276 	int i;
13277 
13278 	for (i = 1; i < env->subprog_cnt; i++) {
13279 		if (env->subprog_info[i].has_ld_abs) {
13280 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13281 			return -EINVAL;
13282 		}
13283 		if (env->subprog_info[i].has_tail_call) {
13284 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13285 			return -EINVAL;
13286 		}
13287 	}
13288 	return 0;
13289 }
13290 
13291 /* The minimum supported BTF func info size */
13292 #define MIN_BPF_FUNCINFO_SIZE	8
13293 #define MAX_FUNCINFO_REC_SIZE	252
13294 
13295 static int check_btf_func(struct bpf_verifier_env *env,
13296 			  const union bpf_attr *attr,
13297 			  bpfptr_t uattr)
13298 {
13299 	const struct btf_type *type, *func_proto, *ret_type;
13300 	u32 i, nfuncs, urec_size, min_size;
13301 	u32 krec_size = sizeof(struct bpf_func_info);
13302 	struct bpf_func_info *krecord;
13303 	struct bpf_func_info_aux *info_aux = NULL;
13304 	struct bpf_prog *prog;
13305 	const struct btf *btf;
13306 	bpfptr_t urecord;
13307 	u32 prev_offset = 0;
13308 	bool scalar_return;
13309 	int ret = -ENOMEM;
13310 
13311 	nfuncs = attr->func_info_cnt;
13312 	if (!nfuncs) {
13313 		if (check_abnormal_return(env))
13314 			return -EINVAL;
13315 		return 0;
13316 	}
13317 
13318 	if (nfuncs != env->subprog_cnt) {
13319 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13320 		return -EINVAL;
13321 	}
13322 
13323 	urec_size = attr->func_info_rec_size;
13324 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13325 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
13326 	    urec_size % sizeof(u32)) {
13327 		verbose(env, "invalid func info rec size %u\n", urec_size);
13328 		return -EINVAL;
13329 	}
13330 
13331 	prog = env->prog;
13332 	btf = prog->aux->btf;
13333 
13334 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13335 	min_size = min_t(u32, krec_size, urec_size);
13336 
13337 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13338 	if (!krecord)
13339 		return -ENOMEM;
13340 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13341 	if (!info_aux)
13342 		goto err_free;
13343 
13344 	for (i = 0; i < nfuncs; i++) {
13345 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13346 		if (ret) {
13347 			if (ret == -E2BIG) {
13348 				verbose(env, "nonzero tailing record in func info");
13349 				/* set the size kernel expects so loader can zero
13350 				 * out the rest of the record.
13351 				 */
13352 				if (copy_to_bpfptr_offset(uattr,
13353 							  offsetof(union bpf_attr, func_info_rec_size),
13354 							  &min_size, sizeof(min_size)))
13355 					ret = -EFAULT;
13356 			}
13357 			goto err_free;
13358 		}
13359 
13360 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13361 			ret = -EFAULT;
13362 			goto err_free;
13363 		}
13364 
13365 		/* check insn_off */
13366 		ret = -EINVAL;
13367 		if (i == 0) {
13368 			if (krecord[i].insn_off) {
13369 				verbose(env,
13370 					"nonzero insn_off %u for the first func info record",
13371 					krecord[i].insn_off);
13372 				goto err_free;
13373 			}
13374 		} else if (krecord[i].insn_off <= prev_offset) {
13375 			verbose(env,
13376 				"same or smaller insn offset (%u) than previous func info record (%u)",
13377 				krecord[i].insn_off, prev_offset);
13378 			goto err_free;
13379 		}
13380 
13381 		if (env->subprog_info[i].start != krecord[i].insn_off) {
13382 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13383 			goto err_free;
13384 		}
13385 
13386 		/* check type_id */
13387 		type = btf_type_by_id(btf, krecord[i].type_id);
13388 		if (!type || !btf_type_is_func(type)) {
13389 			verbose(env, "invalid type id %d in func info",
13390 				krecord[i].type_id);
13391 			goto err_free;
13392 		}
13393 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13394 
13395 		func_proto = btf_type_by_id(btf, type->type);
13396 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13397 			/* btf_func_check() already verified it during BTF load */
13398 			goto err_free;
13399 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13400 		scalar_return =
13401 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13402 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13403 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13404 			goto err_free;
13405 		}
13406 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13407 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13408 			goto err_free;
13409 		}
13410 
13411 		prev_offset = krecord[i].insn_off;
13412 		bpfptr_add(&urecord, urec_size);
13413 	}
13414 
13415 	prog->aux->func_info = krecord;
13416 	prog->aux->func_info_cnt = nfuncs;
13417 	prog->aux->func_info_aux = info_aux;
13418 	return 0;
13419 
13420 err_free:
13421 	kvfree(krecord);
13422 	kfree(info_aux);
13423 	return ret;
13424 }
13425 
13426 static void adjust_btf_func(struct bpf_verifier_env *env)
13427 {
13428 	struct bpf_prog_aux *aux = env->prog->aux;
13429 	int i;
13430 
13431 	if (!aux->func_info)
13432 		return;
13433 
13434 	for (i = 0; i < env->subprog_cnt; i++)
13435 		aux->func_info[i].insn_off = env->subprog_info[i].start;
13436 }
13437 
13438 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
13439 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
13440 
13441 static int check_btf_line(struct bpf_verifier_env *env,
13442 			  const union bpf_attr *attr,
13443 			  bpfptr_t uattr)
13444 {
13445 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13446 	struct bpf_subprog_info *sub;
13447 	struct bpf_line_info *linfo;
13448 	struct bpf_prog *prog;
13449 	const struct btf *btf;
13450 	bpfptr_t ulinfo;
13451 	int err;
13452 
13453 	nr_linfo = attr->line_info_cnt;
13454 	if (!nr_linfo)
13455 		return 0;
13456 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13457 		return -EINVAL;
13458 
13459 	rec_size = attr->line_info_rec_size;
13460 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13461 	    rec_size > MAX_LINEINFO_REC_SIZE ||
13462 	    rec_size & (sizeof(u32) - 1))
13463 		return -EINVAL;
13464 
13465 	/* Need to zero it in case the userspace may
13466 	 * pass in a smaller bpf_line_info object.
13467 	 */
13468 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13469 			 GFP_KERNEL | __GFP_NOWARN);
13470 	if (!linfo)
13471 		return -ENOMEM;
13472 
13473 	prog = env->prog;
13474 	btf = prog->aux->btf;
13475 
13476 	s = 0;
13477 	sub = env->subprog_info;
13478 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13479 	expected_size = sizeof(struct bpf_line_info);
13480 	ncopy = min_t(u32, expected_size, rec_size);
13481 	for (i = 0; i < nr_linfo; i++) {
13482 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13483 		if (err) {
13484 			if (err == -E2BIG) {
13485 				verbose(env, "nonzero tailing record in line_info");
13486 				if (copy_to_bpfptr_offset(uattr,
13487 							  offsetof(union bpf_attr, line_info_rec_size),
13488 							  &expected_size, sizeof(expected_size)))
13489 					err = -EFAULT;
13490 			}
13491 			goto err_free;
13492 		}
13493 
13494 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13495 			err = -EFAULT;
13496 			goto err_free;
13497 		}
13498 
13499 		/*
13500 		 * Check insn_off to ensure
13501 		 * 1) strictly increasing AND
13502 		 * 2) bounded by prog->len
13503 		 *
13504 		 * The linfo[0].insn_off == 0 check logically falls into
13505 		 * the later "missing bpf_line_info for func..." case
13506 		 * because the first linfo[0].insn_off must be the
13507 		 * first sub also and the first sub must have
13508 		 * subprog_info[0].start == 0.
13509 		 */
13510 		if ((i && linfo[i].insn_off <= prev_offset) ||
13511 		    linfo[i].insn_off >= prog->len) {
13512 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13513 				i, linfo[i].insn_off, prev_offset,
13514 				prog->len);
13515 			err = -EINVAL;
13516 			goto err_free;
13517 		}
13518 
13519 		if (!prog->insnsi[linfo[i].insn_off].code) {
13520 			verbose(env,
13521 				"Invalid insn code at line_info[%u].insn_off\n",
13522 				i);
13523 			err = -EINVAL;
13524 			goto err_free;
13525 		}
13526 
13527 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13528 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13529 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13530 			err = -EINVAL;
13531 			goto err_free;
13532 		}
13533 
13534 		if (s != env->subprog_cnt) {
13535 			if (linfo[i].insn_off == sub[s].start) {
13536 				sub[s].linfo_idx = i;
13537 				s++;
13538 			} else if (sub[s].start < linfo[i].insn_off) {
13539 				verbose(env, "missing bpf_line_info for func#%u\n", s);
13540 				err = -EINVAL;
13541 				goto err_free;
13542 			}
13543 		}
13544 
13545 		prev_offset = linfo[i].insn_off;
13546 		bpfptr_add(&ulinfo, rec_size);
13547 	}
13548 
13549 	if (s != env->subprog_cnt) {
13550 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13551 			env->subprog_cnt - s, s);
13552 		err = -EINVAL;
13553 		goto err_free;
13554 	}
13555 
13556 	prog->aux->linfo = linfo;
13557 	prog->aux->nr_linfo = nr_linfo;
13558 
13559 	return 0;
13560 
13561 err_free:
13562 	kvfree(linfo);
13563 	return err;
13564 }
13565 
13566 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
13567 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
13568 
13569 static int check_core_relo(struct bpf_verifier_env *env,
13570 			   const union bpf_attr *attr,
13571 			   bpfptr_t uattr)
13572 {
13573 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13574 	struct bpf_core_relo core_relo = {};
13575 	struct bpf_prog *prog = env->prog;
13576 	const struct btf *btf = prog->aux->btf;
13577 	struct bpf_core_ctx ctx = {
13578 		.log = &env->log,
13579 		.btf = btf,
13580 	};
13581 	bpfptr_t u_core_relo;
13582 	int err;
13583 
13584 	nr_core_relo = attr->core_relo_cnt;
13585 	if (!nr_core_relo)
13586 		return 0;
13587 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13588 		return -EINVAL;
13589 
13590 	rec_size = attr->core_relo_rec_size;
13591 	if (rec_size < MIN_CORE_RELO_SIZE ||
13592 	    rec_size > MAX_CORE_RELO_SIZE ||
13593 	    rec_size % sizeof(u32))
13594 		return -EINVAL;
13595 
13596 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13597 	expected_size = sizeof(struct bpf_core_relo);
13598 	ncopy = min_t(u32, expected_size, rec_size);
13599 
13600 	/* Unlike func_info and line_info, copy and apply each CO-RE
13601 	 * relocation record one at a time.
13602 	 */
13603 	for (i = 0; i < nr_core_relo; i++) {
13604 		/* future proofing when sizeof(bpf_core_relo) changes */
13605 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13606 		if (err) {
13607 			if (err == -E2BIG) {
13608 				verbose(env, "nonzero tailing record in core_relo");
13609 				if (copy_to_bpfptr_offset(uattr,
13610 							  offsetof(union bpf_attr, core_relo_rec_size),
13611 							  &expected_size, sizeof(expected_size)))
13612 					err = -EFAULT;
13613 			}
13614 			break;
13615 		}
13616 
13617 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13618 			err = -EFAULT;
13619 			break;
13620 		}
13621 
13622 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13623 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13624 				i, core_relo.insn_off, prog->len);
13625 			err = -EINVAL;
13626 			break;
13627 		}
13628 
13629 		err = bpf_core_apply(&ctx, &core_relo, i,
13630 				     &prog->insnsi[core_relo.insn_off / 8]);
13631 		if (err)
13632 			break;
13633 		bpfptr_add(&u_core_relo, rec_size);
13634 	}
13635 	return err;
13636 }
13637 
13638 static int check_btf_info(struct bpf_verifier_env *env,
13639 			  const union bpf_attr *attr,
13640 			  bpfptr_t uattr)
13641 {
13642 	struct btf *btf;
13643 	int err;
13644 
13645 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
13646 		if (check_abnormal_return(env))
13647 			return -EINVAL;
13648 		return 0;
13649 	}
13650 
13651 	btf = btf_get_by_fd(attr->prog_btf_fd);
13652 	if (IS_ERR(btf))
13653 		return PTR_ERR(btf);
13654 	if (btf_is_kernel(btf)) {
13655 		btf_put(btf);
13656 		return -EACCES;
13657 	}
13658 	env->prog->aux->btf = btf;
13659 
13660 	err = check_btf_func(env, attr, uattr);
13661 	if (err)
13662 		return err;
13663 
13664 	err = check_btf_line(env, attr, uattr);
13665 	if (err)
13666 		return err;
13667 
13668 	err = check_core_relo(env, attr, uattr);
13669 	if (err)
13670 		return err;
13671 
13672 	return 0;
13673 }
13674 
13675 /* check %cur's range satisfies %old's */
13676 static bool range_within(struct bpf_reg_state *old,
13677 			 struct bpf_reg_state *cur)
13678 {
13679 	return old->umin_value <= cur->umin_value &&
13680 	       old->umax_value >= cur->umax_value &&
13681 	       old->smin_value <= cur->smin_value &&
13682 	       old->smax_value >= cur->smax_value &&
13683 	       old->u32_min_value <= cur->u32_min_value &&
13684 	       old->u32_max_value >= cur->u32_max_value &&
13685 	       old->s32_min_value <= cur->s32_min_value &&
13686 	       old->s32_max_value >= cur->s32_max_value;
13687 }
13688 
13689 /* If in the old state two registers had the same id, then they need to have
13690  * the same id in the new state as well.  But that id could be different from
13691  * the old state, so we need to track the mapping from old to new ids.
13692  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
13693  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
13694  * regs with a different old id could still have new id 9, we don't care about
13695  * that.
13696  * So we look through our idmap to see if this old id has been seen before.  If
13697  * so, we require the new id to match; otherwise, we add the id pair to the map.
13698  */
13699 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
13700 {
13701 	unsigned int i;
13702 
13703 	/* either both IDs should be set or both should be zero */
13704 	if (!!old_id != !!cur_id)
13705 		return false;
13706 
13707 	if (old_id == 0) /* cur_id == 0 as well */
13708 		return true;
13709 
13710 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
13711 		if (!idmap[i].old) {
13712 			/* Reached an empty slot; haven't seen this id before */
13713 			idmap[i].old = old_id;
13714 			idmap[i].cur = cur_id;
13715 			return true;
13716 		}
13717 		if (idmap[i].old == old_id)
13718 			return idmap[i].cur == cur_id;
13719 	}
13720 	/* We ran out of idmap slots, which should be impossible */
13721 	WARN_ON_ONCE(1);
13722 	return false;
13723 }
13724 
13725 static void clean_func_state(struct bpf_verifier_env *env,
13726 			     struct bpf_func_state *st)
13727 {
13728 	enum bpf_reg_liveness live;
13729 	int i, j;
13730 
13731 	for (i = 0; i < BPF_REG_FP; i++) {
13732 		live = st->regs[i].live;
13733 		/* liveness must not touch this register anymore */
13734 		st->regs[i].live |= REG_LIVE_DONE;
13735 		if (!(live & REG_LIVE_READ))
13736 			/* since the register is unused, clear its state
13737 			 * to make further comparison simpler
13738 			 */
13739 			__mark_reg_not_init(env, &st->regs[i]);
13740 	}
13741 
13742 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
13743 		live = st->stack[i].spilled_ptr.live;
13744 		/* liveness must not touch this stack slot anymore */
13745 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
13746 		if (!(live & REG_LIVE_READ)) {
13747 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
13748 			for (j = 0; j < BPF_REG_SIZE; j++)
13749 				st->stack[i].slot_type[j] = STACK_INVALID;
13750 		}
13751 	}
13752 }
13753 
13754 static void clean_verifier_state(struct bpf_verifier_env *env,
13755 				 struct bpf_verifier_state *st)
13756 {
13757 	int i;
13758 
13759 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
13760 		/* all regs in this state in all frames were already marked */
13761 		return;
13762 
13763 	for (i = 0; i <= st->curframe; i++)
13764 		clean_func_state(env, st->frame[i]);
13765 }
13766 
13767 /* the parentage chains form a tree.
13768  * the verifier states are added to state lists at given insn and
13769  * pushed into state stack for future exploration.
13770  * when the verifier reaches bpf_exit insn some of the verifer states
13771  * stored in the state lists have their final liveness state already,
13772  * but a lot of states will get revised from liveness point of view when
13773  * the verifier explores other branches.
13774  * Example:
13775  * 1: r0 = 1
13776  * 2: if r1 == 100 goto pc+1
13777  * 3: r0 = 2
13778  * 4: exit
13779  * when the verifier reaches exit insn the register r0 in the state list of
13780  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13781  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13782  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13783  *
13784  * Since the verifier pushes the branch states as it sees them while exploring
13785  * the program the condition of walking the branch instruction for the second
13786  * time means that all states below this branch were already explored and
13787  * their final liveness marks are already propagated.
13788  * Hence when the verifier completes the search of state list in is_state_visited()
13789  * we can call this clean_live_states() function to mark all liveness states
13790  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13791  * will not be used.
13792  * This function also clears the registers and stack for states that !READ
13793  * to simplify state merging.
13794  *
13795  * Important note here that walking the same branch instruction in the callee
13796  * doesn't meant that the states are DONE. The verifier has to compare
13797  * the callsites
13798  */
13799 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13800 			      struct bpf_verifier_state *cur)
13801 {
13802 	struct bpf_verifier_state_list *sl;
13803 	int i;
13804 
13805 	sl = *explored_state(env, insn);
13806 	while (sl) {
13807 		if (sl->state.branches)
13808 			goto next;
13809 		if (sl->state.insn_idx != insn ||
13810 		    sl->state.curframe != cur->curframe)
13811 			goto next;
13812 		for (i = 0; i <= cur->curframe; i++)
13813 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13814 				goto next;
13815 		clean_verifier_state(env, &sl->state);
13816 next:
13817 		sl = sl->next;
13818 	}
13819 }
13820 
13821 static bool regs_exact(const struct bpf_reg_state *rold,
13822 		       const struct bpf_reg_state *rcur,
13823 		       struct bpf_id_pair *idmap)
13824 {
13825 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13826 	       check_ids(rold->id, rcur->id, idmap) &&
13827 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
13828 }
13829 
13830 /* Returns true if (rold safe implies rcur safe) */
13831 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13832 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13833 {
13834 	if (!(rold->live & REG_LIVE_READ))
13835 		/* explored state didn't use this */
13836 		return true;
13837 	if (rold->type == NOT_INIT)
13838 		/* explored state can't have used this */
13839 		return true;
13840 	if (rcur->type == NOT_INIT)
13841 		return false;
13842 
13843 	/* Enforce that register types have to match exactly, including their
13844 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13845 	 * rule.
13846 	 *
13847 	 * One can make a point that using a pointer register as unbounded
13848 	 * SCALAR would be technically acceptable, but this could lead to
13849 	 * pointer leaks because scalars are allowed to leak while pointers
13850 	 * are not. We could make this safe in special cases if root is
13851 	 * calling us, but it's probably not worth the hassle.
13852 	 *
13853 	 * Also, register types that are *not* MAYBE_NULL could technically be
13854 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13855 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13856 	 * to the same map).
13857 	 * However, if the old MAYBE_NULL register then got NULL checked,
13858 	 * doing so could have affected others with the same id, and we can't
13859 	 * check for that because we lost the id when we converted to
13860 	 * a non-MAYBE_NULL variant.
13861 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
13862 	 * non-MAYBE_NULL registers as well.
13863 	 */
13864 	if (rold->type != rcur->type)
13865 		return false;
13866 
13867 	switch (base_type(rold->type)) {
13868 	case SCALAR_VALUE:
13869 		if (regs_exact(rold, rcur, idmap))
13870 			return true;
13871 		if (env->explore_alu_limits)
13872 			return false;
13873 		if (!rold->precise)
13874 			return true;
13875 		/* new val must satisfy old val knowledge */
13876 		return range_within(rold, rcur) &&
13877 		       tnum_in(rold->var_off, rcur->var_off);
13878 	case PTR_TO_MAP_KEY:
13879 	case PTR_TO_MAP_VALUE:
13880 		/* If the new min/max/var_off satisfy the old ones and
13881 		 * everything else matches, we are OK.
13882 		 */
13883 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13884 		       range_within(rold, rcur) &&
13885 		       tnum_in(rold->var_off, rcur->var_off) &&
13886 		       check_ids(rold->id, rcur->id, idmap);
13887 	case PTR_TO_PACKET_META:
13888 	case PTR_TO_PACKET:
13889 		/* We must have at least as much range as the old ptr
13890 		 * did, so that any accesses which were safe before are
13891 		 * still safe.  This is true even if old range < old off,
13892 		 * since someone could have accessed through (ptr - k), or
13893 		 * even done ptr -= k in a register, to get a safe access.
13894 		 */
13895 		if (rold->range > rcur->range)
13896 			return false;
13897 		/* If the offsets don't match, we can't trust our alignment;
13898 		 * nor can we be sure that we won't fall out of range.
13899 		 */
13900 		if (rold->off != rcur->off)
13901 			return false;
13902 		/* id relations must be preserved */
13903 		if (!check_ids(rold->id, rcur->id, idmap))
13904 			return false;
13905 		/* new val must satisfy old val knowledge */
13906 		return range_within(rold, rcur) &&
13907 		       tnum_in(rold->var_off, rcur->var_off);
13908 	case PTR_TO_STACK:
13909 		/* two stack pointers are equal only if they're pointing to
13910 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13911 		 */
13912 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
13913 	default:
13914 		return regs_exact(rold, rcur, idmap);
13915 	}
13916 }
13917 
13918 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13919 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13920 {
13921 	int i, spi;
13922 
13923 	/* walk slots of the explored stack and ignore any additional
13924 	 * slots in the current stack, since explored(safe) state
13925 	 * didn't use them
13926 	 */
13927 	for (i = 0; i < old->allocated_stack; i++) {
13928 		spi = i / BPF_REG_SIZE;
13929 
13930 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13931 			i += BPF_REG_SIZE - 1;
13932 			/* explored state didn't use this */
13933 			continue;
13934 		}
13935 
13936 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13937 			continue;
13938 
13939 		/* explored stack has more populated slots than current stack
13940 		 * and these slots were used
13941 		 */
13942 		if (i >= cur->allocated_stack)
13943 			return false;
13944 
13945 		/* if old state was safe with misc data in the stack
13946 		 * it will be safe with zero-initialized stack.
13947 		 * The opposite is not true
13948 		 */
13949 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13950 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13951 			continue;
13952 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13953 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13954 			/* Ex: old explored (safe) state has STACK_SPILL in
13955 			 * this stack slot, but current has STACK_MISC ->
13956 			 * this verifier states are not equivalent,
13957 			 * return false to continue verification of this path
13958 			 */
13959 			return false;
13960 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13961 			continue;
13962 		/* Both old and cur are having same slot_type */
13963 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
13964 		case STACK_SPILL:
13965 			/* when explored and current stack slot are both storing
13966 			 * spilled registers, check that stored pointers types
13967 			 * are the same as well.
13968 			 * Ex: explored safe path could have stored
13969 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13970 			 * but current path has stored:
13971 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13972 			 * such verifier states are not equivalent.
13973 			 * return false to continue verification of this path
13974 			 */
13975 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
13976 				     &cur->stack[spi].spilled_ptr, idmap))
13977 				return false;
13978 			break;
13979 		case STACK_DYNPTR:
13980 		{
13981 			const struct bpf_reg_state *old_reg, *cur_reg;
13982 
13983 			old_reg = &old->stack[spi].spilled_ptr;
13984 			cur_reg = &cur->stack[spi].spilled_ptr;
13985 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
13986 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
13987 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
13988 				return false;
13989 			break;
13990 		}
13991 		case STACK_MISC:
13992 		case STACK_ZERO:
13993 		case STACK_INVALID:
13994 			continue;
13995 		/* Ensure that new unhandled slot types return false by default */
13996 		default:
13997 			return false;
13998 		}
13999 	}
14000 	return true;
14001 }
14002 
14003 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14004 		    struct bpf_id_pair *idmap)
14005 {
14006 	int i;
14007 
14008 	if (old->acquired_refs != cur->acquired_refs)
14009 		return false;
14010 
14011 	for (i = 0; i < old->acquired_refs; i++) {
14012 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14013 			return false;
14014 	}
14015 
14016 	return true;
14017 }
14018 
14019 /* compare two verifier states
14020  *
14021  * all states stored in state_list are known to be valid, since
14022  * verifier reached 'bpf_exit' instruction through them
14023  *
14024  * this function is called when verifier exploring different branches of
14025  * execution popped from the state stack. If it sees an old state that has
14026  * more strict register state and more strict stack state then this execution
14027  * branch doesn't need to be explored further, since verifier already
14028  * concluded that more strict state leads to valid finish.
14029  *
14030  * Therefore two states are equivalent if register state is more conservative
14031  * and explored stack state is more conservative than the current one.
14032  * Example:
14033  *       explored                   current
14034  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14035  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14036  *
14037  * In other words if current stack state (one being explored) has more
14038  * valid slots than old one that already passed validation, it means
14039  * the verifier can stop exploring and conclude that current state is valid too
14040  *
14041  * Similarly with registers. If explored state has register type as invalid
14042  * whereas register type in current state is meaningful, it means that
14043  * the current state will reach 'bpf_exit' instruction safely
14044  */
14045 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14046 			      struct bpf_func_state *cur)
14047 {
14048 	int i;
14049 
14050 	for (i = 0; i < MAX_BPF_REG; i++)
14051 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
14052 			     env->idmap_scratch))
14053 			return false;
14054 
14055 	if (!stacksafe(env, old, cur, env->idmap_scratch))
14056 		return false;
14057 
14058 	if (!refsafe(old, cur, env->idmap_scratch))
14059 		return false;
14060 
14061 	return true;
14062 }
14063 
14064 static bool states_equal(struct bpf_verifier_env *env,
14065 			 struct bpf_verifier_state *old,
14066 			 struct bpf_verifier_state *cur)
14067 {
14068 	int i;
14069 
14070 	if (old->curframe != cur->curframe)
14071 		return false;
14072 
14073 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14074 
14075 	/* Verification state from speculative execution simulation
14076 	 * must never prune a non-speculative execution one.
14077 	 */
14078 	if (old->speculative && !cur->speculative)
14079 		return false;
14080 
14081 	if (old->active_lock.ptr != cur->active_lock.ptr)
14082 		return false;
14083 
14084 	/* Old and cur active_lock's have to be either both present
14085 	 * or both absent.
14086 	 */
14087 	if (!!old->active_lock.id != !!cur->active_lock.id)
14088 		return false;
14089 
14090 	if (old->active_lock.id &&
14091 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14092 		return false;
14093 
14094 	if (old->active_rcu_lock != cur->active_rcu_lock)
14095 		return false;
14096 
14097 	/* for states to be equal callsites have to be the same
14098 	 * and all frame states need to be equivalent
14099 	 */
14100 	for (i = 0; i <= old->curframe; i++) {
14101 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
14102 			return false;
14103 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14104 			return false;
14105 	}
14106 	return true;
14107 }
14108 
14109 /* Return 0 if no propagation happened. Return negative error code if error
14110  * happened. Otherwise, return the propagated bit.
14111  */
14112 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14113 				  struct bpf_reg_state *reg,
14114 				  struct bpf_reg_state *parent_reg)
14115 {
14116 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14117 	u8 flag = reg->live & REG_LIVE_READ;
14118 	int err;
14119 
14120 	/* When comes here, read flags of PARENT_REG or REG could be any of
14121 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14122 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14123 	 */
14124 	if (parent_flag == REG_LIVE_READ64 ||
14125 	    /* Or if there is no read flag from REG. */
14126 	    !flag ||
14127 	    /* Or if the read flag from REG is the same as PARENT_REG. */
14128 	    parent_flag == flag)
14129 		return 0;
14130 
14131 	err = mark_reg_read(env, reg, parent_reg, flag);
14132 	if (err)
14133 		return err;
14134 
14135 	return flag;
14136 }
14137 
14138 /* A write screens off any subsequent reads; but write marks come from the
14139  * straight-line code between a state and its parent.  When we arrive at an
14140  * equivalent state (jump target or such) we didn't arrive by the straight-line
14141  * code, so read marks in the state must propagate to the parent regardless
14142  * of the state's write marks. That's what 'parent == state->parent' comparison
14143  * in mark_reg_read() is for.
14144  */
14145 static int propagate_liveness(struct bpf_verifier_env *env,
14146 			      const struct bpf_verifier_state *vstate,
14147 			      struct bpf_verifier_state *vparent)
14148 {
14149 	struct bpf_reg_state *state_reg, *parent_reg;
14150 	struct bpf_func_state *state, *parent;
14151 	int i, frame, err = 0;
14152 
14153 	if (vparent->curframe != vstate->curframe) {
14154 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
14155 		     vparent->curframe, vstate->curframe);
14156 		return -EFAULT;
14157 	}
14158 	/* Propagate read liveness of registers... */
14159 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14160 	for (frame = 0; frame <= vstate->curframe; frame++) {
14161 		parent = vparent->frame[frame];
14162 		state = vstate->frame[frame];
14163 		parent_reg = parent->regs;
14164 		state_reg = state->regs;
14165 		/* We don't need to worry about FP liveness, it's read-only */
14166 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14167 			err = propagate_liveness_reg(env, &state_reg[i],
14168 						     &parent_reg[i]);
14169 			if (err < 0)
14170 				return err;
14171 			if (err == REG_LIVE_READ64)
14172 				mark_insn_zext(env, &parent_reg[i]);
14173 		}
14174 
14175 		/* Propagate stack slots. */
14176 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14177 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14178 			parent_reg = &parent->stack[i].spilled_ptr;
14179 			state_reg = &state->stack[i].spilled_ptr;
14180 			err = propagate_liveness_reg(env, state_reg,
14181 						     parent_reg);
14182 			if (err < 0)
14183 				return err;
14184 		}
14185 	}
14186 	return 0;
14187 }
14188 
14189 /* find precise scalars in the previous equivalent state and
14190  * propagate them into the current state
14191  */
14192 static int propagate_precision(struct bpf_verifier_env *env,
14193 			       const struct bpf_verifier_state *old)
14194 {
14195 	struct bpf_reg_state *state_reg;
14196 	struct bpf_func_state *state;
14197 	int i, err = 0, fr;
14198 
14199 	for (fr = old->curframe; fr >= 0; fr--) {
14200 		state = old->frame[fr];
14201 		state_reg = state->regs;
14202 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14203 			if (state_reg->type != SCALAR_VALUE ||
14204 			    !state_reg->precise)
14205 				continue;
14206 			if (env->log.level & BPF_LOG_LEVEL2)
14207 				verbose(env, "frame %d: propagating r%d\n", i, fr);
14208 			err = mark_chain_precision_frame(env, fr, i);
14209 			if (err < 0)
14210 				return err;
14211 		}
14212 
14213 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14214 			if (!is_spilled_reg(&state->stack[i]))
14215 				continue;
14216 			state_reg = &state->stack[i].spilled_ptr;
14217 			if (state_reg->type != SCALAR_VALUE ||
14218 			    !state_reg->precise)
14219 				continue;
14220 			if (env->log.level & BPF_LOG_LEVEL2)
14221 				verbose(env, "frame %d: propagating fp%d\n",
14222 					(-i - 1) * BPF_REG_SIZE, fr);
14223 			err = mark_chain_precision_stack_frame(env, fr, i);
14224 			if (err < 0)
14225 				return err;
14226 		}
14227 	}
14228 	return 0;
14229 }
14230 
14231 static bool states_maybe_looping(struct bpf_verifier_state *old,
14232 				 struct bpf_verifier_state *cur)
14233 {
14234 	struct bpf_func_state *fold, *fcur;
14235 	int i, fr = cur->curframe;
14236 
14237 	if (old->curframe != fr)
14238 		return false;
14239 
14240 	fold = old->frame[fr];
14241 	fcur = cur->frame[fr];
14242 	for (i = 0; i < MAX_BPF_REG; i++)
14243 		if (memcmp(&fold->regs[i], &fcur->regs[i],
14244 			   offsetof(struct bpf_reg_state, parent)))
14245 			return false;
14246 	return true;
14247 }
14248 
14249 
14250 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14251 {
14252 	struct bpf_verifier_state_list *new_sl;
14253 	struct bpf_verifier_state_list *sl, **pprev;
14254 	struct bpf_verifier_state *cur = env->cur_state, *new;
14255 	int i, j, err, states_cnt = 0;
14256 	bool add_new_state = env->test_state_freq ? true : false;
14257 
14258 	/* bpf progs typically have pruning point every 4 instructions
14259 	 * http://vger.kernel.org/bpfconf2019.html#session-1
14260 	 * Do not add new state for future pruning if the verifier hasn't seen
14261 	 * at least 2 jumps and at least 8 instructions.
14262 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14263 	 * In tests that amounts to up to 50% reduction into total verifier
14264 	 * memory consumption and 20% verifier time speedup.
14265 	 */
14266 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14267 	    env->insn_processed - env->prev_insn_processed >= 8)
14268 		add_new_state = true;
14269 
14270 	pprev = explored_state(env, insn_idx);
14271 	sl = *pprev;
14272 
14273 	clean_live_states(env, insn_idx, cur);
14274 
14275 	while (sl) {
14276 		states_cnt++;
14277 		if (sl->state.insn_idx != insn_idx)
14278 			goto next;
14279 
14280 		if (sl->state.branches) {
14281 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14282 
14283 			if (frame->in_async_callback_fn &&
14284 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14285 				/* Different async_entry_cnt means that the verifier is
14286 				 * processing another entry into async callback.
14287 				 * Seeing the same state is not an indication of infinite
14288 				 * loop or infinite recursion.
14289 				 * But finding the same state doesn't mean that it's safe
14290 				 * to stop processing the current state. The previous state
14291 				 * hasn't yet reached bpf_exit, since state.branches > 0.
14292 				 * Checking in_async_callback_fn alone is not enough either.
14293 				 * Since the verifier still needs to catch infinite loops
14294 				 * inside async callbacks.
14295 				 */
14296 			} else if (states_maybe_looping(&sl->state, cur) &&
14297 				   states_equal(env, &sl->state, cur)) {
14298 				verbose_linfo(env, insn_idx, "; ");
14299 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14300 				return -EINVAL;
14301 			}
14302 			/* if the verifier is processing a loop, avoid adding new state
14303 			 * too often, since different loop iterations have distinct
14304 			 * states and may not help future pruning.
14305 			 * This threshold shouldn't be too low to make sure that
14306 			 * a loop with large bound will be rejected quickly.
14307 			 * The most abusive loop will be:
14308 			 * r1 += 1
14309 			 * if r1 < 1000000 goto pc-2
14310 			 * 1M insn_procssed limit / 100 == 10k peak states.
14311 			 * This threshold shouldn't be too high either, since states
14312 			 * at the end of the loop are likely to be useful in pruning.
14313 			 */
14314 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
14315 			    env->insn_processed - env->prev_insn_processed < 100)
14316 				add_new_state = false;
14317 			goto miss;
14318 		}
14319 		if (states_equal(env, &sl->state, cur)) {
14320 			sl->hit_cnt++;
14321 			/* reached equivalent register/stack state,
14322 			 * prune the search.
14323 			 * Registers read by the continuation are read by us.
14324 			 * If we have any write marks in env->cur_state, they
14325 			 * will prevent corresponding reads in the continuation
14326 			 * from reaching our parent (an explored_state).  Our
14327 			 * own state will get the read marks recorded, but
14328 			 * they'll be immediately forgotten as we're pruning
14329 			 * this state and will pop a new one.
14330 			 */
14331 			err = propagate_liveness(env, &sl->state, cur);
14332 
14333 			/* if previous state reached the exit with precision and
14334 			 * current state is equivalent to it (except precsion marks)
14335 			 * the precision needs to be propagated back in
14336 			 * the current state.
14337 			 */
14338 			err = err ? : push_jmp_history(env, cur);
14339 			err = err ? : propagate_precision(env, &sl->state);
14340 			if (err)
14341 				return err;
14342 			return 1;
14343 		}
14344 miss:
14345 		/* when new state is not going to be added do not increase miss count.
14346 		 * Otherwise several loop iterations will remove the state
14347 		 * recorded earlier. The goal of these heuristics is to have
14348 		 * states from some iterations of the loop (some in the beginning
14349 		 * and some at the end) to help pruning.
14350 		 */
14351 		if (add_new_state)
14352 			sl->miss_cnt++;
14353 		/* heuristic to determine whether this state is beneficial
14354 		 * to keep checking from state equivalence point of view.
14355 		 * Higher numbers increase max_states_per_insn and verification time,
14356 		 * but do not meaningfully decrease insn_processed.
14357 		 */
14358 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14359 			/* the state is unlikely to be useful. Remove it to
14360 			 * speed up verification
14361 			 */
14362 			*pprev = sl->next;
14363 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14364 				u32 br = sl->state.branches;
14365 
14366 				WARN_ONCE(br,
14367 					  "BUG live_done but branches_to_explore %d\n",
14368 					  br);
14369 				free_verifier_state(&sl->state, false);
14370 				kfree(sl);
14371 				env->peak_states--;
14372 			} else {
14373 				/* cannot free this state, since parentage chain may
14374 				 * walk it later. Add it for free_list instead to
14375 				 * be freed at the end of verification
14376 				 */
14377 				sl->next = env->free_list;
14378 				env->free_list = sl;
14379 			}
14380 			sl = *pprev;
14381 			continue;
14382 		}
14383 next:
14384 		pprev = &sl->next;
14385 		sl = *pprev;
14386 	}
14387 
14388 	if (env->max_states_per_insn < states_cnt)
14389 		env->max_states_per_insn = states_cnt;
14390 
14391 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14392 		return 0;
14393 
14394 	if (!add_new_state)
14395 		return 0;
14396 
14397 	/* There were no equivalent states, remember the current one.
14398 	 * Technically the current state is not proven to be safe yet,
14399 	 * but it will either reach outer most bpf_exit (which means it's safe)
14400 	 * or it will be rejected. When there are no loops the verifier won't be
14401 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14402 	 * again on the way to bpf_exit.
14403 	 * When looping the sl->state.branches will be > 0 and this state
14404 	 * will not be considered for equivalence until branches == 0.
14405 	 */
14406 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14407 	if (!new_sl)
14408 		return -ENOMEM;
14409 	env->total_states++;
14410 	env->peak_states++;
14411 	env->prev_jmps_processed = env->jmps_processed;
14412 	env->prev_insn_processed = env->insn_processed;
14413 
14414 	/* forget precise markings we inherited, see __mark_chain_precision */
14415 	if (env->bpf_capable)
14416 		mark_all_scalars_imprecise(env, cur);
14417 
14418 	/* add new state to the head of linked list */
14419 	new = &new_sl->state;
14420 	err = copy_verifier_state(new, cur);
14421 	if (err) {
14422 		free_verifier_state(new, false);
14423 		kfree(new_sl);
14424 		return err;
14425 	}
14426 	new->insn_idx = insn_idx;
14427 	WARN_ONCE(new->branches != 1,
14428 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14429 
14430 	cur->parent = new;
14431 	cur->first_insn_idx = insn_idx;
14432 	clear_jmp_history(cur);
14433 	new_sl->next = *explored_state(env, insn_idx);
14434 	*explored_state(env, insn_idx) = new_sl;
14435 	/* connect new state to parentage chain. Current frame needs all
14436 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
14437 	 * to the stack implicitly by JITs) so in callers' frames connect just
14438 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14439 	 * the state of the call instruction (with WRITTEN set), and r0 comes
14440 	 * from callee with its full parentage chain, anyway.
14441 	 */
14442 	/* clear write marks in current state: the writes we did are not writes
14443 	 * our child did, so they don't screen off its reads from us.
14444 	 * (There are no read marks in current state, because reads always mark
14445 	 * their parent and current state never has children yet.  Only
14446 	 * explored_states can get read marks.)
14447 	 */
14448 	for (j = 0; j <= cur->curframe; j++) {
14449 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14450 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14451 		for (i = 0; i < BPF_REG_FP; i++)
14452 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14453 	}
14454 
14455 	/* all stack frames are accessible from callee, clear them all */
14456 	for (j = 0; j <= cur->curframe; j++) {
14457 		struct bpf_func_state *frame = cur->frame[j];
14458 		struct bpf_func_state *newframe = new->frame[j];
14459 
14460 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14461 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14462 			frame->stack[i].spilled_ptr.parent =
14463 						&newframe->stack[i].spilled_ptr;
14464 		}
14465 	}
14466 	return 0;
14467 }
14468 
14469 /* Return true if it's OK to have the same insn return a different type. */
14470 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14471 {
14472 	switch (base_type(type)) {
14473 	case PTR_TO_CTX:
14474 	case PTR_TO_SOCKET:
14475 	case PTR_TO_SOCK_COMMON:
14476 	case PTR_TO_TCP_SOCK:
14477 	case PTR_TO_XDP_SOCK:
14478 	case PTR_TO_BTF_ID:
14479 		return false;
14480 	default:
14481 		return true;
14482 	}
14483 }
14484 
14485 /* If an instruction was previously used with particular pointer types, then we
14486  * need to be careful to avoid cases such as the below, where it may be ok
14487  * for one branch accessing the pointer, but not ok for the other branch:
14488  *
14489  * R1 = sock_ptr
14490  * goto X;
14491  * ...
14492  * R1 = some_other_valid_ptr;
14493  * goto X;
14494  * ...
14495  * R2 = *(u32 *)(R1 + 0);
14496  */
14497 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14498 {
14499 	return src != prev && (!reg_type_mismatch_ok(src) ||
14500 			       !reg_type_mismatch_ok(prev));
14501 }
14502 
14503 static int do_check(struct bpf_verifier_env *env)
14504 {
14505 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14506 	struct bpf_verifier_state *state = env->cur_state;
14507 	struct bpf_insn *insns = env->prog->insnsi;
14508 	struct bpf_reg_state *regs;
14509 	int insn_cnt = env->prog->len;
14510 	bool do_print_state = false;
14511 	int prev_insn_idx = -1;
14512 
14513 	for (;;) {
14514 		struct bpf_insn *insn;
14515 		u8 class;
14516 		int err;
14517 
14518 		env->prev_insn_idx = prev_insn_idx;
14519 		if (env->insn_idx >= insn_cnt) {
14520 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
14521 				env->insn_idx, insn_cnt);
14522 			return -EFAULT;
14523 		}
14524 
14525 		insn = &insns[env->insn_idx];
14526 		class = BPF_CLASS(insn->code);
14527 
14528 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14529 			verbose(env,
14530 				"BPF program is too large. Processed %d insn\n",
14531 				env->insn_processed);
14532 			return -E2BIG;
14533 		}
14534 
14535 		state->last_insn_idx = env->prev_insn_idx;
14536 
14537 		if (is_prune_point(env, env->insn_idx)) {
14538 			err = is_state_visited(env, env->insn_idx);
14539 			if (err < 0)
14540 				return err;
14541 			if (err == 1) {
14542 				/* found equivalent state, can prune the search */
14543 				if (env->log.level & BPF_LOG_LEVEL) {
14544 					if (do_print_state)
14545 						verbose(env, "\nfrom %d to %d%s: safe\n",
14546 							env->prev_insn_idx, env->insn_idx,
14547 							env->cur_state->speculative ?
14548 							" (speculative execution)" : "");
14549 					else
14550 						verbose(env, "%d: safe\n", env->insn_idx);
14551 				}
14552 				goto process_bpf_exit;
14553 			}
14554 		}
14555 
14556 		if (is_jmp_point(env, env->insn_idx)) {
14557 			err = push_jmp_history(env, state);
14558 			if (err)
14559 				return err;
14560 		}
14561 
14562 		if (signal_pending(current))
14563 			return -EAGAIN;
14564 
14565 		if (need_resched())
14566 			cond_resched();
14567 
14568 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14569 			verbose(env, "\nfrom %d to %d%s:",
14570 				env->prev_insn_idx, env->insn_idx,
14571 				env->cur_state->speculative ?
14572 				" (speculative execution)" : "");
14573 			print_verifier_state(env, state->frame[state->curframe], true);
14574 			do_print_state = false;
14575 		}
14576 
14577 		if (env->log.level & BPF_LOG_LEVEL) {
14578 			const struct bpf_insn_cbs cbs = {
14579 				.cb_call	= disasm_kfunc_name,
14580 				.cb_print	= verbose,
14581 				.private_data	= env,
14582 			};
14583 
14584 			if (verifier_state_scratched(env))
14585 				print_insn_state(env, state->frame[state->curframe]);
14586 
14587 			verbose_linfo(env, env->insn_idx, "; ");
14588 			env->prev_log_len = env->log.len_used;
14589 			verbose(env, "%d: ", env->insn_idx);
14590 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14591 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14592 			env->prev_log_len = env->log.len_used;
14593 		}
14594 
14595 		if (bpf_prog_is_offloaded(env->prog->aux)) {
14596 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14597 							   env->prev_insn_idx);
14598 			if (err)
14599 				return err;
14600 		}
14601 
14602 		regs = cur_regs(env);
14603 		sanitize_mark_insn_seen(env);
14604 		prev_insn_idx = env->insn_idx;
14605 
14606 		if (class == BPF_ALU || class == BPF_ALU64) {
14607 			err = check_alu_op(env, insn);
14608 			if (err)
14609 				return err;
14610 
14611 		} else if (class == BPF_LDX) {
14612 			enum bpf_reg_type *prev_src_type, src_reg_type;
14613 
14614 			/* check for reserved fields is already done */
14615 
14616 			/* check src operand */
14617 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14618 			if (err)
14619 				return err;
14620 
14621 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14622 			if (err)
14623 				return err;
14624 
14625 			src_reg_type = regs[insn->src_reg].type;
14626 
14627 			/* check that memory (src_reg + off) is readable,
14628 			 * the state of dst_reg will be updated by this func
14629 			 */
14630 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
14631 					       insn->off, BPF_SIZE(insn->code),
14632 					       BPF_READ, insn->dst_reg, false);
14633 			if (err)
14634 				return err;
14635 
14636 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14637 
14638 			if (*prev_src_type == NOT_INIT) {
14639 				/* saw a valid insn
14640 				 * dst_reg = *(u32 *)(src_reg + off)
14641 				 * save type to validate intersecting paths
14642 				 */
14643 				*prev_src_type = src_reg_type;
14644 
14645 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
14646 				/* ABuser program is trying to use the same insn
14647 				 * dst_reg = *(u32*) (src_reg + off)
14648 				 * with different pointer types:
14649 				 * src_reg == ctx in one branch and
14650 				 * src_reg == stack|map in some other branch.
14651 				 * Reject it.
14652 				 */
14653 				verbose(env, "same insn cannot be used with different pointers\n");
14654 				return -EINVAL;
14655 			}
14656 
14657 		} else if (class == BPF_STX) {
14658 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
14659 
14660 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
14661 				err = check_atomic(env, env->insn_idx, insn);
14662 				if (err)
14663 					return err;
14664 				env->insn_idx++;
14665 				continue;
14666 			}
14667 
14668 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
14669 				verbose(env, "BPF_STX uses reserved fields\n");
14670 				return -EINVAL;
14671 			}
14672 
14673 			/* check src1 operand */
14674 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14675 			if (err)
14676 				return err;
14677 			/* check src2 operand */
14678 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14679 			if (err)
14680 				return err;
14681 
14682 			dst_reg_type = regs[insn->dst_reg].type;
14683 
14684 			/* check that memory (dst_reg + off) is writeable */
14685 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14686 					       insn->off, BPF_SIZE(insn->code),
14687 					       BPF_WRITE, insn->src_reg, false);
14688 			if (err)
14689 				return err;
14690 
14691 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14692 
14693 			if (*prev_dst_type == NOT_INIT) {
14694 				*prev_dst_type = dst_reg_type;
14695 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
14696 				verbose(env, "same insn cannot be used with different pointers\n");
14697 				return -EINVAL;
14698 			}
14699 
14700 		} else if (class == BPF_ST) {
14701 			if (BPF_MODE(insn->code) != BPF_MEM ||
14702 			    insn->src_reg != BPF_REG_0) {
14703 				verbose(env, "BPF_ST uses reserved fields\n");
14704 				return -EINVAL;
14705 			}
14706 			/* check src operand */
14707 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14708 			if (err)
14709 				return err;
14710 
14711 			if (is_ctx_reg(env, insn->dst_reg)) {
14712 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
14713 					insn->dst_reg,
14714 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
14715 				return -EACCES;
14716 			}
14717 
14718 			/* check that memory (dst_reg + off) is writeable */
14719 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
14720 					       insn->off, BPF_SIZE(insn->code),
14721 					       BPF_WRITE, -1, false);
14722 			if (err)
14723 				return err;
14724 
14725 		} else if (class == BPF_JMP || class == BPF_JMP32) {
14726 			u8 opcode = BPF_OP(insn->code);
14727 
14728 			env->jmps_processed++;
14729 			if (opcode == BPF_CALL) {
14730 				if (BPF_SRC(insn->code) != BPF_K ||
14731 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
14732 				     && insn->off != 0) ||
14733 				    (insn->src_reg != BPF_REG_0 &&
14734 				     insn->src_reg != BPF_PSEUDO_CALL &&
14735 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
14736 				    insn->dst_reg != BPF_REG_0 ||
14737 				    class == BPF_JMP32) {
14738 					verbose(env, "BPF_CALL uses reserved fields\n");
14739 					return -EINVAL;
14740 				}
14741 
14742 				if (env->cur_state->active_lock.ptr) {
14743 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
14744 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
14745 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
14746 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
14747 						verbose(env, "function calls are not allowed while holding a lock\n");
14748 						return -EINVAL;
14749 					}
14750 				}
14751 				if (insn->src_reg == BPF_PSEUDO_CALL)
14752 					err = check_func_call(env, insn, &env->insn_idx);
14753 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
14754 					err = check_kfunc_call(env, insn, &env->insn_idx);
14755 				else
14756 					err = check_helper_call(env, insn, &env->insn_idx);
14757 				if (err)
14758 					return err;
14759 			} else if (opcode == BPF_JA) {
14760 				if (BPF_SRC(insn->code) != BPF_K ||
14761 				    insn->imm != 0 ||
14762 				    insn->src_reg != BPF_REG_0 ||
14763 				    insn->dst_reg != BPF_REG_0 ||
14764 				    class == BPF_JMP32) {
14765 					verbose(env, "BPF_JA uses reserved fields\n");
14766 					return -EINVAL;
14767 				}
14768 
14769 				env->insn_idx += insn->off + 1;
14770 				continue;
14771 
14772 			} else if (opcode == BPF_EXIT) {
14773 				if (BPF_SRC(insn->code) != BPF_K ||
14774 				    insn->imm != 0 ||
14775 				    insn->src_reg != BPF_REG_0 ||
14776 				    insn->dst_reg != BPF_REG_0 ||
14777 				    class == BPF_JMP32) {
14778 					verbose(env, "BPF_EXIT uses reserved fields\n");
14779 					return -EINVAL;
14780 				}
14781 
14782 				if (env->cur_state->active_lock.ptr &&
14783 				    !in_rbtree_lock_required_cb(env)) {
14784 					verbose(env, "bpf_spin_unlock is missing\n");
14785 					return -EINVAL;
14786 				}
14787 
14788 				if (env->cur_state->active_rcu_lock) {
14789 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14790 					return -EINVAL;
14791 				}
14792 
14793 				/* We must do check_reference_leak here before
14794 				 * prepare_func_exit to handle the case when
14795 				 * state->curframe > 0, it may be a callback
14796 				 * function, for which reference_state must
14797 				 * match caller reference state when it exits.
14798 				 */
14799 				err = check_reference_leak(env);
14800 				if (err)
14801 					return err;
14802 
14803 				if (state->curframe) {
14804 					/* exit from nested function */
14805 					err = prepare_func_exit(env, &env->insn_idx);
14806 					if (err)
14807 						return err;
14808 					do_print_state = true;
14809 					continue;
14810 				}
14811 
14812 				err = check_return_code(env);
14813 				if (err)
14814 					return err;
14815 process_bpf_exit:
14816 				mark_verifier_state_scratched(env);
14817 				update_branch_counts(env, env->cur_state);
14818 				err = pop_stack(env, &prev_insn_idx,
14819 						&env->insn_idx, pop_log);
14820 				if (err < 0) {
14821 					if (err != -ENOENT)
14822 						return err;
14823 					break;
14824 				} else {
14825 					do_print_state = true;
14826 					continue;
14827 				}
14828 			} else {
14829 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14830 				if (err)
14831 					return err;
14832 			}
14833 		} else if (class == BPF_LD) {
14834 			u8 mode = BPF_MODE(insn->code);
14835 
14836 			if (mode == BPF_ABS || mode == BPF_IND) {
14837 				err = check_ld_abs(env, insn);
14838 				if (err)
14839 					return err;
14840 
14841 			} else if (mode == BPF_IMM) {
14842 				err = check_ld_imm(env, insn);
14843 				if (err)
14844 					return err;
14845 
14846 				env->insn_idx++;
14847 				sanitize_mark_insn_seen(env);
14848 			} else {
14849 				verbose(env, "invalid BPF_LD mode\n");
14850 				return -EINVAL;
14851 			}
14852 		} else {
14853 			verbose(env, "unknown insn class %d\n", class);
14854 			return -EINVAL;
14855 		}
14856 
14857 		env->insn_idx++;
14858 	}
14859 
14860 	return 0;
14861 }
14862 
14863 static int find_btf_percpu_datasec(struct btf *btf)
14864 {
14865 	const struct btf_type *t;
14866 	const char *tname;
14867 	int i, n;
14868 
14869 	/*
14870 	 * Both vmlinux and module each have their own ".data..percpu"
14871 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14872 	 * types to look at only module's own BTF types.
14873 	 */
14874 	n = btf_nr_types(btf);
14875 	if (btf_is_module(btf))
14876 		i = btf_nr_types(btf_vmlinux);
14877 	else
14878 		i = 1;
14879 
14880 	for(; i < n; i++) {
14881 		t = btf_type_by_id(btf, i);
14882 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14883 			continue;
14884 
14885 		tname = btf_name_by_offset(btf, t->name_off);
14886 		if (!strcmp(tname, ".data..percpu"))
14887 			return i;
14888 	}
14889 
14890 	return -ENOENT;
14891 }
14892 
14893 /* replace pseudo btf_id with kernel symbol address */
14894 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14895 			       struct bpf_insn *insn,
14896 			       struct bpf_insn_aux_data *aux)
14897 {
14898 	const struct btf_var_secinfo *vsi;
14899 	const struct btf_type *datasec;
14900 	struct btf_mod_pair *btf_mod;
14901 	const struct btf_type *t;
14902 	const char *sym_name;
14903 	bool percpu = false;
14904 	u32 type, id = insn->imm;
14905 	struct btf *btf;
14906 	s32 datasec_id;
14907 	u64 addr;
14908 	int i, btf_fd, err;
14909 
14910 	btf_fd = insn[1].imm;
14911 	if (btf_fd) {
14912 		btf = btf_get_by_fd(btf_fd);
14913 		if (IS_ERR(btf)) {
14914 			verbose(env, "invalid module BTF object FD specified.\n");
14915 			return -EINVAL;
14916 		}
14917 	} else {
14918 		if (!btf_vmlinux) {
14919 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14920 			return -EINVAL;
14921 		}
14922 		btf = btf_vmlinux;
14923 		btf_get(btf);
14924 	}
14925 
14926 	t = btf_type_by_id(btf, id);
14927 	if (!t) {
14928 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14929 		err = -ENOENT;
14930 		goto err_put;
14931 	}
14932 
14933 	if (!btf_type_is_var(t)) {
14934 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14935 		err = -EINVAL;
14936 		goto err_put;
14937 	}
14938 
14939 	sym_name = btf_name_by_offset(btf, t->name_off);
14940 	addr = kallsyms_lookup_name(sym_name);
14941 	if (!addr) {
14942 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14943 			sym_name);
14944 		err = -ENOENT;
14945 		goto err_put;
14946 	}
14947 
14948 	datasec_id = find_btf_percpu_datasec(btf);
14949 	if (datasec_id > 0) {
14950 		datasec = btf_type_by_id(btf, datasec_id);
14951 		for_each_vsi(i, datasec, vsi) {
14952 			if (vsi->type == id) {
14953 				percpu = true;
14954 				break;
14955 			}
14956 		}
14957 	}
14958 
14959 	insn[0].imm = (u32)addr;
14960 	insn[1].imm = addr >> 32;
14961 
14962 	type = t->type;
14963 	t = btf_type_skip_modifiers(btf, type, NULL);
14964 	if (percpu) {
14965 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14966 		aux->btf_var.btf = btf;
14967 		aux->btf_var.btf_id = type;
14968 	} else if (!btf_type_is_struct(t)) {
14969 		const struct btf_type *ret;
14970 		const char *tname;
14971 		u32 tsize;
14972 
14973 		/* resolve the type size of ksym. */
14974 		ret = btf_resolve_size(btf, t, &tsize);
14975 		if (IS_ERR(ret)) {
14976 			tname = btf_name_by_offset(btf, t->name_off);
14977 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14978 				tname, PTR_ERR(ret));
14979 			err = -EINVAL;
14980 			goto err_put;
14981 		}
14982 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14983 		aux->btf_var.mem_size = tsize;
14984 	} else {
14985 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14986 		aux->btf_var.btf = btf;
14987 		aux->btf_var.btf_id = type;
14988 	}
14989 
14990 	/* check whether we recorded this BTF (and maybe module) already */
14991 	for (i = 0; i < env->used_btf_cnt; i++) {
14992 		if (env->used_btfs[i].btf == btf) {
14993 			btf_put(btf);
14994 			return 0;
14995 		}
14996 	}
14997 
14998 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14999 		err = -E2BIG;
15000 		goto err_put;
15001 	}
15002 
15003 	btf_mod = &env->used_btfs[env->used_btf_cnt];
15004 	btf_mod->btf = btf;
15005 	btf_mod->module = NULL;
15006 
15007 	/* if we reference variables from kernel module, bump its refcount */
15008 	if (btf_is_module(btf)) {
15009 		btf_mod->module = btf_try_get_module(btf);
15010 		if (!btf_mod->module) {
15011 			err = -ENXIO;
15012 			goto err_put;
15013 		}
15014 	}
15015 
15016 	env->used_btf_cnt++;
15017 
15018 	return 0;
15019 err_put:
15020 	btf_put(btf);
15021 	return err;
15022 }
15023 
15024 static bool is_tracing_prog_type(enum bpf_prog_type type)
15025 {
15026 	switch (type) {
15027 	case BPF_PROG_TYPE_KPROBE:
15028 	case BPF_PROG_TYPE_TRACEPOINT:
15029 	case BPF_PROG_TYPE_PERF_EVENT:
15030 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15031 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15032 		return true;
15033 	default:
15034 		return false;
15035 	}
15036 }
15037 
15038 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15039 					struct bpf_map *map,
15040 					struct bpf_prog *prog)
15041 
15042 {
15043 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15044 
15045 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15046 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
15047 		if (is_tracing_prog_type(prog_type)) {
15048 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15049 			return -EINVAL;
15050 		}
15051 	}
15052 
15053 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15054 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15055 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15056 			return -EINVAL;
15057 		}
15058 
15059 		if (is_tracing_prog_type(prog_type)) {
15060 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15061 			return -EINVAL;
15062 		}
15063 
15064 		if (prog->aux->sleepable) {
15065 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15066 			return -EINVAL;
15067 		}
15068 	}
15069 
15070 	if (btf_record_has_field(map->record, BPF_TIMER)) {
15071 		if (is_tracing_prog_type(prog_type)) {
15072 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
15073 			return -EINVAL;
15074 		}
15075 	}
15076 
15077 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15078 	    !bpf_offload_prog_map_match(prog, map)) {
15079 		verbose(env, "offload device mismatch between prog and map\n");
15080 		return -EINVAL;
15081 	}
15082 
15083 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15084 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15085 		return -EINVAL;
15086 	}
15087 
15088 	if (prog->aux->sleepable)
15089 		switch (map->map_type) {
15090 		case BPF_MAP_TYPE_HASH:
15091 		case BPF_MAP_TYPE_LRU_HASH:
15092 		case BPF_MAP_TYPE_ARRAY:
15093 		case BPF_MAP_TYPE_PERCPU_HASH:
15094 		case BPF_MAP_TYPE_PERCPU_ARRAY:
15095 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15096 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15097 		case BPF_MAP_TYPE_HASH_OF_MAPS:
15098 		case BPF_MAP_TYPE_RINGBUF:
15099 		case BPF_MAP_TYPE_USER_RINGBUF:
15100 		case BPF_MAP_TYPE_INODE_STORAGE:
15101 		case BPF_MAP_TYPE_SK_STORAGE:
15102 		case BPF_MAP_TYPE_TASK_STORAGE:
15103 		case BPF_MAP_TYPE_CGRP_STORAGE:
15104 			break;
15105 		default:
15106 			verbose(env,
15107 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15108 			return -EINVAL;
15109 		}
15110 
15111 	return 0;
15112 }
15113 
15114 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15115 {
15116 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15117 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15118 }
15119 
15120 /* find and rewrite pseudo imm in ld_imm64 instructions:
15121  *
15122  * 1. if it accesses map FD, replace it with actual map pointer.
15123  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15124  *
15125  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15126  */
15127 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15128 {
15129 	struct bpf_insn *insn = env->prog->insnsi;
15130 	int insn_cnt = env->prog->len;
15131 	int i, j, err;
15132 
15133 	err = bpf_prog_calc_tag(env->prog);
15134 	if (err)
15135 		return err;
15136 
15137 	for (i = 0; i < insn_cnt; i++, insn++) {
15138 		if (BPF_CLASS(insn->code) == BPF_LDX &&
15139 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15140 			verbose(env, "BPF_LDX uses reserved fields\n");
15141 			return -EINVAL;
15142 		}
15143 
15144 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15145 			struct bpf_insn_aux_data *aux;
15146 			struct bpf_map *map;
15147 			struct fd f;
15148 			u64 addr;
15149 			u32 fd;
15150 
15151 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
15152 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15153 			    insn[1].off != 0) {
15154 				verbose(env, "invalid bpf_ld_imm64 insn\n");
15155 				return -EINVAL;
15156 			}
15157 
15158 			if (insn[0].src_reg == 0)
15159 				/* valid generic load 64-bit imm */
15160 				goto next_insn;
15161 
15162 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15163 				aux = &env->insn_aux_data[i];
15164 				err = check_pseudo_btf_id(env, insn, aux);
15165 				if (err)
15166 					return err;
15167 				goto next_insn;
15168 			}
15169 
15170 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15171 				aux = &env->insn_aux_data[i];
15172 				aux->ptr_type = PTR_TO_FUNC;
15173 				goto next_insn;
15174 			}
15175 
15176 			/* In final convert_pseudo_ld_imm64() step, this is
15177 			 * converted into regular 64-bit imm load insn.
15178 			 */
15179 			switch (insn[0].src_reg) {
15180 			case BPF_PSEUDO_MAP_VALUE:
15181 			case BPF_PSEUDO_MAP_IDX_VALUE:
15182 				break;
15183 			case BPF_PSEUDO_MAP_FD:
15184 			case BPF_PSEUDO_MAP_IDX:
15185 				if (insn[1].imm == 0)
15186 					break;
15187 				fallthrough;
15188 			default:
15189 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15190 				return -EINVAL;
15191 			}
15192 
15193 			switch (insn[0].src_reg) {
15194 			case BPF_PSEUDO_MAP_IDX_VALUE:
15195 			case BPF_PSEUDO_MAP_IDX:
15196 				if (bpfptr_is_null(env->fd_array)) {
15197 					verbose(env, "fd_idx without fd_array is invalid\n");
15198 					return -EPROTO;
15199 				}
15200 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
15201 							    insn[0].imm * sizeof(fd),
15202 							    sizeof(fd)))
15203 					return -EFAULT;
15204 				break;
15205 			default:
15206 				fd = insn[0].imm;
15207 				break;
15208 			}
15209 
15210 			f = fdget(fd);
15211 			map = __bpf_map_get(f);
15212 			if (IS_ERR(map)) {
15213 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
15214 					insn[0].imm);
15215 				return PTR_ERR(map);
15216 			}
15217 
15218 			err = check_map_prog_compatibility(env, map, env->prog);
15219 			if (err) {
15220 				fdput(f);
15221 				return err;
15222 			}
15223 
15224 			aux = &env->insn_aux_data[i];
15225 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15226 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15227 				addr = (unsigned long)map;
15228 			} else {
15229 				u32 off = insn[1].imm;
15230 
15231 				if (off >= BPF_MAX_VAR_OFF) {
15232 					verbose(env, "direct value offset of %u is not allowed\n", off);
15233 					fdput(f);
15234 					return -EINVAL;
15235 				}
15236 
15237 				if (!map->ops->map_direct_value_addr) {
15238 					verbose(env, "no direct value access support for this map type\n");
15239 					fdput(f);
15240 					return -EINVAL;
15241 				}
15242 
15243 				err = map->ops->map_direct_value_addr(map, &addr, off);
15244 				if (err) {
15245 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15246 						map->value_size, off);
15247 					fdput(f);
15248 					return err;
15249 				}
15250 
15251 				aux->map_off = off;
15252 				addr += off;
15253 			}
15254 
15255 			insn[0].imm = (u32)addr;
15256 			insn[1].imm = addr >> 32;
15257 
15258 			/* check whether we recorded this map already */
15259 			for (j = 0; j < env->used_map_cnt; j++) {
15260 				if (env->used_maps[j] == map) {
15261 					aux->map_index = j;
15262 					fdput(f);
15263 					goto next_insn;
15264 				}
15265 			}
15266 
15267 			if (env->used_map_cnt >= MAX_USED_MAPS) {
15268 				fdput(f);
15269 				return -E2BIG;
15270 			}
15271 
15272 			/* hold the map. If the program is rejected by verifier,
15273 			 * the map will be released by release_maps() or it
15274 			 * will be used by the valid program until it's unloaded
15275 			 * and all maps are released in free_used_maps()
15276 			 */
15277 			bpf_map_inc(map);
15278 
15279 			aux->map_index = env->used_map_cnt;
15280 			env->used_maps[env->used_map_cnt++] = map;
15281 
15282 			if (bpf_map_is_cgroup_storage(map) &&
15283 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
15284 				verbose(env, "only one cgroup storage of each type is allowed\n");
15285 				fdput(f);
15286 				return -EBUSY;
15287 			}
15288 
15289 			fdput(f);
15290 next_insn:
15291 			insn++;
15292 			i++;
15293 			continue;
15294 		}
15295 
15296 		/* Basic sanity check before we invest more work here. */
15297 		if (!bpf_opcode_in_insntable(insn->code)) {
15298 			verbose(env, "unknown opcode %02x\n", insn->code);
15299 			return -EINVAL;
15300 		}
15301 	}
15302 
15303 	/* now all pseudo BPF_LD_IMM64 instructions load valid
15304 	 * 'struct bpf_map *' into a register instead of user map_fd.
15305 	 * These pointers will be used later by verifier to validate map access.
15306 	 */
15307 	return 0;
15308 }
15309 
15310 /* drop refcnt of maps used by the rejected program */
15311 static void release_maps(struct bpf_verifier_env *env)
15312 {
15313 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
15314 			     env->used_map_cnt);
15315 }
15316 
15317 /* drop refcnt of maps used by the rejected program */
15318 static void release_btfs(struct bpf_verifier_env *env)
15319 {
15320 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15321 			     env->used_btf_cnt);
15322 }
15323 
15324 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15325 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15326 {
15327 	struct bpf_insn *insn = env->prog->insnsi;
15328 	int insn_cnt = env->prog->len;
15329 	int i;
15330 
15331 	for (i = 0; i < insn_cnt; i++, insn++) {
15332 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15333 			continue;
15334 		if (insn->src_reg == BPF_PSEUDO_FUNC)
15335 			continue;
15336 		insn->src_reg = 0;
15337 	}
15338 }
15339 
15340 /* single env->prog->insni[off] instruction was replaced with the range
15341  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
15342  * [0, off) and [off, end) to new locations, so the patched range stays zero
15343  */
15344 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15345 				 struct bpf_insn_aux_data *new_data,
15346 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
15347 {
15348 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15349 	struct bpf_insn *insn = new_prog->insnsi;
15350 	u32 old_seen = old_data[off].seen;
15351 	u32 prog_len;
15352 	int i;
15353 
15354 	/* aux info at OFF always needs adjustment, no matter fast path
15355 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15356 	 * original insn at old prog.
15357 	 */
15358 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15359 
15360 	if (cnt == 1)
15361 		return;
15362 	prog_len = new_prog->len;
15363 
15364 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15365 	memcpy(new_data + off + cnt - 1, old_data + off,
15366 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15367 	for (i = off; i < off + cnt - 1; i++) {
15368 		/* Expand insni[off]'s seen count to the patched range. */
15369 		new_data[i].seen = old_seen;
15370 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
15371 	}
15372 	env->insn_aux_data = new_data;
15373 	vfree(old_data);
15374 }
15375 
15376 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15377 {
15378 	int i;
15379 
15380 	if (len == 1)
15381 		return;
15382 	/* NOTE: fake 'exit' subprog should be updated as well. */
15383 	for (i = 0; i <= env->subprog_cnt; i++) {
15384 		if (env->subprog_info[i].start <= off)
15385 			continue;
15386 		env->subprog_info[i].start += len - 1;
15387 	}
15388 }
15389 
15390 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15391 {
15392 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15393 	int i, sz = prog->aux->size_poke_tab;
15394 	struct bpf_jit_poke_descriptor *desc;
15395 
15396 	for (i = 0; i < sz; i++) {
15397 		desc = &tab[i];
15398 		if (desc->insn_idx <= off)
15399 			continue;
15400 		desc->insn_idx += len - 1;
15401 	}
15402 }
15403 
15404 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15405 					    const struct bpf_insn *patch, u32 len)
15406 {
15407 	struct bpf_prog *new_prog;
15408 	struct bpf_insn_aux_data *new_data = NULL;
15409 
15410 	if (len > 1) {
15411 		new_data = vzalloc(array_size(env->prog->len + len - 1,
15412 					      sizeof(struct bpf_insn_aux_data)));
15413 		if (!new_data)
15414 			return NULL;
15415 	}
15416 
15417 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15418 	if (IS_ERR(new_prog)) {
15419 		if (PTR_ERR(new_prog) == -ERANGE)
15420 			verbose(env,
15421 				"insn %d cannot be patched due to 16-bit range\n",
15422 				env->insn_aux_data[off].orig_idx);
15423 		vfree(new_data);
15424 		return NULL;
15425 	}
15426 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
15427 	adjust_subprog_starts(env, off, len);
15428 	adjust_poke_descs(new_prog, off, len);
15429 	return new_prog;
15430 }
15431 
15432 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15433 					      u32 off, u32 cnt)
15434 {
15435 	int i, j;
15436 
15437 	/* find first prog starting at or after off (first to remove) */
15438 	for (i = 0; i < env->subprog_cnt; i++)
15439 		if (env->subprog_info[i].start >= off)
15440 			break;
15441 	/* find first prog starting at or after off + cnt (first to stay) */
15442 	for (j = i; j < env->subprog_cnt; j++)
15443 		if (env->subprog_info[j].start >= off + cnt)
15444 			break;
15445 	/* if j doesn't start exactly at off + cnt, we are just removing
15446 	 * the front of previous prog
15447 	 */
15448 	if (env->subprog_info[j].start != off + cnt)
15449 		j--;
15450 
15451 	if (j > i) {
15452 		struct bpf_prog_aux *aux = env->prog->aux;
15453 		int move;
15454 
15455 		/* move fake 'exit' subprog as well */
15456 		move = env->subprog_cnt + 1 - j;
15457 
15458 		memmove(env->subprog_info + i,
15459 			env->subprog_info + j,
15460 			sizeof(*env->subprog_info) * move);
15461 		env->subprog_cnt -= j - i;
15462 
15463 		/* remove func_info */
15464 		if (aux->func_info) {
15465 			move = aux->func_info_cnt - j;
15466 
15467 			memmove(aux->func_info + i,
15468 				aux->func_info + j,
15469 				sizeof(*aux->func_info) * move);
15470 			aux->func_info_cnt -= j - i;
15471 			/* func_info->insn_off is set after all code rewrites,
15472 			 * in adjust_btf_func() - no need to adjust
15473 			 */
15474 		}
15475 	} else {
15476 		/* convert i from "first prog to remove" to "first to adjust" */
15477 		if (env->subprog_info[i].start == off)
15478 			i++;
15479 	}
15480 
15481 	/* update fake 'exit' subprog as well */
15482 	for (; i <= env->subprog_cnt; i++)
15483 		env->subprog_info[i].start -= cnt;
15484 
15485 	return 0;
15486 }
15487 
15488 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15489 				      u32 cnt)
15490 {
15491 	struct bpf_prog *prog = env->prog;
15492 	u32 i, l_off, l_cnt, nr_linfo;
15493 	struct bpf_line_info *linfo;
15494 
15495 	nr_linfo = prog->aux->nr_linfo;
15496 	if (!nr_linfo)
15497 		return 0;
15498 
15499 	linfo = prog->aux->linfo;
15500 
15501 	/* find first line info to remove, count lines to be removed */
15502 	for (i = 0; i < nr_linfo; i++)
15503 		if (linfo[i].insn_off >= off)
15504 			break;
15505 
15506 	l_off = i;
15507 	l_cnt = 0;
15508 	for (; i < nr_linfo; i++)
15509 		if (linfo[i].insn_off < off + cnt)
15510 			l_cnt++;
15511 		else
15512 			break;
15513 
15514 	/* First live insn doesn't match first live linfo, it needs to "inherit"
15515 	 * last removed linfo.  prog is already modified, so prog->len == off
15516 	 * means no live instructions after (tail of the program was removed).
15517 	 */
15518 	if (prog->len != off && l_cnt &&
15519 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15520 		l_cnt--;
15521 		linfo[--i].insn_off = off + cnt;
15522 	}
15523 
15524 	/* remove the line info which refer to the removed instructions */
15525 	if (l_cnt) {
15526 		memmove(linfo + l_off, linfo + i,
15527 			sizeof(*linfo) * (nr_linfo - i));
15528 
15529 		prog->aux->nr_linfo -= l_cnt;
15530 		nr_linfo = prog->aux->nr_linfo;
15531 	}
15532 
15533 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
15534 	for (i = l_off; i < nr_linfo; i++)
15535 		linfo[i].insn_off -= cnt;
15536 
15537 	/* fix up all subprogs (incl. 'exit') which start >= off */
15538 	for (i = 0; i <= env->subprog_cnt; i++)
15539 		if (env->subprog_info[i].linfo_idx > l_off) {
15540 			/* program may have started in the removed region but
15541 			 * may not be fully removed
15542 			 */
15543 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15544 				env->subprog_info[i].linfo_idx -= l_cnt;
15545 			else
15546 				env->subprog_info[i].linfo_idx = l_off;
15547 		}
15548 
15549 	return 0;
15550 }
15551 
15552 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15553 {
15554 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15555 	unsigned int orig_prog_len = env->prog->len;
15556 	int err;
15557 
15558 	if (bpf_prog_is_offloaded(env->prog->aux))
15559 		bpf_prog_offload_remove_insns(env, off, cnt);
15560 
15561 	err = bpf_remove_insns(env->prog, off, cnt);
15562 	if (err)
15563 		return err;
15564 
15565 	err = adjust_subprog_starts_after_remove(env, off, cnt);
15566 	if (err)
15567 		return err;
15568 
15569 	err = bpf_adj_linfo_after_remove(env, off, cnt);
15570 	if (err)
15571 		return err;
15572 
15573 	memmove(aux_data + off,	aux_data + off + cnt,
15574 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
15575 
15576 	return 0;
15577 }
15578 
15579 /* The verifier does more data flow analysis than llvm and will not
15580  * explore branches that are dead at run time. Malicious programs can
15581  * have dead code too. Therefore replace all dead at-run-time code
15582  * with 'ja -1'.
15583  *
15584  * Just nops are not optimal, e.g. if they would sit at the end of the
15585  * program and through another bug we would manage to jump there, then
15586  * we'd execute beyond program memory otherwise. Returning exception
15587  * code also wouldn't work since we can have subprogs where the dead
15588  * code could be located.
15589  */
15590 static void sanitize_dead_code(struct bpf_verifier_env *env)
15591 {
15592 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15593 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15594 	struct bpf_insn *insn = env->prog->insnsi;
15595 	const int insn_cnt = env->prog->len;
15596 	int i;
15597 
15598 	for (i = 0; i < insn_cnt; i++) {
15599 		if (aux_data[i].seen)
15600 			continue;
15601 		memcpy(insn + i, &trap, sizeof(trap));
15602 		aux_data[i].zext_dst = false;
15603 	}
15604 }
15605 
15606 static bool insn_is_cond_jump(u8 code)
15607 {
15608 	u8 op;
15609 
15610 	if (BPF_CLASS(code) == BPF_JMP32)
15611 		return true;
15612 
15613 	if (BPF_CLASS(code) != BPF_JMP)
15614 		return false;
15615 
15616 	op = BPF_OP(code);
15617 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15618 }
15619 
15620 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15621 {
15622 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15623 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15624 	struct bpf_insn *insn = env->prog->insnsi;
15625 	const int insn_cnt = env->prog->len;
15626 	int i;
15627 
15628 	for (i = 0; i < insn_cnt; i++, insn++) {
15629 		if (!insn_is_cond_jump(insn->code))
15630 			continue;
15631 
15632 		if (!aux_data[i + 1].seen)
15633 			ja.off = insn->off;
15634 		else if (!aux_data[i + 1 + insn->off].seen)
15635 			ja.off = 0;
15636 		else
15637 			continue;
15638 
15639 		if (bpf_prog_is_offloaded(env->prog->aux))
15640 			bpf_prog_offload_replace_insn(env, i, &ja);
15641 
15642 		memcpy(insn, &ja, sizeof(ja));
15643 	}
15644 }
15645 
15646 static int opt_remove_dead_code(struct bpf_verifier_env *env)
15647 {
15648 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15649 	int insn_cnt = env->prog->len;
15650 	int i, err;
15651 
15652 	for (i = 0; i < insn_cnt; i++) {
15653 		int j;
15654 
15655 		j = 0;
15656 		while (i + j < insn_cnt && !aux_data[i + j].seen)
15657 			j++;
15658 		if (!j)
15659 			continue;
15660 
15661 		err = verifier_remove_insns(env, i, j);
15662 		if (err)
15663 			return err;
15664 		insn_cnt = env->prog->len;
15665 	}
15666 
15667 	return 0;
15668 }
15669 
15670 static int opt_remove_nops(struct bpf_verifier_env *env)
15671 {
15672 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15673 	struct bpf_insn *insn = env->prog->insnsi;
15674 	int insn_cnt = env->prog->len;
15675 	int i, err;
15676 
15677 	for (i = 0; i < insn_cnt; i++) {
15678 		if (memcmp(&insn[i], &ja, sizeof(ja)))
15679 			continue;
15680 
15681 		err = verifier_remove_insns(env, i, 1);
15682 		if (err)
15683 			return err;
15684 		insn_cnt--;
15685 		i--;
15686 	}
15687 
15688 	return 0;
15689 }
15690 
15691 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
15692 					 const union bpf_attr *attr)
15693 {
15694 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
15695 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15696 	int i, patch_len, delta = 0, len = env->prog->len;
15697 	struct bpf_insn *insns = env->prog->insnsi;
15698 	struct bpf_prog *new_prog;
15699 	bool rnd_hi32;
15700 
15701 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
15702 	zext_patch[1] = BPF_ZEXT_REG(0);
15703 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
15704 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
15705 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
15706 	for (i = 0; i < len; i++) {
15707 		int adj_idx = i + delta;
15708 		struct bpf_insn insn;
15709 		int load_reg;
15710 
15711 		insn = insns[adj_idx];
15712 		load_reg = insn_def_regno(&insn);
15713 		if (!aux[adj_idx].zext_dst) {
15714 			u8 code, class;
15715 			u32 imm_rnd;
15716 
15717 			if (!rnd_hi32)
15718 				continue;
15719 
15720 			code = insn.code;
15721 			class = BPF_CLASS(code);
15722 			if (load_reg == -1)
15723 				continue;
15724 
15725 			/* NOTE: arg "reg" (the fourth one) is only used for
15726 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
15727 			 *       here.
15728 			 */
15729 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
15730 				if (class == BPF_LD &&
15731 				    BPF_MODE(code) == BPF_IMM)
15732 					i++;
15733 				continue;
15734 			}
15735 
15736 			/* ctx load could be transformed into wider load. */
15737 			if (class == BPF_LDX &&
15738 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
15739 				continue;
15740 
15741 			imm_rnd = get_random_u32();
15742 			rnd_hi32_patch[0] = insn;
15743 			rnd_hi32_patch[1].imm = imm_rnd;
15744 			rnd_hi32_patch[3].dst_reg = load_reg;
15745 			patch = rnd_hi32_patch;
15746 			patch_len = 4;
15747 			goto apply_patch_buffer;
15748 		}
15749 
15750 		/* Add in an zero-extend instruction if a) the JIT has requested
15751 		 * it or b) it's a CMPXCHG.
15752 		 *
15753 		 * The latter is because: BPF_CMPXCHG always loads a value into
15754 		 * R0, therefore always zero-extends. However some archs'
15755 		 * equivalent instruction only does this load when the
15756 		 * comparison is successful. This detail of CMPXCHG is
15757 		 * orthogonal to the general zero-extension behaviour of the
15758 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
15759 		 */
15760 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
15761 			continue;
15762 
15763 		/* Zero-extension is done by the caller. */
15764 		if (bpf_pseudo_kfunc_call(&insn))
15765 			continue;
15766 
15767 		if (WARN_ON(load_reg == -1)) {
15768 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
15769 			return -EFAULT;
15770 		}
15771 
15772 		zext_patch[0] = insn;
15773 		zext_patch[1].dst_reg = load_reg;
15774 		zext_patch[1].src_reg = load_reg;
15775 		patch = zext_patch;
15776 		patch_len = 2;
15777 apply_patch_buffer:
15778 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
15779 		if (!new_prog)
15780 			return -ENOMEM;
15781 		env->prog = new_prog;
15782 		insns = new_prog->insnsi;
15783 		aux = env->insn_aux_data;
15784 		delta += patch_len - 1;
15785 	}
15786 
15787 	return 0;
15788 }
15789 
15790 /* convert load instructions that access fields of a context type into a
15791  * sequence of instructions that access fields of the underlying structure:
15792  *     struct __sk_buff    -> struct sk_buff
15793  *     struct bpf_sock_ops -> struct sock
15794  */
15795 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15796 {
15797 	const struct bpf_verifier_ops *ops = env->ops;
15798 	int i, cnt, size, ctx_field_size, delta = 0;
15799 	const int insn_cnt = env->prog->len;
15800 	struct bpf_insn insn_buf[16], *insn;
15801 	u32 target_size, size_default, off;
15802 	struct bpf_prog *new_prog;
15803 	enum bpf_access_type type;
15804 	bool is_narrower_load;
15805 
15806 	if (ops->gen_prologue || env->seen_direct_write) {
15807 		if (!ops->gen_prologue) {
15808 			verbose(env, "bpf verifier is misconfigured\n");
15809 			return -EINVAL;
15810 		}
15811 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15812 					env->prog);
15813 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15814 			verbose(env, "bpf verifier is misconfigured\n");
15815 			return -EINVAL;
15816 		} else if (cnt) {
15817 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15818 			if (!new_prog)
15819 				return -ENOMEM;
15820 
15821 			env->prog = new_prog;
15822 			delta += cnt - 1;
15823 		}
15824 	}
15825 
15826 	if (bpf_prog_is_offloaded(env->prog->aux))
15827 		return 0;
15828 
15829 	insn = env->prog->insnsi + delta;
15830 
15831 	for (i = 0; i < insn_cnt; i++, insn++) {
15832 		bpf_convert_ctx_access_t convert_ctx_access;
15833 		bool ctx_access;
15834 
15835 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15836 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15837 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15838 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15839 			type = BPF_READ;
15840 			ctx_access = true;
15841 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15842 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15843 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15844 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15845 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15846 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15847 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15848 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15849 			type = BPF_WRITE;
15850 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15851 		} else {
15852 			continue;
15853 		}
15854 
15855 		if (type == BPF_WRITE &&
15856 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15857 			struct bpf_insn patch[] = {
15858 				*insn,
15859 				BPF_ST_NOSPEC(),
15860 			};
15861 
15862 			cnt = ARRAY_SIZE(patch);
15863 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15864 			if (!new_prog)
15865 				return -ENOMEM;
15866 
15867 			delta    += cnt - 1;
15868 			env->prog = new_prog;
15869 			insn      = new_prog->insnsi + i + delta;
15870 			continue;
15871 		}
15872 
15873 		if (!ctx_access)
15874 			continue;
15875 
15876 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15877 		case PTR_TO_CTX:
15878 			if (!ops->convert_ctx_access)
15879 				continue;
15880 			convert_ctx_access = ops->convert_ctx_access;
15881 			break;
15882 		case PTR_TO_SOCKET:
15883 		case PTR_TO_SOCK_COMMON:
15884 			convert_ctx_access = bpf_sock_convert_ctx_access;
15885 			break;
15886 		case PTR_TO_TCP_SOCK:
15887 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15888 			break;
15889 		case PTR_TO_XDP_SOCK:
15890 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15891 			break;
15892 		case PTR_TO_BTF_ID:
15893 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15894 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15895 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15896 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15897 		 * any faults for loads into such types. BPF_WRITE is disallowed
15898 		 * for this case.
15899 		 */
15900 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15901 			if (type == BPF_READ) {
15902 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15903 					BPF_SIZE((insn)->code);
15904 				env->prog->aux->num_exentries++;
15905 			}
15906 			continue;
15907 		default:
15908 			continue;
15909 		}
15910 
15911 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15912 		size = BPF_LDST_BYTES(insn);
15913 
15914 		/* If the read access is a narrower load of the field,
15915 		 * convert to a 4/8-byte load, to minimum program type specific
15916 		 * convert_ctx_access changes. If conversion is successful,
15917 		 * we will apply proper mask to the result.
15918 		 */
15919 		is_narrower_load = size < ctx_field_size;
15920 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15921 		off = insn->off;
15922 		if (is_narrower_load) {
15923 			u8 size_code;
15924 
15925 			if (type == BPF_WRITE) {
15926 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15927 				return -EINVAL;
15928 			}
15929 
15930 			size_code = BPF_H;
15931 			if (ctx_field_size == 4)
15932 				size_code = BPF_W;
15933 			else if (ctx_field_size == 8)
15934 				size_code = BPF_DW;
15935 
15936 			insn->off = off & ~(size_default - 1);
15937 			insn->code = BPF_LDX | BPF_MEM | size_code;
15938 		}
15939 
15940 		target_size = 0;
15941 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15942 					 &target_size);
15943 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15944 		    (ctx_field_size && !target_size)) {
15945 			verbose(env, "bpf verifier is misconfigured\n");
15946 			return -EINVAL;
15947 		}
15948 
15949 		if (is_narrower_load && size < target_size) {
15950 			u8 shift = bpf_ctx_narrow_access_offset(
15951 				off, size, size_default) * 8;
15952 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15953 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15954 				return -EINVAL;
15955 			}
15956 			if (ctx_field_size <= 4) {
15957 				if (shift)
15958 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15959 									insn->dst_reg,
15960 									shift);
15961 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15962 								(1 << size * 8) - 1);
15963 			} else {
15964 				if (shift)
15965 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15966 									insn->dst_reg,
15967 									shift);
15968 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15969 								(1ULL << size * 8) - 1);
15970 			}
15971 		}
15972 
15973 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15974 		if (!new_prog)
15975 			return -ENOMEM;
15976 
15977 		delta += cnt - 1;
15978 
15979 		/* keep walking new program and skip insns we just inserted */
15980 		env->prog = new_prog;
15981 		insn      = new_prog->insnsi + i + delta;
15982 	}
15983 
15984 	return 0;
15985 }
15986 
15987 static int jit_subprogs(struct bpf_verifier_env *env)
15988 {
15989 	struct bpf_prog *prog = env->prog, **func, *tmp;
15990 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15991 	struct bpf_map *map_ptr;
15992 	struct bpf_insn *insn;
15993 	void *old_bpf_func;
15994 	int err, num_exentries;
15995 
15996 	if (env->subprog_cnt <= 1)
15997 		return 0;
15998 
15999 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16000 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
16001 			continue;
16002 
16003 		/* Upon error here we cannot fall back to interpreter but
16004 		 * need a hard reject of the program. Thus -EFAULT is
16005 		 * propagated in any case.
16006 		 */
16007 		subprog = find_subprog(env, i + insn->imm + 1);
16008 		if (subprog < 0) {
16009 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
16010 				  i + insn->imm + 1);
16011 			return -EFAULT;
16012 		}
16013 		/* temporarily remember subprog id inside insn instead of
16014 		 * aux_data, since next loop will split up all insns into funcs
16015 		 */
16016 		insn->off = subprog;
16017 		/* remember original imm in case JIT fails and fallback
16018 		 * to interpreter will be needed
16019 		 */
16020 		env->insn_aux_data[i].call_imm = insn->imm;
16021 		/* point imm to __bpf_call_base+1 from JITs point of view */
16022 		insn->imm = 1;
16023 		if (bpf_pseudo_func(insn))
16024 			/* jit (e.g. x86_64) may emit fewer instructions
16025 			 * if it learns a u32 imm is the same as a u64 imm.
16026 			 * Force a non zero here.
16027 			 */
16028 			insn[1].imm = 1;
16029 	}
16030 
16031 	err = bpf_prog_alloc_jited_linfo(prog);
16032 	if (err)
16033 		goto out_undo_insn;
16034 
16035 	err = -ENOMEM;
16036 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16037 	if (!func)
16038 		goto out_undo_insn;
16039 
16040 	for (i = 0; i < env->subprog_cnt; i++) {
16041 		subprog_start = subprog_end;
16042 		subprog_end = env->subprog_info[i + 1].start;
16043 
16044 		len = subprog_end - subprog_start;
16045 		/* bpf_prog_run() doesn't call subprogs directly,
16046 		 * hence main prog stats include the runtime of subprogs.
16047 		 * subprogs don't have IDs and not reachable via prog_get_next_id
16048 		 * func[i]->stats will never be accessed and stays NULL
16049 		 */
16050 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16051 		if (!func[i])
16052 			goto out_free;
16053 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16054 		       len * sizeof(struct bpf_insn));
16055 		func[i]->type = prog->type;
16056 		func[i]->len = len;
16057 		if (bpf_prog_calc_tag(func[i]))
16058 			goto out_free;
16059 		func[i]->is_func = 1;
16060 		func[i]->aux->func_idx = i;
16061 		/* Below members will be freed only at prog->aux */
16062 		func[i]->aux->btf = prog->aux->btf;
16063 		func[i]->aux->func_info = prog->aux->func_info;
16064 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16065 		func[i]->aux->poke_tab = prog->aux->poke_tab;
16066 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16067 
16068 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
16069 			struct bpf_jit_poke_descriptor *poke;
16070 
16071 			poke = &prog->aux->poke_tab[j];
16072 			if (poke->insn_idx < subprog_end &&
16073 			    poke->insn_idx >= subprog_start)
16074 				poke->aux = func[i]->aux;
16075 		}
16076 
16077 		func[i]->aux->name[0] = 'F';
16078 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16079 		func[i]->jit_requested = 1;
16080 		func[i]->blinding_requested = prog->blinding_requested;
16081 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16082 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16083 		func[i]->aux->linfo = prog->aux->linfo;
16084 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16085 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16086 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16087 		num_exentries = 0;
16088 		insn = func[i]->insnsi;
16089 		for (j = 0; j < func[i]->len; j++, insn++) {
16090 			if (BPF_CLASS(insn->code) == BPF_LDX &&
16091 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
16092 				num_exentries++;
16093 		}
16094 		func[i]->aux->num_exentries = num_exentries;
16095 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16096 		func[i] = bpf_int_jit_compile(func[i]);
16097 		if (!func[i]->jited) {
16098 			err = -ENOTSUPP;
16099 			goto out_free;
16100 		}
16101 		cond_resched();
16102 	}
16103 
16104 	/* at this point all bpf functions were successfully JITed
16105 	 * now populate all bpf_calls with correct addresses and
16106 	 * run last pass of JIT
16107 	 */
16108 	for (i = 0; i < env->subprog_cnt; i++) {
16109 		insn = func[i]->insnsi;
16110 		for (j = 0; j < func[i]->len; j++, insn++) {
16111 			if (bpf_pseudo_func(insn)) {
16112 				subprog = insn->off;
16113 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16114 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16115 				continue;
16116 			}
16117 			if (!bpf_pseudo_call(insn))
16118 				continue;
16119 			subprog = insn->off;
16120 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16121 		}
16122 
16123 		/* we use the aux data to keep a list of the start addresses
16124 		 * of the JITed images for each function in the program
16125 		 *
16126 		 * for some architectures, such as powerpc64, the imm field
16127 		 * might not be large enough to hold the offset of the start
16128 		 * address of the callee's JITed image from __bpf_call_base
16129 		 *
16130 		 * in such cases, we can lookup the start address of a callee
16131 		 * by using its subprog id, available from the off field of
16132 		 * the call instruction, as an index for this list
16133 		 */
16134 		func[i]->aux->func = func;
16135 		func[i]->aux->func_cnt = env->subprog_cnt;
16136 	}
16137 	for (i = 0; i < env->subprog_cnt; i++) {
16138 		old_bpf_func = func[i]->bpf_func;
16139 		tmp = bpf_int_jit_compile(func[i]);
16140 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16141 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16142 			err = -ENOTSUPP;
16143 			goto out_free;
16144 		}
16145 		cond_resched();
16146 	}
16147 
16148 	/* finally lock prog and jit images for all functions and
16149 	 * populate kallsysm
16150 	 */
16151 	for (i = 0; i < env->subprog_cnt; i++) {
16152 		bpf_prog_lock_ro(func[i]);
16153 		bpf_prog_kallsyms_add(func[i]);
16154 	}
16155 
16156 	/* Last step: make now unused interpreter insns from main
16157 	 * prog consistent for later dump requests, so they can
16158 	 * later look the same as if they were interpreted only.
16159 	 */
16160 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16161 		if (bpf_pseudo_func(insn)) {
16162 			insn[0].imm = env->insn_aux_data[i].call_imm;
16163 			insn[1].imm = insn->off;
16164 			insn->off = 0;
16165 			continue;
16166 		}
16167 		if (!bpf_pseudo_call(insn))
16168 			continue;
16169 		insn->off = env->insn_aux_data[i].call_imm;
16170 		subprog = find_subprog(env, i + insn->off + 1);
16171 		insn->imm = subprog;
16172 	}
16173 
16174 	prog->jited = 1;
16175 	prog->bpf_func = func[0]->bpf_func;
16176 	prog->jited_len = func[0]->jited_len;
16177 	prog->aux->func = func;
16178 	prog->aux->func_cnt = env->subprog_cnt;
16179 	bpf_prog_jit_attempt_done(prog);
16180 	return 0;
16181 out_free:
16182 	/* We failed JIT'ing, so at this point we need to unregister poke
16183 	 * descriptors from subprogs, so that kernel is not attempting to
16184 	 * patch it anymore as we're freeing the subprog JIT memory.
16185 	 */
16186 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16187 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16188 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16189 	}
16190 	/* At this point we're guaranteed that poke descriptors are not
16191 	 * live anymore. We can just unlink its descriptor table as it's
16192 	 * released with the main prog.
16193 	 */
16194 	for (i = 0; i < env->subprog_cnt; i++) {
16195 		if (!func[i])
16196 			continue;
16197 		func[i]->aux->poke_tab = NULL;
16198 		bpf_jit_free(func[i]);
16199 	}
16200 	kfree(func);
16201 out_undo_insn:
16202 	/* cleanup main prog to be interpreted */
16203 	prog->jit_requested = 0;
16204 	prog->blinding_requested = 0;
16205 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16206 		if (!bpf_pseudo_call(insn))
16207 			continue;
16208 		insn->off = 0;
16209 		insn->imm = env->insn_aux_data[i].call_imm;
16210 	}
16211 	bpf_prog_jit_attempt_done(prog);
16212 	return err;
16213 }
16214 
16215 static int fixup_call_args(struct bpf_verifier_env *env)
16216 {
16217 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16218 	struct bpf_prog *prog = env->prog;
16219 	struct bpf_insn *insn = prog->insnsi;
16220 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16221 	int i, depth;
16222 #endif
16223 	int err = 0;
16224 
16225 	if (env->prog->jit_requested &&
16226 	    !bpf_prog_is_offloaded(env->prog->aux)) {
16227 		err = jit_subprogs(env);
16228 		if (err == 0)
16229 			return 0;
16230 		if (err == -EFAULT)
16231 			return err;
16232 	}
16233 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16234 	if (has_kfunc_call) {
16235 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16236 		return -EINVAL;
16237 	}
16238 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16239 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
16240 		 * have to be rejected, since interpreter doesn't support them yet.
16241 		 */
16242 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16243 		return -EINVAL;
16244 	}
16245 	for (i = 0; i < prog->len; i++, insn++) {
16246 		if (bpf_pseudo_func(insn)) {
16247 			/* When JIT fails the progs with callback calls
16248 			 * have to be rejected, since interpreter doesn't support them yet.
16249 			 */
16250 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
16251 			return -EINVAL;
16252 		}
16253 
16254 		if (!bpf_pseudo_call(insn))
16255 			continue;
16256 		depth = get_callee_stack_depth(env, insn, i);
16257 		if (depth < 0)
16258 			return depth;
16259 		bpf_patch_call_args(insn, depth);
16260 	}
16261 	err = 0;
16262 #endif
16263 	return err;
16264 }
16265 
16266 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16267 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16268 {
16269 	const struct bpf_kfunc_desc *desc;
16270 	void *xdp_kfunc;
16271 
16272 	if (!insn->imm) {
16273 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16274 		return -EINVAL;
16275 	}
16276 
16277 	*cnt = 0;
16278 
16279 	if (bpf_dev_bound_kfunc_id(insn->imm)) {
16280 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16281 		if (xdp_kfunc) {
16282 			insn->imm = BPF_CALL_IMM(xdp_kfunc);
16283 			return 0;
16284 		}
16285 
16286 		/* fallback to default kfunc when not supported by netdev */
16287 	}
16288 
16289 	/* insn->imm has the btf func_id. Replace it with
16290 	 * an address (relative to __bpf_call_base).
16291 	 */
16292 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16293 	if (!desc) {
16294 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16295 			insn->imm);
16296 		return -EFAULT;
16297 	}
16298 
16299 	insn->imm = desc->imm;
16300 	if (insn->off)
16301 		return 0;
16302 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16303 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16304 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16305 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16306 
16307 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16308 		insn_buf[1] = addr[0];
16309 		insn_buf[2] = addr[1];
16310 		insn_buf[3] = *insn;
16311 		*cnt = 4;
16312 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16313 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16314 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16315 
16316 		insn_buf[0] = addr[0];
16317 		insn_buf[1] = addr[1];
16318 		insn_buf[2] = *insn;
16319 		*cnt = 3;
16320 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16321 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16322 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16323 		*cnt = 1;
16324 	}
16325 	return 0;
16326 }
16327 
16328 /* Do various post-verification rewrites in a single program pass.
16329  * These rewrites simplify JIT and interpreter implementations.
16330  */
16331 static int do_misc_fixups(struct bpf_verifier_env *env)
16332 {
16333 	struct bpf_prog *prog = env->prog;
16334 	enum bpf_attach_type eatype = prog->expected_attach_type;
16335 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16336 	struct bpf_insn *insn = prog->insnsi;
16337 	const struct bpf_func_proto *fn;
16338 	const int insn_cnt = prog->len;
16339 	const struct bpf_map_ops *ops;
16340 	struct bpf_insn_aux_data *aux;
16341 	struct bpf_insn insn_buf[16];
16342 	struct bpf_prog *new_prog;
16343 	struct bpf_map *map_ptr;
16344 	int i, ret, cnt, delta = 0;
16345 
16346 	for (i = 0; i < insn_cnt; i++, insn++) {
16347 		/* Make divide-by-zero exceptions impossible. */
16348 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16349 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16350 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16351 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16352 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16353 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16354 			struct bpf_insn *patchlet;
16355 			struct bpf_insn chk_and_div[] = {
16356 				/* [R,W]x div 0 -> 0 */
16357 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16358 					     BPF_JNE | BPF_K, insn->src_reg,
16359 					     0, 2, 0),
16360 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16361 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16362 				*insn,
16363 			};
16364 			struct bpf_insn chk_and_mod[] = {
16365 				/* [R,W]x mod 0 -> [R,W]x */
16366 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16367 					     BPF_JEQ | BPF_K, insn->src_reg,
16368 					     0, 1 + (is64 ? 0 : 1), 0),
16369 				*insn,
16370 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16371 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16372 			};
16373 
16374 			patchlet = isdiv ? chk_and_div : chk_and_mod;
16375 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16376 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16377 
16378 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16379 			if (!new_prog)
16380 				return -ENOMEM;
16381 
16382 			delta    += cnt - 1;
16383 			env->prog = prog = new_prog;
16384 			insn      = new_prog->insnsi + i + delta;
16385 			continue;
16386 		}
16387 
16388 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16389 		if (BPF_CLASS(insn->code) == BPF_LD &&
16390 		    (BPF_MODE(insn->code) == BPF_ABS ||
16391 		     BPF_MODE(insn->code) == BPF_IND)) {
16392 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
16393 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16394 				verbose(env, "bpf verifier is misconfigured\n");
16395 				return -EINVAL;
16396 			}
16397 
16398 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16399 			if (!new_prog)
16400 				return -ENOMEM;
16401 
16402 			delta    += cnt - 1;
16403 			env->prog = prog = new_prog;
16404 			insn      = new_prog->insnsi + i + delta;
16405 			continue;
16406 		}
16407 
16408 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
16409 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16410 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16411 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16412 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16413 			struct bpf_insn *patch = &insn_buf[0];
16414 			bool issrc, isneg, isimm;
16415 			u32 off_reg;
16416 
16417 			aux = &env->insn_aux_data[i + delta];
16418 			if (!aux->alu_state ||
16419 			    aux->alu_state == BPF_ALU_NON_POINTER)
16420 				continue;
16421 
16422 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16423 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16424 				BPF_ALU_SANITIZE_SRC;
16425 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16426 
16427 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
16428 			if (isimm) {
16429 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16430 			} else {
16431 				if (isneg)
16432 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16433 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16434 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16435 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16436 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16437 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16438 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16439 			}
16440 			if (!issrc)
16441 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16442 			insn->src_reg = BPF_REG_AX;
16443 			if (isneg)
16444 				insn->code = insn->code == code_add ?
16445 					     code_sub : code_add;
16446 			*patch++ = *insn;
16447 			if (issrc && isneg && !isimm)
16448 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16449 			cnt = patch - insn_buf;
16450 
16451 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16452 			if (!new_prog)
16453 				return -ENOMEM;
16454 
16455 			delta    += cnt - 1;
16456 			env->prog = prog = new_prog;
16457 			insn      = new_prog->insnsi + i + delta;
16458 			continue;
16459 		}
16460 
16461 		if (insn->code != (BPF_JMP | BPF_CALL))
16462 			continue;
16463 		if (insn->src_reg == BPF_PSEUDO_CALL)
16464 			continue;
16465 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16466 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16467 			if (ret)
16468 				return ret;
16469 			if (cnt == 0)
16470 				continue;
16471 
16472 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16473 			if (!new_prog)
16474 				return -ENOMEM;
16475 
16476 			delta	 += cnt - 1;
16477 			env->prog = prog = new_prog;
16478 			insn	  = new_prog->insnsi + i + delta;
16479 			continue;
16480 		}
16481 
16482 		if (insn->imm == BPF_FUNC_get_route_realm)
16483 			prog->dst_needed = 1;
16484 		if (insn->imm == BPF_FUNC_get_prandom_u32)
16485 			bpf_user_rnd_init_once();
16486 		if (insn->imm == BPF_FUNC_override_return)
16487 			prog->kprobe_override = 1;
16488 		if (insn->imm == BPF_FUNC_tail_call) {
16489 			/* If we tail call into other programs, we
16490 			 * cannot make any assumptions since they can
16491 			 * be replaced dynamically during runtime in
16492 			 * the program array.
16493 			 */
16494 			prog->cb_access = 1;
16495 			if (!allow_tail_call_in_subprogs(env))
16496 				prog->aux->stack_depth = MAX_BPF_STACK;
16497 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16498 
16499 			/* mark bpf_tail_call as different opcode to avoid
16500 			 * conditional branch in the interpreter for every normal
16501 			 * call and to prevent accidental JITing by JIT compiler
16502 			 * that doesn't support bpf_tail_call yet
16503 			 */
16504 			insn->imm = 0;
16505 			insn->code = BPF_JMP | BPF_TAIL_CALL;
16506 
16507 			aux = &env->insn_aux_data[i + delta];
16508 			if (env->bpf_capable && !prog->blinding_requested &&
16509 			    prog->jit_requested &&
16510 			    !bpf_map_key_poisoned(aux) &&
16511 			    !bpf_map_ptr_poisoned(aux) &&
16512 			    !bpf_map_ptr_unpriv(aux)) {
16513 				struct bpf_jit_poke_descriptor desc = {
16514 					.reason = BPF_POKE_REASON_TAIL_CALL,
16515 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16516 					.tail_call.key = bpf_map_key_immediate(aux),
16517 					.insn_idx = i + delta,
16518 				};
16519 
16520 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
16521 				if (ret < 0) {
16522 					verbose(env, "adding tail call poke descriptor failed\n");
16523 					return ret;
16524 				}
16525 
16526 				insn->imm = ret + 1;
16527 				continue;
16528 			}
16529 
16530 			if (!bpf_map_ptr_unpriv(aux))
16531 				continue;
16532 
16533 			/* instead of changing every JIT dealing with tail_call
16534 			 * emit two extra insns:
16535 			 * if (index >= max_entries) goto out;
16536 			 * index &= array->index_mask;
16537 			 * to avoid out-of-bounds cpu speculation
16538 			 */
16539 			if (bpf_map_ptr_poisoned(aux)) {
16540 				verbose(env, "tail_call abusing map_ptr\n");
16541 				return -EINVAL;
16542 			}
16543 
16544 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16545 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16546 						  map_ptr->max_entries, 2);
16547 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16548 						    container_of(map_ptr,
16549 								 struct bpf_array,
16550 								 map)->index_mask);
16551 			insn_buf[2] = *insn;
16552 			cnt = 3;
16553 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16554 			if (!new_prog)
16555 				return -ENOMEM;
16556 
16557 			delta    += cnt - 1;
16558 			env->prog = prog = new_prog;
16559 			insn      = new_prog->insnsi + i + delta;
16560 			continue;
16561 		}
16562 
16563 		if (insn->imm == BPF_FUNC_timer_set_callback) {
16564 			/* The verifier will process callback_fn as many times as necessary
16565 			 * with different maps and the register states prepared by
16566 			 * set_timer_callback_state will be accurate.
16567 			 *
16568 			 * The following use case is valid:
16569 			 *   map1 is shared by prog1, prog2, prog3.
16570 			 *   prog1 calls bpf_timer_init for some map1 elements
16571 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
16572 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
16573 			 *   prog3 calls bpf_timer_start for some map1 elements.
16574 			 *     Those that were not both bpf_timer_init-ed and
16575 			 *     bpf_timer_set_callback-ed will return -EINVAL.
16576 			 */
16577 			struct bpf_insn ld_addrs[2] = {
16578 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16579 			};
16580 
16581 			insn_buf[0] = ld_addrs[0];
16582 			insn_buf[1] = ld_addrs[1];
16583 			insn_buf[2] = *insn;
16584 			cnt = 3;
16585 
16586 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16587 			if (!new_prog)
16588 				return -ENOMEM;
16589 
16590 			delta    += cnt - 1;
16591 			env->prog = prog = new_prog;
16592 			insn      = new_prog->insnsi + i + delta;
16593 			goto patch_call_imm;
16594 		}
16595 
16596 		if (is_storage_get_function(insn->imm)) {
16597 			if (!env->prog->aux->sleepable ||
16598 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
16599 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16600 			else
16601 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16602 			insn_buf[1] = *insn;
16603 			cnt = 2;
16604 
16605 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16606 			if (!new_prog)
16607 				return -ENOMEM;
16608 
16609 			delta += cnt - 1;
16610 			env->prog = prog = new_prog;
16611 			insn = new_prog->insnsi + i + delta;
16612 			goto patch_call_imm;
16613 		}
16614 
16615 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16616 		 * and other inlining handlers are currently limited to 64 bit
16617 		 * only.
16618 		 */
16619 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16620 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
16621 		     insn->imm == BPF_FUNC_map_update_elem ||
16622 		     insn->imm == BPF_FUNC_map_delete_elem ||
16623 		     insn->imm == BPF_FUNC_map_push_elem   ||
16624 		     insn->imm == BPF_FUNC_map_pop_elem    ||
16625 		     insn->imm == BPF_FUNC_map_peek_elem   ||
16626 		     insn->imm == BPF_FUNC_redirect_map    ||
16627 		     insn->imm == BPF_FUNC_for_each_map_elem ||
16628 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16629 			aux = &env->insn_aux_data[i + delta];
16630 			if (bpf_map_ptr_poisoned(aux))
16631 				goto patch_call_imm;
16632 
16633 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16634 			ops = map_ptr->ops;
16635 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
16636 			    ops->map_gen_lookup) {
16637 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16638 				if (cnt == -EOPNOTSUPP)
16639 					goto patch_map_ops_generic;
16640 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16641 					verbose(env, "bpf verifier is misconfigured\n");
16642 					return -EINVAL;
16643 				}
16644 
16645 				new_prog = bpf_patch_insn_data(env, i + delta,
16646 							       insn_buf, cnt);
16647 				if (!new_prog)
16648 					return -ENOMEM;
16649 
16650 				delta    += cnt - 1;
16651 				env->prog = prog = new_prog;
16652 				insn      = new_prog->insnsi + i + delta;
16653 				continue;
16654 			}
16655 
16656 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
16657 				     (void *(*)(struct bpf_map *map, void *key))NULL));
16658 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
16659 				     (int (*)(struct bpf_map *map, void *key))NULL));
16660 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
16661 				     (int (*)(struct bpf_map *map, void *key, void *value,
16662 					      u64 flags))NULL));
16663 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
16664 				     (int (*)(struct bpf_map *map, void *value,
16665 					      u64 flags))NULL));
16666 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
16667 				     (int (*)(struct bpf_map *map, void *value))NULL));
16668 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
16669 				     (int (*)(struct bpf_map *map, void *value))NULL));
16670 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
16671 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
16672 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
16673 				     (int (*)(struct bpf_map *map,
16674 					      bpf_callback_t callback_fn,
16675 					      void *callback_ctx,
16676 					      u64 flags))NULL));
16677 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
16678 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
16679 
16680 patch_map_ops_generic:
16681 			switch (insn->imm) {
16682 			case BPF_FUNC_map_lookup_elem:
16683 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
16684 				continue;
16685 			case BPF_FUNC_map_update_elem:
16686 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
16687 				continue;
16688 			case BPF_FUNC_map_delete_elem:
16689 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
16690 				continue;
16691 			case BPF_FUNC_map_push_elem:
16692 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
16693 				continue;
16694 			case BPF_FUNC_map_pop_elem:
16695 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
16696 				continue;
16697 			case BPF_FUNC_map_peek_elem:
16698 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
16699 				continue;
16700 			case BPF_FUNC_redirect_map:
16701 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
16702 				continue;
16703 			case BPF_FUNC_for_each_map_elem:
16704 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
16705 				continue;
16706 			case BPF_FUNC_map_lookup_percpu_elem:
16707 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
16708 				continue;
16709 			}
16710 
16711 			goto patch_call_imm;
16712 		}
16713 
16714 		/* Implement bpf_jiffies64 inline. */
16715 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16716 		    insn->imm == BPF_FUNC_jiffies64) {
16717 			struct bpf_insn ld_jiffies_addr[2] = {
16718 				BPF_LD_IMM64(BPF_REG_0,
16719 					     (unsigned long)&jiffies),
16720 			};
16721 
16722 			insn_buf[0] = ld_jiffies_addr[0];
16723 			insn_buf[1] = ld_jiffies_addr[1];
16724 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
16725 						  BPF_REG_0, 0);
16726 			cnt = 3;
16727 
16728 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
16729 						       cnt);
16730 			if (!new_prog)
16731 				return -ENOMEM;
16732 
16733 			delta    += cnt - 1;
16734 			env->prog = prog = new_prog;
16735 			insn      = new_prog->insnsi + i + delta;
16736 			continue;
16737 		}
16738 
16739 		/* Implement bpf_get_func_arg inline. */
16740 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16741 		    insn->imm == BPF_FUNC_get_func_arg) {
16742 			/* Load nr_args from ctx - 8 */
16743 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16744 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
16745 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
16746 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
16747 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
16748 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16749 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
16750 			insn_buf[7] = BPF_JMP_A(1);
16751 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
16752 			cnt = 9;
16753 
16754 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16755 			if (!new_prog)
16756 				return -ENOMEM;
16757 
16758 			delta    += cnt - 1;
16759 			env->prog = prog = new_prog;
16760 			insn      = new_prog->insnsi + i + delta;
16761 			continue;
16762 		}
16763 
16764 		/* Implement bpf_get_func_ret inline. */
16765 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16766 		    insn->imm == BPF_FUNC_get_func_ret) {
16767 			if (eatype == BPF_TRACE_FEXIT ||
16768 			    eatype == BPF_MODIFY_RETURN) {
16769 				/* Load nr_args from ctx - 8 */
16770 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16771 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
16772 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
16773 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
16774 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
16775 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
16776 				cnt = 6;
16777 			} else {
16778 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
16779 				cnt = 1;
16780 			}
16781 
16782 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16783 			if (!new_prog)
16784 				return -ENOMEM;
16785 
16786 			delta    += cnt - 1;
16787 			env->prog = prog = new_prog;
16788 			insn      = new_prog->insnsi + i + delta;
16789 			continue;
16790 		}
16791 
16792 		/* Implement get_func_arg_cnt inline. */
16793 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16794 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
16795 			/* Load nr_args from ctx - 8 */
16796 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16797 
16798 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16799 			if (!new_prog)
16800 				return -ENOMEM;
16801 
16802 			env->prog = prog = new_prog;
16803 			insn      = new_prog->insnsi + i + delta;
16804 			continue;
16805 		}
16806 
16807 		/* Implement bpf_get_func_ip inline. */
16808 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16809 		    insn->imm == BPF_FUNC_get_func_ip) {
16810 			/* Load IP address from ctx - 16 */
16811 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16812 
16813 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16814 			if (!new_prog)
16815 				return -ENOMEM;
16816 
16817 			env->prog = prog = new_prog;
16818 			insn      = new_prog->insnsi + i + delta;
16819 			continue;
16820 		}
16821 
16822 patch_call_imm:
16823 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16824 		/* all functions that have prototype and verifier allowed
16825 		 * programs to call them, must be real in-kernel functions
16826 		 */
16827 		if (!fn->func) {
16828 			verbose(env,
16829 				"kernel subsystem misconfigured func %s#%d\n",
16830 				func_id_name(insn->imm), insn->imm);
16831 			return -EFAULT;
16832 		}
16833 		insn->imm = fn->func - __bpf_call_base;
16834 	}
16835 
16836 	/* Since poke tab is now finalized, publish aux to tracker. */
16837 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16838 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16839 		if (!map_ptr->ops->map_poke_track ||
16840 		    !map_ptr->ops->map_poke_untrack ||
16841 		    !map_ptr->ops->map_poke_run) {
16842 			verbose(env, "bpf verifier is misconfigured\n");
16843 			return -EINVAL;
16844 		}
16845 
16846 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16847 		if (ret < 0) {
16848 			verbose(env, "tracking tail call prog failed\n");
16849 			return ret;
16850 		}
16851 	}
16852 
16853 	sort_kfunc_descs_by_imm(env->prog);
16854 
16855 	return 0;
16856 }
16857 
16858 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16859 					int position,
16860 					s32 stack_base,
16861 					u32 callback_subprogno,
16862 					u32 *cnt)
16863 {
16864 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16865 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16866 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16867 	int reg_loop_max = BPF_REG_6;
16868 	int reg_loop_cnt = BPF_REG_7;
16869 	int reg_loop_ctx = BPF_REG_8;
16870 
16871 	struct bpf_prog *new_prog;
16872 	u32 callback_start;
16873 	u32 call_insn_offset;
16874 	s32 callback_offset;
16875 
16876 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16877 	 * be careful to modify this code in sync.
16878 	 */
16879 	struct bpf_insn insn_buf[] = {
16880 		/* Return error and jump to the end of the patch if
16881 		 * expected number of iterations is too big.
16882 		 */
16883 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16884 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16885 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16886 		/* spill R6, R7, R8 to use these as loop vars */
16887 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16888 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16889 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16890 		/* initialize loop vars */
16891 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16892 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16893 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16894 		/* loop header,
16895 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16896 		 */
16897 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16898 		/* callback call,
16899 		 * correct callback offset would be set after patching
16900 		 */
16901 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16902 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16903 		BPF_CALL_REL(0),
16904 		/* increment loop counter */
16905 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16906 		/* jump to loop header if callback returned 0 */
16907 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16908 		/* return value of bpf_loop,
16909 		 * set R0 to the number of iterations
16910 		 */
16911 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16912 		/* restore original values of R6, R7, R8 */
16913 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16914 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16915 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16916 	};
16917 
16918 	*cnt = ARRAY_SIZE(insn_buf);
16919 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16920 	if (!new_prog)
16921 		return new_prog;
16922 
16923 	/* callback start is known only after patching */
16924 	callback_start = env->subprog_info[callback_subprogno].start;
16925 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16926 	call_insn_offset = position + 12;
16927 	callback_offset = callback_start - call_insn_offset - 1;
16928 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16929 
16930 	return new_prog;
16931 }
16932 
16933 static bool is_bpf_loop_call(struct bpf_insn *insn)
16934 {
16935 	return insn->code == (BPF_JMP | BPF_CALL) &&
16936 		insn->src_reg == 0 &&
16937 		insn->imm == BPF_FUNC_loop;
16938 }
16939 
16940 /* For all sub-programs in the program (including main) check
16941  * insn_aux_data to see if there are bpf_loop calls that require
16942  * inlining. If such calls are found the calls are replaced with a
16943  * sequence of instructions produced by `inline_bpf_loop` function and
16944  * subprog stack_depth is increased by the size of 3 registers.
16945  * This stack space is used to spill values of the R6, R7, R8.  These
16946  * registers are used to store the loop bound, counter and context
16947  * variables.
16948  */
16949 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16950 {
16951 	struct bpf_subprog_info *subprogs = env->subprog_info;
16952 	int i, cur_subprog = 0, cnt, delta = 0;
16953 	struct bpf_insn *insn = env->prog->insnsi;
16954 	int insn_cnt = env->prog->len;
16955 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16956 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16957 	u16 stack_depth_extra = 0;
16958 
16959 	for (i = 0; i < insn_cnt; i++, insn++) {
16960 		struct bpf_loop_inline_state *inline_state =
16961 			&env->insn_aux_data[i + delta].loop_inline_state;
16962 
16963 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16964 			struct bpf_prog *new_prog;
16965 
16966 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16967 			new_prog = inline_bpf_loop(env,
16968 						   i + delta,
16969 						   -(stack_depth + stack_depth_extra),
16970 						   inline_state->callback_subprogno,
16971 						   &cnt);
16972 			if (!new_prog)
16973 				return -ENOMEM;
16974 
16975 			delta     += cnt - 1;
16976 			env->prog  = new_prog;
16977 			insn       = new_prog->insnsi + i + delta;
16978 		}
16979 
16980 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16981 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16982 			cur_subprog++;
16983 			stack_depth = subprogs[cur_subprog].stack_depth;
16984 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16985 			stack_depth_extra = 0;
16986 		}
16987 	}
16988 
16989 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16990 
16991 	return 0;
16992 }
16993 
16994 static void free_states(struct bpf_verifier_env *env)
16995 {
16996 	struct bpf_verifier_state_list *sl, *sln;
16997 	int i;
16998 
16999 	sl = env->free_list;
17000 	while (sl) {
17001 		sln = sl->next;
17002 		free_verifier_state(&sl->state, false);
17003 		kfree(sl);
17004 		sl = sln;
17005 	}
17006 	env->free_list = NULL;
17007 
17008 	if (!env->explored_states)
17009 		return;
17010 
17011 	for (i = 0; i < state_htab_size(env); i++) {
17012 		sl = env->explored_states[i];
17013 
17014 		while (sl) {
17015 			sln = sl->next;
17016 			free_verifier_state(&sl->state, false);
17017 			kfree(sl);
17018 			sl = sln;
17019 		}
17020 		env->explored_states[i] = NULL;
17021 	}
17022 }
17023 
17024 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17025 {
17026 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17027 	struct bpf_verifier_state *state;
17028 	struct bpf_reg_state *regs;
17029 	int ret, i;
17030 
17031 	env->prev_linfo = NULL;
17032 	env->pass_cnt++;
17033 
17034 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17035 	if (!state)
17036 		return -ENOMEM;
17037 	state->curframe = 0;
17038 	state->speculative = false;
17039 	state->branches = 1;
17040 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17041 	if (!state->frame[0]) {
17042 		kfree(state);
17043 		return -ENOMEM;
17044 	}
17045 	env->cur_state = state;
17046 	init_func_state(env, state->frame[0],
17047 			BPF_MAIN_FUNC /* callsite */,
17048 			0 /* frameno */,
17049 			subprog);
17050 	state->first_insn_idx = env->subprog_info[subprog].start;
17051 	state->last_insn_idx = -1;
17052 
17053 	regs = state->frame[state->curframe]->regs;
17054 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17055 		ret = btf_prepare_func_args(env, subprog, regs);
17056 		if (ret)
17057 			goto out;
17058 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17059 			if (regs[i].type == PTR_TO_CTX)
17060 				mark_reg_known_zero(env, regs, i);
17061 			else if (regs[i].type == SCALAR_VALUE)
17062 				mark_reg_unknown(env, regs, i);
17063 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
17064 				const u32 mem_size = regs[i].mem_size;
17065 
17066 				mark_reg_known_zero(env, regs, i);
17067 				regs[i].mem_size = mem_size;
17068 				regs[i].id = ++env->id_gen;
17069 			}
17070 		}
17071 	} else {
17072 		/* 1st arg to a function */
17073 		regs[BPF_REG_1].type = PTR_TO_CTX;
17074 		mark_reg_known_zero(env, regs, BPF_REG_1);
17075 		ret = btf_check_subprog_arg_match(env, subprog, regs);
17076 		if (ret == -EFAULT)
17077 			/* unlikely verifier bug. abort.
17078 			 * ret == 0 and ret < 0 are sadly acceptable for
17079 			 * main() function due to backward compatibility.
17080 			 * Like socket filter program may be written as:
17081 			 * int bpf_prog(struct pt_regs *ctx)
17082 			 * and never dereference that ctx in the program.
17083 			 * 'struct pt_regs' is a type mismatch for socket
17084 			 * filter that should be using 'struct __sk_buff'.
17085 			 */
17086 			goto out;
17087 	}
17088 
17089 	ret = do_check(env);
17090 out:
17091 	/* check for NULL is necessary, since cur_state can be freed inside
17092 	 * do_check() under memory pressure.
17093 	 */
17094 	if (env->cur_state) {
17095 		free_verifier_state(env->cur_state, true);
17096 		env->cur_state = NULL;
17097 	}
17098 	while (!pop_stack(env, NULL, NULL, false));
17099 	if (!ret && pop_log)
17100 		bpf_vlog_reset(&env->log, 0);
17101 	free_states(env);
17102 	return ret;
17103 }
17104 
17105 /* Verify all global functions in a BPF program one by one based on their BTF.
17106  * All global functions must pass verification. Otherwise the whole program is rejected.
17107  * Consider:
17108  * int bar(int);
17109  * int foo(int f)
17110  * {
17111  *    return bar(f);
17112  * }
17113  * int bar(int b)
17114  * {
17115  *    ...
17116  * }
17117  * foo() will be verified first for R1=any_scalar_value. During verification it
17118  * will be assumed that bar() already verified successfully and call to bar()
17119  * from foo() will be checked for type match only. Later bar() will be verified
17120  * independently to check that it's safe for R1=any_scalar_value.
17121  */
17122 static int do_check_subprogs(struct bpf_verifier_env *env)
17123 {
17124 	struct bpf_prog_aux *aux = env->prog->aux;
17125 	int i, ret;
17126 
17127 	if (!aux->func_info)
17128 		return 0;
17129 
17130 	for (i = 1; i < env->subprog_cnt; i++) {
17131 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17132 			continue;
17133 		env->insn_idx = env->subprog_info[i].start;
17134 		WARN_ON_ONCE(env->insn_idx == 0);
17135 		ret = do_check_common(env, i);
17136 		if (ret) {
17137 			return ret;
17138 		} else if (env->log.level & BPF_LOG_LEVEL) {
17139 			verbose(env,
17140 				"Func#%d is safe for any args that match its prototype\n",
17141 				i);
17142 		}
17143 	}
17144 	return 0;
17145 }
17146 
17147 static int do_check_main(struct bpf_verifier_env *env)
17148 {
17149 	int ret;
17150 
17151 	env->insn_idx = 0;
17152 	ret = do_check_common(env, 0);
17153 	if (!ret)
17154 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17155 	return ret;
17156 }
17157 
17158 
17159 static void print_verification_stats(struct bpf_verifier_env *env)
17160 {
17161 	int i;
17162 
17163 	if (env->log.level & BPF_LOG_STATS) {
17164 		verbose(env, "verification time %lld usec\n",
17165 			div_u64(env->verification_time, 1000));
17166 		verbose(env, "stack depth ");
17167 		for (i = 0; i < env->subprog_cnt; i++) {
17168 			u32 depth = env->subprog_info[i].stack_depth;
17169 
17170 			verbose(env, "%d", depth);
17171 			if (i + 1 < env->subprog_cnt)
17172 				verbose(env, "+");
17173 		}
17174 		verbose(env, "\n");
17175 	}
17176 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17177 		"total_states %d peak_states %d mark_read %d\n",
17178 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17179 		env->max_states_per_insn, env->total_states,
17180 		env->peak_states, env->longest_mark_read_walk);
17181 }
17182 
17183 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17184 {
17185 	const struct btf_type *t, *func_proto;
17186 	const struct bpf_struct_ops *st_ops;
17187 	const struct btf_member *member;
17188 	struct bpf_prog *prog = env->prog;
17189 	u32 btf_id, member_idx;
17190 	const char *mname;
17191 
17192 	if (!prog->gpl_compatible) {
17193 		verbose(env, "struct ops programs must have a GPL compatible license\n");
17194 		return -EINVAL;
17195 	}
17196 
17197 	btf_id = prog->aux->attach_btf_id;
17198 	st_ops = bpf_struct_ops_find(btf_id);
17199 	if (!st_ops) {
17200 		verbose(env, "attach_btf_id %u is not a supported struct\n",
17201 			btf_id);
17202 		return -ENOTSUPP;
17203 	}
17204 
17205 	t = st_ops->type;
17206 	member_idx = prog->expected_attach_type;
17207 	if (member_idx >= btf_type_vlen(t)) {
17208 		verbose(env, "attach to invalid member idx %u of struct %s\n",
17209 			member_idx, st_ops->name);
17210 		return -EINVAL;
17211 	}
17212 
17213 	member = &btf_type_member(t)[member_idx];
17214 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17215 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17216 					       NULL);
17217 	if (!func_proto) {
17218 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17219 			mname, member_idx, st_ops->name);
17220 		return -EINVAL;
17221 	}
17222 
17223 	if (st_ops->check_member) {
17224 		int err = st_ops->check_member(t, member, prog);
17225 
17226 		if (err) {
17227 			verbose(env, "attach to unsupported member %s of struct %s\n",
17228 				mname, st_ops->name);
17229 			return err;
17230 		}
17231 	}
17232 
17233 	prog->aux->attach_func_proto = func_proto;
17234 	prog->aux->attach_func_name = mname;
17235 	env->ops = st_ops->verifier_ops;
17236 
17237 	return 0;
17238 }
17239 #define SECURITY_PREFIX "security_"
17240 
17241 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17242 {
17243 	if (within_error_injection_list(addr) ||
17244 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17245 		return 0;
17246 
17247 	return -EINVAL;
17248 }
17249 
17250 /* list of non-sleepable functions that are otherwise on
17251  * ALLOW_ERROR_INJECTION list
17252  */
17253 BTF_SET_START(btf_non_sleepable_error_inject)
17254 /* Three functions below can be called from sleepable and non-sleepable context.
17255  * Assume non-sleepable from bpf safety point of view.
17256  */
17257 BTF_ID(func, __filemap_add_folio)
17258 BTF_ID(func, should_fail_alloc_page)
17259 BTF_ID(func, should_failslab)
17260 BTF_SET_END(btf_non_sleepable_error_inject)
17261 
17262 static int check_non_sleepable_error_inject(u32 btf_id)
17263 {
17264 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17265 }
17266 
17267 int bpf_check_attach_target(struct bpf_verifier_log *log,
17268 			    const struct bpf_prog *prog,
17269 			    const struct bpf_prog *tgt_prog,
17270 			    u32 btf_id,
17271 			    struct bpf_attach_target_info *tgt_info)
17272 {
17273 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17274 	const char prefix[] = "btf_trace_";
17275 	int ret = 0, subprog = -1, i;
17276 	const struct btf_type *t;
17277 	bool conservative = true;
17278 	const char *tname;
17279 	struct btf *btf;
17280 	long addr = 0;
17281 
17282 	if (!btf_id) {
17283 		bpf_log(log, "Tracing programs must provide btf_id\n");
17284 		return -EINVAL;
17285 	}
17286 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17287 	if (!btf) {
17288 		bpf_log(log,
17289 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17290 		return -EINVAL;
17291 	}
17292 	t = btf_type_by_id(btf, btf_id);
17293 	if (!t) {
17294 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17295 		return -EINVAL;
17296 	}
17297 	tname = btf_name_by_offset(btf, t->name_off);
17298 	if (!tname) {
17299 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17300 		return -EINVAL;
17301 	}
17302 	if (tgt_prog) {
17303 		struct bpf_prog_aux *aux = tgt_prog->aux;
17304 
17305 		if (bpf_prog_is_dev_bound(prog->aux) &&
17306 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17307 			bpf_log(log, "Target program bound device mismatch");
17308 			return -EINVAL;
17309 		}
17310 
17311 		for (i = 0; i < aux->func_info_cnt; i++)
17312 			if (aux->func_info[i].type_id == btf_id) {
17313 				subprog = i;
17314 				break;
17315 			}
17316 		if (subprog == -1) {
17317 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
17318 			return -EINVAL;
17319 		}
17320 		conservative = aux->func_info_aux[subprog].unreliable;
17321 		if (prog_extension) {
17322 			if (conservative) {
17323 				bpf_log(log,
17324 					"Cannot replace static functions\n");
17325 				return -EINVAL;
17326 			}
17327 			if (!prog->jit_requested) {
17328 				bpf_log(log,
17329 					"Extension programs should be JITed\n");
17330 				return -EINVAL;
17331 			}
17332 		}
17333 		if (!tgt_prog->jited) {
17334 			bpf_log(log, "Can attach to only JITed progs\n");
17335 			return -EINVAL;
17336 		}
17337 		if (tgt_prog->type == prog->type) {
17338 			/* Cannot fentry/fexit another fentry/fexit program.
17339 			 * Cannot attach program extension to another extension.
17340 			 * It's ok to attach fentry/fexit to extension program.
17341 			 */
17342 			bpf_log(log, "Cannot recursively attach\n");
17343 			return -EINVAL;
17344 		}
17345 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17346 		    prog_extension &&
17347 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17348 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17349 			/* Program extensions can extend all program types
17350 			 * except fentry/fexit. The reason is the following.
17351 			 * The fentry/fexit programs are used for performance
17352 			 * analysis, stats and can be attached to any program
17353 			 * type except themselves. When extension program is
17354 			 * replacing XDP function it is necessary to allow
17355 			 * performance analysis of all functions. Both original
17356 			 * XDP program and its program extension. Hence
17357 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17358 			 * allowed. If extending of fentry/fexit was allowed it
17359 			 * would be possible to create long call chain
17360 			 * fentry->extension->fentry->extension beyond
17361 			 * reasonable stack size. Hence extending fentry is not
17362 			 * allowed.
17363 			 */
17364 			bpf_log(log, "Cannot extend fentry/fexit\n");
17365 			return -EINVAL;
17366 		}
17367 	} else {
17368 		if (prog_extension) {
17369 			bpf_log(log, "Cannot replace kernel functions\n");
17370 			return -EINVAL;
17371 		}
17372 	}
17373 
17374 	switch (prog->expected_attach_type) {
17375 	case BPF_TRACE_RAW_TP:
17376 		if (tgt_prog) {
17377 			bpf_log(log,
17378 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17379 			return -EINVAL;
17380 		}
17381 		if (!btf_type_is_typedef(t)) {
17382 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
17383 				btf_id);
17384 			return -EINVAL;
17385 		}
17386 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17387 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17388 				btf_id, tname);
17389 			return -EINVAL;
17390 		}
17391 		tname += sizeof(prefix) - 1;
17392 		t = btf_type_by_id(btf, t->type);
17393 		if (!btf_type_is_ptr(t))
17394 			/* should never happen in valid vmlinux build */
17395 			return -EINVAL;
17396 		t = btf_type_by_id(btf, t->type);
17397 		if (!btf_type_is_func_proto(t))
17398 			/* should never happen in valid vmlinux build */
17399 			return -EINVAL;
17400 
17401 		break;
17402 	case BPF_TRACE_ITER:
17403 		if (!btf_type_is_func(t)) {
17404 			bpf_log(log, "attach_btf_id %u is not a function\n",
17405 				btf_id);
17406 			return -EINVAL;
17407 		}
17408 		t = btf_type_by_id(btf, t->type);
17409 		if (!btf_type_is_func_proto(t))
17410 			return -EINVAL;
17411 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17412 		if (ret)
17413 			return ret;
17414 		break;
17415 	default:
17416 		if (!prog_extension)
17417 			return -EINVAL;
17418 		fallthrough;
17419 	case BPF_MODIFY_RETURN:
17420 	case BPF_LSM_MAC:
17421 	case BPF_LSM_CGROUP:
17422 	case BPF_TRACE_FENTRY:
17423 	case BPF_TRACE_FEXIT:
17424 		if (!btf_type_is_func(t)) {
17425 			bpf_log(log, "attach_btf_id %u is not a function\n",
17426 				btf_id);
17427 			return -EINVAL;
17428 		}
17429 		if (prog_extension &&
17430 		    btf_check_type_match(log, prog, btf, t))
17431 			return -EINVAL;
17432 		t = btf_type_by_id(btf, t->type);
17433 		if (!btf_type_is_func_proto(t))
17434 			return -EINVAL;
17435 
17436 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17437 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17438 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17439 			return -EINVAL;
17440 
17441 		if (tgt_prog && conservative)
17442 			t = NULL;
17443 
17444 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17445 		if (ret < 0)
17446 			return ret;
17447 
17448 		if (tgt_prog) {
17449 			if (subprog == 0)
17450 				addr = (long) tgt_prog->bpf_func;
17451 			else
17452 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17453 		} else {
17454 			addr = kallsyms_lookup_name(tname);
17455 			if (!addr) {
17456 				bpf_log(log,
17457 					"The address of function %s cannot be found\n",
17458 					tname);
17459 				return -ENOENT;
17460 			}
17461 		}
17462 
17463 		if (prog->aux->sleepable) {
17464 			ret = -EINVAL;
17465 			switch (prog->type) {
17466 			case BPF_PROG_TYPE_TRACING:
17467 
17468 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
17469 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17470 				 */
17471 				if (!check_non_sleepable_error_inject(btf_id) &&
17472 				    within_error_injection_list(addr))
17473 					ret = 0;
17474 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
17475 				 * in the fmodret id set with the KF_SLEEPABLE flag.
17476 				 */
17477 				else {
17478 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17479 
17480 					if (flags && (*flags & KF_SLEEPABLE))
17481 						ret = 0;
17482 				}
17483 				break;
17484 			case BPF_PROG_TYPE_LSM:
17485 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
17486 				 * Only some of them are sleepable.
17487 				 */
17488 				if (bpf_lsm_is_sleepable_hook(btf_id))
17489 					ret = 0;
17490 				break;
17491 			default:
17492 				break;
17493 			}
17494 			if (ret) {
17495 				bpf_log(log, "%s is not sleepable\n", tname);
17496 				return ret;
17497 			}
17498 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17499 			if (tgt_prog) {
17500 				bpf_log(log, "can't modify return codes of BPF programs\n");
17501 				return -EINVAL;
17502 			}
17503 			ret = -EINVAL;
17504 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
17505 			    !check_attach_modify_return(addr, tname))
17506 				ret = 0;
17507 			if (ret) {
17508 				bpf_log(log, "%s() is not modifiable\n", tname);
17509 				return ret;
17510 			}
17511 		}
17512 
17513 		break;
17514 	}
17515 	tgt_info->tgt_addr = addr;
17516 	tgt_info->tgt_name = tname;
17517 	tgt_info->tgt_type = t;
17518 	return 0;
17519 }
17520 
17521 BTF_SET_START(btf_id_deny)
17522 BTF_ID_UNUSED
17523 #ifdef CONFIG_SMP
17524 BTF_ID(func, migrate_disable)
17525 BTF_ID(func, migrate_enable)
17526 #endif
17527 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17528 BTF_ID(func, rcu_read_unlock_strict)
17529 #endif
17530 BTF_SET_END(btf_id_deny)
17531 
17532 static bool can_be_sleepable(struct bpf_prog *prog)
17533 {
17534 	if (prog->type == BPF_PROG_TYPE_TRACING) {
17535 		switch (prog->expected_attach_type) {
17536 		case BPF_TRACE_FENTRY:
17537 		case BPF_TRACE_FEXIT:
17538 		case BPF_MODIFY_RETURN:
17539 		case BPF_TRACE_ITER:
17540 			return true;
17541 		default:
17542 			return false;
17543 		}
17544 	}
17545 	return prog->type == BPF_PROG_TYPE_LSM ||
17546 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17547 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17548 }
17549 
17550 static int check_attach_btf_id(struct bpf_verifier_env *env)
17551 {
17552 	struct bpf_prog *prog = env->prog;
17553 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17554 	struct bpf_attach_target_info tgt_info = {};
17555 	u32 btf_id = prog->aux->attach_btf_id;
17556 	struct bpf_trampoline *tr;
17557 	int ret;
17558 	u64 key;
17559 
17560 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17561 		if (prog->aux->sleepable)
17562 			/* attach_btf_id checked to be zero already */
17563 			return 0;
17564 		verbose(env, "Syscall programs can only be sleepable\n");
17565 		return -EINVAL;
17566 	}
17567 
17568 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17569 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17570 		return -EINVAL;
17571 	}
17572 
17573 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17574 		return check_struct_ops_btf_id(env);
17575 
17576 	if (prog->type != BPF_PROG_TYPE_TRACING &&
17577 	    prog->type != BPF_PROG_TYPE_LSM &&
17578 	    prog->type != BPF_PROG_TYPE_EXT)
17579 		return 0;
17580 
17581 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17582 	if (ret)
17583 		return ret;
17584 
17585 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17586 		/* to make freplace equivalent to their targets, they need to
17587 		 * inherit env->ops and expected_attach_type for the rest of the
17588 		 * verification
17589 		 */
17590 		env->ops = bpf_verifier_ops[tgt_prog->type];
17591 		prog->expected_attach_type = tgt_prog->expected_attach_type;
17592 	}
17593 
17594 	/* store info about the attachment target that will be used later */
17595 	prog->aux->attach_func_proto = tgt_info.tgt_type;
17596 	prog->aux->attach_func_name = tgt_info.tgt_name;
17597 
17598 	if (tgt_prog) {
17599 		prog->aux->saved_dst_prog_type = tgt_prog->type;
17600 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17601 	}
17602 
17603 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17604 		prog->aux->attach_btf_trace = true;
17605 		return 0;
17606 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17607 		if (!bpf_iter_prog_supported(prog))
17608 			return -EINVAL;
17609 		return 0;
17610 	}
17611 
17612 	if (prog->type == BPF_PROG_TYPE_LSM) {
17613 		ret = bpf_lsm_verify_prog(&env->log, prog);
17614 		if (ret < 0)
17615 			return ret;
17616 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
17617 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
17618 		return -EINVAL;
17619 	}
17620 
17621 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17622 	tr = bpf_trampoline_get(key, &tgt_info);
17623 	if (!tr)
17624 		return -ENOMEM;
17625 
17626 	prog->aux->dst_trampoline = tr;
17627 	return 0;
17628 }
17629 
17630 struct btf *bpf_get_btf_vmlinux(void)
17631 {
17632 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17633 		mutex_lock(&bpf_verifier_lock);
17634 		if (!btf_vmlinux)
17635 			btf_vmlinux = btf_parse_vmlinux();
17636 		mutex_unlock(&bpf_verifier_lock);
17637 	}
17638 	return btf_vmlinux;
17639 }
17640 
17641 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
17642 {
17643 	u64 start_time = ktime_get_ns();
17644 	struct bpf_verifier_env *env;
17645 	struct bpf_verifier_log *log;
17646 	int i, len, ret = -EINVAL;
17647 	bool is_priv;
17648 
17649 	/* no program is valid */
17650 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
17651 		return -EINVAL;
17652 
17653 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
17654 	 * allocate/free it every time bpf_check() is called
17655 	 */
17656 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
17657 	if (!env)
17658 		return -ENOMEM;
17659 	log = &env->log;
17660 
17661 	len = (*prog)->len;
17662 	env->insn_aux_data =
17663 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
17664 	ret = -ENOMEM;
17665 	if (!env->insn_aux_data)
17666 		goto err_free_env;
17667 	for (i = 0; i < len; i++)
17668 		env->insn_aux_data[i].orig_idx = i;
17669 	env->prog = *prog;
17670 	env->ops = bpf_verifier_ops[env->prog->type];
17671 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
17672 	is_priv = bpf_capable();
17673 
17674 	bpf_get_btf_vmlinux();
17675 
17676 	/* grab the mutex to protect few globals used by verifier */
17677 	if (!is_priv)
17678 		mutex_lock(&bpf_verifier_lock);
17679 
17680 	if (attr->log_level || attr->log_buf || attr->log_size) {
17681 		/* user requested verbose verifier output
17682 		 * and supplied buffer to store the verification trace
17683 		 */
17684 		log->level = attr->log_level;
17685 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
17686 		log->len_total = attr->log_size;
17687 
17688 		/* log attributes have to be sane */
17689 		if (!bpf_verifier_log_attr_valid(log)) {
17690 			ret = -EINVAL;
17691 			goto err_unlock;
17692 		}
17693 	}
17694 
17695 	mark_verifier_state_clean(env);
17696 
17697 	if (IS_ERR(btf_vmlinux)) {
17698 		/* Either gcc or pahole or kernel are broken. */
17699 		verbose(env, "in-kernel BTF is malformed\n");
17700 		ret = PTR_ERR(btf_vmlinux);
17701 		goto skip_full_check;
17702 	}
17703 
17704 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
17705 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
17706 		env->strict_alignment = true;
17707 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
17708 		env->strict_alignment = false;
17709 
17710 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
17711 	env->allow_uninit_stack = bpf_allow_uninit_stack();
17712 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
17713 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
17714 	env->bpf_capable = bpf_capable();
17715 	env->rcu_tag_supported = btf_vmlinux &&
17716 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
17717 
17718 	if (is_priv)
17719 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
17720 
17721 	env->explored_states = kvcalloc(state_htab_size(env),
17722 				       sizeof(struct bpf_verifier_state_list *),
17723 				       GFP_USER);
17724 	ret = -ENOMEM;
17725 	if (!env->explored_states)
17726 		goto skip_full_check;
17727 
17728 	ret = add_subprog_and_kfunc(env);
17729 	if (ret < 0)
17730 		goto skip_full_check;
17731 
17732 	ret = check_subprogs(env);
17733 	if (ret < 0)
17734 		goto skip_full_check;
17735 
17736 	ret = check_btf_info(env, attr, uattr);
17737 	if (ret < 0)
17738 		goto skip_full_check;
17739 
17740 	ret = check_attach_btf_id(env);
17741 	if (ret)
17742 		goto skip_full_check;
17743 
17744 	ret = resolve_pseudo_ldimm64(env);
17745 	if (ret < 0)
17746 		goto skip_full_check;
17747 
17748 	if (bpf_prog_is_offloaded(env->prog->aux)) {
17749 		ret = bpf_prog_offload_verifier_prep(env->prog);
17750 		if (ret)
17751 			goto skip_full_check;
17752 	}
17753 
17754 	ret = check_cfg(env);
17755 	if (ret < 0)
17756 		goto skip_full_check;
17757 
17758 	ret = do_check_subprogs(env);
17759 	ret = ret ?: do_check_main(env);
17760 
17761 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
17762 		ret = bpf_prog_offload_finalize(env);
17763 
17764 skip_full_check:
17765 	kvfree(env->explored_states);
17766 
17767 	if (ret == 0)
17768 		ret = check_max_stack_depth(env);
17769 
17770 	/* instruction rewrites happen after this point */
17771 	if (ret == 0)
17772 		ret = optimize_bpf_loop(env);
17773 
17774 	if (is_priv) {
17775 		if (ret == 0)
17776 			opt_hard_wire_dead_code_branches(env);
17777 		if (ret == 0)
17778 			ret = opt_remove_dead_code(env);
17779 		if (ret == 0)
17780 			ret = opt_remove_nops(env);
17781 	} else {
17782 		if (ret == 0)
17783 			sanitize_dead_code(env);
17784 	}
17785 
17786 	if (ret == 0)
17787 		/* program is valid, convert *(u32*)(ctx + off) accesses */
17788 		ret = convert_ctx_accesses(env);
17789 
17790 	if (ret == 0)
17791 		ret = do_misc_fixups(env);
17792 
17793 	/* do 32-bit optimization after insn patching has done so those patched
17794 	 * insns could be handled correctly.
17795 	 */
17796 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
17797 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
17798 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
17799 								     : false;
17800 	}
17801 
17802 	if (ret == 0)
17803 		ret = fixup_call_args(env);
17804 
17805 	env->verification_time = ktime_get_ns() - start_time;
17806 	print_verification_stats(env);
17807 	env->prog->aux->verified_insns = env->insn_processed;
17808 
17809 	if (log->level && bpf_verifier_log_full(log))
17810 		ret = -ENOSPC;
17811 	if (log->level && !log->ubuf) {
17812 		ret = -EFAULT;
17813 		goto err_release_maps;
17814 	}
17815 
17816 	if (ret)
17817 		goto err_release_maps;
17818 
17819 	if (env->used_map_cnt) {
17820 		/* if program passed verifier, update used_maps in bpf_prog_info */
17821 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17822 							  sizeof(env->used_maps[0]),
17823 							  GFP_KERNEL);
17824 
17825 		if (!env->prog->aux->used_maps) {
17826 			ret = -ENOMEM;
17827 			goto err_release_maps;
17828 		}
17829 
17830 		memcpy(env->prog->aux->used_maps, env->used_maps,
17831 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17832 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17833 	}
17834 	if (env->used_btf_cnt) {
17835 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17836 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17837 							  sizeof(env->used_btfs[0]),
17838 							  GFP_KERNEL);
17839 		if (!env->prog->aux->used_btfs) {
17840 			ret = -ENOMEM;
17841 			goto err_release_maps;
17842 		}
17843 
17844 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17845 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17846 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17847 	}
17848 	if (env->used_map_cnt || env->used_btf_cnt) {
17849 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17850 		 * bpf_ld_imm64 instructions
17851 		 */
17852 		convert_pseudo_ld_imm64(env);
17853 	}
17854 
17855 	adjust_btf_func(env);
17856 
17857 err_release_maps:
17858 	if (!env->prog->aux->used_maps)
17859 		/* if we didn't copy map pointers into bpf_prog_info, release
17860 		 * them now. Otherwise free_used_maps() will release them.
17861 		 */
17862 		release_maps(env);
17863 	if (!env->prog->aux->used_btfs)
17864 		release_btfs(env);
17865 
17866 	/* extension progs temporarily inherit the attach_type of their targets
17867 	   for verification purposes, so set it back to zero before returning
17868 	 */
17869 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17870 		env->prog->expected_attach_type = 0;
17871 
17872 	*prog = env->prog;
17873 err_unlock:
17874 	if (!is_priv)
17875 		mutex_unlock(&bpf_verifier_lock);
17876 	vfree(env->insn_aux_data);
17877 err_free_env:
17878 	kfree(env);
17879 	return ret;
17880 }
17881