xref: /linux/kernel/bpf/verifier.c (revision a8aa6a6ddce9b5585f2b74f27f3feea1427fb4e7)
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 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 struct bpf_mem_alloc bpf_global_percpu_ma;
48 static bool bpf_global_percpu_ma_set;
49 
50 /* bpf_check() is a static code analyzer that walks eBPF program
51  * instruction by instruction and updates register/stack state.
52  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
53  *
54  * The first pass is depth-first-search to check that the program is a DAG.
55  * It rejects the following programs:
56  * - larger than BPF_MAXINSNS insns
57  * - if loop is present (detected via back-edge)
58  * - unreachable insns exist (shouldn't be a forest. program = one function)
59  * - out of bounds or malformed jumps
60  * The second pass is all possible path descent from the 1st insn.
61  * Since it's analyzing all paths through the program, the length of the
62  * analysis is limited to 64k insn, which may be hit even if total number of
63  * insn is less then 4K, but there are too many branches that change stack/regs.
64  * Number of 'branches to be analyzed' is limited to 1k
65  *
66  * On entry to each instruction, each register has a type, and the instruction
67  * changes the types of the registers depending on instruction semantics.
68  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
69  * copied to R1.
70  *
71  * All registers are 64-bit.
72  * R0 - return register
73  * R1-R5 argument passing registers
74  * R6-R9 callee saved registers
75  * R10 - frame pointer read-only
76  *
77  * At the start of BPF program the register R1 contains a pointer to bpf_context
78  * and has type PTR_TO_CTX.
79  *
80  * Verifier tracks arithmetic operations on pointers in case:
81  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
82  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
83  * 1st insn copies R10 (which has FRAME_PTR) type into R1
84  * and 2nd arithmetic instruction is pattern matched to recognize
85  * that it wants to construct a pointer to some element within stack.
86  * So after 2nd insn, the register R1 has type PTR_TO_STACK
87  * (and -20 constant is saved for further stack bounds checking).
88  * Meaning that this reg is a pointer to stack plus known immediate constant.
89  *
90  * Most of the time the registers have SCALAR_VALUE type, which
91  * means the register has some value, but it's not a valid pointer.
92  * (like pointer plus pointer becomes SCALAR_VALUE type)
93  *
94  * When verifier sees load or store instructions the type of base register
95  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
96  * four pointer types recognized by check_mem_access() function.
97  *
98  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
99  * and the range of [ptr, ptr + map's value_size) is accessible.
100  *
101  * registers used to pass values to function calls are checked against
102  * function argument constraints.
103  *
104  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
105  * It means that the register type passed to this function must be
106  * PTR_TO_STACK and it will be used inside the function as
107  * 'pointer to map element key'
108  *
109  * For example the argument constraints for bpf_map_lookup_elem():
110  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
111  *   .arg1_type = ARG_CONST_MAP_PTR,
112  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
113  *
114  * ret_type says that this function returns 'pointer to map elem value or null'
115  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
116  * 2nd argument should be a pointer to stack, which will be used inside
117  * the helper function as a pointer to map element key.
118  *
119  * On the kernel side the helper function looks like:
120  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
121  * {
122  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
123  *    void *key = (void *) (unsigned long) r2;
124  *    void *value;
125  *
126  *    here kernel can access 'key' and 'map' pointers safely, knowing that
127  *    [key, key + map->key_size) bytes are valid and were initialized on
128  *    the stack of eBPF program.
129  * }
130  *
131  * Corresponding eBPF program may look like:
132  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
133  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
134  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
135  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
136  * here verifier looks at prototype of map_lookup_elem() and sees:
137  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
138  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
139  *
140  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
141  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
142  * and were initialized prior to this call.
143  * If it's ok, then verifier allows this BPF_CALL insn and looks at
144  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
145  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
146  * returns either pointer to map value or NULL.
147  *
148  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
149  * insn, the register holding that pointer in the true branch changes state to
150  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
151  * branch. See check_cond_jmp_op().
152  *
153  * After the call R0 is set to return type of the function and registers R1-R5
154  * are set to NOT_INIT to indicate that they are no longer readable.
155  *
156  * The following reference types represent a potential reference to a kernel
157  * resource which, after first being allocated, must be checked and freed by
158  * the BPF program:
159  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
160  *
161  * When the verifier sees a helper call return a reference type, it allocates a
162  * pointer id for the reference and stores it in the current function state.
163  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
164  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
165  * passes through a NULL-check conditional. For the branch wherein the state is
166  * changed to CONST_IMM, the verifier releases the reference.
167  *
168  * For each helper function that allocates a reference, such as
169  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
170  * bpf_sk_release(). When a reference type passes into the release function,
171  * the verifier also releases the reference. If any unchecked or unreleased
172  * reference remains at the end of the program, the verifier rejects it.
173  */
174 
175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
176 struct bpf_verifier_stack_elem {
177 	/* verifier state is 'st'
178 	 * before processing instruction 'insn_idx'
179 	 * and after processing instruction 'prev_insn_idx'
180 	 */
181 	struct bpf_verifier_state st;
182 	int insn_idx;
183 	int prev_insn_idx;
184 	struct bpf_verifier_stack_elem *next;
185 	/* length of verifier log at the time this state was pushed on stack */
186 	u32 log_pos;
187 };
188 
189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
190 #define BPF_COMPLEXITY_LIMIT_STATES	64
191 
192 #define BPF_MAP_KEY_POISON	(1ULL << 63)
193 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
194 
195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
196 
197 #define BPF_PRIV_STACK_MIN_SIZE		64
198 
199 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
200 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 			      struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 			     u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209 
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212 	return aux->map_ptr_state.poison;
213 }
214 
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217 	return aux->map_ptr_state.unpriv;
218 }
219 
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 			      struct bpf_map *map,
222 			      bool unpriv, bool poison)
223 {
224 	unpriv |= bpf_map_ptr_unpriv(aux);
225 	aux->map_ptr_state.unpriv = unpriv;
226 	aux->map_ptr_state.poison = poison;
227 	aux->map_ptr_state.map_ptr = map;
228 }
229 
230 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
231 {
232 	return aux->map_key_state & BPF_MAP_KEY_POISON;
233 }
234 
235 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
236 {
237 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
238 }
239 
240 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
241 {
242 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
243 }
244 
245 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
246 {
247 	bool poisoned = bpf_map_key_poisoned(aux);
248 
249 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
250 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
251 }
252 
253 static bool bpf_helper_call(const struct bpf_insn *insn)
254 {
255 	return insn->code == (BPF_JMP | BPF_CALL) &&
256 	       insn->src_reg == 0;
257 }
258 
259 static bool bpf_pseudo_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == BPF_PSEUDO_CALL;
263 }
264 
265 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
269 }
270 
271 struct bpf_call_arg_meta {
272 	struct bpf_map *map_ptr;
273 	bool raw_mode;
274 	bool pkt_access;
275 	u8 release_regno;
276 	int regno;
277 	int access_size;
278 	int mem_size;
279 	u64 msize_max_value;
280 	int ref_obj_id;
281 	int dynptr_id;
282 	int map_uid;
283 	int func_id;
284 	struct btf *btf;
285 	u32 btf_id;
286 	struct btf *ret_btf;
287 	u32 ret_btf_id;
288 	u32 subprogno;
289 	struct btf_field *kptr_field;
290 	s64 const_map_key;
291 };
292 
293 struct bpf_kfunc_call_arg_meta {
294 	/* In parameters */
295 	struct btf *btf;
296 	u32 func_id;
297 	u32 kfunc_flags;
298 	const struct btf_type *func_proto;
299 	const char *func_name;
300 	/* Out parameters */
301 	u32 ref_obj_id;
302 	u8 release_regno;
303 	bool r0_rdonly;
304 	u32 ret_btf_id;
305 	u64 r0_size;
306 	u32 subprogno;
307 	struct {
308 		u64 value;
309 		bool found;
310 	} arg_constant;
311 
312 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
313 	 * generally to pass info about user-defined local kptr types to later
314 	 * verification logic
315 	 *   bpf_obj_drop/bpf_percpu_obj_drop
316 	 *     Record the local kptr type to be drop'd
317 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
318 	 *     Record the local kptr type to be refcount_incr'd and use
319 	 *     arg_owning_ref to determine whether refcount_acquire should be
320 	 *     fallible
321 	 */
322 	struct btf *arg_btf;
323 	u32 arg_btf_id;
324 	bool arg_owning_ref;
325 
326 	struct {
327 		struct btf_field *field;
328 	} arg_list_head;
329 	struct {
330 		struct btf_field *field;
331 	} arg_rbtree_root;
332 	struct {
333 		enum bpf_dynptr_type type;
334 		u32 id;
335 		u32 ref_obj_id;
336 	} initialized_dynptr;
337 	struct {
338 		u8 spi;
339 		u8 frameno;
340 	} iter;
341 	struct {
342 		struct bpf_map *ptr;
343 		int uid;
344 	} map;
345 	u64 mem_size;
346 };
347 
348 struct btf *btf_vmlinux;
349 
350 static const char *btf_type_name(const struct btf *btf, u32 id)
351 {
352 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
353 }
354 
355 static DEFINE_MUTEX(bpf_verifier_lock);
356 static DEFINE_MUTEX(bpf_percpu_ma_lock);
357 
358 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
359 {
360 	struct bpf_verifier_env *env = private_data;
361 	va_list args;
362 
363 	if (!bpf_verifier_log_needed(&env->log))
364 		return;
365 
366 	va_start(args, fmt);
367 	bpf_verifier_vlog(&env->log, fmt, args);
368 	va_end(args);
369 }
370 
371 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
372 				   struct bpf_reg_state *reg,
373 				   struct bpf_retval_range range, const char *ctx,
374 				   const char *reg_name)
375 {
376 	bool unknown = true;
377 
378 	verbose(env, "%s the register %s has", ctx, reg_name);
379 	if (reg->smin_value > S64_MIN) {
380 		verbose(env, " smin=%lld", reg->smin_value);
381 		unknown = false;
382 	}
383 	if (reg->smax_value < S64_MAX) {
384 		verbose(env, " smax=%lld", reg->smax_value);
385 		unknown = false;
386 	}
387 	if (unknown)
388 		verbose(env, " unknown scalar value");
389 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
390 }
391 
392 static bool reg_not_null(const struct bpf_reg_state *reg)
393 {
394 	enum bpf_reg_type type;
395 
396 	type = reg->type;
397 	if (type_may_be_null(type))
398 		return false;
399 
400 	type = base_type(type);
401 	return type == PTR_TO_SOCKET ||
402 		type == PTR_TO_TCP_SOCK ||
403 		type == PTR_TO_MAP_VALUE ||
404 		type == PTR_TO_MAP_KEY ||
405 		type == PTR_TO_SOCK_COMMON ||
406 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
407 		type == PTR_TO_MEM;
408 }
409 
410 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
411 {
412 	struct btf_record *rec = NULL;
413 	struct btf_struct_meta *meta;
414 
415 	if (reg->type == PTR_TO_MAP_VALUE) {
416 		rec = reg->map_ptr->record;
417 	} else if (type_is_ptr_alloc_obj(reg->type)) {
418 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
419 		if (meta)
420 			rec = meta->record;
421 	}
422 	return rec;
423 }
424 
425 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
426 {
427 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
428 
429 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
430 }
431 
432 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
433 {
434 	struct bpf_func_info *info;
435 
436 	if (!env->prog->aux->func_info)
437 		return "";
438 
439 	info = &env->prog->aux->func_info[subprog];
440 	return btf_type_name(env->prog->aux->btf, info->type_id);
441 }
442 
443 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
444 {
445 	struct bpf_subprog_info *info = subprog_info(env, subprog);
446 
447 	info->is_cb = true;
448 	info->is_async_cb = true;
449 	info->is_exception_cb = true;
450 }
451 
452 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
453 {
454 	return subprog_info(env, subprog)->is_exception_cb;
455 }
456 
457 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
458 {
459 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
460 }
461 
462 static bool type_is_rdonly_mem(u32 type)
463 {
464 	return type & MEM_RDONLY;
465 }
466 
467 static bool is_acquire_function(enum bpf_func_id func_id,
468 				const struct bpf_map *map)
469 {
470 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
471 
472 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
473 	    func_id == BPF_FUNC_sk_lookup_udp ||
474 	    func_id == BPF_FUNC_skc_lookup_tcp ||
475 	    func_id == BPF_FUNC_ringbuf_reserve ||
476 	    func_id == BPF_FUNC_kptr_xchg)
477 		return true;
478 
479 	if (func_id == BPF_FUNC_map_lookup_elem &&
480 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
481 	     map_type == BPF_MAP_TYPE_SOCKHASH))
482 		return true;
483 
484 	return false;
485 }
486 
487 static bool is_ptr_cast_function(enum bpf_func_id func_id)
488 {
489 	return func_id == BPF_FUNC_tcp_sock ||
490 		func_id == BPF_FUNC_sk_fullsock ||
491 		func_id == BPF_FUNC_skc_to_tcp_sock ||
492 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
493 		func_id == BPF_FUNC_skc_to_udp6_sock ||
494 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
497 }
498 
499 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
500 {
501 	return func_id == BPF_FUNC_dynptr_data;
502 }
503 
504 static bool is_sync_callback_calling_kfunc(u32 btf_id);
505 static bool is_async_callback_calling_kfunc(u32 btf_id);
506 static bool is_callback_calling_kfunc(u32 btf_id);
507 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
508 
509 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
510 
511 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
512 {
513 	return func_id == BPF_FUNC_for_each_map_elem ||
514 	       func_id == BPF_FUNC_find_vma ||
515 	       func_id == BPF_FUNC_loop ||
516 	       func_id == BPF_FUNC_user_ringbuf_drain;
517 }
518 
519 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_timer_set_callback;
522 }
523 
524 static bool is_callback_calling_function(enum bpf_func_id func_id)
525 {
526 	return is_sync_callback_calling_function(func_id) ||
527 	       is_async_callback_calling_function(func_id);
528 }
529 
530 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
531 {
532 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
533 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
534 }
535 
536 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
537 {
538 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
539 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
540 }
541 
542 static bool is_may_goto_insn(struct bpf_insn *insn)
543 {
544 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
545 }
546 
547 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
548 {
549 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
550 }
551 
552 static bool is_storage_get_function(enum bpf_func_id func_id)
553 {
554 	return func_id == BPF_FUNC_sk_storage_get ||
555 	       func_id == BPF_FUNC_inode_storage_get ||
556 	       func_id == BPF_FUNC_task_storage_get ||
557 	       func_id == BPF_FUNC_cgrp_storage_get;
558 }
559 
560 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
561 					const struct bpf_map *map)
562 {
563 	int ref_obj_uses = 0;
564 
565 	if (is_ptr_cast_function(func_id))
566 		ref_obj_uses++;
567 	if (is_acquire_function(func_id, map))
568 		ref_obj_uses++;
569 	if (is_dynptr_ref_function(func_id))
570 		ref_obj_uses++;
571 
572 	return ref_obj_uses > 1;
573 }
574 
575 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
576 {
577 	return BPF_CLASS(insn->code) == BPF_STX &&
578 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
579 	       insn->imm == BPF_CMPXCHG;
580 }
581 
582 static int __get_spi(s32 off)
583 {
584 	return (-off - 1) / BPF_REG_SIZE;
585 }
586 
587 static struct bpf_func_state *func(struct bpf_verifier_env *env,
588 				   const struct bpf_reg_state *reg)
589 {
590 	struct bpf_verifier_state *cur = env->cur_state;
591 
592 	return cur->frame[reg->frameno];
593 }
594 
595 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
596 {
597        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
598 
599        /* We need to check that slots between [spi - nr_slots + 1, spi] are
600 	* within [0, allocated_stack).
601 	*
602 	* Please note that the spi grows downwards. For example, a dynptr
603 	* takes the size of two stack slots; the first slot will be at
604 	* spi and the second slot will be at spi - 1.
605 	*/
606        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
607 }
608 
609 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
610 			          const char *obj_kind, int nr_slots)
611 {
612 	int off, spi;
613 
614 	if (!tnum_is_const(reg->var_off)) {
615 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
616 		return -EINVAL;
617 	}
618 
619 	off = reg->off + reg->var_off.value;
620 	if (off % BPF_REG_SIZE) {
621 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
622 		return -EINVAL;
623 	}
624 
625 	spi = __get_spi(off);
626 	if (spi + 1 < nr_slots) {
627 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
628 		return -EINVAL;
629 	}
630 
631 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
632 		return -ERANGE;
633 	return spi;
634 }
635 
636 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
637 {
638 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
639 }
640 
641 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
642 {
643 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
644 }
645 
646 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
647 {
648 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
649 }
650 
651 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
652 {
653 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
654 	case DYNPTR_TYPE_LOCAL:
655 		return BPF_DYNPTR_TYPE_LOCAL;
656 	case DYNPTR_TYPE_RINGBUF:
657 		return BPF_DYNPTR_TYPE_RINGBUF;
658 	case DYNPTR_TYPE_SKB:
659 		return BPF_DYNPTR_TYPE_SKB;
660 	case DYNPTR_TYPE_XDP:
661 		return BPF_DYNPTR_TYPE_XDP;
662 	default:
663 		return BPF_DYNPTR_TYPE_INVALID;
664 	}
665 }
666 
667 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
668 {
669 	switch (type) {
670 	case BPF_DYNPTR_TYPE_LOCAL:
671 		return DYNPTR_TYPE_LOCAL;
672 	case BPF_DYNPTR_TYPE_RINGBUF:
673 		return DYNPTR_TYPE_RINGBUF;
674 	case BPF_DYNPTR_TYPE_SKB:
675 		return DYNPTR_TYPE_SKB;
676 	case BPF_DYNPTR_TYPE_XDP:
677 		return DYNPTR_TYPE_XDP;
678 	default:
679 		return 0;
680 	}
681 }
682 
683 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
684 {
685 	return type == BPF_DYNPTR_TYPE_RINGBUF;
686 }
687 
688 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
689 			      enum bpf_dynptr_type type,
690 			      bool first_slot, int dynptr_id);
691 
692 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
693 				struct bpf_reg_state *reg);
694 
695 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
696 				   struct bpf_reg_state *sreg1,
697 				   struct bpf_reg_state *sreg2,
698 				   enum bpf_dynptr_type type)
699 {
700 	int id = ++env->id_gen;
701 
702 	__mark_dynptr_reg(sreg1, type, true, id);
703 	__mark_dynptr_reg(sreg2, type, false, id);
704 }
705 
706 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
707 			       struct bpf_reg_state *reg,
708 			       enum bpf_dynptr_type type)
709 {
710 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
711 }
712 
713 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
714 				        struct bpf_func_state *state, int spi);
715 
716 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
717 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
718 {
719 	struct bpf_func_state *state = func(env, reg);
720 	enum bpf_dynptr_type type;
721 	int spi, i, err;
722 
723 	spi = dynptr_get_spi(env, reg);
724 	if (spi < 0)
725 		return spi;
726 
727 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
728 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
729 	 * to ensure that for the following example:
730 	 *	[d1][d1][d2][d2]
731 	 * spi    3   2   1   0
732 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
733 	 * case they do belong to same dynptr, second call won't see slot_type
734 	 * as STACK_DYNPTR and will simply skip destruction.
735 	 */
736 	err = destroy_if_dynptr_stack_slot(env, state, spi);
737 	if (err)
738 		return err;
739 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
740 	if (err)
741 		return err;
742 
743 	for (i = 0; i < BPF_REG_SIZE; i++) {
744 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
745 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
746 	}
747 
748 	type = arg_to_dynptr_type(arg_type);
749 	if (type == BPF_DYNPTR_TYPE_INVALID)
750 		return -EINVAL;
751 
752 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
753 			       &state->stack[spi - 1].spilled_ptr, type);
754 
755 	if (dynptr_type_refcounted(type)) {
756 		/* The id is used to track proper releasing */
757 		int id;
758 
759 		if (clone_ref_obj_id)
760 			id = clone_ref_obj_id;
761 		else
762 			id = acquire_reference(env, insn_idx);
763 
764 		if (id < 0)
765 			return id;
766 
767 		state->stack[spi].spilled_ptr.ref_obj_id = id;
768 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
769 	}
770 
771 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
772 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
773 
774 	return 0;
775 }
776 
777 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
778 {
779 	int i;
780 
781 	for (i = 0; i < BPF_REG_SIZE; i++) {
782 		state->stack[spi].slot_type[i] = STACK_INVALID;
783 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
784 	}
785 
786 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
787 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
788 
789 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
790 	 *
791 	 * While we don't allow reading STACK_INVALID, it is still possible to
792 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
793 	 * helpers or insns can do partial read of that part without failing,
794 	 * but check_stack_range_initialized, check_stack_read_var_off, and
795 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
796 	 * the slot conservatively. Hence we need to prevent those liveness
797 	 * marking walks.
798 	 *
799 	 * This was not a problem before because STACK_INVALID is only set by
800 	 * default (where the default reg state has its reg->parent as NULL), or
801 	 * in clean_live_states after REG_LIVE_DONE (at which point
802 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
803 	 * verifier state exploration (like we did above). Hence, for our case
804 	 * parentage chain will still be live (i.e. reg->parent may be
805 	 * non-NULL), while earlier reg->parent was NULL, so we need
806 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
807 	 * done later on reads or by mark_dynptr_read as well to unnecessary
808 	 * mark registers in verifier state.
809 	 */
810 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
811 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
812 }
813 
814 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
815 {
816 	struct bpf_func_state *state = func(env, reg);
817 	int spi, ref_obj_id, i;
818 
819 	spi = dynptr_get_spi(env, reg);
820 	if (spi < 0)
821 		return spi;
822 
823 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
824 		invalidate_dynptr(env, state, spi);
825 		return 0;
826 	}
827 
828 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
829 
830 	/* If the dynptr has a ref_obj_id, then we need to invalidate
831 	 * two things:
832 	 *
833 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
834 	 * 2) Any slices derived from this dynptr.
835 	 */
836 
837 	/* Invalidate any slices associated with this dynptr */
838 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
839 
840 	/* Invalidate any dynptr clones */
841 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
842 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
843 			continue;
844 
845 		/* it should always be the case that if the ref obj id
846 		 * matches then the stack slot also belongs to a
847 		 * dynptr
848 		 */
849 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
850 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
851 			return -EFAULT;
852 		}
853 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
854 			invalidate_dynptr(env, state, i);
855 	}
856 
857 	return 0;
858 }
859 
860 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
861 			       struct bpf_reg_state *reg);
862 
863 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
864 {
865 	if (!env->allow_ptr_leaks)
866 		__mark_reg_not_init(env, reg);
867 	else
868 		__mark_reg_unknown(env, reg);
869 }
870 
871 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
872 				        struct bpf_func_state *state, int spi)
873 {
874 	struct bpf_func_state *fstate;
875 	struct bpf_reg_state *dreg;
876 	int i, dynptr_id;
877 
878 	/* We always ensure that STACK_DYNPTR is never set partially,
879 	 * hence just checking for slot_type[0] is enough. This is
880 	 * different for STACK_SPILL, where it may be only set for
881 	 * 1 byte, so code has to use is_spilled_reg.
882 	 */
883 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
884 		return 0;
885 
886 	/* Reposition spi to first slot */
887 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
888 		spi = spi + 1;
889 
890 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
891 		verbose(env, "cannot overwrite referenced dynptr\n");
892 		return -EINVAL;
893 	}
894 
895 	mark_stack_slot_scratched(env, spi);
896 	mark_stack_slot_scratched(env, spi - 1);
897 
898 	/* Writing partially to one dynptr stack slot destroys both. */
899 	for (i = 0; i < BPF_REG_SIZE; i++) {
900 		state->stack[spi].slot_type[i] = STACK_INVALID;
901 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
902 	}
903 
904 	dynptr_id = state->stack[spi].spilled_ptr.id;
905 	/* Invalidate any slices associated with this dynptr */
906 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
907 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
908 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
909 			continue;
910 		if (dreg->dynptr_id == dynptr_id)
911 			mark_reg_invalid(env, dreg);
912 	}));
913 
914 	/* Do not release reference state, we are destroying dynptr on stack,
915 	 * not using some helper to release it. Just reset register.
916 	 */
917 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
918 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
919 
920 	/* Same reason as unmark_stack_slots_dynptr above */
921 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
922 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
923 
924 	return 0;
925 }
926 
927 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
928 {
929 	int spi;
930 
931 	if (reg->type == CONST_PTR_TO_DYNPTR)
932 		return false;
933 
934 	spi = dynptr_get_spi(env, reg);
935 
936 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
937 	 * error because this just means the stack state hasn't been updated yet.
938 	 * We will do check_mem_access to check and update stack bounds later.
939 	 */
940 	if (spi < 0 && spi != -ERANGE)
941 		return false;
942 
943 	/* We don't need to check if the stack slots are marked by previous
944 	 * dynptr initializations because we allow overwriting existing unreferenced
945 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
946 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
947 	 * touching are completely destructed before we reinitialize them for a new
948 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
949 	 * instead of delaying it until the end where the user will get "Unreleased
950 	 * reference" error.
951 	 */
952 	return true;
953 }
954 
955 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
956 {
957 	struct bpf_func_state *state = func(env, reg);
958 	int i, spi;
959 
960 	/* This already represents first slot of initialized bpf_dynptr.
961 	 *
962 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
963 	 * check_func_arg_reg_off's logic, so we don't need to check its
964 	 * offset and alignment.
965 	 */
966 	if (reg->type == CONST_PTR_TO_DYNPTR)
967 		return true;
968 
969 	spi = dynptr_get_spi(env, reg);
970 	if (spi < 0)
971 		return false;
972 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
973 		return false;
974 
975 	for (i = 0; i < BPF_REG_SIZE; i++) {
976 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
977 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
978 			return false;
979 	}
980 
981 	return true;
982 }
983 
984 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
985 				    enum bpf_arg_type arg_type)
986 {
987 	struct bpf_func_state *state = func(env, reg);
988 	enum bpf_dynptr_type dynptr_type;
989 	int spi;
990 
991 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
992 	if (arg_type == ARG_PTR_TO_DYNPTR)
993 		return true;
994 
995 	dynptr_type = arg_to_dynptr_type(arg_type);
996 	if (reg->type == CONST_PTR_TO_DYNPTR) {
997 		return reg->dynptr.type == dynptr_type;
998 	} else {
999 		spi = dynptr_get_spi(env, reg);
1000 		if (spi < 0)
1001 			return false;
1002 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1003 	}
1004 }
1005 
1006 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1007 
1008 static bool in_rcu_cs(struct bpf_verifier_env *env);
1009 
1010 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1011 
1012 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1013 				 struct bpf_kfunc_call_arg_meta *meta,
1014 				 struct bpf_reg_state *reg, int insn_idx,
1015 				 struct btf *btf, u32 btf_id, int nr_slots)
1016 {
1017 	struct bpf_func_state *state = func(env, reg);
1018 	int spi, i, j, id;
1019 
1020 	spi = iter_get_spi(env, reg, nr_slots);
1021 	if (spi < 0)
1022 		return spi;
1023 
1024 	id = acquire_reference(env, insn_idx);
1025 	if (id < 0)
1026 		return id;
1027 
1028 	for (i = 0; i < nr_slots; i++) {
1029 		struct bpf_stack_state *slot = &state->stack[spi - i];
1030 		struct bpf_reg_state *st = &slot->spilled_ptr;
1031 
1032 		__mark_reg_known_zero(st);
1033 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1034 		if (is_kfunc_rcu_protected(meta)) {
1035 			if (in_rcu_cs(env))
1036 				st->type |= MEM_RCU;
1037 			else
1038 				st->type |= PTR_UNTRUSTED;
1039 		}
1040 		st->live |= REG_LIVE_WRITTEN;
1041 		st->ref_obj_id = i == 0 ? id : 0;
1042 		st->iter.btf = btf;
1043 		st->iter.btf_id = btf_id;
1044 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1045 		st->iter.depth = 0;
1046 
1047 		for (j = 0; j < BPF_REG_SIZE; j++)
1048 			slot->slot_type[j] = STACK_ITER;
1049 
1050 		mark_stack_slot_scratched(env, spi - i);
1051 	}
1052 
1053 	return 0;
1054 }
1055 
1056 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1057 				   struct bpf_reg_state *reg, int nr_slots)
1058 {
1059 	struct bpf_func_state *state = func(env, reg);
1060 	int spi, i, j;
1061 
1062 	spi = iter_get_spi(env, reg, nr_slots);
1063 	if (spi < 0)
1064 		return spi;
1065 
1066 	for (i = 0; i < nr_slots; i++) {
1067 		struct bpf_stack_state *slot = &state->stack[spi - i];
1068 		struct bpf_reg_state *st = &slot->spilled_ptr;
1069 
1070 		if (i == 0)
1071 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1072 
1073 		__mark_reg_not_init(env, st);
1074 
1075 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1076 		st->live |= REG_LIVE_WRITTEN;
1077 
1078 		for (j = 0; j < BPF_REG_SIZE; j++)
1079 			slot->slot_type[j] = STACK_INVALID;
1080 
1081 		mark_stack_slot_scratched(env, spi - i);
1082 	}
1083 
1084 	return 0;
1085 }
1086 
1087 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1088 				     struct bpf_reg_state *reg, int nr_slots)
1089 {
1090 	struct bpf_func_state *state = func(env, reg);
1091 	int spi, i, j;
1092 
1093 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1094 	 * will do check_mem_access to check and update stack bounds later, so
1095 	 * return true for that case.
1096 	 */
1097 	spi = iter_get_spi(env, reg, nr_slots);
1098 	if (spi == -ERANGE)
1099 		return true;
1100 	if (spi < 0)
1101 		return false;
1102 
1103 	for (i = 0; i < nr_slots; i++) {
1104 		struct bpf_stack_state *slot = &state->stack[spi - i];
1105 
1106 		for (j = 0; j < BPF_REG_SIZE; j++)
1107 			if (slot->slot_type[j] == STACK_ITER)
1108 				return false;
1109 	}
1110 
1111 	return true;
1112 }
1113 
1114 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1115 				   struct btf *btf, u32 btf_id, int nr_slots)
1116 {
1117 	struct bpf_func_state *state = func(env, reg);
1118 	int spi, i, j;
1119 
1120 	spi = iter_get_spi(env, reg, nr_slots);
1121 	if (spi < 0)
1122 		return -EINVAL;
1123 
1124 	for (i = 0; i < nr_slots; i++) {
1125 		struct bpf_stack_state *slot = &state->stack[spi - i];
1126 		struct bpf_reg_state *st = &slot->spilled_ptr;
1127 
1128 		if (st->type & PTR_UNTRUSTED)
1129 			return -EPROTO;
1130 		/* only main (first) slot has ref_obj_id set */
1131 		if (i == 0 && !st->ref_obj_id)
1132 			return -EINVAL;
1133 		if (i != 0 && st->ref_obj_id)
1134 			return -EINVAL;
1135 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1136 			return -EINVAL;
1137 
1138 		for (j = 0; j < BPF_REG_SIZE; j++)
1139 			if (slot->slot_type[j] != STACK_ITER)
1140 				return -EINVAL;
1141 	}
1142 
1143 	return 0;
1144 }
1145 
1146 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1147 static int release_irq_state(struct bpf_verifier_state *state, int id);
1148 
1149 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1150 				     struct bpf_kfunc_call_arg_meta *meta,
1151 				     struct bpf_reg_state *reg, int insn_idx)
1152 {
1153 	struct bpf_func_state *state = func(env, reg);
1154 	struct bpf_stack_state *slot;
1155 	struct bpf_reg_state *st;
1156 	int spi, i, id;
1157 
1158 	spi = irq_flag_get_spi(env, reg);
1159 	if (spi < 0)
1160 		return spi;
1161 
1162 	id = acquire_irq_state(env, insn_idx);
1163 	if (id < 0)
1164 		return id;
1165 
1166 	slot = &state->stack[spi];
1167 	st = &slot->spilled_ptr;
1168 
1169 	__mark_reg_known_zero(st);
1170 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1171 	st->live |= REG_LIVE_WRITTEN;
1172 	st->ref_obj_id = id;
1173 
1174 	for (i = 0; i < BPF_REG_SIZE; i++)
1175 		slot->slot_type[i] = STACK_IRQ_FLAG;
1176 
1177 	mark_stack_slot_scratched(env, spi);
1178 	return 0;
1179 }
1180 
1181 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1182 {
1183 	struct bpf_func_state *state = func(env, reg);
1184 	struct bpf_stack_state *slot;
1185 	struct bpf_reg_state *st;
1186 	int spi, i, err;
1187 
1188 	spi = irq_flag_get_spi(env, reg);
1189 	if (spi < 0)
1190 		return spi;
1191 
1192 	slot = &state->stack[spi];
1193 	st = &slot->spilled_ptr;
1194 
1195 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1196 	WARN_ON_ONCE(err && err != -EACCES);
1197 	if (err) {
1198 		int insn_idx = 0;
1199 
1200 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1201 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1202 				insn_idx = env->cur_state->refs[i].insn_idx;
1203 				break;
1204 			}
1205 		}
1206 
1207 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1208 			env->cur_state->active_irq_id, insn_idx);
1209 		return err;
1210 	}
1211 
1212 	__mark_reg_not_init(env, st);
1213 
1214 	/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1215 	st->live |= REG_LIVE_WRITTEN;
1216 
1217 	for (i = 0; i < BPF_REG_SIZE; i++)
1218 		slot->slot_type[i] = STACK_INVALID;
1219 
1220 	mark_stack_slot_scratched(env, spi);
1221 	return 0;
1222 }
1223 
1224 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	struct bpf_stack_state *slot;
1228 	int spi, i;
1229 
1230 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1231 	 * will do check_mem_access to check and update stack bounds later, so
1232 	 * return true for that case.
1233 	 */
1234 	spi = irq_flag_get_spi(env, reg);
1235 	if (spi == -ERANGE)
1236 		return true;
1237 	if (spi < 0)
1238 		return false;
1239 
1240 	slot = &state->stack[spi];
1241 
1242 	for (i = 0; i < BPF_REG_SIZE; i++)
1243 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1244 			return false;
1245 	return true;
1246 }
1247 
1248 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1249 {
1250 	struct bpf_func_state *state = func(env, reg);
1251 	struct bpf_stack_state *slot;
1252 	struct bpf_reg_state *st;
1253 	int spi, i;
1254 
1255 	spi = irq_flag_get_spi(env, reg);
1256 	if (spi < 0)
1257 		return -EINVAL;
1258 
1259 	slot = &state->stack[spi];
1260 	st = &slot->spilled_ptr;
1261 
1262 	if (!st->ref_obj_id)
1263 		return -EINVAL;
1264 
1265 	for (i = 0; i < BPF_REG_SIZE; i++)
1266 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1267 			return -EINVAL;
1268 	return 0;
1269 }
1270 
1271 /* Check if given stack slot is "special":
1272  *   - spilled register state (STACK_SPILL);
1273  *   - dynptr state (STACK_DYNPTR);
1274  *   - iter state (STACK_ITER).
1275  *   - irq flag state (STACK_IRQ_FLAG)
1276  */
1277 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1278 {
1279 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1280 
1281 	switch (type) {
1282 	case STACK_SPILL:
1283 	case STACK_DYNPTR:
1284 	case STACK_ITER:
1285 	case STACK_IRQ_FLAG:
1286 		return true;
1287 	case STACK_INVALID:
1288 	case STACK_MISC:
1289 	case STACK_ZERO:
1290 		return false;
1291 	default:
1292 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1293 		return true;
1294 	}
1295 }
1296 
1297 /* The reg state of a pointer or a bounded scalar was saved when
1298  * it was spilled to the stack.
1299  */
1300 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1301 {
1302 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1303 }
1304 
1305 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1306 {
1307 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1308 	       stack->spilled_ptr.type == SCALAR_VALUE;
1309 }
1310 
1311 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1312 {
1313 	return stack->slot_type[0] == STACK_SPILL &&
1314 	       stack->spilled_ptr.type == SCALAR_VALUE;
1315 }
1316 
1317 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1318  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1319  * more precise STACK_ZERO.
1320  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1321  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1322  * unnecessary as both are considered equivalent when loading data and pruning,
1323  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1324  * slots.
1325  */
1326 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1327 {
1328 	if (*stype == STACK_ZERO)
1329 		return;
1330 	if (*stype == STACK_INVALID)
1331 		return;
1332 	*stype = STACK_MISC;
1333 }
1334 
1335 static void scrub_spilled_slot(u8 *stype)
1336 {
1337 	if (*stype != STACK_INVALID)
1338 		*stype = STACK_MISC;
1339 }
1340 
1341 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1342  * small to hold src. This is different from krealloc since we don't want to preserve
1343  * the contents of dst.
1344  *
1345  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1346  * not be allocated.
1347  */
1348 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1349 {
1350 	size_t alloc_bytes;
1351 	void *orig = dst;
1352 	size_t bytes;
1353 
1354 	if (ZERO_OR_NULL_PTR(src))
1355 		goto out;
1356 
1357 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1358 		return NULL;
1359 
1360 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1361 	dst = krealloc(orig, alloc_bytes, flags);
1362 	if (!dst) {
1363 		kfree(orig);
1364 		return NULL;
1365 	}
1366 
1367 	memcpy(dst, src, bytes);
1368 out:
1369 	return dst ? dst : ZERO_SIZE_PTR;
1370 }
1371 
1372 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1373  * small to hold new_n items. new items are zeroed out if the array grows.
1374  *
1375  * Contrary to krealloc_array, does not free arr if new_n is zero.
1376  */
1377 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1378 {
1379 	size_t alloc_size;
1380 	void *new_arr;
1381 
1382 	if (!new_n || old_n == new_n)
1383 		goto out;
1384 
1385 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1386 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1387 	if (!new_arr) {
1388 		kfree(arr);
1389 		return NULL;
1390 	}
1391 	arr = new_arr;
1392 
1393 	if (new_n > old_n)
1394 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1395 
1396 out:
1397 	return arr ? arr : ZERO_SIZE_PTR;
1398 }
1399 
1400 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1401 {
1402 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1403 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1404 	if (!dst->refs)
1405 		return -ENOMEM;
1406 
1407 	dst->acquired_refs = src->acquired_refs;
1408 	dst->active_locks = src->active_locks;
1409 	dst->active_preempt_locks = src->active_preempt_locks;
1410 	dst->active_rcu_lock = src->active_rcu_lock;
1411 	dst->active_irq_id = src->active_irq_id;
1412 	return 0;
1413 }
1414 
1415 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1416 {
1417 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1418 
1419 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1420 				GFP_KERNEL);
1421 	if (!dst->stack)
1422 		return -ENOMEM;
1423 
1424 	dst->allocated_stack = src->allocated_stack;
1425 	return 0;
1426 }
1427 
1428 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1429 {
1430 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1431 				    sizeof(struct bpf_reference_state));
1432 	if (!state->refs)
1433 		return -ENOMEM;
1434 
1435 	state->acquired_refs = n;
1436 	return 0;
1437 }
1438 
1439 /* Possibly update state->allocated_stack to be at least size bytes. Also
1440  * possibly update the function's high-water mark in its bpf_subprog_info.
1441  */
1442 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1443 {
1444 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1445 
1446 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1447 	size = round_up(size, BPF_REG_SIZE);
1448 	n = size / BPF_REG_SIZE;
1449 
1450 	if (old_n >= n)
1451 		return 0;
1452 
1453 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1454 	if (!state->stack)
1455 		return -ENOMEM;
1456 
1457 	state->allocated_stack = size;
1458 
1459 	/* update known max for given subprogram */
1460 	if (env->subprog_info[state->subprogno].stack_depth < size)
1461 		env->subprog_info[state->subprogno].stack_depth = size;
1462 
1463 	return 0;
1464 }
1465 
1466 /* Acquire a pointer id from the env and update the state->refs to include
1467  * this new pointer reference.
1468  * On success, returns a valid pointer id to associate with the register
1469  * On failure, returns a negative errno.
1470  */
1471 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1472 {
1473 	struct bpf_verifier_state *state = env->cur_state;
1474 	int new_ofs = state->acquired_refs;
1475 	int err;
1476 
1477 	err = resize_reference_state(state, state->acquired_refs + 1);
1478 	if (err)
1479 		return NULL;
1480 	state->refs[new_ofs].insn_idx = insn_idx;
1481 
1482 	return &state->refs[new_ofs];
1483 }
1484 
1485 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1486 {
1487 	struct bpf_reference_state *s;
1488 
1489 	s = acquire_reference_state(env, insn_idx);
1490 	if (!s)
1491 		return -ENOMEM;
1492 	s->type = REF_TYPE_PTR;
1493 	s->id = ++env->id_gen;
1494 	return s->id;
1495 }
1496 
1497 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1498 			      int id, void *ptr)
1499 {
1500 	struct bpf_verifier_state *state = env->cur_state;
1501 	struct bpf_reference_state *s;
1502 
1503 	s = acquire_reference_state(env, insn_idx);
1504 	s->type = type;
1505 	s->id = id;
1506 	s->ptr = ptr;
1507 
1508 	state->active_locks++;
1509 	return 0;
1510 }
1511 
1512 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1513 {
1514 	struct bpf_verifier_state *state = env->cur_state;
1515 	struct bpf_reference_state *s;
1516 
1517 	s = acquire_reference_state(env, insn_idx);
1518 	if (!s)
1519 		return -ENOMEM;
1520 	s->type = REF_TYPE_IRQ;
1521 	s->id = ++env->id_gen;
1522 
1523 	state->active_irq_id = s->id;
1524 	return s->id;
1525 }
1526 
1527 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1528 {
1529 	int last_idx;
1530 	size_t rem;
1531 
1532 	/* IRQ state requires the relative ordering of elements remaining the
1533 	 * same, since it relies on the refs array to behave as a stack, so that
1534 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1535 	 * the array instead of swapping the final element into the deleted idx.
1536 	 */
1537 	last_idx = state->acquired_refs - 1;
1538 	rem = state->acquired_refs - idx - 1;
1539 	if (last_idx && idx != last_idx)
1540 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1541 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1542 	state->acquired_refs--;
1543 	return;
1544 }
1545 
1546 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1547 {
1548 	int i;
1549 
1550 	for (i = 0; i < state->acquired_refs; i++) {
1551 		if (state->refs[i].type != type)
1552 			continue;
1553 		if (state->refs[i].id == id && state->refs[i].ptr == ptr) {
1554 			release_reference_state(state, i);
1555 			state->active_locks--;
1556 			return 0;
1557 		}
1558 	}
1559 	return -EINVAL;
1560 }
1561 
1562 static int release_irq_state(struct bpf_verifier_state *state, int id)
1563 {
1564 	u32 prev_id = 0;
1565 	int i;
1566 
1567 	if (id != state->active_irq_id)
1568 		return -EACCES;
1569 
1570 	for (i = 0; i < state->acquired_refs; i++) {
1571 		if (state->refs[i].type != REF_TYPE_IRQ)
1572 			continue;
1573 		if (state->refs[i].id == id) {
1574 			release_reference_state(state, i);
1575 			state->active_irq_id = prev_id;
1576 			return 0;
1577 		} else {
1578 			prev_id = state->refs[i].id;
1579 		}
1580 	}
1581 	return -EINVAL;
1582 }
1583 
1584 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1585 						   int id, void *ptr)
1586 {
1587 	int i;
1588 
1589 	for (i = 0; i < state->acquired_refs; i++) {
1590 		struct bpf_reference_state *s = &state->refs[i];
1591 
1592 		if (s->type != type)
1593 			continue;
1594 
1595 		if (s->id == id && s->ptr == ptr)
1596 			return s;
1597 	}
1598 	return NULL;
1599 }
1600 
1601 static void free_func_state(struct bpf_func_state *state)
1602 {
1603 	if (!state)
1604 		return;
1605 	kfree(state->stack);
1606 	kfree(state);
1607 }
1608 
1609 static void free_verifier_state(struct bpf_verifier_state *state,
1610 				bool free_self)
1611 {
1612 	int i;
1613 
1614 	for (i = 0; i <= state->curframe; i++) {
1615 		free_func_state(state->frame[i]);
1616 		state->frame[i] = NULL;
1617 	}
1618 	kfree(state->refs);
1619 	if (free_self)
1620 		kfree(state);
1621 }
1622 
1623 /* copy verifier state from src to dst growing dst stack space
1624  * when necessary to accommodate larger src stack
1625  */
1626 static int copy_func_state(struct bpf_func_state *dst,
1627 			   const struct bpf_func_state *src)
1628 {
1629 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1630 	return copy_stack_state(dst, src);
1631 }
1632 
1633 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1634 			       const struct bpf_verifier_state *src)
1635 {
1636 	struct bpf_func_state *dst;
1637 	int i, err;
1638 
1639 	/* if dst has more stack frames then src frame, free them, this is also
1640 	 * necessary in case of exceptional exits using bpf_throw.
1641 	 */
1642 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1643 		free_func_state(dst_state->frame[i]);
1644 		dst_state->frame[i] = NULL;
1645 	}
1646 	err = copy_reference_state(dst_state, src);
1647 	if (err)
1648 		return err;
1649 	dst_state->speculative = src->speculative;
1650 	dst_state->in_sleepable = src->in_sleepable;
1651 	dst_state->curframe = src->curframe;
1652 	dst_state->branches = src->branches;
1653 	dst_state->parent = src->parent;
1654 	dst_state->first_insn_idx = src->first_insn_idx;
1655 	dst_state->last_insn_idx = src->last_insn_idx;
1656 	dst_state->insn_hist_start = src->insn_hist_start;
1657 	dst_state->insn_hist_end = src->insn_hist_end;
1658 	dst_state->dfs_depth = src->dfs_depth;
1659 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1660 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1661 	dst_state->may_goto_depth = src->may_goto_depth;
1662 	for (i = 0; i <= src->curframe; i++) {
1663 		dst = dst_state->frame[i];
1664 		if (!dst) {
1665 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1666 			if (!dst)
1667 				return -ENOMEM;
1668 			dst_state->frame[i] = dst;
1669 		}
1670 		err = copy_func_state(dst, src->frame[i]);
1671 		if (err)
1672 			return err;
1673 	}
1674 	return 0;
1675 }
1676 
1677 static u32 state_htab_size(struct bpf_verifier_env *env)
1678 {
1679 	return env->prog->len;
1680 }
1681 
1682 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1683 {
1684 	struct bpf_verifier_state *cur = env->cur_state;
1685 	struct bpf_func_state *state = cur->frame[cur->curframe];
1686 
1687 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1688 }
1689 
1690 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1691 {
1692 	int fr;
1693 
1694 	if (a->curframe != b->curframe)
1695 		return false;
1696 
1697 	for (fr = a->curframe; fr >= 0; fr--)
1698 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1699 			return false;
1700 
1701 	return true;
1702 }
1703 
1704 /* Open coded iterators allow back-edges in the state graph in order to
1705  * check unbounded loops that iterators.
1706  *
1707  * In is_state_visited() it is necessary to know if explored states are
1708  * part of some loops in order to decide whether non-exact states
1709  * comparison could be used:
1710  * - non-exact states comparison establishes sub-state relation and uses
1711  *   read and precision marks to do so, these marks are propagated from
1712  *   children states and thus are not guaranteed to be final in a loop;
1713  * - exact states comparison just checks if current and explored states
1714  *   are identical (and thus form a back-edge).
1715  *
1716  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1717  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1718  * algorithm for loop structure detection and gives an overview of
1719  * relevant terminology. It also has helpful illustrations.
1720  *
1721  * [1] https://api.semanticscholar.org/CorpusID:15784067
1722  *
1723  * We use a similar algorithm but because loop nested structure is
1724  * irrelevant for verifier ours is significantly simpler and resembles
1725  * strongly connected components algorithm from Sedgewick's textbook.
1726  *
1727  * Define topmost loop entry as a first node of the loop traversed in a
1728  * depth first search starting from initial state. The goal of the loop
1729  * tracking algorithm is to associate topmost loop entries with states
1730  * derived from these entries.
1731  *
1732  * For each step in the DFS states traversal algorithm needs to identify
1733  * the following situations:
1734  *
1735  *          initial                     initial                   initial
1736  *            |                           |                         |
1737  *            V                           V                         V
1738  *           ...                         ...           .---------> hdr
1739  *            |                           |            |            |
1740  *            V                           V            |            V
1741  *           cur                     .-> succ          |    .------...
1742  *            |                      |    |            |    |       |
1743  *            V                      |    V            |    V       V
1744  *           succ                    '-- cur           |   ...     ...
1745  *                                                     |    |       |
1746  *                                                     |    V       V
1747  *                                                     |   succ <- cur
1748  *                                                     |    |
1749  *                                                     |    V
1750  *                                                     |   ...
1751  *                                                     |    |
1752  *                                                     '----'
1753  *
1754  *  (A) successor state of cur   (B) successor state of cur or it's entry
1755  *      not yet traversed            are in current DFS path, thus cur and succ
1756  *                                   are members of the same outermost loop
1757  *
1758  *                      initial                  initial
1759  *                        |                        |
1760  *                        V                        V
1761  *                       ...                      ...
1762  *                        |                        |
1763  *                        V                        V
1764  *                .------...               .------...
1765  *                |       |                |       |
1766  *                V       V                V       V
1767  *           .-> hdr     ...              ...     ...
1768  *           |    |       |                |       |
1769  *           |    V       V                V       V
1770  *           |   succ <- cur              succ <- cur
1771  *           |    |                        |
1772  *           |    V                        V
1773  *           |   ...                      ...
1774  *           |    |                        |
1775  *           '----'                       exit
1776  *
1777  * (C) successor state of cur is a part of some loop but this loop
1778  *     does not include cur or successor state is not in a loop at all.
1779  *
1780  * Algorithm could be described as the following python code:
1781  *
1782  *     traversed = set()   # Set of traversed nodes
1783  *     entries = {}        # Mapping from node to loop entry
1784  *     depths = {}         # Depth level assigned to graph node
1785  *     path = set()        # Current DFS path
1786  *
1787  *     # Find outermost loop entry known for n
1788  *     def get_loop_entry(n):
1789  *         h = entries.get(n, None)
1790  *         while h in entries and entries[h] != h:
1791  *             h = entries[h]
1792  *         return h
1793  *
1794  *     # Update n's loop entry if h's outermost entry comes
1795  *     # before n's outermost entry in current DFS path.
1796  *     def update_loop_entry(n, h):
1797  *         n1 = get_loop_entry(n) or n
1798  *         h1 = get_loop_entry(h) or h
1799  *         if h1 in path and depths[h1] <= depths[n1]:
1800  *             entries[n] = h1
1801  *
1802  *     def dfs(n, depth):
1803  *         traversed.add(n)
1804  *         path.add(n)
1805  *         depths[n] = depth
1806  *         for succ in G.successors(n):
1807  *             if succ not in traversed:
1808  *                 # Case A: explore succ and update cur's loop entry
1809  *                 #         only if succ's entry is in current DFS path.
1810  *                 dfs(succ, depth + 1)
1811  *                 h = get_loop_entry(succ)
1812  *                 update_loop_entry(n, h)
1813  *             else:
1814  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1815  *                 update_loop_entry(n, succ)
1816  *         path.remove(n)
1817  *
1818  * To adapt this algorithm for use with verifier:
1819  * - use st->branch == 0 as a signal that DFS of succ had been finished
1820  *   and cur's loop entry has to be updated (case A), handle this in
1821  *   update_branch_counts();
1822  * - use st->branch > 0 as a signal that st is in the current DFS path;
1823  * - handle cases B and C in is_state_visited();
1824  * - update topmost loop entry for intermediate states in get_loop_entry().
1825  */
1826 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1827 {
1828 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1829 
1830 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1831 		topmost = topmost->loop_entry;
1832 	/* Update loop entries for intermediate states to avoid this
1833 	 * traversal in future get_loop_entry() calls.
1834 	 */
1835 	while (st && st->loop_entry != topmost) {
1836 		old = st->loop_entry;
1837 		st->loop_entry = topmost;
1838 		st = old;
1839 	}
1840 	return topmost;
1841 }
1842 
1843 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1844 {
1845 	struct bpf_verifier_state *cur1, *hdr1;
1846 
1847 	cur1 = get_loop_entry(cur) ?: cur;
1848 	hdr1 = get_loop_entry(hdr) ?: hdr;
1849 	/* The head1->branches check decides between cases B and C in
1850 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1851 	 * head's topmost loop entry is not in current DFS path,
1852 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1853 	 * no need to update cur->loop_entry.
1854 	 */
1855 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1856 		cur->loop_entry = hdr;
1857 		hdr->used_as_loop_entry = true;
1858 	}
1859 }
1860 
1861 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1862 {
1863 	while (st) {
1864 		u32 br = --st->branches;
1865 
1866 		/* br == 0 signals that DFS exploration for 'st' is finished,
1867 		 * thus it is necessary to update parent's loop entry if it
1868 		 * turned out that st is a part of some loop.
1869 		 * This is a part of 'case A' in get_loop_entry() comment.
1870 		 */
1871 		if (br == 0 && st->parent && st->loop_entry)
1872 			update_loop_entry(st->parent, st->loop_entry);
1873 
1874 		/* WARN_ON(br > 1) technically makes sense here,
1875 		 * but see comment in push_stack(), hence:
1876 		 */
1877 		WARN_ONCE((int)br < 0,
1878 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1879 			  br);
1880 		if (br)
1881 			break;
1882 		st = st->parent;
1883 	}
1884 }
1885 
1886 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1887 		     int *insn_idx, bool pop_log)
1888 {
1889 	struct bpf_verifier_state *cur = env->cur_state;
1890 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1891 	int err;
1892 
1893 	if (env->head == NULL)
1894 		return -ENOENT;
1895 
1896 	if (cur) {
1897 		err = copy_verifier_state(cur, &head->st);
1898 		if (err)
1899 			return err;
1900 	}
1901 	if (pop_log)
1902 		bpf_vlog_reset(&env->log, head->log_pos);
1903 	if (insn_idx)
1904 		*insn_idx = head->insn_idx;
1905 	if (prev_insn_idx)
1906 		*prev_insn_idx = head->prev_insn_idx;
1907 	elem = head->next;
1908 	free_verifier_state(&head->st, false);
1909 	kfree(head);
1910 	env->head = elem;
1911 	env->stack_size--;
1912 	return 0;
1913 }
1914 
1915 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1916 					     int insn_idx, int prev_insn_idx,
1917 					     bool speculative)
1918 {
1919 	struct bpf_verifier_state *cur = env->cur_state;
1920 	struct bpf_verifier_stack_elem *elem;
1921 	int err;
1922 
1923 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1924 	if (!elem)
1925 		goto err;
1926 
1927 	elem->insn_idx = insn_idx;
1928 	elem->prev_insn_idx = prev_insn_idx;
1929 	elem->next = env->head;
1930 	elem->log_pos = env->log.end_pos;
1931 	env->head = elem;
1932 	env->stack_size++;
1933 	err = copy_verifier_state(&elem->st, cur);
1934 	if (err)
1935 		goto err;
1936 	elem->st.speculative |= speculative;
1937 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1938 		verbose(env, "The sequence of %d jumps is too complex.\n",
1939 			env->stack_size);
1940 		goto err;
1941 	}
1942 	if (elem->st.parent) {
1943 		++elem->st.parent->branches;
1944 		/* WARN_ON(branches > 2) technically makes sense here,
1945 		 * but
1946 		 * 1. speculative states will bump 'branches' for non-branch
1947 		 * instructions
1948 		 * 2. is_state_visited() heuristics may decide not to create
1949 		 * a new state for a sequence of branches and all such current
1950 		 * and cloned states will be pointing to a single parent state
1951 		 * which might have large 'branches' count.
1952 		 */
1953 	}
1954 	return &elem->st;
1955 err:
1956 	free_verifier_state(env->cur_state, true);
1957 	env->cur_state = NULL;
1958 	/* pop all elements and return */
1959 	while (!pop_stack(env, NULL, NULL, false));
1960 	return NULL;
1961 }
1962 
1963 #define CALLER_SAVED_REGS 6
1964 static const int caller_saved[CALLER_SAVED_REGS] = {
1965 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1966 };
1967 
1968 /* This helper doesn't clear reg->id */
1969 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1970 {
1971 	reg->var_off = tnum_const(imm);
1972 	reg->smin_value = (s64)imm;
1973 	reg->smax_value = (s64)imm;
1974 	reg->umin_value = imm;
1975 	reg->umax_value = imm;
1976 
1977 	reg->s32_min_value = (s32)imm;
1978 	reg->s32_max_value = (s32)imm;
1979 	reg->u32_min_value = (u32)imm;
1980 	reg->u32_max_value = (u32)imm;
1981 }
1982 
1983 /* Mark the unknown part of a register (variable offset or scalar value) as
1984  * known to have the value @imm.
1985  */
1986 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1987 {
1988 	/* Clear off and union(map_ptr, range) */
1989 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1990 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1991 	reg->id = 0;
1992 	reg->ref_obj_id = 0;
1993 	___mark_reg_known(reg, imm);
1994 }
1995 
1996 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1997 {
1998 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1999 	reg->s32_min_value = (s32)imm;
2000 	reg->s32_max_value = (s32)imm;
2001 	reg->u32_min_value = (u32)imm;
2002 	reg->u32_max_value = (u32)imm;
2003 }
2004 
2005 /* Mark the 'variable offset' part of a register as zero.  This should be
2006  * used only on registers holding a pointer type.
2007  */
2008 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2009 {
2010 	__mark_reg_known(reg, 0);
2011 }
2012 
2013 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2014 {
2015 	__mark_reg_known(reg, 0);
2016 	reg->type = SCALAR_VALUE;
2017 	/* all scalars are assumed imprecise initially (unless unprivileged,
2018 	 * in which case everything is forced to be precise)
2019 	 */
2020 	reg->precise = !env->bpf_capable;
2021 }
2022 
2023 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2024 				struct bpf_reg_state *regs, u32 regno)
2025 {
2026 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2027 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2028 		/* Something bad happened, let's kill all regs */
2029 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2030 			__mark_reg_not_init(env, regs + regno);
2031 		return;
2032 	}
2033 	__mark_reg_known_zero(regs + regno);
2034 }
2035 
2036 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2037 			      bool first_slot, int dynptr_id)
2038 {
2039 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2040 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2041 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2042 	 */
2043 	__mark_reg_known_zero(reg);
2044 	reg->type = CONST_PTR_TO_DYNPTR;
2045 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2046 	reg->id = dynptr_id;
2047 	reg->dynptr.type = type;
2048 	reg->dynptr.first_slot = first_slot;
2049 }
2050 
2051 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2052 {
2053 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2054 		const struct bpf_map *map = reg->map_ptr;
2055 
2056 		if (map->inner_map_meta) {
2057 			reg->type = CONST_PTR_TO_MAP;
2058 			reg->map_ptr = map->inner_map_meta;
2059 			/* transfer reg's id which is unique for every map_lookup_elem
2060 			 * as UID of the inner map.
2061 			 */
2062 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2063 				reg->map_uid = reg->id;
2064 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
2065 				reg->map_uid = reg->id;
2066 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2067 			reg->type = PTR_TO_XDP_SOCK;
2068 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2069 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2070 			reg->type = PTR_TO_SOCKET;
2071 		} else {
2072 			reg->type = PTR_TO_MAP_VALUE;
2073 		}
2074 		return;
2075 	}
2076 
2077 	reg->type &= ~PTR_MAYBE_NULL;
2078 }
2079 
2080 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2081 				struct btf_field_graph_root *ds_head)
2082 {
2083 	__mark_reg_known_zero(&regs[regno]);
2084 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2085 	regs[regno].btf = ds_head->btf;
2086 	regs[regno].btf_id = ds_head->value_btf_id;
2087 	regs[regno].off = ds_head->node_offset;
2088 }
2089 
2090 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2091 {
2092 	return type_is_pkt_pointer(reg->type);
2093 }
2094 
2095 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2096 {
2097 	return reg_is_pkt_pointer(reg) ||
2098 	       reg->type == PTR_TO_PACKET_END;
2099 }
2100 
2101 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2102 {
2103 	return base_type(reg->type) == PTR_TO_MEM &&
2104 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2105 }
2106 
2107 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2108 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2109 				    enum bpf_reg_type which)
2110 {
2111 	/* The register can already have a range from prior markings.
2112 	 * This is fine as long as it hasn't been advanced from its
2113 	 * origin.
2114 	 */
2115 	return reg->type == which &&
2116 	       reg->id == 0 &&
2117 	       reg->off == 0 &&
2118 	       tnum_equals_const(reg->var_off, 0);
2119 }
2120 
2121 /* Reset the min/max bounds of a register */
2122 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2123 {
2124 	reg->smin_value = S64_MIN;
2125 	reg->smax_value = S64_MAX;
2126 	reg->umin_value = 0;
2127 	reg->umax_value = U64_MAX;
2128 
2129 	reg->s32_min_value = S32_MIN;
2130 	reg->s32_max_value = S32_MAX;
2131 	reg->u32_min_value = 0;
2132 	reg->u32_max_value = U32_MAX;
2133 }
2134 
2135 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2136 {
2137 	reg->smin_value = S64_MIN;
2138 	reg->smax_value = S64_MAX;
2139 	reg->umin_value = 0;
2140 	reg->umax_value = U64_MAX;
2141 }
2142 
2143 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2144 {
2145 	reg->s32_min_value = S32_MIN;
2146 	reg->s32_max_value = S32_MAX;
2147 	reg->u32_min_value = 0;
2148 	reg->u32_max_value = U32_MAX;
2149 }
2150 
2151 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2152 {
2153 	struct tnum var32_off = tnum_subreg(reg->var_off);
2154 
2155 	/* min signed is max(sign bit) | min(other bits) */
2156 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2157 			var32_off.value | (var32_off.mask & S32_MIN));
2158 	/* max signed is min(sign bit) | max(other bits) */
2159 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2160 			var32_off.value | (var32_off.mask & S32_MAX));
2161 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2162 	reg->u32_max_value = min(reg->u32_max_value,
2163 				 (u32)(var32_off.value | var32_off.mask));
2164 }
2165 
2166 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2167 {
2168 	/* min signed is max(sign bit) | min(other bits) */
2169 	reg->smin_value = max_t(s64, reg->smin_value,
2170 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2171 	/* max signed is min(sign bit) | max(other bits) */
2172 	reg->smax_value = min_t(s64, reg->smax_value,
2173 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2174 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2175 	reg->umax_value = min(reg->umax_value,
2176 			      reg->var_off.value | reg->var_off.mask);
2177 }
2178 
2179 static void __update_reg_bounds(struct bpf_reg_state *reg)
2180 {
2181 	__update_reg32_bounds(reg);
2182 	__update_reg64_bounds(reg);
2183 }
2184 
2185 /* Uses signed min/max values to inform unsigned, and vice-versa */
2186 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2187 {
2188 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2189 	 * bits to improve our u32/s32 boundaries.
2190 	 *
2191 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2192 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2193 	 * [10, 20] range. But this property holds for any 64-bit range as
2194 	 * long as upper 32 bits in that entire range of values stay the same.
2195 	 *
2196 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2197 	 * in decimal) has the same upper 32 bits throughout all the values in
2198 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2199 	 * range.
2200 	 *
2201 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2202 	 * following the rules outlined below about u64/s64 correspondence
2203 	 * (which equally applies to u32 vs s32 correspondence). In general it
2204 	 * depends on actual hexadecimal values of 32-bit range. They can form
2205 	 * only valid u32, or only valid s32 ranges in some cases.
2206 	 *
2207 	 * So we use all these insights to derive bounds for subregisters here.
2208 	 */
2209 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2210 		/* u64 to u32 casting preserves validity of low 32 bits as
2211 		 * a range, if upper 32 bits are the same
2212 		 */
2213 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2214 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2215 
2216 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2217 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2218 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2219 		}
2220 	}
2221 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2222 		/* low 32 bits should form a proper u32 range */
2223 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2224 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2225 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2226 		}
2227 		/* low 32 bits should form a proper s32 range */
2228 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2229 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2230 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2231 		}
2232 	}
2233 	/* Special case where upper bits form a small sequence of two
2234 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2235 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2236 	 * going from negative numbers to positive numbers. E.g., let's say we
2237 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2238 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2239 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2240 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2241 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2242 	 * upper 32 bits. As a random example, s64 range
2243 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2244 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2245 	 */
2246 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2247 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2248 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2249 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2250 	}
2251 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2252 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2253 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2254 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2255 	}
2256 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2257 	 * try to learn from that
2258 	 */
2259 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2260 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2261 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2262 	}
2263 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2264 	 * are the same, so combine.  This works even in the negative case, e.g.
2265 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2266 	 */
2267 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2268 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2269 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2270 	}
2271 }
2272 
2273 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2274 {
2275 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2276 	 * try to learn from that. Let's do a bit of ASCII art to see when
2277 	 * this is happening. Let's take u64 range first:
2278 	 *
2279 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2280 	 * |-------------------------------|--------------------------------|
2281 	 *
2282 	 * Valid u64 range is formed when umin and umax are anywhere in the
2283 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2284 	 * straightforward. Let's see how s64 range maps onto the same range
2285 	 * of values, annotated below the line for comparison:
2286 	 *
2287 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2288 	 * |-------------------------------|--------------------------------|
2289 	 * 0                        S64_MAX S64_MIN                        -1
2290 	 *
2291 	 * So s64 values basically start in the middle and they are logically
2292 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2293 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2294 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2295 	 * more visually as mapped to sign-agnostic range of hex values.
2296 	 *
2297 	 *  u64 start                                               u64 end
2298 	 *  _______________________________________________________________
2299 	 * /                                                               \
2300 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2301 	 * |-------------------------------|--------------------------------|
2302 	 * 0                        S64_MAX S64_MIN                        -1
2303 	 *                                / \
2304 	 * >------------------------------   ------------------------------->
2305 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2306 	 *
2307 	 * What this means is that, in general, we can't always derive
2308 	 * something new about u64 from any random s64 range, and vice versa.
2309 	 *
2310 	 * But we can do that in two particular cases. One is when entire
2311 	 * u64/s64 range is *entirely* contained within left half of the above
2312 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2313 	 *
2314 	 * |-------------------------------|--------------------------------|
2315 	 *     ^                   ^            ^                 ^
2316 	 *     A                   B            C                 D
2317 	 *
2318 	 * [A, B] and [C, D] are contained entirely in their respective halves
2319 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2320 	 * will be non-negative both as u64 and s64 (and in fact it will be
2321 	 * identical ranges no matter the signedness). [C, D] treated as s64
2322 	 * will be a range of negative values, while in u64 it will be
2323 	 * non-negative range of values larger than 0x8000000000000000.
2324 	 *
2325 	 * Now, any other range here can't be represented in both u64 and s64
2326 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2327 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2328 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2329 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2330 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2331 	 * ranges as u64. Currently reg_state can't represent two segments per
2332 	 * numeric domain, so in such situations we can only derive maximal
2333 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2334 	 *
2335 	 * So we use these facts to derive umin/umax from smin/smax and vice
2336 	 * versa only if they stay within the same "half". This is equivalent
2337 	 * to checking sign bit: lower half will have sign bit as zero, upper
2338 	 * half have sign bit 1. Below in code we simplify this by just
2339 	 * casting umin/umax as smin/smax and checking if they form valid
2340 	 * range, and vice versa. Those are equivalent checks.
2341 	 */
2342 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2343 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2344 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2345 	}
2346 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2347 	 * are the same, so combine.  This works even in the negative case, e.g.
2348 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2349 	 */
2350 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2351 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2352 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2353 	}
2354 }
2355 
2356 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2357 {
2358 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2359 	 * values on both sides of 64-bit range in hope to have tighter range.
2360 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2361 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2362 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2363 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2364 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2365 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2366 	 * We just need to make sure that derived bounds we are intersecting
2367 	 * with are well-formed ranges in respective s64 or u64 domain, just
2368 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2369 	 */
2370 	__u64 new_umin, new_umax;
2371 	__s64 new_smin, new_smax;
2372 
2373 	/* u32 -> u64 tightening, it's always well-formed */
2374 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2375 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2376 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2377 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2378 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2379 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2380 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2381 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2382 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2383 
2384 	/* if s32 can be treated as valid u32 range, we can use it as well */
2385 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2386 		/* s32 -> u64 tightening */
2387 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2388 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2389 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2390 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2391 		/* s32 -> s64 tightening */
2392 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2393 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2394 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2395 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2396 	}
2397 
2398 	/* Here we would like to handle a special case after sign extending load,
2399 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2400 	 *
2401 	 * Upper bits are all 1s when register is in a range:
2402 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2403 	 * Upper bits are all 0s when register is in a range:
2404 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2405 	 * Together this forms are continuous range:
2406 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2407 	 *
2408 	 * Now, suppose that register range is in fact tighter:
2409 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2410 	 * Also suppose that it's 32-bit range is positive,
2411 	 * meaning that lower 32-bits of the full 64-bit register
2412 	 * are in the range:
2413 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2414 	 *
2415 	 * If this happens, then any value in a range:
2416 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2417 	 * is smaller than a lowest bound of the range (R):
2418 	 *   0xffff_ffff_8000_0000
2419 	 * which means that upper bits of the full 64-bit register
2420 	 * can't be all 1s, when lower bits are in range (W).
2421 	 *
2422 	 * Note that:
2423 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2424 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2425 	 * These relations are used in the conditions below.
2426 	 */
2427 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2428 		reg->smin_value = reg->s32_min_value;
2429 		reg->smax_value = reg->s32_max_value;
2430 		reg->umin_value = reg->s32_min_value;
2431 		reg->umax_value = reg->s32_max_value;
2432 		reg->var_off = tnum_intersect(reg->var_off,
2433 					      tnum_range(reg->smin_value, reg->smax_value));
2434 	}
2435 }
2436 
2437 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2438 {
2439 	__reg32_deduce_bounds(reg);
2440 	__reg64_deduce_bounds(reg);
2441 	__reg_deduce_mixed_bounds(reg);
2442 }
2443 
2444 /* Attempts to improve var_off based on unsigned min/max information */
2445 static void __reg_bound_offset(struct bpf_reg_state *reg)
2446 {
2447 	struct tnum var64_off = tnum_intersect(reg->var_off,
2448 					       tnum_range(reg->umin_value,
2449 							  reg->umax_value));
2450 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2451 					       tnum_range(reg->u32_min_value,
2452 							  reg->u32_max_value));
2453 
2454 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2455 }
2456 
2457 static void reg_bounds_sync(struct bpf_reg_state *reg)
2458 {
2459 	/* We might have learned new bounds from the var_off. */
2460 	__update_reg_bounds(reg);
2461 	/* We might have learned something about the sign bit. */
2462 	__reg_deduce_bounds(reg);
2463 	__reg_deduce_bounds(reg);
2464 	/* We might have learned some bits from the bounds. */
2465 	__reg_bound_offset(reg);
2466 	/* Intersecting with the old var_off might have improved our bounds
2467 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2468 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2469 	 */
2470 	__update_reg_bounds(reg);
2471 }
2472 
2473 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2474 				   struct bpf_reg_state *reg, const char *ctx)
2475 {
2476 	const char *msg;
2477 
2478 	if (reg->umin_value > reg->umax_value ||
2479 	    reg->smin_value > reg->smax_value ||
2480 	    reg->u32_min_value > reg->u32_max_value ||
2481 	    reg->s32_min_value > reg->s32_max_value) {
2482 		    msg = "range bounds violation";
2483 		    goto out;
2484 	}
2485 
2486 	if (tnum_is_const(reg->var_off)) {
2487 		u64 uval = reg->var_off.value;
2488 		s64 sval = (s64)uval;
2489 
2490 		if (reg->umin_value != uval || reg->umax_value != uval ||
2491 		    reg->smin_value != sval || reg->smax_value != sval) {
2492 			msg = "const tnum out of sync with range bounds";
2493 			goto out;
2494 		}
2495 	}
2496 
2497 	if (tnum_subreg_is_const(reg->var_off)) {
2498 		u32 uval32 = tnum_subreg(reg->var_off).value;
2499 		s32 sval32 = (s32)uval32;
2500 
2501 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2502 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2503 			msg = "const subreg tnum out of sync with range bounds";
2504 			goto out;
2505 		}
2506 	}
2507 
2508 	return 0;
2509 out:
2510 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2511 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2512 		ctx, msg, reg->umin_value, reg->umax_value,
2513 		reg->smin_value, reg->smax_value,
2514 		reg->u32_min_value, reg->u32_max_value,
2515 		reg->s32_min_value, reg->s32_max_value,
2516 		reg->var_off.value, reg->var_off.mask);
2517 	if (env->test_reg_invariants)
2518 		return -EFAULT;
2519 	__mark_reg_unbounded(reg);
2520 	return 0;
2521 }
2522 
2523 static bool __reg32_bound_s64(s32 a)
2524 {
2525 	return a >= 0 && a <= S32_MAX;
2526 }
2527 
2528 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2529 {
2530 	reg->umin_value = reg->u32_min_value;
2531 	reg->umax_value = reg->u32_max_value;
2532 
2533 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2534 	 * be positive otherwise set to worse case bounds and refine later
2535 	 * from tnum.
2536 	 */
2537 	if (__reg32_bound_s64(reg->s32_min_value) &&
2538 	    __reg32_bound_s64(reg->s32_max_value)) {
2539 		reg->smin_value = reg->s32_min_value;
2540 		reg->smax_value = reg->s32_max_value;
2541 	} else {
2542 		reg->smin_value = 0;
2543 		reg->smax_value = U32_MAX;
2544 	}
2545 }
2546 
2547 /* Mark a register as having a completely unknown (scalar) value. */
2548 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2549 {
2550 	/*
2551 	 * Clear type, off, and union(map_ptr, range) and
2552 	 * padding between 'type' and union
2553 	 */
2554 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2555 	reg->type = SCALAR_VALUE;
2556 	reg->id = 0;
2557 	reg->ref_obj_id = 0;
2558 	reg->var_off = tnum_unknown;
2559 	reg->frameno = 0;
2560 	reg->precise = false;
2561 	__mark_reg_unbounded(reg);
2562 }
2563 
2564 /* Mark a register as having a completely unknown (scalar) value,
2565  * initialize .precise as true when not bpf capable.
2566  */
2567 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2568 			       struct bpf_reg_state *reg)
2569 {
2570 	__mark_reg_unknown_imprecise(reg);
2571 	reg->precise = !env->bpf_capable;
2572 }
2573 
2574 static void mark_reg_unknown(struct bpf_verifier_env *env,
2575 			     struct bpf_reg_state *regs, u32 regno)
2576 {
2577 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2578 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2579 		/* Something bad happened, let's kill all regs except FP */
2580 		for (regno = 0; regno < BPF_REG_FP; regno++)
2581 			__mark_reg_not_init(env, regs + regno);
2582 		return;
2583 	}
2584 	__mark_reg_unknown(env, regs + regno);
2585 }
2586 
2587 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2588 				struct bpf_reg_state *regs,
2589 				u32 regno,
2590 				s32 s32_min,
2591 				s32 s32_max)
2592 {
2593 	struct bpf_reg_state *reg = regs + regno;
2594 
2595 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2596 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2597 
2598 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2599 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2600 
2601 	reg_bounds_sync(reg);
2602 
2603 	return reg_bounds_sanity_check(env, reg, "s32_range");
2604 }
2605 
2606 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2607 				struct bpf_reg_state *reg)
2608 {
2609 	__mark_reg_unknown(env, reg);
2610 	reg->type = NOT_INIT;
2611 }
2612 
2613 static void mark_reg_not_init(struct bpf_verifier_env *env,
2614 			      struct bpf_reg_state *regs, u32 regno)
2615 {
2616 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2617 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2618 		/* Something bad happened, let's kill all regs except FP */
2619 		for (regno = 0; regno < BPF_REG_FP; regno++)
2620 			__mark_reg_not_init(env, regs + regno);
2621 		return;
2622 	}
2623 	__mark_reg_not_init(env, regs + regno);
2624 }
2625 
2626 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2627 			    struct bpf_reg_state *regs, u32 regno,
2628 			    enum bpf_reg_type reg_type,
2629 			    struct btf *btf, u32 btf_id,
2630 			    enum bpf_type_flag flag)
2631 {
2632 	if (reg_type == SCALAR_VALUE) {
2633 		mark_reg_unknown(env, regs, regno);
2634 		return;
2635 	}
2636 	mark_reg_known_zero(env, regs, regno);
2637 	regs[regno].type = PTR_TO_BTF_ID | flag;
2638 	regs[regno].btf = btf;
2639 	regs[regno].btf_id = btf_id;
2640 	if (type_may_be_null(flag))
2641 		regs[regno].id = ++env->id_gen;
2642 }
2643 
2644 #define DEF_NOT_SUBREG	(0)
2645 static void init_reg_state(struct bpf_verifier_env *env,
2646 			   struct bpf_func_state *state)
2647 {
2648 	struct bpf_reg_state *regs = state->regs;
2649 	int i;
2650 
2651 	for (i = 0; i < MAX_BPF_REG; i++) {
2652 		mark_reg_not_init(env, regs, i);
2653 		regs[i].live = REG_LIVE_NONE;
2654 		regs[i].parent = NULL;
2655 		regs[i].subreg_def = DEF_NOT_SUBREG;
2656 	}
2657 
2658 	/* frame pointer */
2659 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2660 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2661 	regs[BPF_REG_FP].frameno = state->frameno;
2662 }
2663 
2664 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2665 {
2666 	return (struct bpf_retval_range){ minval, maxval };
2667 }
2668 
2669 #define BPF_MAIN_FUNC (-1)
2670 static void init_func_state(struct bpf_verifier_env *env,
2671 			    struct bpf_func_state *state,
2672 			    int callsite, int frameno, int subprogno)
2673 {
2674 	state->callsite = callsite;
2675 	state->frameno = frameno;
2676 	state->subprogno = subprogno;
2677 	state->callback_ret_range = retval_range(0, 0);
2678 	init_reg_state(env, state);
2679 	mark_verifier_state_scratched(env);
2680 }
2681 
2682 /* Similar to push_stack(), but for async callbacks */
2683 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2684 						int insn_idx, int prev_insn_idx,
2685 						int subprog, bool is_sleepable)
2686 {
2687 	struct bpf_verifier_stack_elem *elem;
2688 	struct bpf_func_state *frame;
2689 
2690 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2691 	if (!elem)
2692 		goto err;
2693 
2694 	elem->insn_idx = insn_idx;
2695 	elem->prev_insn_idx = prev_insn_idx;
2696 	elem->next = env->head;
2697 	elem->log_pos = env->log.end_pos;
2698 	env->head = elem;
2699 	env->stack_size++;
2700 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2701 		verbose(env,
2702 			"The sequence of %d jumps is too complex for async cb.\n",
2703 			env->stack_size);
2704 		goto err;
2705 	}
2706 	/* Unlike push_stack() do not copy_verifier_state().
2707 	 * The caller state doesn't matter.
2708 	 * This is async callback. It starts in a fresh stack.
2709 	 * Initialize it similar to do_check_common().
2710 	 * But we do need to make sure to not clobber insn_hist, so we keep
2711 	 * chaining insn_hist_start/insn_hist_end indices as for a normal
2712 	 * child state.
2713 	 */
2714 	elem->st.branches = 1;
2715 	elem->st.in_sleepable = is_sleepable;
2716 	elem->st.insn_hist_start = env->cur_state->insn_hist_end;
2717 	elem->st.insn_hist_end = elem->st.insn_hist_start;
2718 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2719 	if (!frame)
2720 		goto err;
2721 	init_func_state(env, frame,
2722 			BPF_MAIN_FUNC /* callsite */,
2723 			0 /* frameno within this callchain */,
2724 			subprog /* subprog number within this prog */);
2725 	elem->st.frame[0] = frame;
2726 	return &elem->st;
2727 err:
2728 	free_verifier_state(env->cur_state, true);
2729 	env->cur_state = NULL;
2730 	/* pop all elements and return */
2731 	while (!pop_stack(env, NULL, NULL, false));
2732 	return NULL;
2733 }
2734 
2735 
2736 enum reg_arg_type {
2737 	SRC_OP,		/* register is used as source operand */
2738 	DST_OP,		/* register is used as destination operand */
2739 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2740 };
2741 
2742 static int cmp_subprogs(const void *a, const void *b)
2743 {
2744 	return ((struct bpf_subprog_info *)a)->start -
2745 	       ((struct bpf_subprog_info *)b)->start;
2746 }
2747 
2748 /* Find subprogram that contains instruction at 'off' */
2749 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2750 {
2751 	struct bpf_subprog_info *vals = env->subprog_info;
2752 	int l, r, m;
2753 
2754 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2755 		return NULL;
2756 
2757 	l = 0;
2758 	r = env->subprog_cnt - 1;
2759 	while (l < r) {
2760 		m = l + (r - l + 1) / 2;
2761 		if (vals[m].start <= off)
2762 			l = m;
2763 		else
2764 			r = m - 1;
2765 	}
2766 	return &vals[l];
2767 }
2768 
2769 /* Find subprogram that starts exactly at 'off' */
2770 static int find_subprog(struct bpf_verifier_env *env, int off)
2771 {
2772 	struct bpf_subprog_info *p;
2773 
2774 	p = find_containing_subprog(env, off);
2775 	if (!p || p->start != off)
2776 		return -ENOENT;
2777 	return p - env->subprog_info;
2778 }
2779 
2780 static int add_subprog(struct bpf_verifier_env *env, int off)
2781 {
2782 	int insn_cnt = env->prog->len;
2783 	int ret;
2784 
2785 	if (off >= insn_cnt || off < 0) {
2786 		verbose(env, "call to invalid destination\n");
2787 		return -EINVAL;
2788 	}
2789 	ret = find_subprog(env, off);
2790 	if (ret >= 0)
2791 		return ret;
2792 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2793 		verbose(env, "too many subprograms\n");
2794 		return -E2BIG;
2795 	}
2796 	/* determine subprog starts. The end is one before the next starts */
2797 	env->subprog_info[env->subprog_cnt++].start = off;
2798 	sort(env->subprog_info, env->subprog_cnt,
2799 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2800 	return env->subprog_cnt - 1;
2801 }
2802 
2803 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2804 {
2805 	struct bpf_prog_aux *aux = env->prog->aux;
2806 	struct btf *btf = aux->btf;
2807 	const struct btf_type *t;
2808 	u32 main_btf_id, id;
2809 	const char *name;
2810 	int ret, i;
2811 
2812 	/* Non-zero func_info_cnt implies valid btf */
2813 	if (!aux->func_info_cnt)
2814 		return 0;
2815 	main_btf_id = aux->func_info[0].type_id;
2816 
2817 	t = btf_type_by_id(btf, main_btf_id);
2818 	if (!t) {
2819 		verbose(env, "invalid btf id for main subprog in func_info\n");
2820 		return -EINVAL;
2821 	}
2822 
2823 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2824 	if (IS_ERR(name)) {
2825 		ret = PTR_ERR(name);
2826 		/* If there is no tag present, there is no exception callback */
2827 		if (ret == -ENOENT)
2828 			ret = 0;
2829 		else if (ret == -EEXIST)
2830 			verbose(env, "multiple exception callback tags for main subprog\n");
2831 		return ret;
2832 	}
2833 
2834 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2835 	if (ret < 0) {
2836 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2837 		return ret;
2838 	}
2839 	id = ret;
2840 	t = btf_type_by_id(btf, id);
2841 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2842 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2843 		return -EINVAL;
2844 	}
2845 	ret = 0;
2846 	for (i = 0; i < aux->func_info_cnt; i++) {
2847 		if (aux->func_info[i].type_id != id)
2848 			continue;
2849 		ret = aux->func_info[i].insn_off;
2850 		/* Further func_info and subprog checks will also happen
2851 		 * later, so assume this is the right insn_off for now.
2852 		 */
2853 		if (!ret) {
2854 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2855 			ret = -EINVAL;
2856 		}
2857 	}
2858 	if (!ret) {
2859 		verbose(env, "exception callback type id not found in func_info\n");
2860 		ret = -EINVAL;
2861 	}
2862 	return ret;
2863 }
2864 
2865 #define MAX_KFUNC_DESCS 256
2866 #define MAX_KFUNC_BTFS	256
2867 
2868 struct bpf_kfunc_desc {
2869 	struct btf_func_model func_model;
2870 	u32 func_id;
2871 	s32 imm;
2872 	u16 offset;
2873 	unsigned long addr;
2874 };
2875 
2876 struct bpf_kfunc_btf {
2877 	struct btf *btf;
2878 	struct module *module;
2879 	u16 offset;
2880 };
2881 
2882 struct bpf_kfunc_desc_tab {
2883 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2884 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2885 	 * available, therefore at the end of verification do_misc_fixups()
2886 	 * sorts this by imm and offset.
2887 	 */
2888 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2889 	u32 nr_descs;
2890 };
2891 
2892 struct bpf_kfunc_btf_tab {
2893 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2894 	u32 nr_descs;
2895 };
2896 
2897 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2898 {
2899 	const struct bpf_kfunc_desc *d0 = a;
2900 	const struct bpf_kfunc_desc *d1 = b;
2901 
2902 	/* func_id is not greater than BTF_MAX_TYPE */
2903 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2904 }
2905 
2906 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2907 {
2908 	const struct bpf_kfunc_btf *d0 = a;
2909 	const struct bpf_kfunc_btf *d1 = b;
2910 
2911 	return d0->offset - d1->offset;
2912 }
2913 
2914 static const struct bpf_kfunc_desc *
2915 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2916 {
2917 	struct bpf_kfunc_desc desc = {
2918 		.func_id = func_id,
2919 		.offset = offset,
2920 	};
2921 	struct bpf_kfunc_desc_tab *tab;
2922 
2923 	tab = prog->aux->kfunc_tab;
2924 	return bsearch(&desc, tab->descs, tab->nr_descs,
2925 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2926 }
2927 
2928 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2929 		       u16 btf_fd_idx, u8 **func_addr)
2930 {
2931 	const struct bpf_kfunc_desc *desc;
2932 
2933 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2934 	if (!desc)
2935 		return -EFAULT;
2936 
2937 	*func_addr = (u8 *)desc->addr;
2938 	return 0;
2939 }
2940 
2941 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2942 					 s16 offset)
2943 {
2944 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2945 	struct bpf_kfunc_btf_tab *tab;
2946 	struct bpf_kfunc_btf *b;
2947 	struct module *mod;
2948 	struct btf *btf;
2949 	int btf_fd;
2950 
2951 	tab = env->prog->aux->kfunc_btf_tab;
2952 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2953 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2954 	if (!b) {
2955 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2956 			verbose(env, "too many different module BTFs\n");
2957 			return ERR_PTR(-E2BIG);
2958 		}
2959 
2960 		if (bpfptr_is_null(env->fd_array)) {
2961 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2962 			return ERR_PTR(-EPROTO);
2963 		}
2964 
2965 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2966 					    offset * sizeof(btf_fd),
2967 					    sizeof(btf_fd)))
2968 			return ERR_PTR(-EFAULT);
2969 
2970 		btf = btf_get_by_fd(btf_fd);
2971 		if (IS_ERR(btf)) {
2972 			verbose(env, "invalid module BTF fd specified\n");
2973 			return btf;
2974 		}
2975 
2976 		if (!btf_is_module(btf)) {
2977 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2978 			btf_put(btf);
2979 			return ERR_PTR(-EINVAL);
2980 		}
2981 
2982 		mod = btf_try_get_module(btf);
2983 		if (!mod) {
2984 			btf_put(btf);
2985 			return ERR_PTR(-ENXIO);
2986 		}
2987 
2988 		b = &tab->descs[tab->nr_descs++];
2989 		b->btf = btf;
2990 		b->module = mod;
2991 		b->offset = offset;
2992 
2993 		/* sort() reorders entries by value, so b may no longer point
2994 		 * to the right entry after this
2995 		 */
2996 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2997 		     kfunc_btf_cmp_by_off, NULL);
2998 	} else {
2999 		btf = b->btf;
3000 	}
3001 
3002 	return btf;
3003 }
3004 
3005 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3006 {
3007 	if (!tab)
3008 		return;
3009 
3010 	while (tab->nr_descs--) {
3011 		module_put(tab->descs[tab->nr_descs].module);
3012 		btf_put(tab->descs[tab->nr_descs].btf);
3013 	}
3014 	kfree(tab);
3015 }
3016 
3017 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3018 {
3019 	if (offset) {
3020 		if (offset < 0) {
3021 			/* In the future, this can be allowed to increase limit
3022 			 * of fd index into fd_array, interpreted as u16.
3023 			 */
3024 			verbose(env, "negative offset disallowed for kernel module function call\n");
3025 			return ERR_PTR(-EINVAL);
3026 		}
3027 
3028 		return __find_kfunc_desc_btf(env, offset);
3029 	}
3030 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3031 }
3032 
3033 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3034 {
3035 	const struct btf_type *func, *func_proto;
3036 	struct bpf_kfunc_btf_tab *btf_tab;
3037 	struct bpf_kfunc_desc_tab *tab;
3038 	struct bpf_prog_aux *prog_aux;
3039 	struct bpf_kfunc_desc *desc;
3040 	const char *func_name;
3041 	struct btf *desc_btf;
3042 	unsigned long call_imm;
3043 	unsigned long addr;
3044 	int err;
3045 
3046 	prog_aux = env->prog->aux;
3047 	tab = prog_aux->kfunc_tab;
3048 	btf_tab = prog_aux->kfunc_btf_tab;
3049 	if (!tab) {
3050 		if (!btf_vmlinux) {
3051 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3052 			return -ENOTSUPP;
3053 		}
3054 
3055 		if (!env->prog->jit_requested) {
3056 			verbose(env, "JIT is required for calling kernel function\n");
3057 			return -ENOTSUPP;
3058 		}
3059 
3060 		if (!bpf_jit_supports_kfunc_call()) {
3061 			verbose(env, "JIT does not support calling kernel function\n");
3062 			return -ENOTSUPP;
3063 		}
3064 
3065 		if (!env->prog->gpl_compatible) {
3066 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3067 			return -EINVAL;
3068 		}
3069 
3070 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
3071 		if (!tab)
3072 			return -ENOMEM;
3073 		prog_aux->kfunc_tab = tab;
3074 	}
3075 
3076 	/* func_id == 0 is always invalid, but instead of returning an error, be
3077 	 * conservative and wait until the code elimination pass before returning
3078 	 * error, so that invalid calls that get pruned out can be in BPF programs
3079 	 * loaded from userspace.  It is also required that offset be untouched
3080 	 * for such calls.
3081 	 */
3082 	if (!func_id && !offset)
3083 		return 0;
3084 
3085 	if (!btf_tab && offset) {
3086 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
3087 		if (!btf_tab)
3088 			return -ENOMEM;
3089 		prog_aux->kfunc_btf_tab = btf_tab;
3090 	}
3091 
3092 	desc_btf = find_kfunc_desc_btf(env, offset);
3093 	if (IS_ERR(desc_btf)) {
3094 		verbose(env, "failed to find BTF for kernel function\n");
3095 		return PTR_ERR(desc_btf);
3096 	}
3097 
3098 	if (find_kfunc_desc(env->prog, func_id, offset))
3099 		return 0;
3100 
3101 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3102 		verbose(env, "too many different kernel function calls\n");
3103 		return -E2BIG;
3104 	}
3105 
3106 	func = btf_type_by_id(desc_btf, func_id);
3107 	if (!func || !btf_type_is_func(func)) {
3108 		verbose(env, "kernel btf_id %u is not a function\n",
3109 			func_id);
3110 		return -EINVAL;
3111 	}
3112 	func_proto = btf_type_by_id(desc_btf, func->type);
3113 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3114 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3115 			func_id);
3116 		return -EINVAL;
3117 	}
3118 
3119 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3120 	addr = kallsyms_lookup_name(func_name);
3121 	if (!addr) {
3122 		verbose(env, "cannot find address for kernel function %s\n",
3123 			func_name);
3124 		return -EINVAL;
3125 	}
3126 	specialize_kfunc(env, func_id, offset, &addr);
3127 
3128 	if (bpf_jit_supports_far_kfunc_call()) {
3129 		call_imm = func_id;
3130 	} else {
3131 		call_imm = BPF_CALL_IMM(addr);
3132 		/* Check whether the relative offset overflows desc->imm */
3133 		if ((unsigned long)(s32)call_imm != call_imm) {
3134 			verbose(env, "address of kernel function %s is out of range\n",
3135 				func_name);
3136 			return -EINVAL;
3137 		}
3138 	}
3139 
3140 	if (bpf_dev_bound_kfunc_id(func_id)) {
3141 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3142 		if (err)
3143 			return err;
3144 	}
3145 
3146 	desc = &tab->descs[tab->nr_descs++];
3147 	desc->func_id = func_id;
3148 	desc->imm = call_imm;
3149 	desc->offset = offset;
3150 	desc->addr = addr;
3151 	err = btf_distill_func_proto(&env->log, desc_btf,
3152 				     func_proto, func_name,
3153 				     &desc->func_model);
3154 	if (!err)
3155 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3156 		     kfunc_desc_cmp_by_id_off, NULL);
3157 	return err;
3158 }
3159 
3160 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3161 {
3162 	const struct bpf_kfunc_desc *d0 = a;
3163 	const struct bpf_kfunc_desc *d1 = b;
3164 
3165 	if (d0->imm != d1->imm)
3166 		return d0->imm < d1->imm ? -1 : 1;
3167 	if (d0->offset != d1->offset)
3168 		return d0->offset < d1->offset ? -1 : 1;
3169 	return 0;
3170 }
3171 
3172 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3173 {
3174 	struct bpf_kfunc_desc_tab *tab;
3175 
3176 	tab = prog->aux->kfunc_tab;
3177 	if (!tab)
3178 		return;
3179 
3180 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3181 	     kfunc_desc_cmp_by_imm_off, NULL);
3182 }
3183 
3184 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3185 {
3186 	return !!prog->aux->kfunc_tab;
3187 }
3188 
3189 const struct btf_func_model *
3190 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3191 			 const struct bpf_insn *insn)
3192 {
3193 	const struct bpf_kfunc_desc desc = {
3194 		.imm = insn->imm,
3195 		.offset = insn->off,
3196 	};
3197 	const struct bpf_kfunc_desc *res;
3198 	struct bpf_kfunc_desc_tab *tab;
3199 
3200 	tab = prog->aux->kfunc_tab;
3201 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3202 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3203 
3204 	return res ? &res->func_model : NULL;
3205 }
3206 
3207 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3208 {
3209 	struct bpf_subprog_info *subprog = env->subprog_info;
3210 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3211 	struct bpf_insn *insn = env->prog->insnsi;
3212 
3213 	/* Add entry function. */
3214 	ret = add_subprog(env, 0);
3215 	if (ret)
3216 		return ret;
3217 
3218 	for (i = 0; i < insn_cnt; i++, insn++) {
3219 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3220 		    !bpf_pseudo_kfunc_call(insn))
3221 			continue;
3222 
3223 		if (!env->bpf_capable) {
3224 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3225 			return -EPERM;
3226 		}
3227 
3228 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3229 			ret = add_subprog(env, i + insn->imm + 1);
3230 		else
3231 			ret = add_kfunc_call(env, insn->imm, insn->off);
3232 
3233 		if (ret < 0)
3234 			return ret;
3235 	}
3236 
3237 	ret = bpf_find_exception_callback_insn_off(env);
3238 	if (ret < 0)
3239 		return ret;
3240 	ex_cb_insn = ret;
3241 
3242 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3243 	 * marked using BTF decl tag to serve as the exception callback.
3244 	 */
3245 	if (ex_cb_insn) {
3246 		ret = add_subprog(env, ex_cb_insn);
3247 		if (ret < 0)
3248 			return ret;
3249 		for (i = 1; i < env->subprog_cnt; i++) {
3250 			if (env->subprog_info[i].start != ex_cb_insn)
3251 				continue;
3252 			env->exception_callback_subprog = i;
3253 			mark_subprog_exc_cb(env, i);
3254 			break;
3255 		}
3256 	}
3257 
3258 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3259 	 * logic. 'subprog_cnt' should not be increased.
3260 	 */
3261 	subprog[env->subprog_cnt].start = insn_cnt;
3262 
3263 	if (env->log.level & BPF_LOG_LEVEL2)
3264 		for (i = 0; i < env->subprog_cnt; i++)
3265 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3266 
3267 	return 0;
3268 }
3269 
3270 static int check_subprogs(struct bpf_verifier_env *env)
3271 {
3272 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3273 	struct bpf_subprog_info *subprog = env->subprog_info;
3274 	struct bpf_insn *insn = env->prog->insnsi;
3275 	int insn_cnt = env->prog->len;
3276 
3277 	/* now check that all jumps are within the same subprog */
3278 	subprog_start = subprog[cur_subprog].start;
3279 	subprog_end = subprog[cur_subprog + 1].start;
3280 	for (i = 0; i < insn_cnt; i++) {
3281 		u8 code = insn[i].code;
3282 
3283 		if (code == (BPF_JMP | BPF_CALL) &&
3284 		    insn[i].src_reg == 0 &&
3285 		    insn[i].imm == BPF_FUNC_tail_call) {
3286 			subprog[cur_subprog].has_tail_call = true;
3287 			subprog[cur_subprog].tail_call_reachable = true;
3288 		}
3289 		if (BPF_CLASS(code) == BPF_LD &&
3290 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3291 			subprog[cur_subprog].has_ld_abs = true;
3292 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3293 			goto next;
3294 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3295 			goto next;
3296 		if (code == (BPF_JMP32 | BPF_JA))
3297 			off = i + insn[i].imm + 1;
3298 		else
3299 			off = i + insn[i].off + 1;
3300 		if (off < subprog_start || off >= subprog_end) {
3301 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3302 			return -EINVAL;
3303 		}
3304 next:
3305 		if (i == subprog_end - 1) {
3306 			/* to avoid fall-through from one subprog into another
3307 			 * the last insn of the subprog should be either exit
3308 			 * or unconditional jump back or bpf_throw call
3309 			 */
3310 			if (code != (BPF_JMP | BPF_EXIT) &&
3311 			    code != (BPF_JMP32 | BPF_JA) &&
3312 			    code != (BPF_JMP | BPF_JA)) {
3313 				verbose(env, "last insn is not an exit or jmp\n");
3314 				return -EINVAL;
3315 			}
3316 			subprog_start = subprog_end;
3317 			cur_subprog++;
3318 			if (cur_subprog < env->subprog_cnt)
3319 				subprog_end = subprog[cur_subprog + 1].start;
3320 		}
3321 	}
3322 	return 0;
3323 }
3324 
3325 /* Parentage chain of this register (or stack slot) should take care of all
3326  * issues like callee-saved registers, stack slot allocation time, etc.
3327  */
3328 static int mark_reg_read(struct bpf_verifier_env *env,
3329 			 const struct bpf_reg_state *state,
3330 			 struct bpf_reg_state *parent, u8 flag)
3331 {
3332 	bool writes = parent == state->parent; /* Observe write marks */
3333 	int cnt = 0;
3334 
3335 	while (parent) {
3336 		/* if read wasn't screened by an earlier write ... */
3337 		if (writes && state->live & REG_LIVE_WRITTEN)
3338 			break;
3339 		if (parent->live & REG_LIVE_DONE) {
3340 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3341 				reg_type_str(env, parent->type),
3342 				parent->var_off.value, parent->off);
3343 			return -EFAULT;
3344 		}
3345 		/* The first condition is more likely to be true than the
3346 		 * second, checked it first.
3347 		 */
3348 		if ((parent->live & REG_LIVE_READ) == flag ||
3349 		    parent->live & REG_LIVE_READ64)
3350 			/* The parentage chain never changes and
3351 			 * this parent was already marked as LIVE_READ.
3352 			 * There is no need to keep walking the chain again and
3353 			 * keep re-marking all parents as LIVE_READ.
3354 			 * This case happens when the same register is read
3355 			 * multiple times without writes into it in-between.
3356 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3357 			 * then no need to set the weak REG_LIVE_READ32.
3358 			 */
3359 			break;
3360 		/* ... then we depend on parent's value */
3361 		parent->live |= flag;
3362 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3363 		if (flag == REG_LIVE_READ64)
3364 			parent->live &= ~REG_LIVE_READ32;
3365 		state = parent;
3366 		parent = state->parent;
3367 		writes = true;
3368 		cnt++;
3369 	}
3370 
3371 	if (env->longest_mark_read_walk < cnt)
3372 		env->longest_mark_read_walk = cnt;
3373 	return 0;
3374 }
3375 
3376 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3377 				    int spi, int nr_slots)
3378 {
3379 	struct bpf_func_state *state = func(env, reg);
3380 	int err, i;
3381 
3382 	for (i = 0; i < nr_slots; i++) {
3383 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3384 
3385 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3386 		if (err)
3387 			return err;
3388 
3389 		mark_stack_slot_scratched(env, spi - i);
3390 	}
3391 	return 0;
3392 }
3393 
3394 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3395 {
3396 	int spi;
3397 
3398 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3399 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3400 	 * check_kfunc_call.
3401 	 */
3402 	if (reg->type == CONST_PTR_TO_DYNPTR)
3403 		return 0;
3404 	spi = dynptr_get_spi(env, reg);
3405 	if (spi < 0)
3406 		return spi;
3407 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3408 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3409 	 * read.
3410 	 */
3411 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3412 }
3413 
3414 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3415 			  int spi, int nr_slots)
3416 {
3417 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3418 }
3419 
3420 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3421 {
3422 	int spi;
3423 
3424 	spi = irq_flag_get_spi(env, reg);
3425 	if (spi < 0)
3426 		return spi;
3427 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3428 }
3429 
3430 /* This function is supposed to be used by the following 32-bit optimization
3431  * code only. It returns TRUE if the source or destination register operates
3432  * on 64-bit, otherwise return FALSE.
3433  */
3434 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3435 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3436 {
3437 	u8 code, class, op;
3438 
3439 	code = insn->code;
3440 	class = BPF_CLASS(code);
3441 	op = BPF_OP(code);
3442 	if (class == BPF_JMP) {
3443 		/* BPF_EXIT for "main" will reach here. Return TRUE
3444 		 * conservatively.
3445 		 */
3446 		if (op == BPF_EXIT)
3447 			return true;
3448 		if (op == BPF_CALL) {
3449 			/* BPF to BPF call will reach here because of marking
3450 			 * caller saved clobber with DST_OP_NO_MARK for which we
3451 			 * don't care the register def because they are anyway
3452 			 * marked as NOT_INIT already.
3453 			 */
3454 			if (insn->src_reg == BPF_PSEUDO_CALL)
3455 				return false;
3456 			/* Helper call will reach here because of arg type
3457 			 * check, conservatively return TRUE.
3458 			 */
3459 			if (t == SRC_OP)
3460 				return true;
3461 
3462 			return false;
3463 		}
3464 	}
3465 
3466 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3467 		return false;
3468 
3469 	if (class == BPF_ALU64 || class == BPF_JMP ||
3470 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3471 		return true;
3472 
3473 	if (class == BPF_ALU || class == BPF_JMP32)
3474 		return false;
3475 
3476 	if (class == BPF_LDX) {
3477 		if (t != SRC_OP)
3478 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3479 		/* LDX source must be ptr. */
3480 		return true;
3481 	}
3482 
3483 	if (class == BPF_STX) {
3484 		/* BPF_STX (including atomic variants) has multiple source
3485 		 * operands, one of which is a ptr. Check whether the caller is
3486 		 * asking about it.
3487 		 */
3488 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3489 			return true;
3490 		return BPF_SIZE(code) == BPF_DW;
3491 	}
3492 
3493 	if (class == BPF_LD) {
3494 		u8 mode = BPF_MODE(code);
3495 
3496 		/* LD_IMM64 */
3497 		if (mode == BPF_IMM)
3498 			return true;
3499 
3500 		/* Both LD_IND and LD_ABS return 32-bit data. */
3501 		if (t != SRC_OP)
3502 			return  false;
3503 
3504 		/* Implicit ctx ptr. */
3505 		if (regno == BPF_REG_6)
3506 			return true;
3507 
3508 		/* Explicit source could be any width. */
3509 		return true;
3510 	}
3511 
3512 	if (class == BPF_ST)
3513 		/* The only source register for BPF_ST is a ptr. */
3514 		return true;
3515 
3516 	/* Conservatively return true at default. */
3517 	return true;
3518 }
3519 
3520 /* Return the regno defined by the insn, or -1. */
3521 static int insn_def_regno(const struct bpf_insn *insn)
3522 {
3523 	switch (BPF_CLASS(insn->code)) {
3524 	case BPF_JMP:
3525 	case BPF_JMP32:
3526 	case BPF_ST:
3527 		return -1;
3528 	case BPF_STX:
3529 		if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3530 		     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3531 		    (insn->imm & BPF_FETCH)) {
3532 			if (insn->imm == BPF_CMPXCHG)
3533 				return BPF_REG_0;
3534 			else
3535 				return insn->src_reg;
3536 		} else {
3537 			return -1;
3538 		}
3539 	default:
3540 		return insn->dst_reg;
3541 	}
3542 }
3543 
3544 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3545 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3546 {
3547 	int dst_reg = insn_def_regno(insn);
3548 
3549 	if (dst_reg == -1)
3550 		return false;
3551 
3552 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3553 }
3554 
3555 static void mark_insn_zext(struct bpf_verifier_env *env,
3556 			   struct bpf_reg_state *reg)
3557 {
3558 	s32 def_idx = reg->subreg_def;
3559 
3560 	if (def_idx == DEF_NOT_SUBREG)
3561 		return;
3562 
3563 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3564 	/* The dst will be zero extended, so won't be sub-register anymore. */
3565 	reg->subreg_def = DEF_NOT_SUBREG;
3566 }
3567 
3568 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3569 			   enum reg_arg_type t)
3570 {
3571 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3572 	struct bpf_reg_state *reg;
3573 	bool rw64;
3574 
3575 	if (regno >= MAX_BPF_REG) {
3576 		verbose(env, "R%d is invalid\n", regno);
3577 		return -EINVAL;
3578 	}
3579 
3580 	mark_reg_scratched(env, regno);
3581 
3582 	reg = &regs[regno];
3583 	rw64 = is_reg64(env, insn, regno, reg, t);
3584 	if (t == SRC_OP) {
3585 		/* check whether register used as source operand can be read */
3586 		if (reg->type == NOT_INIT) {
3587 			verbose(env, "R%d !read_ok\n", regno);
3588 			return -EACCES;
3589 		}
3590 		/* We don't need to worry about FP liveness because it's read-only */
3591 		if (regno == BPF_REG_FP)
3592 			return 0;
3593 
3594 		if (rw64)
3595 			mark_insn_zext(env, reg);
3596 
3597 		return mark_reg_read(env, reg, reg->parent,
3598 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3599 	} else {
3600 		/* check whether register used as dest operand can be written to */
3601 		if (regno == BPF_REG_FP) {
3602 			verbose(env, "frame pointer is read only\n");
3603 			return -EACCES;
3604 		}
3605 		reg->live |= REG_LIVE_WRITTEN;
3606 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3607 		if (t == DST_OP)
3608 			mark_reg_unknown(env, regs, regno);
3609 	}
3610 	return 0;
3611 }
3612 
3613 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3614 			 enum reg_arg_type t)
3615 {
3616 	struct bpf_verifier_state *vstate = env->cur_state;
3617 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3618 
3619 	return __check_reg_arg(env, state->regs, regno, t);
3620 }
3621 
3622 static int insn_stack_access_flags(int frameno, int spi)
3623 {
3624 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3625 }
3626 
3627 static int insn_stack_access_spi(int insn_flags)
3628 {
3629 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3630 }
3631 
3632 static int insn_stack_access_frameno(int insn_flags)
3633 {
3634 	return insn_flags & INSN_F_FRAMENO_MASK;
3635 }
3636 
3637 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3638 {
3639 	env->insn_aux_data[idx].jmp_point = true;
3640 }
3641 
3642 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3643 {
3644 	return env->insn_aux_data[insn_idx].jmp_point;
3645 }
3646 
3647 #define LR_FRAMENO_BITS	3
3648 #define LR_SPI_BITS	6
3649 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3650 #define LR_SIZE_BITS	4
3651 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3652 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3653 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3654 #define LR_SPI_OFF	LR_FRAMENO_BITS
3655 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3656 #define LINKED_REGS_MAX	6
3657 
3658 struct linked_reg {
3659 	u8 frameno;
3660 	union {
3661 		u8 spi;
3662 		u8 regno;
3663 	};
3664 	bool is_reg;
3665 };
3666 
3667 struct linked_regs {
3668 	int cnt;
3669 	struct linked_reg entries[LINKED_REGS_MAX];
3670 };
3671 
3672 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3673 {
3674 	if (s->cnt < LINKED_REGS_MAX)
3675 		return &s->entries[s->cnt++];
3676 
3677 	return NULL;
3678 }
3679 
3680 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3681  * number of elements currently in stack.
3682  * Pack one history entry for linked registers as 10 bits in the following format:
3683  * - 3-bits frameno
3684  * - 6-bits spi_or_reg
3685  * - 1-bit  is_reg
3686  */
3687 static u64 linked_regs_pack(struct linked_regs *s)
3688 {
3689 	u64 val = 0;
3690 	int i;
3691 
3692 	for (i = 0; i < s->cnt; ++i) {
3693 		struct linked_reg *e = &s->entries[i];
3694 		u64 tmp = 0;
3695 
3696 		tmp |= e->frameno;
3697 		tmp |= e->spi << LR_SPI_OFF;
3698 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3699 
3700 		val <<= LR_ENTRY_BITS;
3701 		val |= tmp;
3702 	}
3703 	val <<= LR_SIZE_BITS;
3704 	val |= s->cnt;
3705 	return val;
3706 }
3707 
3708 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3709 {
3710 	int i;
3711 
3712 	s->cnt = val & LR_SIZE_MASK;
3713 	val >>= LR_SIZE_BITS;
3714 
3715 	for (i = 0; i < s->cnt; ++i) {
3716 		struct linked_reg *e = &s->entries[i];
3717 
3718 		e->frameno =  val & LR_FRAMENO_MASK;
3719 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3720 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3721 		val >>= LR_ENTRY_BITS;
3722 	}
3723 }
3724 
3725 /* for any branch, call, exit record the history of jmps in the given state */
3726 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3727 			     int insn_flags, u64 linked_regs)
3728 {
3729 	struct bpf_insn_hist_entry *p;
3730 	size_t alloc_size;
3731 
3732 	/* combine instruction flags if we already recorded this instruction */
3733 	if (env->cur_hist_ent) {
3734 		/* atomic instructions push insn_flags twice, for READ and
3735 		 * WRITE sides, but they should agree on stack slot
3736 		 */
3737 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3738 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3739 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3740 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3741 		env->cur_hist_ent->flags |= insn_flags;
3742 		WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
3743 			  "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
3744 			  env->insn_idx, env->cur_hist_ent->linked_regs);
3745 		env->cur_hist_ent->linked_regs = linked_regs;
3746 		return 0;
3747 	}
3748 
3749 	if (cur->insn_hist_end + 1 > env->insn_hist_cap) {
3750 		alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p));
3751 		p = kvrealloc(env->insn_hist, alloc_size, GFP_USER);
3752 		if (!p)
3753 			return -ENOMEM;
3754 		env->insn_hist = p;
3755 		env->insn_hist_cap = alloc_size / sizeof(*p);
3756 	}
3757 
3758 	p = &env->insn_hist[cur->insn_hist_end];
3759 	p->idx = env->insn_idx;
3760 	p->prev_idx = env->prev_insn_idx;
3761 	p->flags = insn_flags;
3762 	p->linked_regs = linked_regs;
3763 
3764 	cur->insn_hist_end++;
3765 	env->cur_hist_ent = p;
3766 
3767 	return 0;
3768 }
3769 
3770 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env,
3771 						       u32 hist_start, u32 hist_end, int insn_idx)
3772 {
3773 	if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx)
3774 		return &env->insn_hist[hist_end - 1];
3775 	return NULL;
3776 }
3777 
3778 /* Backtrack one insn at a time. If idx is not at the top of recorded
3779  * history then previous instruction came from straight line execution.
3780  * Return -ENOENT if we exhausted all instructions within given state.
3781  *
3782  * It's legal to have a bit of a looping with the same starting and ending
3783  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3784  * instruction index is the same as state's first_idx doesn't mean we are
3785  * done. If there is still some jump history left, we should keep going. We
3786  * need to take into account that we might have a jump history between given
3787  * state's parent and itself, due to checkpointing. In this case, we'll have
3788  * history entry recording a jump from last instruction of parent state and
3789  * first instruction of given state.
3790  */
3791 static int get_prev_insn_idx(const struct bpf_verifier_env *env,
3792 			     struct bpf_verifier_state *st,
3793 			     int insn_idx, u32 hist_start, u32 *hist_endp)
3794 {
3795 	u32 hist_end = *hist_endp;
3796 	u32 cnt = hist_end - hist_start;
3797 
3798 	if (insn_idx == st->first_insn_idx) {
3799 		if (cnt == 0)
3800 			return -ENOENT;
3801 		if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx)
3802 			return -ENOENT;
3803 	}
3804 
3805 	if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) {
3806 		(*hist_endp)--;
3807 		return env->insn_hist[hist_end - 1].prev_idx;
3808 	} else {
3809 		return insn_idx - 1;
3810 	}
3811 }
3812 
3813 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3814 {
3815 	const struct btf_type *func;
3816 	struct btf *desc_btf;
3817 
3818 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3819 		return NULL;
3820 
3821 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3822 	if (IS_ERR(desc_btf))
3823 		return "<error>";
3824 
3825 	func = btf_type_by_id(desc_btf, insn->imm);
3826 	return btf_name_by_offset(desc_btf, func->name_off);
3827 }
3828 
3829 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3830 {
3831 	bt->frame = frame;
3832 }
3833 
3834 static inline void bt_reset(struct backtrack_state *bt)
3835 {
3836 	struct bpf_verifier_env *env = bt->env;
3837 
3838 	memset(bt, 0, sizeof(*bt));
3839 	bt->env = env;
3840 }
3841 
3842 static inline u32 bt_empty(struct backtrack_state *bt)
3843 {
3844 	u64 mask = 0;
3845 	int i;
3846 
3847 	for (i = 0; i <= bt->frame; i++)
3848 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3849 
3850 	return mask == 0;
3851 }
3852 
3853 static inline int bt_subprog_enter(struct backtrack_state *bt)
3854 {
3855 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3856 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3857 		WARN_ONCE(1, "verifier backtracking bug");
3858 		return -EFAULT;
3859 	}
3860 	bt->frame++;
3861 	return 0;
3862 }
3863 
3864 static inline int bt_subprog_exit(struct backtrack_state *bt)
3865 {
3866 	if (bt->frame == 0) {
3867 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3868 		WARN_ONCE(1, "verifier backtracking bug");
3869 		return -EFAULT;
3870 	}
3871 	bt->frame--;
3872 	return 0;
3873 }
3874 
3875 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3876 {
3877 	bt->reg_masks[frame] |= 1 << reg;
3878 }
3879 
3880 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3881 {
3882 	bt->reg_masks[frame] &= ~(1 << reg);
3883 }
3884 
3885 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3886 {
3887 	bt_set_frame_reg(bt, bt->frame, reg);
3888 }
3889 
3890 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3891 {
3892 	bt_clear_frame_reg(bt, bt->frame, reg);
3893 }
3894 
3895 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3896 {
3897 	bt->stack_masks[frame] |= 1ull << slot;
3898 }
3899 
3900 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3901 {
3902 	bt->stack_masks[frame] &= ~(1ull << slot);
3903 }
3904 
3905 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3906 {
3907 	return bt->reg_masks[frame];
3908 }
3909 
3910 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3911 {
3912 	return bt->reg_masks[bt->frame];
3913 }
3914 
3915 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3916 {
3917 	return bt->stack_masks[frame];
3918 }
3919 
3920 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3921 {
3922 	return bt->stack_masks[bt->frame];
3923 }
3924 
3925 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3926 {
3927 	return bt->reg_masks[bt->frame] & (1 << reg);
3928 }
3929 
3930 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
3931 {
3932 	return bt->reg_masks[frame] & (1 << reg);
3933 }
3934 
3935 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3936 {
3937 	return bt->stack_masks[frame] & (1ull << slot);
3938 }
3939 
3940 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3941 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3942 {
3943 	DECLARE_BITMAP(mask, 64);
3944 	bool first = true;
3945 	int i, n;
3946 
3947 	buf[0] = '\0';
3948 
3949 	bitmap_from_u64(mask, reg_mask);
3950 	for_each_set_bit(i, mask, 32) {
3951 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3952 		first = false;
3953 		buf += n;
3954 		buf_sz -= n;
3955 		if (buf_sz < 0)
3956 			break;
3957 	}
3958 }
3959 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3960 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3961 {
3962 	DECLARE_BITMAP(mask, 64);
3963 	bool first = true;
3964 	int i, n;
3965 
3966 	buf[0] = '\0';
3967 
3968 	bitmap_from_u64(mask, stack_mask);
3969 	for_each_set_bit(i, mask, 64) {
3970 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3971 		first = false;
3972 		buf += n;
3973 		buf_sz -= n;
3974 		if (buf_sz < 0)
3975 			break;
3976 	}
3977 }
3978 
3979 /* If any register R in hist->linked_regs is marked as precise in bt,
3980  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3981  */
3982 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist)
3983 {
3984 	struct linked_regs linked_regs;
3985 	bool some_precise = false;
3986 	int i;
3987 
3988 	if (!hist || hist->linked_regs == 0)
3989 		return;
3990 
3991 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3992 	for (i = 0; i < linked_regs.cnt; ++i) {
3993 		struct linked_reg *e = &linked_regs.entries[i];
3994 
3995 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3996 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3997 			some_precise = true;
3998 			break;
3999 		}
4000 	}
4001 
4002 	if (!some_precise)
4003 		return;
4004 
4005 	for (i = 0; i < linked_regs.cnt; ++i) {
4006 		struct linked_reg *e = &linked_regs.entries[i];
4007 
4008 		if (e->is_reg)
4009 			bt_set_frame_reg(bt, e->frameno, e->regno);
4010 		else
4011 			bt_set_frame_slot(bt, e->frameno, e->spi);
4012 	}
4013 }
4014 
4015 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
4016 
4017 /* For given verifier state backtrack_insn() is called from the last insn to
4018  * the first insn. Its purpose is to compute a bitmask of registers and
4019  * stack slots that needs precision in the parent verifier state.
4020  *
4021  * @idx is an index of the instruction we are currently processing;
4022  * @subseq_idx is an index of the subsequent instruction that:
4023  *   - *would be* executed next, if jump history is viewed in forward order;
4024  *   - *was* processed previously during backtracking.
4025  */
4026 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4027 			  struct bpf_insn_hist_entry *hist, struct backtrack_state *bt)
4028 {
4029 	const struct bpf_insn_cbs cbs = {
4030 		.cb_call	= disasm_kfunc_name,
4031 		.cb_print	= verbose,
4032 		.private_data	= env,
4033 	};
4034 	struct bpf_insn *insn = env->prog->insnsi + idx;
4035 	u8 class = BPF_CLASS(insn->code);
4036 	u8 opcode = BPF_OP(insn->code);
4037 	u8 mode = BPF_MODE(insn->code);
4038 	u32 dreg = insn->dst_reg;
4039 	u32 sreg = insn->src_reg;
4040 	u32 spi, i, fr;
4041 
4042 	if (insn->code == 0)
4043 		return 0;
4044 	if (env->log.level & BPF_LOG_LEVEL2) {
4045 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4046 		verbose(env, "mark_precise: frame%d: regs=%s ",
4047 			bt->frame, env->tmp_str_buf);
4048 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4049 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4050 		verbose(env, "%d: ", idx);
4051 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4052 	}
4053 
4054 	/* If there is a history record that some registers gained range at this insn,
4055 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4056 	 * accounts for these registers.
4057 	 */
4058 	bt_sync_linked_regs(bt, hist);
4059 
4060 	if (class == BPF_ALU || class == BPF_ALU64) {
4061 		if (!bt_is_reg_set(bt, dreg))
4062 			return 0;
4063 		if (opcode == BPF_END || opcode == BPF_NEG) {
4064 			/* sreg is reserved and unused
4065 			 * dreg still need precision before this insn
4066 			 */
4067 			return 0;
4068 		} else if (opcode == BPF_MOV) {
4069 			if (BPF_SRC(insn->code) == BPF_X) {
4070 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4071 				 * dreg needs precision after this insn
4072 				 * sreg needs precision before this insn
4073 				 */
4074 				bt_clear_reg(bt, dreg);
4075 				if (sreg != BPF_REG_FP)
4076 					bt_set_reg(bt, sreg);
4077 			} else {
4078 				/* dreg = K
4079 				 * dreg needs precision after this insn.
4080 				 * Corresponding register is already marked
4081 				 * as precise=true in this verifier state.
4082 				 * No further markings in parent are necessary
4083 				 */
4084 				bt_clear_reg(bt, dreg);
4085 			}
4086 		} else {
4087 			if (BPF_SRC(insn->code) == BPF_X) {
4088 				/* dreg += sreg
4089 				 * both dreg and sreg need precision
4090 				 * before this insn
4091 				 */
4092 				if (sreg != BPF_REG_FP)
4093 					bt_set_reg(bt, sreg);
4094 			} /* else dreg += K
4095 			   * dreg still needs precision before this insn
4096 			   */
4097 		}
4098 	} else if (class == BPF_LDX) {
4099 		if (!bt_is_reg_set(bt, dreg))
4100 			return 0;
4101 		bt_clear_reg(bt, dreg);
4102 
4103 		/* scalars can only be spilled into stack w/o losing precision.
4104 		 * Load from any other memory can be zero extended.
4105 		 * The desire to keep that precision is already indicated
4106 		 * by 'precise' mark in corresponding register of this state.
4107 		 * No further tracking necessary.
4108 		 */
4109 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4110 			return 0;
4111 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4112 		 * that [fp - off] slot contains scalar that needs to be
4113 		 * tracked with precision
4114 		 */
4115 		spi = insn_stack_access_spi(hist->flags);
4116 		fr = insn_stack_access_frameno(hist->flags);
4117 		bt_set_frame_slot(bt, fr, spi);
4118 	} else if (class == BPF_STX || class == BPF_ST) {
4119 		if (bt_is_reg_set(bt, dreg))
4120 			/* stx & st shouldn't be using _scalar_ dst_reg
4121 			 * to access memory. It means backtracking
4122 			 * encountered a case of pointer subtraction.
4123 			 */
4124 			return -ENOTSUPP;
4125 		/* scalars can only be spilled into stack */
4126 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4127 			return 0;
4128 		spi = insn_stack_access_spi(hist->flags);
4129 		fr = insn_stack_access_frameno(hist->flags);
4130 		if (!bt_is_frame_slot_set(bt, fr, spi))
4131 			return 0;
4132 		bt_clear_frame_slot(bt, fr, spi);
4133 		if (class == BPF_STX)
4134 			bt_set_reg(bt, sreg);
4135 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4136 		if (bpf_pseudo_call(insn)) {
4137 			int subprog_insn_idx, subprog;
4138 
4139 			subprog_insn_idx = idx + insn->imm + 1;
4140 			subprog = find_subprog(env, subprog_insn_idx);
4141 			if (subprog < 0)
4142 				return -EFAULT;
4143 
4144 			if (subprog_is_global(env, subprog)) {
4145 				/* check that jump history doesn't have any
4146 				 * extra instructions from subprog; the next
4147 				 * instruction after call to global subprog
4148 				 * should be literally next instruction in
4149 				 * caller program
4150 				 */
4151 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
4152 				/* r1-r5 are invalidated after subprog call,
4153 				 * so for global func call it shouldn't be set
4154 				 * anymore
4155 				 */
4156 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4157 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4158 					WARN_ONCE(1, "verifier backtracking bug");
4159 					return -EFAULT;
4160 				}
4161 				/* global subprog always sets R0 */
4162 				bt_clear_reg(bt, BPF_REG_0);
4163 				return 0;
4164 			} else {
4165 				/* static subprog call instruction, which
4166 				 * means that we are exiting current subprog,
4167 				 * so only r1-r5 could be still requested as
4168 				 * precise, r0 and r6-r10 or any stack slot in
4169 				 * the current frame should be zero by now
4170 				 */
4171 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4172 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4173 					WARN_ONCE(1, "verifier backtracking bug");
4174 					return -EFAULT;
4175 				}
4176 				/* we are now tracking register spills correctly,
4177 				 * so any instance of leftover slots is a bug
4178 				 */
4179 				if (bt_stack_mask(bt) != 0) {
4180 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4181 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
4182 					return -EFAULT;
4183 				}
4184 				/* propagate r1-r5 to the caller */
4185 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4186 					if (bt_is_reg_set(bt, i)) {
4187 						bt_clear_reg(bt, i);
4188 						bt_set_frame_reg(bt, bt->frame - 1, i);
4189 					}
4190 				}
4191 				if (bt_subprog_exit(bt))
4192 					return -EFAULT;
4193 				return 0;
4194 			}
4195 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4196 			/* exit from callback subprog to callback-calling helper or
4197 			 * kfunc call. Use idx/subseq_idx check to discern it from
4198 			 * straight line code backtracking.
4199 			 * Unlike the subprog call handling above, we shouldn't
4200 			 * propagate precision of r1-r5 (if any requested), as they are
4201 			 * not actually arguments passed directly to callback subprogs
4202 			 */
4203 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4204 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4205 				WARN_ONCE(1, "verifier backtracking bug");
4206 				return -EFAULT;
4207 			}
4208 			if (bt_stack_mask(bt) != 0) {
4209 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4210 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
4211 				return -EFAULT;
4212 			}
4213 			/* clear r1-r5 in callback subprog's mask */
4214 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4215 				bt_clear_reg(bt, i);
4216 			if (bt_subprog_exit(bt))
4217 				return -EFAULT;
4218 			return 0;
4219 		} else if (opcode == BPF_CALL) {
4220 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4221 			 * catch this error later. Make backtracking conservative
4222 			 * with ENOTSUPP.
4223 			 */
4224 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4225 				return -ENOTSUPP;
4226 			/* regular helper call sets R0 */
4227 			bt_clear_reg(bt, BPF_REG_0);
4228 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4229 				/* if backtracing was looking for registers R1-R5
4230 				 * they should have been found already.
4231 				 */
4232 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4233 				WARN_ONCE(1, "verifier backtracking bug");
4234 				return -EFAULT;
4235 			}
4236 		} else if (opcode == BPF_EXIT) {
4237 			bool r0_precise;
4238 
4239 			/* Backtracking to a nested function call, 'idx' is a part of
4240 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4241 			 * In case of a regular function call, instructions giving
4242 			 * precision to registers R1-R5 should have been found already.
4243 			 * In case of a callback, it is ok to have R1-R5 marked for
4244 			 * backtracking, as these registers are set by the function
4245 			 * invoking callback.
4246 			 */
4247 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4248 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4249 					bt_clear_reg(bt, i);
4250 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4251 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4252 				WARN_ONCE(1, "verifier backtracking bug");
4253 				return -EFAULT;
4254 			}
4255 
4256 			/* BPF_EXIT in subprog or callback always returns
4257 			 * right after the call instruction, so by checking
4258 			 * whether the instruction at subseq_idx-1 is subprog
4259 			 * call or not we can distinguish actual exit from
4260 			 * *subprog* from exit from *callback*. In the former
4261 			 * case, we need to propagate r0 precision, if
4262 			 * necessary. In the former we never do that.
4263 			 */
4264 			r0_precise = subseq_idx - 1 >= 0 &&
4265 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4266 				     bt_is_reg_set(bt, BPF_REG_0);
4267 
4268 			bt_clear_reg(bt, BPF_REG_0);
4269 			if (bt_subprog_enter(bt))
4270 				return -EFAULT;
4271 
4272 			if (r0_precise)
4273 				bt_set_reg(bt, BPF_REG_0);
4274 			/* r6-r9 and stack slots will stay set in caller frame
4275 			 * bitmasks until we return back from callee(s)
4276 			 */
4277 			return 0;
4278 		} else if (BPF_SRC(insn->code) == BPF_X) {
4279 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4280 				return 0;
4281 			/* dreg <cond> sreg
4282 			 * Both dreg and sreg need precision before
4283 			 * this insn. If only sreg was marked precise
4284 			 * before it would be equally necessary to
4285 			 * propagate it to dreg.
4286 			 */
4287 			bt_set_reg(bt, dreg);
4288 			bt_set_reg(bt, sreg);
4289 		} else if (BPF_SRC(insn->code) == BPF_K) {
4290 			 /* dreg <cond> K
4291 			  * Only dreg still needs precision before
4292 			  * this insn, so for the K-based conditional
4293 			  * there is nothing new to be marked.
4294 			  */
4295 		}
4296 	} else if (class == BPF_LD) {
4297 		if (!bt_is_reg_set(bt, dreg))
4298 			return 0;
4299 		bt_clear_reg(bt, dreg);
4300 		/* It's ld_imm64 or ld_abs or ld_ind.
4301 		 * For ld_imm64 no further tracking of precision
4302 		 * into parent is necessary
4303 		 */
4304 		if (mode == BPF_IND || mode == BPF_ABS)
4305 			/* to be analyzed */
4306 			return -ENOTSUPP;
4307 	}
4308 	/* Propagate precision marks to linked registers, to account for
4309 	 * registers marked as precise in this function.
4310 	 */
4311 	bt_sync_linked_regs(bt, hist);
4312 	return 0;
4313 }
4314 
4315 /* the scalar precision tracking algorithm:
4316  * . at the start all registers have precise=false.
4317  * . scalar ranges are tracked as normal through alu and jmp insns.
4318  * . once precise value of the scalar register is used in:
4319  *   .  ptr + scalar alu
4320  *   . if (scalar cond K|scalar)
4321  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4322  *   backtrack through the verifier states and mark all registers and
4323  *   stack slots with spilled constants that these scalar regisers
4324  *   should be precise.
4325  * . during state pruning two registers (or spilled stack slots)
4326  *   are equivalent if both are not precise.
4327  *
4328  * Note the verifier cannot simply walk register parentage chain,
4329  * since many different registers and stack slots could have been
4330  * used to compute single precise scalar.
4331  *
4332  * The approach of starting with precise=true for all registers and then
4333  * backtrack to mark a register as not precise when the verifier detects
4334  * that program doesn't care about specific value (e.g., when helper
4335  * takes register as ARG_ANYTHING parameter) is not safe.
4336  *
4337  * It's ok to walk single parentage chain of the verifier states.
4338  * It's possible that this backtracking will go all the way till 1st insn.
4339  * All other branches will be explored for needing precision later.
4340  *
4341  * The backtracking needs to deal with cases like:
4342  *   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)
4343  * r9 -= r8
4344  * r5 = r9
4345  * if r5 > 0x79f goto pc+7
4346  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4347  * r5 += 1
4348  * ...
4349  * call bpf_perf_event_output#25
4350  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4351  *
4352  * and this case:
4353  * r6 = 1
4354  * call foo // uses callee's r6 inside to compute r0
4355  * r0 += r6
4356  * if r0 == 0 goto
4357  *
4358  * to track above reg_mask/stack_mask needs to be independent for each frame.
4359  *
4360  * Also if parent's curframe > frame where backtracking started,
4361  * the verifier need to mark registers in both frames, otherwise callees
4362  * may incorrectly prune callers. This is similar to
4363  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4364  *
4365  * For now backtracking falls back into conservative marking.
4366  */
4367 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4368 				     struct bpf_verifier_state *st)
4369 {
4370 	struct bpf_func_state *func;
4371 	struct bpf_reg_state *reg;
4372 	int i, j;
4373 
4374 	if (env->log.level & BPF_LOG_LEVEL2) {
4375 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4376 			st->curframe);
4377 	}
4378 
4379 	/* big hammer: mark all scalars precise in this path.
4380 	 * pop_stack may still get !precise scalars.
4381 	 * We also skip current state and go straight to first parent state,
4382 	 * because precision markings in current non-checkpointed state are
4383 	 * not needed. See why in the comment in __mark_chain_precision below.
4384 	 */
4385 	for (st = st->parent; st; st = st->parent) {
4386 		for (i = 0; i <= st->curframe; i++) {
4387 			func = st->frame[i];
4388 			for (j = 0; j < BPF_REG_FP; j++) {
4389 				reg = &func->regs[j];
4390 				if (reg->type != SCALAR_VALUE || reg->precise)
4391 					continue;
4392 				reg->precise = true;
4393 				if (env->log.level & BPF_LOG_LEVEL2) {
4394 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4395 						i, j);
4396 				}
4397 			}
4398 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4399 				if (!is_spilled_reg(&func->stack[j]))
4400 					continue;
4401 				reg = &func->stack[j].spilled_ptr;
4402 				if (reg->type != SCALAR_VALUE || reg->precise)
4403 					continue;
4404 				reg->precise = true;
4405 				if (env->log.level & BPF_LOG_LEVEL2) {
4406 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4407 						i, -(j + 1) * 8);
4408 				}
4409 			}
4410 		}
4411 	}
4412 }
4413 
4414 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4415 {
4416 	struct bpf_func_state *func;
4417 	struct bpf_reg_state *reg;
4418 	int i, j;
4419 
4420 	for (i = 0; i <= st->curframe; i++) {
4421 		func = st->frame[i];
4422 		for (j = 0; j < BPF_REG_FP; j++) {
4423 			reg = &func->regs[j];
4424 			if (reg->type != SCALAR_VALUE)
4425 				continue;
4426 			reg->precise = false;
4427 		}
4428 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4429 			if (!is_spilled_reg(&func->stack[j]))
4430 				continue;
4431 			reg = &func->stack[j].spilled_ptr;
4432 			if (reg->type != SCALAR_VALUE)
4433 				continue;
4434 			reg->precise = false;
4435 		}
4436 	}
4437 }
4438 
4439 /*
4440  * __mark_chain_precision() backtracks BPF program instruction sequence and
4441  * chain of verifier states making sure that register *regno* (if regno >= 0)
4442  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4443  * SCALARS, as well as any other registers and slots that contribute to
4444  * a tracked state of given registers/stack slots, depending on specific BPF
4445  * assembly instructions (see backtrack_insns() for exact instruction handling
4446  * logic). This backtracking relies on recorded insn_hist and is able to
4447  * traverse entire chain of parent states. This process ends only when all the
4448  * necessary registers/slots and their transitive dependencies are marked as
4449  * precise.
4450  *
4451  * One important and subtle aspect is that precise marks *do not matter* in
4452  * the currently verified state (current state). It is important to understand
4453  * why this is the case.
4454  *
4455  * First, note that current state is the state that is not yet "checkpointed",
4456  * i.e., it is not yet put into env->explored_states, and it has no children
4457  * states as well. It's ephemeral, and can end up either a) being discarded if
4458  * compatible explored state is found at some point or BPF_EXIT instruction is
4459  * reached or b) checkpointed and put into env->explored_states, branching out
4460  * into one or more children states.
4461  *
4462  * In the former case, precise markings in current state are completely
4463  * ignored by state comparison code (see regsafe() for details). Only
4464  * checkpointed ("old") state precise markings are important, and if old
4465  * state's register/slot is precise, regsafe() assumes current state's
4466  * register/slot as precise and checks value ranges exactly and precisely. If
4467  * states turn out to be compatible, current state's necessary precise
4468  * markings and any required parent states' precise markings are enforced
4469  * after the fact with propagate_precision() logic, after the fact. But it's
4470  * important to realize that in this case, even after marking current state
4471  * registers/slots as precise, we immediately discard current state. So what
4472  * actually matters is any of the precise markings propagated into current
4473  * state's parent states, which are always checkpointed (due to b) case above).
4474  * As such, for scenario a) it doesn't matter if current state has precise
4475  * markings set or not.
4476  *
4477  * Now, for the scenario b), checkpointing and forking into child(ren)
4478  * state(s). Note that before current state gets to checkpointing step, any
4479  * processed instruction always assumes precise SCALAR register/slot
4480  * knowledge: if precise value or range is useful to prune jump branch, BPF
4481  * verifier takes this opportunity enthusiastically. Similarly, when
4482  * register's value is used to calculate offset or memory address, exact
4483  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4484  * what we mentioned above about state comparison ignoring precise markings
4485  * during state comparison, BPF verifier ignores and also assumes precise
4486  * markings *at will* during instruction verification process. But as verifier
4487  * assumes precision, it also propagates any precision dependencies across
4488  * parent states, which are not yet finalized, so can be further restricted
4489  * based on new knowledge gained from restrictions enforced by their children
4490  * states. This is so that once those parent states are finalized, i.e., when
4491  * they have no more active children state, state comparison logic in
4492  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4493  * required for correctness.
4494  *
4495  * To build a bit more intuition, note also that once a state is checkpointed,
4496  * the path we took to get to that state is not important. This is crucial
4497  * property for state pruning. When state is checkpointed and finalized at
4498  * some instruction index, it can be correctly and safely used to "short
4499  * circuit" any *compatible* state that reaches exactly the same instruction
4500  * index. I.e., if we jumped to that instruction from a completely different
4501  * code path than original finalized state was derived from, it doesn't
4502  * matter, current state can be discarded because from that instruction
4503  * forward having a compatible state will ensure we will safely reach the
4504  * exit. States describe preconditions for further exploration, but completely
4505  * forget the history of how we got here.
4506  *
4507  * This also means that even if we needed precise SCALAR range to get to
4508  * finalized state, but from that point forward *that same* SCALAR register is
4509  * never used in a precise context (i.e., it's precise value is not needed for
4510  * correctness), it's correct and safe to mark such register as "imprecise"
4511  * (i.e., precise marking set to false). This is what we rely on when we do
4512  * not set precise marking in current state. If no child state requires
4513  * precision for any given SCALAR register, it's safe to dictate that it can
4514  * be imprecise. If any child state does require this register to be precise,
4515  * we'll mark it precise later retroactively during precise markings
4516  * propagation from child state to parent states.
4517  *
4518  * Skipping precise marking setting in current state is a mild version of
4519  * relying on the above observation. But we can utilize this property even
4520  * more aggressively by proactively forgetting any precise marking in the
4521  * current state (which we inherited from the parent state), right before we
4522  * checkpoint it and branch off into new child state. This is done by
4523  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4524  * finalized states which help in short circuiting more future states.
4525  */
4526 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4527 {
4528 	struct backtrack_state *bt = &env->bt;
4529 	struct bpf_verifier_state *st = env->cur_state;
4530 	int first_idx = st->first_insn_idx;
4531 	int last_idx = env->insn_idx;
4532 	int subseq_idx = -1;
4533 	struct bpf_func_state *func;
4534 	struct bpf_reg_state *reg;
4535 	bool skip_first = true;
4536 	int i, fr, err;
4537 
4538 	if (!env->bpf_capable)
4539 		return 0;
4540 
4541 	/* set frame number from which we are starting to backtrack */
4542 	bt_init(bt, env->cur_state->curframe);
4543 
4544 	/* Do sanity checks against current state of register and/or stack
4545 	 * slot, but don't set precise flag in current state, as precision
4546 	 * tracking in the current state is unnecessary.
4547 	 */
4548 	func = st->frame[bt->frame];
4549 	if (regno >= 0) {
4550 		reg = &func->regs[regno];
4551 		if (reg->type != SCALAR_VALUE) {
4552 			WARN_ONCE(1, "backtracing misuse");
4553 			return -EFAULT;
4554 		}
4555 		bt_set_reg(bt, regno);
4556 	}
4557 
4558 	if (bt_empty(bt))
4559 		return 0;
4560 
4561 	for (;;) {
4562 		DECLARE_BITMAP(mask, 64);
4563 		u32 hist_start = st->insn_hist_start;
4564 		u32 hist_end = st->insn_hist_end;
4565 		struct bpf_insn_hist_entry *hist;
4566 
4567 		if (env->log.level & BPF_LOG_LEVEL2) {
4568 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4569 				bt->frame, last_idx, first_idx, subseq_idx);
4570 		}
4571 
4572 		if (last_idx < 0) {
4573 			/* we are at the entry into subprog, which
4574 			 * is expected for global funcs, but only if
4575 			 * requested precise registers are R1-R5
4576 			 * (which are global func's input arguments)
4577 			 */
4578 			if (st->curframe == 0 &&
4579 			    st->frame[0]->subprogno > 0 &&
4580 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4581 			    bt_stack_mask(bt) == 0 &&
4582 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4583 				bitmap_from_u64(mask, bt_reg_mask(bt));
4584 				for_each_set_bit(i, mask, 32) {
4585 					reg = &st->frame[0]->regs[i];
4586 					bt_clear_reg(bt, i);
4587 					if (reg->type == SCALAR_VALUE)
4588 						reg->precise = true;
4589 				}
4590 				return 0;
4591 			}
4592 
4593 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4594 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4595 			WARN_ONCE(1, "verifier backtracking bug");
4596 			return -EFAULT;
4597 		}
4598 
4599 		for (i = last_idx;;) {
4600 			if (skip_first) {
4601 				err = 0;
4602 				skip_first = false;
4603 			} else {
4604 				hist = get_insn_hist_entry(env, hist_start, hist_end, i);
4605 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4606 			}
4607 			if (err == -ENOTSUPP) {
4608 				mark_all_scalars_precise(env, env->cur_state);
4609 				bt_reset(bt);
4610 				return 0;
4611 			} else if (err) {
4612 				return err;
4613 			}
4614 			if (bt_empty(bt))
4615 				/* Found assignment(s) into tracked register in this state.
4616 				 * Since this state is already marked, just return.
4617 				 * Nothing to be tracked further in the parent state.
4618 				 */
4619 				return 0;
4620 			subseq_idx = i;
4621 			i = get_prev_insn_idx(env, st, i, hist_start, &hist_end);
4622 			if (i == -ENOENT)
4623 				break;
4624 			if (i >= env->prog->len) {
4625 				/* This can happen if backtracking reached insn 0
4626 				 * and there are still reg_mask or stack_mask
4627 				 * to backtrack.
4628 				 * It means the backtracking missed the spot where
4629 				 * particular register was initialized with a constant.
4630 				 */
4631 				verbose(env, "BUG backtracking idx %d\n", i);
4632 				WARN_ONCE(1, "verifier backtracking bug");
4633 				return -EFAULT;
4634 			}
4635 		}
4636 		st = st->parent;
4637 		if (!st)
4638 			break;
4639 
4640 		for (fr = bt->frame; fr >= 0; fr--) {
4641 			func = st->frame[fr];
4642 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4643 			for_each_set_bit(i, mask, 32) {
4644 				reg = &func->regs[i];
4645 				if (reg->type != SCALAR_VALUE) {
4646 					bt_clear_frame_reg(bt, fr, i);
4647 					continue;
4648 				}
4649 				if (reg->precise)
4650 					bt_clear_frame_reg(bt, fr, i);
4651 				else
4652 					reg->precise = true;
4653 			}
4654 
4655 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4656 			for_each_set_bit(i, mask, 64) {
4657 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4658 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4659 						i, func->allocated_stack / BPF_REG_SIZE);
4660 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4661 					return -EFAULT;
4662 				}
4663 
4664 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4665 					bt_clear_frame_slot(bt, fr, i);
4666 					continue;
4667 				}
4668 				reg = &func->stack[i].spilled_ptr;
4669 				if (reg->precise)
4670 					bt_clear_frame_slot(bt, fr, i);
4671 				else
4672 					reg->precise = true;
4673 			}
4674 			if (env->log.level & BPF_LOG_LEVEL2) {
4675 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4676 					     bt_frame_reg_mask(bt, fr));
4677 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4678 					fr, env->tmp_str_buf);
4679 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4680 					       bt_frame_stack_mask(bt, fr));
4681 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4682 				print_verifier_state(env, st, fr, true);
4683 			}
4684 		}
4685 
4686 		if (bt_empty(bt))
4687 			return 0;
4688 
4689 		subseq_idx = first_idx;
4690 		last_idx = st->last_insn_idx;
4691 		first_idx = st->first_insn_idx;
4692 	}
4693 
4694 	/* if we still have requested precise regs or slots, we missed
4695 	 * something (e.g., stack access through non-r10 register), so
4696 	 * fallback to marking all precise
4697 	 */
4698 	if (!bt_empty(bt)) {
4699 		mark_all_scalars_precise(env, env->cur_state);
4700 		bt_reset(bt);
4701 	}
4702 
4703 	return 0;
4704 }
4705 
4706 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4707 {
4708 	return __mark_chain_precision(env, regno);
4709 }
4710 
4711 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4712  * desired reg and stack masks across all relevant frames
4713  */
4714 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4715 {
4716 	return __mark_chain_precision(env, -1);
4717 }
4718 
4719 static bool is_spillable_regtype(enum bpf_reg_type type)
4720 {
4721 	switch (base_type(type)) {
4722 	case PTR_TO_MAP_VALUE:
4723 	case PTR_TO_STACK:
4724 	case PTR_TO_CTX:
4725 	case PTR_TO_PACKET:
4726 	case PTR_TO_PACKET_META:
4727 	case PTR_TO_PACKET_END:
4728 	case PTR_TO_FLOW_KEYS:
4729 	case CONST_PTR_TO_MAP:
4730 	case PTR_TO_SOCKET:
4731 	case PTR_TO_SOCK_COMMON:
4732 	case PTR_TO_TCP_SOCK:
4733 	case PTR_TO_XDP_SOCK:
4734 	case PTR_TO_BTF_ID:
4735 	case PTR_TO_BUF:
4736 	case PTR_TO_MEM:
4737 	case PTR_TO_FUNC:
4738 	case PTR_TO_MAP_KEY:
4739 	case PTR_TO_ARENA:
4740 		return true;
4741 	default:
4742 		return false;
4743 	}
4744 }
4745 
4746 /* Does this register contain a constant zero? */
4747 static bool register_is_null(struct bpf_reg_state *reg)
4748 {
4749 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4750 }
4751 
4752 /* check if register is a constant scalar value */
4753 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4754 {
4755 	return reg->type == SCALAR_VALUE &&
4756 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4757 }
4758 
4759 /* assuming is_reg_const() is true, return constant value of a register */
4760 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4761 {
4762 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4763 }
4764 
4765 static bool __is_pointer_value(bool allow_ptr_leaks,
4766 			       const struct bpf_reg_state *reg)
4767 {
4768 	if (allow_ptr_leaks)
4769 		return false;
4770 
4771 	return reg->type != SCALAR_VALUE;
4772 }
4773 
4774 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4775 					struct bpf_reg_state *src_reg)
4776 {
4777 	if (src_reg->type != SCALAR_VALUE)
4778 		return;
4779 
4780 	if (src_reg->id & BPF_ADD_CONST) {
4781 		/*
4782 		 * The verifier is processing rX = rY insn and
4783 		 * rY->id has special linked register already.
4784 		 * Cleared it, since multiple rX += const are not supported.
4785 		 */
4786 		src_reg->id = 0;
4787 		src_reg->off = 0;
4788 	}
4789 
4790 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4791 		/* Ensure that src_reg has a valid ID that will be copied to
4792 		 * dst_reg and then will be used by sync_linked_regs() to
4793 		 * propagate min/max range.
4794 		 */
4795 		src_reg->id = ++env->id_gen;
4796 }
4797 
4798 /* Copy src state preserving dst->parent and dst->live fields */
4799 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4800 {
4801 	struct bpf_reg_state *parent = dst->parent;
4802 	enum bpf_reg_liveness live = dst->live;
4803 
4804 	*dst = *src;
4805 	dst->parent = parent;
4806 	dst->live = live;
4807 }
4808 
4809 static void save_register_state(struct bpf_verifier_env *env,
4810 				struct bpf_func_state *state,
4811 				int spi, struct bpf_reg_state *reg,
4812 				int size)
4813 {
4814 	int i;
4815 
4816 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4817 	if (size == BPF_REG_SIZE)
4818 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4819 
4820 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4821 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4822 
4823 	/* size < 8 bytes spill */
4824 	for (; i; i--)
4825 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4826 }
4827 
4828 static bool is_bpf_st_mem(struct bpf_insn *insn)
4829 {
4830 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4831 }
4832 
4833 static int get_reg_width(struct bpf_reg_state *reg)
4834 {
4835 	return fls64(reg->umax_value);
4836 }
4837 
4838 /* See comment for mark_fastcall_pattern_for_call() */
4839 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4840 					  struct bpf_func_state *state, int insn_idx, int off)
4841 {
4842 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4843 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
4844 	int i;
4845 
4846 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4847 		return;
4848 	/* access to the region [max_stack_depth .. fastcall_stack_off)
4849 	 * from something that is not a part of the fastcall pattern,
4850 	 * disable fastcall rewrites for current subprogram by setting
4851 	 * fastcall_stack_off to a value smaller than any possible offset.
4852 	 */
4853 	subprog->fastcall_stack_off = S16_MIN;
4854 	/* reset fastcall aux flags within subprogram,
4855 	 * happens at most once per subprogram
4856 	 */
4857 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4858 		aux[i].fastcall_spills_num = 0;
4859 		aux[i].fastcall_pattern = 0;
4860 	}
4861 }
4862 
4863 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4864  * stack boundary and alignment are checked in check_mem_access()
4865  */
4866 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4867 				       /* stack frame we're writing to */
4868 				       struct bpf_func_state *state,
4869 				       int off, int size, int value_regno,
4870 				       int insn_idx)
4871 {
4872 	struct bpf_func_state *cur; /* state of the current function */
4873 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4874 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4875 	struct bpf_reg_state *reg = NULL;
4876 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4877 
4878 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4879 	 * so it's aligned access and [off, off + size) are within stack limits
4880 	 */
4881 	if (!env->allow_ptr_leaks &&
4882 	    is_spilled_reg(&state->stack[spi]) &&
4883 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
4884 	    size != BPF_REG_SIZE) {
4885 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4886 		return -EACCES;
4887 	}
4888 
4889 	cur = env->cur_state->frame[env->cur_state->curframe];
4890 	if (value_regno >= 0)
4891 		reg = &cur->regs[value_regno];
4892 	if (!env->bypass_spec_v4) {
4893 		bool sanitize = reg && is_spillable_regtype(reg->type);
4894 
4895 		for (i = 0; i < size; i++) {
4896 			u8 type = state->stack[spi].slot_type[i];
4897 
4898 			if (type != STACK_MISC && type != STACK_ZERO) {
4899 				sanitize = true;
4900 				break;
4901 			}
4902 		}
4903 
4904 		if (sanitize)
4905 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4906 	}
4907 
4908 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4909 	if (err)
4910 		return err;
4911 
4912 	check_fastcall_stack_contract(env, state, insn_idx, off);
4913 	mark_stack_slot_scratched(env, spi);
4914 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4915 		bool reg_value_fits;
4916 
4917 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4918 		/* Make sure that reg had an ID to build a relation on spill. */
4919 		if (reg_value_fits)
4920 			assign_scalar_id_before_mov(env, reg);
4921 		save_register_state(env, state, spi, reg, size);
4922 		/* Break the relation on a narrowing spill. */
4923 		if (!reg_value_fits)
4924 			state->stack[spi].spilled_ptr.id = 0;
4925 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4926 		   env->bpf_capable) {
4927 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4928 
4929 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4930 		__mark_reg_known(tmp_reg, insn->imm);
4931 		tmp_reg->type = SCALAR_VALUE;
4932 		save_register_state(env, state, spi, tmp_reg, size);
4933 	} else if (reg && is_spillable_regtype(reg->type)) {
4934 		/* register containing pointer is being spilled into stack */
4935 		if (size != BPF_REG_SIZE) {
4936 			verbose_linfo(env, insn_idx, "; ");
4937 			verbose(env, "invalid size of register spill\n");
4938 			return -EACCES;
4939 		}
4940 		if (state != cur && reg->type == PTR_TO_STACK) {
4941 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4942 			return -EINVAL;
4943 		}
4944 		save_register_state(env, state, spi, reg, size);
4945 	} else {
4946 		u8 type = STACK_MISC;
4947 
4948 		/* regular write of data into stack destroys any spilled ptr */
4949 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4950 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4951 		if (is_stack_slot_special(&state->stack[spi]))
4952 			for (i = 0; i < BPF_REG_SIZE; i++)
4953 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4954 
4955 		/* only mark the slot as written if all 8 bytes were written
4956 		 * otherwise read propagation may incorrectly stop too soon
4957 		 * when stack slots are partially written.
4958 		 * This heuristic means that read propagation will be
4959 		 * conservative, since it will add reg_live_read marks
4960 		 * to stack slots all the way to first state when programs
4961 		 * writes+reads less than 8 bytes
4962 		 */
4963 		if (size == BPF_REG_SIZE)
4964 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4965 
4966 		/* when we zero initialize stack slots mark them as such */
4967 		if ((reg && register_is_null(reg)) ||
4968 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4969 			/* STACK_ZERO case happened because register spill
4970 			 * wasn't properly aligned at the stack slot boundary,
4971 			 * so it's not a register spill anymore; force
4972 			 * originating register to be precise to make
4973 			 * STACK_ZERO correct for subsequent states
4974 			 */
4975 			err = mark_chain_precision(env, value_regno);
4976 			if (err)
4977 				return err;
4978 			type = STACK_ZERO;
4979 		}
4980 
4981 		/* Mark slots affected by this stack write. */
4982 		for (i = 0; i < size; i++)
4983 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4984 		insn_flags = 0; /* not a register spill */
4985 	}
4986 
4987 	if (insn_flags)
4988 		return push_insn_history(env, env->cur_state, insn_flags, 0);
4989 	return 0;
4990 }
4991 
4992 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4993  * known to contain a variable offset.
4994  * This function checks whether the write is permitted and conservatively
4995  * tracks the effects of the write, considering that each stack slot in the
4996  * dynamic range is potentially written to.
4997  *
4998  * 'off' includes 'regno->off'.
4999  * 'value_regno' can be -1, meaning that an unknown value is being written to
5000  * the stack.
5001  *
5002  * Spilled pointers in range are not marked as written because we don't know
5003  * what's going to be actually written. This means that read propagation for
5004  * future reads cannot be terminated by this write.
5005  *
5006  * For privileged programs, uninitialized stack slots are considered
5007  * initialized by this write (even though we don't know exactly what offsets
5008  * are going to be written to). The idea is that we don't want the verifier to
5009  * reject future reads that access slots written to through variable offsets.
5010  */
5011 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5012 				     /* func where register points to */
5013 				     struct bpf_func_state *state,
5014 				     int ptr_regno, int off, int size,
5015 				     int value_regno, int insn_idx)
5016 {
5017 	struct bpf_func_state *cur; /* state of the current function */
5018 	int min_off, max_off;
5019 	int i, err;
5020 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5021 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5022 	bool writing_zero = false;
5023 	/* set if the fact that we're writing a zero is used to let any
5024 	 * stack slots remain STACK_ZERO
5025 	 */
5026 	bool zero_used = false;
5027 
5028 	cur = env->cur_state->frame[env->cur_state->curframe];
5029 	ptr_reg = &cur->regs[ptr_regno];
5030 	min_off = ptr_reg->smin_value + off;
5031 	max_off = ptr_reg->smax_value + off + size;
5032 	if (value_regno >= 0)
5033 		value_reg = &cur->regs[value_regno];
5034 	if ((value_reg && register_is_null(value_reg)) ||
5035 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5036 		writing_zero = true;
5037 
5038 	for (i = min_off; i < max_off; i++) {
5039 		int spi;
5040 
5041 		spi = __get_spi(i);
5042 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5043 		if (err)
5044 			return err;
5045 	}
5046 
5047 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5048 	/* Variable offset writes destroy any spilled pointers in range. */
5049 	for (i = min_off; i < max_off; i++) {
5050 		u8 new_type, *stype;
5051 		int slot, spi;
5052 
5053 		slot = -i - 1;
5054 		spi = slot / BPF_REG_SIZE;
5055 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5056 		mark_stack_slot_scratched(env, spi);
5057 
5058 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5059 			/* Reject the write if range we may write to has not
5060 			 * been initialized beforehand. If we didn't reject
5061 			 * here, the ptr status would be erased below (even
5062 			 * though not all slots are actually overwritten),
5063 			 * possibly opening the door to leaks.
5064 			 *
5065 			 * We do however catch STACK_INVALID case below, and
5066 			 * only allow reading possibly uninitialized memory
5067 			 * later for CAP_PERFMON, as the write may not happen to
5068 			 * that slot.
5069 			 */
5070 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5071 				insn_idx, i);
5072 			return -EINVAL;
5073 		}
5074 
5075 		/* If writing_zero and the spi slot contains a spill of value 0,
5076 		 * maintain the spill type.
5077 		 */
5078 		if (writing_zero && *stype == STACK_SPILL &&
5079 		    is_spilled_scalar_reg(&state->stack[spi])) {
5080 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5081 
5082 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5083 				zero_used = true;
5084 				continue;
5085 			}
5086 		}
5087 
5088 		/* Erase all other spilled pointers. */
5089 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5090 
5091 		/* Update the slot type. */
5092 		new_type = STACK_MISC;
5093 		if (writing_zero && *stype == STACK_ZERO) {
5094 			new_type = STACK_ZERO;
5095 			zero_used = true;
5096 		}
5097 		/* If the slot is STACK_INVALID, we check whether it's OK to
5098 		 * pretend that it will be initialized by this write. The slot
5099 		 * might not actually be written to, and so if we mark it as
5100 		 * initialized future reads might leak uninitialized memory.
5101 		 * For privileged programs, we will accept such reads to slots
5102 		 * that may or may not be written because, if we're reject
5103 		 * them, the error would be too confusing.
5104 		 */
5105 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5106 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5107 					insn_idx, i);
5108 			return -EINVAL;
5109 		}
5110 		*stype = new_type;
5111 	}
5112 	if (zero_used) {
5113 		/* backtracking doesn't work for STACK_ZERO yet. */
5114 		err = mark_chain_precision(env, value_regno);
5115 		if (err)
5116 			return err;
5117 	}
5118 	return 0;
5119 }
5120 
5121 /* When register 'dst_regno' is assigned some values from stack[min_off,
5122  * max_off), we set the register's type according to the types of the
5123  * respective stack slots. If all the stack values are known to be zeros, then
5124  * so is the destination reg. Otherwise, the register is considered to be
5125  * SCALAR. This function does not deal with register filling; the caller must
5126  * ensure that all spilled registers in the stack range have been marked as
5127  * read.
5128  */
5129 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5130 				/* func where src register points to */
5131 				struct bpf_func_state *ptr_state,
5132 				int min_off, int max_off, int dst_regno)
5133 {
5134 	struct bpf_verifier_state *vstate = env->cur_state;
5135 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5136 	int i, slot, spi;
5137 	u8 *stype;
5138 	int zeros = 0;
5139 
5140 	for (i = min_off; i < max_off; i++) {
5141 		slot = -i - 1;
5142 		spi = slot / BPF_REG_SIZE;
5143 		mark_stack_slot_scratched(env, spi);
5144 		stype = ptr_state->stack[spi].slot_type;
5145 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5146 			break;
5147 		zeros++;
5148 	}
5149 	if (zeros == max_off - min_off) {
5150 		/* Any access_size read into register is zero extended,
5151 		 * so the whole register == const_zero.
5152 		 */
5153 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5154 	} else {
5155 		/* have read misc data from the stack */
5156 		mark_reg_unknown(env, state->regs, dst_regno);
5157 	}
5158 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5159 }
5160 
5161 /* Read the stack at 'off' and put the results into the register indicated by
5162  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5163  * spilled reg.
5164  *
5165  * 'dst_regno' can be -1, meaning that the read value is not going to a
5166  * register.
5167  *
5168  * The access is assumed to be within the current stack bounds.
5169  */
5170 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5171 				      /* func where src register points to */
5172 				      struct bpf_func_state *reg_state,
5173 				      int off, int size, int dst_regno)
5174 {
5175 	struct bpf_verifier_state *vstate = env->cur_state;
5176 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5177 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5178 	struct bpf_reg_state *reg;
5179 	u8 *stype, type;
5180 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5181 
5182 	stype = reg_state->stack[spi].slot_type;
5183 	reg = &reg_state->stack[spi].spilled_ptr;
5184 
5185 	mark_stack_slot_scratched(env, spi);
5186 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5187 
5188 	if (is_spilled_reg(&reg_state->stack[spi])) {
5189 		u8 spill_size = 1;
5190 
5191 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5192 			spill_size++;
5193 
5194 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5195 			if (reg->type != SCALAR_VALUE) {
5196 				verbose_linfo(env, env->insn_idx, "; ");
5197 				verbose(env, "invalid size of register fill\n");
5198 				return -EACCES;
5199 			}
5200 
5201 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5202 			if (dst_regno < 0)
5203 				return 0;
5204 
5205 			if (size <= spill_size &&
5206 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5207 				/* The earlier check_reg_arg() has decided the
5208 				 * subreg_def for this insn.  Save it first.
5209 				 */
5210 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5211 
5212 				copy_register_state(&state->regs[dst_regno], reg);
5213 				state->regs[dst_regno].subreg_def = subreg_def;
5214 
5215 				/* Break the relation on a narrowing fill.
5216 				 * coerce_reg_to_size will adjust the boundaries.
5217 				 */
5218 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5219 					state->regs[dst_regno].id = 0;
5220 			} else {
5221 				int spill_cnt = 0, zero_cnt = 0;
5222 
5223 				for (i = 0; i < size; i++) {
5224 					type = stype[(slot - i) % BPF_REG_SIZE];
5225 					if (type == STACK_SPILL) {
5226 						spill_cnt++;
5227 						continue;
5228 					}
5229 					if (type == STACK_MISC)
5230 						continue;
5231 					if (type == STACK_ZERO) {
5232 						zero_cnt++;
5233 						continue;
5234 					}
5235 					if (type == STACK_INVALID && env->allow_uninit_stack)
5236 						continue;
5237 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5238 						off, i, size);
5239 					return -EACCES;
5240 				}
5241 
5242 				if (spill_cnt == size &&
5243 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5244 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5245 					/* this IS register fill, so keep insn_flags */
5246 				} else if (zero_cnt == size) {
5247 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5248 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5249 					insn_flags = 0; /* not restoring original register state */
5250 				} else {
5251 					mark_reg_unknown(env, state->regs, dst_regno);
5252 					insn_flags = 0; /* not restoring original register state */
5253 				}
5254 			}
5255 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5256 		} else if (dst_regno >= 0) {
5257 			/* restore register state from stack */
5258 			copy_register_state(&state->regs[dst_regno], reg);
5259 			/* mark reg as written since spilled pointer state likely
5260 			 * has its liveness marks cleared by is_state_visited()
5261 			 * which resets stack/reg liveness for state transitions
5262 			 */
5263 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5264 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5265 			/* If dst_regno==-1, the caller is asking us whether
5266 			 * it is acceptable to use this value as a SCALAR_VALUE
5267 			 * (e.g. for XADD).
5268 			 * We must not allow unprivileged callers to do that
5269 			 * with spilled pointers.
5270 			 */
5271 			verbose(env, "leaking pointer from stack off %d\n",
5272 				off);
5273 			return -EACCES;
5274 		}
5275 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5276 	} else {
5277 		for (i = 0; i < size; i++) {
5278 			type = stype[(slot - i) % BPF_REG_SIZE];
5279 			if (type == STACK_MISC)
5280 				continue;
5281 			if (type == STACK_ZERO)
5282 				continue;
5283 			if (type == STACK_INVALID && env->allow_uninit_stack)
5284 				continue;
5285 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5286 				off, i, size);
5287 			return -EACCES;
5288 		}
5289 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5290 		if (dst_regno >= 0)
5291 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5292 		insn_flags = 0; /* we are not restoring spilled register */
5293 	}
5294 	if (insn_flags)
5295 		return push_insn_history(env, env->cur_state, insn_flags, 0);
5296 	return 0;
5297 }
5298 
5299 enum bpf_access_src {
5300 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5301 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5302 };
5303 
5304 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5305 					 int regno, int off, int access_size,
5306 					 bool zero_size_allowed,
5307 					 enum bpf_access_type type,
5308 					 struct bpf_call_arg_meta *meta);
5309 
5310 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5311 {
5312 	return cur_regs(env) + regno;
5313 }
5314 
5315 /* Read the stack at 'ptr_regno + off' and put the result into the register
5316  * 'dst_regno'.
5317  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5318  * but not its variable offset.
5319  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5320  *
5321  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5322  * filling registers (i.e. reads of spilled register cannot be detected when
5323  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5324  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5325  * offset; for a fixed offset check_stack_read_fixed_off should be used
5326  * instead.
5327  */
5328 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5329 				    int ptr_regno, int off, int size, int dst_regno)
5330 {
5331 	/* The state of the source register. */
5332 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5333 	struct bpf_func_state *ptr_state = func(env, reg);
5334 	int err;
5335 	int min_off, max_off;
5336 
5337 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5338 	 */
5339 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5340 					    false, BPF_READ, NULL);
5341 	if (err)
5342 		return err;
5343 
5344 	min_off = reg->smin_value + off;
5345 	max_off = reg->smax_value + off;
5346 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5347 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5348 	return 0;
5349 }
5350 
5351 /* check_stack_read dispatches to check_stack_read_fixed_off or
5352  * check_stack_read_var_off.
5353  *
5354  * The caller must ensure that the offset falls within the allocated stack
5355  * bounds.
5356  *
5357  * 'dst_regno' is a register which will receive the value from the stack. It
5358  * can be -1, meaning that the read value is not going to a register.
5359  */
5360 static int check_stack_read(struct bpf_verifier_env *env,
5361 			    int ptr_regno, int off, int size,
5362 			    int dst_regno)
5363 {
5364 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5365 	struct bpf_func_state *state = func(env, reg);
5366 	int err;
5367 	/* Some accesses are only permitted with a static offset. */
5368 	bool var_off = !tnum_is_const(reg->var_off);
5369 
5370 	/* The offset is required to be static when reads don't go to a
5371 	 * register, in order to not leak pointers (see
5372 	 * check_stack_read_fixed_off).
5373 	 */
5374 	if (dst_regno < 0 && var_off) {
5375 		char tn_buf[48];
5376 
5377 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5378 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5379 			tn_buf, off, size);
5380 		return -EACCES;
5381 	}
5382 	/* Variable offset is prohibited for unprivileged mode for simplicity
5383 	 * since it requires corresponding support in Spectre masking for stack
5384 	 * ALU. See also retrieve_ptr_limit(). The check in
5385 	 * check_stack_access_for_ptr_arithmetic() called by
5386 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5387 	 * with variable offsets, therefore no check is required here. Further,
5388 	 * just checking it here would be insufficient as speculative stack
5389 	 * writes could still lead to unsafe speculative behaviour.
5390 	 */
5391 	if (!var_off) {
5392 		off += reg->var_off.value;
5393 		err = check_stack_read_fixed_off(env, state, off, size,
5394 						 dst_regno);
5395 	} else {
5396 		/* Variable offset stack reads need more conservative handling
5397 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5398 		 * branch.
5399 		 */
5400 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5401 					       dst_regno);
5402 	}
5403 	return err;
5404 }
5405 
5406 
5407 /* check_stack_write dispatches to check_stack_write_fixed_off or
5408  * check_stack_write_var_off.
5409  *
5410  * 'ptr_regno' is the register used as a pointer into the stack.
5411  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5412  * 'value_regno' is the register whose value we're writing to the stack. It can
5413  * be -1, meaning that we're not writing from a register.
5414  *
5415  * The caller must ensure that the offset falls within the maximum stack size.
5416  */
5417 static int check_stack_write(struct bpf_verifier_env *env,
5418 			     int ptr_regno, int off, int size,
5419 			     int value_regno, int insn_idx)
5420 {
5421 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5422 	struct bpf_func_state *state = func(env, reg);
5423 	int err;
5424 
5425 	if (tnum_is_const(reg->var_off)) {
5426 		off += reg->var_off.value;
5427 		err = check_stack_write_fixed_off(env, state, off, size,
5428 						  value_regno, insn_idx);
5429 	} else {
5430 		/* Variable offset stack reads need more conservative handling
5431 		 * than fixed offset ones.
5432 		 */
5433 		err = check_stack_write_var_off(env, state,
5434 						ptr_regno, off, size,
5435 						value_regno, insn_idx);
5436 	}
5437 	return err;
5438 }
5439 
5440 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5441 				 int off, int size, enum bpf_access_type type)
5442 {
5443 	struct bpf_reg_state *regs = cur_regs(env);
5444 	struct bpf_map *map = regs[regno].map_ptr;
5445 	u32 cap = bpf_map_flags_to_cap(map);
5446 
5447 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5448 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5449 			map->value_size, off, size);
5450 		return -EACCES;
5451 	}
5452 
5453 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5454 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5455 			map->value_size, off, size);
5456 		return -EACCES;
5457 	}
5458 
5459 	return 0;
5460 }
5461 
5462 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5463 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5464 			      int off, int size, u32 mem_size,
5465 			      bool zero_size_allowed)
5466 {
5467 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5468 	struct bpf_reg_state *reg;
5469 
5470 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5471 		return 0;
5472 
5473 	reg = &cur_regs(env)[regno];
5474 	switch (reg->type) {
5475 	case PTR_TO_MAP_KEY:
5476 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5477 			mem_size, off, size);
5478 		break;
5479 	case PTR_TO_MAP_VALUE:
5480 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5481 			mem_size, off, size);
5482 		break;
5483 	case PTR_TO_PACKET:
5484 	case PTR_TO_PACKET_META:
5485 	case PTR_TO_PACKET_END:
5486 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5487 			off, size, regno, reg->id, off, mem_size);
5488 		break;
5489 	case PTR_TO_MEM:
5490 	default:
5491 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5492 			mem_size, off, size);
5493 	}
5494 
5495 	return -EACCES;
5496 }
5497 
5498 /* check read/write into a memory region with possible variable offset */
5499 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5500 				   int off, int size, u32 mem_size,
5501 				   bool zero_size_allowed)
5502 {
5503 	struct bpf_verifier_state *vstate = env->cur_state;
5504 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5505 	struct bpf_reg_state *reg = &state->regs[regno];
5506 	int err;
5507 
5508 	/* We may have adjusted the register pointing to memory region, so we
5509 	 * need to try adding each of min_value and max_value to off
5510 	 * to make sure our theoretical access will be safe.
5511 	 *
5512 	 * The minimum value is only important with signed
5513 	 * comparisons where we can't assume the floor of a
5514 	 * value is 0.  If we are using signed variables for our
5515 	 * index'es we need to make sure that whatever we use
5516 	 * will have a set floor within our range.
5517 	 */
5518 	if (reg->smin_value < 0 &&
5519 	    (reg->smin_value == S64_MIN ||
5520 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5521 	      reg->smin_value + off < 0)) {
5522 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5523 			regno);
5524 		return -EACCES;
5525 	}
5526 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5527 				 mem_size, zero_size_allowed);
5528 	if (err) {
5529 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5530 			regno);
5531 		return err;
5532 	}
5533 
5534 	/* If we haven't set a max value then we need to bail since we can't be
5535 	 * sure we won't do bad things.
5536 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5537 	 */
5538 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5539 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5540 			regno);
5541 		return -EACCES;
5542 	}
5543 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5544 				 mem_size, zero_size_allowed);
5545 	if (err) {
5546 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5547 			regno);
5548 		return err;
5549 	}
5550 
5551 	return 0;
5552 }
5553 
5554 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5555 			       const struct bpf_reg_state *reg, int regno,
5556 			       bool fixed_off_ok)
5557 {
5558 	/* Access to this pointer-typed register or passing it to a helper
5559 	 * is only allowed in its original, unmodified form.
5560 	 */
5561 
5562 	if (reg->off < 0) {
5563 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5564 			reg_type_str(env, reg->type), regno, reg->off);
5565 		return -EACCES;
5566 	}
5567 
5568 	if (!fixed_off_ok && reg->off) {
5569 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5570 			reg_type_str(env, reg->type), regno, reg->off);
5571 		return -EACCES;
5572 	}
5573 
5574 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5575 		char tn_buf[48];
5576 
5577 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5578 		verbose(env, "variable %s access var_off=%s disallowed\n",
5579 			reg_type_str(env, reg->type), tn_buf);
5580 		return -EACCES;
5581 	}
5582 
5583 	return 0;
5584 }
5585 
5586 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5587 		             const struct bpf_reg_state *reg, int regno)
5588 {
5589 	return __check_ptr_off_reg(env, reg, regno, false);
5590 }
5591 
5592 static int map_kptr_match_type(struct bpf_verifier_env *env,
5593 			       struct btf_field *kptr_field,
5594 			       struct bpf_reg_state *reg, u32 regno)
5595 {
5596 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5597 	int perm_flags;
5598 	const char *reg_name = "";
5599 
5600 	if (btf_is_kernel(reg->btf)) {
5601 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5602 
5603 		/* Only unreferenced case accepts untrusted pointers */
5604 		if (kptr_field->type == BPF_KPTR_UNREF)
5605 			perm_flags |= PTR_UNTRUSTED;
5606 	} else {
5607 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5608 		if (kptr_field->type == BPF_KPTR_PERCPU)
5609 			perm_flags |= MEM_PERCPU;
5610 	}
5611 
5612 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5613 		goto bad_type;
5614 
5615 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5616 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5617 
5618 	/* For ref_ptr case, release function check should ensure we get one
5619 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5620 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5621 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5622 	 * reg->off and reg->ref_obj_id are not needed here.
5623 	 */
5624 	if (__check_ptr_off_reg(env, reg, regno, true))
5625 		return -EACCES;
5626 
5627 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5628 	 * we also need to take into account the reg->off.
5629 	 *
5630 	 * We want to support cases like:
5631 	 *
5632 	 * struct foo {
5633 	 *         struct bar br;
5634 	 *         struct baz bz;
5635 	 * };
5636 	 *
5637 	 * struct foo *v;
5638 	 * v = func();	      // PTR_TO_BTF_ID
5639 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5640 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5641 	 *                    // first member type of struct after comparison fails
5642 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5643 	 *                    // to match type
5644 	 *
5645 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5646 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5647 	 * the struct to match type against first member of struct, i.e. reject
5648 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5649 	 * strict mode to true for type match.
5650 	 */
5651 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5652 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5653 				  kptr_field->type != BPF_KPTR_UNREF))
5654 		goto bad_type;
5655 	return 0;
5656 bad_type:
5657 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5658 		reg_type_str(env, reg->type), reg_name);
5659 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5660 	if (kptr_field->type == BPF_KPTR_UNREF)
5661 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5662 			targ_name);
5663 	else
5664 		verbose(env, "\n");
5665 	return -EINVAL;
5666 }
5667 
5668 static bool in_sleepable(struct bpf_verifier_env *env)
5669 {
5670 	return env->prog->sleepable ||
5671 	       (env->cur_state && env->cur_state->in_sleepable);
5672 }
5673 
5674 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5675  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5676  */
5677 static bool in_rcu_cs(struct bpf_verifier_env *env)
5678 {
5679 	return env->cur_state->active_rcu_lock ||
5680 	       env->cur_state->active_locks ||
5681 	       !in_sleepable(env);
5682 }
5683 
5684 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5685 BTF_SET_START(rcu_protected_types)
5686 #ifdef CONFIG_NET
5687 BTF_ID(struct, prog_test_ref_kfunc)
5688 #endif
5689 #ifdef CONFIG_CGROUPS
5690 BTF_ID(struct, cgroup)
5691 #endif
5692 #ifdef CONFIG_BPF_JIT
5693 BTF_ID(struct, bpf_cpumask)
5694 #endif
5695 BTF_ID(struct, task_struct)
5696 #ifdef CONFIG_CRYPTO
5697 BTF_ID(struct, bpf_crypto_ctx)
5698 #endif
5699 BTF_SET_END(rcu_protected_types)
5700 
5701 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5702 {
5703 	if (!btf_is_kernel(btf))
5704 		return true;
5705 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5706 }
5707 
5708 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5709 {
5710 	struct btf_struct_meta *meta;
5711 
5712 	if (btf_is_kernel(kptr_field->kptr.btf))
5713 		return NULL;
5714 
5715 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5716 				    kptr_field->kptr.btf_id);
5717 
5718 	return meta ? meta->record : NULL;
5719 }
5720 
5721 static bool rcu_safe_kptr(const struct btf_field *field)
5722 {
5723 	const struct btf_field_kptr *kptr = &field->kptr;
5724 
5725 	return field->type == BPF_KPTR_PERCPU ||
5726 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5727 }
5728 
5729 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5730 {
5731 	struct btf_record *rec;
5732 	u32 ret;
5733 
5734 	ret = PTR_MAYBE_NULL;
5735 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5736 		ret |= MEM_RCU;
5737 		if (kptr_field->type == BPF_KPTR_PERCPU)
5738 			ret |= MEM_PERCPU;
5739 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5740 			ret |= MEM_ALLOC;
5741 
5742 		rec = kptr_pointee_btf_record(kptr_field);
5743 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5744 			ret |= NON_OWN_REF;
5745 	} else {
5746 		ret |= PTR_UNTRUSTED;
5747 	}
5748 
5749 	return ret;
5750 }
5751 
5752 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5753 			    struct btf_field *field)
5754 {
5755 	struct bpf_reg_state *reg;
5756 	const struct btf_type *t;
5757 
5758 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5759 	mark_reg_known_zero(env, cur_regs(env), regno);
5760 	reg = reg_state(env, regno);
5761 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5762 	reg->mem_size = t->size;
5763 	reg->id = ++env->id_gen;
5764 
5765 	return 0;
5766 }
5767 
5768 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5769 				 int value_regno, int insn_idx,
5770 				 struct btf_field *kptr_field)
5771 {
5772 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5773 	int class = BPF_CLASS(insn->code);
5774 	struct bpf_reg_state *val_reg;
5775 
5776 	/* Things we already checked for in check_map_access and caller:
5777 	 *  - Reject cases where variable offset may touch kptr
5778 	 *  - size of access (must be BPF_DW)
5779 	 *  - tnum_is_const(reg->var_off)
5780 	 *  - kptr_field->offset == off + reg->var_off.value
5781 	 */
5782 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5783 	if (BPF_MODE(insn->code) != BPF_MEM) {
5784 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5785 		return -EACCES;
5786 	}
5787 
5788 	/* We only allow loading referenced kptr, since it will be marked as
5789 	 * untrusted, similar to unreferenced kptr.
5790 	 */
5791 	if (class != BPF_LDX &&
5792 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5793 		verbose(env, "store to referenced kptr disallowed\n");
5794 		return -EACCES;
5795 	}
5796 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5797 		verbose(env, "store to uptr disallowed\n");
5798 		return -EACCES;
5799 	}
5800 
5801 	if (class == BPF_LDX) {
5802 		if (kptr_field->type == BPF_UPTR)
5803 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5804 
5805 		/* We can simply mark the value_regno receiving the pointer
5806 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5807 		 */
5808 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5809 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5810 	} else if (class == BPF_STX) {
5811 		val_reg = reg_state(env, value_regno);
5812 		if (!register_is_null(val_reg) &&
5813 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5814 			return -EACCES;
5815 	} else if (class == BPF_ST) {
5816 		if (insn->imm) {
5817 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5818 				kptr_field->offset);
5819 			return -EACCES;
5820 		}
5821 	} else {
5822 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5823 		return -EACCES;
5824 	}
5825 	return 0;
5826 }
5827 
5828 /* check read/write into a map element with possible variable offset */
5829 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5830 			    int off, int size, bool zero_size_allowed,
5831 			    enum bpf_access_src src)
5832 {
5833 	struct bpf_verifier_state *vstate = env->cur_state;
5834 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5835 	struct bpf_reg_state *reg = &state->regs[regno];
5836 	struct bpf_map *map = reg->map_ptr;
5837 	struct btf_record *rec;
5838 	int err, i;
5839 
5840 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5841 				      zero_size_allowed);
5842 	if (err)
5843 		return err;
5844 
5845 	if (IS_ERR_OR_NULL(map->record))
5846 		return 0;
5847 	rec = map->record;
5848 	for (i = 0; i < rec->cnt; i++) {
5849 		struct btf_field *field = &rec->fields[i];
5850 		u32 p = field->offset;
5851 
5852 		/* If any part of a field  can be touched by load/store, reject
5853 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5854 		 * it is sufficient to check x1 < y2 && y1 < x2.
5855 		 */
5856 		if (reg->smin_value + off < p + field->size &&
5857 		    p < reg->umax_value + off + size) {
5858 			switch (field->type) {
5859 			case BPF_KPTR_UNREF:
5860 			case BPF_KPTR_REF:
5861 			case BPF_KPTR_PERCPU:
5862 			case BPF_UPTR:
5863 				if (src != ACCESS_DIRECT) {
5864 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5865 						btf_field_type_name(field->type));
5866 					return -EACCES;
5867 				}
5868 				if (!tnum_is_const(reg->var_off)) {
5869 					verbose(env, "%s access cannot have variable offset\n",
5870 						btf_field_type_name(field->type));
5871 					return -EACCES;
5872 				}
5873 				if (p != off + reg->var_off.value) {
5874 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5875 						btf_field_type_name(field->type),
5876 						p, off + reg->var_off.value);
5877 					return -EACCES;
5878 				}
5879 				if (size != bpf_size_to_bytes(BPF_DW)) {
5880 					verbose(env, "%s access size must be BPF_DW\n",
5881 						btf_field_type_name(field->type));
5882 					return -EACCES;
5883 				}
5884 				break;
5885 			default:
5886 				verbose(env, "%s cannot be accessed directly by load/store\n",
5887 					btf_field_type_name(field->type));
5888 				return -EACCES;
5889 			}
5890 		}
5891 	}
5892 	return 0;
5893 }
5894 
5895 #define MAX_PACKET_OFF 0xffff
5896 
5897 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5898 				       const struct bpf_call_arg_meta *meta,
5899 				       enum bpf_access_type t)
5900 {
5901 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5902 
5903 	switch (prog_type) {
5904 	/* Program types only with direct read access go here! */
5905 	case BPF_PROG_TYPE_LWT_IN:
5906 	case BPF_PROG_TYPE_LWT_OUT:
5907 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5908 	case BPF_PROG_TYPE_SK_REUSEPORT:
5909 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5910 	case BPF_PROG_TYPE_CGROUP_SKB:
5911 		if (t == BPF_WRITE)
5912 			return false;
5913 		fallthrough;
5914 
5915 	/* Program types with direct read + write access go here! */
5916 	case BPF_PROG_TYPE_SCHED_CLS:
5917 	case BPF_PROG_TYPE_SCHED_ACT:
5918 	case BPF_PROG_TYPE_XDP:
5919 	case BPF_PROG_TYPE_LWT_XMIT:
5920 	case BPF_PROG_TYPE_SK_SKB:
5921 	case BPF_PROG_TYPE_SK_MSG:
5922 		if (meta)
5923 			return meta->pkt_access;
5924 
5925 		env->seen_direct_write = true;
5926 		return true;
5927 
5928 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5929 		if (t == BPF_WRITE)
5930 			env->seen_direct_write = true;
5931 
5932 		return true;
5933 
5934 	default:
5935 		return false;
5936 	}
5937 }
5938 
5939 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5940 			       int size, bool zero_size_allowed)
5941 {
5942 	struct bpf_reg_state *regs = cur_regs(env);
5943 	struct bpf_reg_state *reg = &regs[regno];
5944 	int err;
5945 
5946 	/* We may have added a variable offset to the packet pointer; but any
5947 	 * reg->range we have comes after that.  We are only checking the fixed
5948 	 * offset.
5949 	 */
5950 
5951 	/* We don't allow negative numbers, because we aren't tracking enough
5952 	 * detail to prove they're safe.
5953 	 */
5954 	if (reg->smin_value < 0) {
5955 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5956 			regno);
5957 		return -EACCES;
5958 	}
5959 
5960 	err = reg->range < 0 ? -EINVAL :
5961 	      __check_mem_access(env, regno, off, size, reg->range,
5962 				 zero_size_allowed);
5963 	if (err) {
5964 		verbose(env, "R%d offset is outside of the packet\n", regno);
5965 		return err;
5966 	}
5967 
5968 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5969 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5970 	 * otherwise find_good_pkt_pointers would have refused to set range info
5971 	 * that __check_mem_access would have rejected this pkt access.
5972 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5973 	 */
5974 	env->prog->aux->max_pkt_offset =
5975 		max_t(u32, env->prog->aux->max_pkt_offset,
5976 		      off + reg->umax_value + size - 1);
5977 
5978 	return err;
5979 }
5980 
5981 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5982 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5983 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5984 			    struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
5985 {
5986 	struct bpf_insn_access_aux info = {
5987 		.reg_type = *reg_type,
5988 		.log = &env->log,
5989 		.is_retval = false,
5990 		.is_ldsx = is_ldsx,
5991 	};
5992 
5993 	if (env->ops->is_valid_access &&
5994 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5995 		/* A non zero info.ctx_field_size indicates that this field is a
5996 		 * candidate for later verifier transformation to load the whole
5997 		 * field and then apply a mask when accessed with a narrower
5998 		 * access than actual ctx access size. A zero info.ctx_field_size
5999 		 * will only allow for whole field access and rejects any other
6000 		 * type of narrower access.
6001 		 */
6002 		*reg_type = info.reg_type;
6003 		*is_retval = info.is_retval;
6004 
6005 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
6006 			*btf = info.btf;
6007 			*btf_id = info.btf_id;
6008 		} else {
6009 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
6010 		}
6011 		/* remember the offset of last byte accessed in ctx */
6012 		if (env->prog->aux->max_ctx_offset < off + size)
6013 			env->prog->aux->max_ctx_offset = off + size;
6014 		return 0;
6015 	}
6016 
6017 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6018 	return -EACCES;
6019 }
6020 
6021 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6022 				  int size)
6023 {
6024 	if (size < 0 || off < 0 ||
6025 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6026 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6027 			off, size);
6028 		return -EACCES;
6029 	}
6030 	return 0;
6031 }
6032 
6033 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6034 			     u32 regno, int off, int size,
6035 			     enum bpf_access_type t)
6036 {
6037 	struct bpf_reg_state *regs = cur_regs(env);
6038 	struct bpf_reg_state *reg = &regs[regno];
6039 	struct bpf_insn_access_aux info = {};
6040 	bool valid;
6041 
6042 	if (reg->smin_value < 0) {
6043 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6044 			regno);
6045 		return -EACCES;
6046 	}
6047 
6048 	switch (reg->type) {
6049 	case PTR_TO_SOCK_COMMON:
6050 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6051 		break;
6052 	case PTR_TO_SOCKET:
6053 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6054 		break;
6055 	case PTR_TO_TCP_SOCK:
6056 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6057 		break;
6058 	case PTR_TO_XDP_SOCK:
6059 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6060 		break;
6061 	default:
6062 		valid = false;
6063 	}
6064 
6065 
6066 	if (valid) {
6067 		env->insn_aux_data[insn_idx].ctx_field_size =
6068 			info.ctx_field_size;
6069 		return 0;
6070 	}
6071 
6072 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6073 		regno, reg_type_str(env, reg->type), off, size);
6074 
6075 	return -EACCES;
6076 }
6077 
6078 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6079 {
6080 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6081 }
6082 
6083 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6084 {
6085 	const struct bpf_reg_state *reg = reg_state(env, regno);
6086 
6087 	return reg->type == PTR_TO_CTX;
6088 }
6089 
6090 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6091 {
6092 	const struct bpf_reg_state *reg = reg_state(env, regno);
6093 
6094 	return type_is_sk_pointer(reg->type);
6095 }
6096 
6097 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6098 {
6099 	const struct bpf_reg_state *reg = reg_state(env, regno);
6100 
6101 	return type_is_pkt_pointer(reg->type);
6102 }
6103 
6104 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6105 {
6106 	const struct bpf_reg_state *reg = reg_state(env, regno);
6107 
6108 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6109 	return reg->type == PTR_TO_FLOW_KEYS;
6110 }
6111 
6112 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6113 {
6114 	const struct bpf_reg_state *reg = reg_state(env, regno);
6115 
6116 	return reg->type == PTR_TO_ARENA;
6117 }
6118 
6119 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6120 #ifdef CONFIG_NET
6121 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6122 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6123 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6124 #endif
6125 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6126 };
6127 
6128 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6129 {
6130 	/* A referenced register is always trusted. */
6131 	if (reg->ref_obj_id)
6132 		return true;
6133 
6134 	/* Types listed in the reg2btf_ids are always trusted */
6135 	if (reg2btf_ids[base_type(reg->type)] &&
6136 	    !bpf_type_has_unsafe_modifiers(reg->type))
6137 		return true;
6138 
6139 	/* If a register is not referenced, it is trusted if it has the
6140 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6141 	 * other type modifiers may be safe, but we elect to take an opt-in
6142 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6143 	 * not.
6144 	 *
6145 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6146 	 * for whether a register is trusted.
6147 	 */
6148 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6149 	       !bpf_type_has_unsafe_modifiers(reg->type);
6150 }
6151 
6152 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6153 {
6154 	return reg->type & MEM_RCU;
6155 }
6156 
6157 static void clear_trusted_flags(enum bpf_type_flag *flag)
6158 {
6159 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6160 }
6161 
6162 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6163 				   const struct bpf_reg_state *reg,
6164 				   int off, int size, bool strict)
6165 {
6166 	struct tnum reg_off;
6167 	int ip_align;
6168 
6169 	/* Byte size accesses are always allowed. */
6170 	if (!strict || size == 1)
6171 		return 0;
6172 
6173 	/* For platforms that do not have a Kconfig enabling
6174 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6175 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6176 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6177 	 * to this code only in strict mode where we want to emulate
6178 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6179 	 * unconditional IP align value of '2'.
6180 	 */
6181 	ip_align = 2;
6182 
6183 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6184 	if (!tnum_is_aligned(reg_off, size)) {
6185 		char tn_buf[48];
6186 
6187 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6188 		verbose(env,
6189 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6190 			ip_align, tn_buf, reg->off, off, size);
6191 		return -EACCES;
6192 	}
6193 
6194 	return 0;
6195 }
6196 
6197 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6198 				       const struct bpf_reg_state *reg,
6199 				       const char *pointer_desc,
6200 				       int off, int size, bool strict)
6201 {
6202 	struct tnum reg_off;
6203 
6204 	/* Byte size accesses are always allowed. */
6205 	if (!strict || size == 1)
6206 		return 0;
6207 
6208 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6209 	if (!tnum_is_aligned(reg_off, size)) {
6210 		char tn_buf[48];
6211 
6212 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6213 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6214 			pointer_desc, tn_buf, reg->off, off, size);
6215 		return -EACCES;
6216 	}
6217 
6218 	return 0;
6219 }
6220 
6221 static int check_ptr_alignment(struct bpf_verifier_env *env,
6222 			       const struct bpf_reg_state *reg, int off,
6223 			       int size, bool strict_alignment_once)
6224 {
6225 	bool strict = env->strict_alignment || strict_alignment_once;
6226 	const char *pointer_desc = "";
6227 
6228 	switch (reg->type) {
6229 	case PTR_TO_PACKET:
6230 	case PTR_TO_PACKET_META:
6231 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6232 		 * right in front, treat it the very same way.
6233 		 */
6234 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6235 	case PTR_TO_FLOW_KEYS:
6236 		pointer_desc = "flow keys ";
6237 		break;
6238 	case PTR_TO_MAP_KEY:
6239 		pointer_desc = "key ";
6240 		break;
6241 	case PTR_TO_MAP_VALUE:
6242 		pointer_desc = "value ";
6243 		break;
6244 	case PTR_TO_CTX:
6245 		pointer_desc = "context ";
6246 		break;
6247 	case PTR_TO_STACK:
6248 		pointer_desc = "stack ";
6249 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6250 		 * and check_stack_read_fixed_off() relies on stack accesses being
6251 		 * aligned.
6252 		 */
6253 		strict = true;
6254 		break;
6255 	case PTR_TO_SOCKET:
6256 		pointer_desc = "sock ";
6257 		break;
6258 	case PTR_TO_SOCK_COMMON:
6259 		pointer_desc = "sock_common ";
6260 		break;
6261 	case PTR_TO_TCP_SOCK:
6262 		pointer_desc = "tcp_sock ";
6263 		break;
6264 	case PTR_TO_XDP_SOCK:
6265 		pointer_desc = "xdp_sock ";
6266 		break;
6267 	case PTR_TO_ARENA:
6268 		return 0;
6269 	default:
6270 		break;
6271 	}
6272 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6273 					   strict);
6274 }
6275 
6276 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6277 {
6278 	if (!bpf_jit_supports_private_stack())
6279 		return NO_PRIV_STACK;
6280 
6281 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6282 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6283 	 * explicitly.
6284 	 */
6285 	switch (prog->type) {
6286 	case BPF_PROG_TYPE_KPROBE:
6287 	case BPF_PROG_TYPE_TRACEPOINT:
6288 	case BPF_PROG_TYPE_PERF_EVENT:
6289 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6290 		return PRIV_STACK_ADAPTIVE;
6291 	case BPF_PROG_TYPE_TRACING:
6292 	case BPF_PROG_TYPE_LSM:
6293 	case BPF_PROG_TYPE_STRUCT_OPS:
6294 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6295 			return PRIV_STACK_ADAPTIVE;
6296 		fallthrough;
6297 	default:
6298 		break;
6299 	}
6300 
6301 	return NO_PRIV_STACK;
6302 }
6303 
6304 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6305 {
6306 	if (env->prog->jit_requested)
6307 		return round_up(stack_depth, 16);
6308 
6309 	/* round up to 32-bytes, since this is granularity
6310 	 * of interpreter stack size
6311 	 */
6312 	return round_up(max_t(u32, stack_depth, 1), 32);
6313 }
6314 
6315 /* starting from main bpf function walk all instructions of the function
6316  * and recursively walk all callees that given function can call.
6317  * Ignore jump and exit insns.
6318  * Since recursion is prevented by check_cfg() this algorithm
6319  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6320  */
6321 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6322 					 bool priv_stack_supported)
6323 {
6324 	struct bpf_subprog_info *subprog = env->subprog_info;
6325 	struct bpf_insn *insn = env->prog->insnsi;
6326 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6327 	bool tail_call_reachable = false;
6328 	int ret_insn[MAX_CALL_FRAMES];
6329 	int ret_prog[MAX_CALL_FRAMES];
6330 	int j;
6331 
6332 	i = subprog[idx].start;
6333 	if (!priv_stack_supported)
6334 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6335 process_func:
6336 	/* protect against potential stack overflow that might happen when
6337 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6338 	 * depth for such case down to 256 so that the worst case scenario
6339 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6340 	 * 8k).
6341 	 *
6342 	 * To get the idea what might happen, see an example:
6343 	 * func1 -> sub rsp, 128
6344 	 *  subfunc1 -> sub rsp, 256
6345 	 *  tailcall1 -> add rsp, 256
6346 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6347 	 *   subfunc2 -> sub rsp, 64
6348 	 *   subfunc22 -> sub rsp, 128
6349 	 *   tailcall2 -> add rsp, 128
6350 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6351 	 *
6352 	 * tailcall will unwind the current stack frame but it will not get rid
6353 	 * of caller's stack as shown on the example above.
6354 	 */
6355 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6356 		verbose(env,
6357 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6358 			depth);
6359 		return -EACCES;
6360 	}
6361 
6362 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6363 	if (priv_stack_supported) {
6364 		/* Request private stack support only if the subprog stack
6365 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6366 		 * avoid jit penalty if the stack usage is small.
6367 		 */
6368 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6369 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6370 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6371 	}
6372 
6373 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6374 		if (subprog_depth > MAX_BPF_STACK) {
6375 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6376 				idx, subprog_depth);
6377 			return -EACCES;
6378 		}
6379 	} else {
6380 		depth += subprog_depth;
6381 		if (depth > MAX_BPF_STACK) {
6382 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6383 				frame + 1, depth);
6384 			return -EACCES;
6385 		}
6386 	}
6387 continue_func:
6388 	subprog_end = subprog[idx + 1].start;
6389 	for (; i < subprog_end; i++) {
6390 		int next_insn, sidx;
6391 
6392 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6393 			bool err = false;
6394 
6395 			if (!is_bpf_throw_kfunc(insn + i))
6396 				continue;
6397 			if (subprog[idx].is_cb)
6398 				err = true;
6399 			for (int c = 0; c < frame && !err; c++) {
6400 				if (subprog[ret_prog[c]].is_cb) {
6401 					err = true;
6402 					break;
6403 				}
6404 			}
6405 			if (!err)
6406 				continue;
6407 			verbose(env,
6408 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6409 				i, idx);
6410 			return -EINVAL;
6411 		}
6412 
6413 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6414 			continue;
6415 		/* remember insn and function to return to */
6416 		ret_insn[frame] = i + 1;
6417 		ret_prog[frame] = idx;
6418 
6419 		/* find the callee */
6420 		next_insn = i + insn[i].imm + 1;
6421 		sidx = find_subprog(env, next_insn);
6422 		if (sidx < 0) {
6423 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6424 				  next_insn);
6425 			return -EFAULT;
6426 		}
6427 		if (subprog[sidx].is_async_cb) {
6428 			if (subprog[sidx].has_tail_call) {
6429 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6430 				return -EFAULT;
6431 			}
6432 			/* async callbacks don't increase bpf prog stack size unless called directly */
6433 			if (!bpf_pseudo_call(insn + i))
6434 				continue;
6435 			if (subprog[sidx].is_exception_cb) {
6436 				verbose(env, "insn %d cannot call exception cb directly\n", i);
6437 				return -EINVAL;
6438 			}
6439 		}
6440 		i = next_insn;
6441 		idx = sidx;
6442 		if (!priv_stack_supported)
6443 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6444 
6445 		if (subprog[idx].has_tail_call)
6446 			tail_call_reachable = true;
6447 
6448 		frame++;
6449 		if (frame >= MAX_CALL_FRAMES) {
6450 			verbose(env, "the call stack of %d frames is too deep !\n",
6451 				frame);
6452 			return -E2BIG;
6453 		}
6454 		goto process_func;
6455 	}
6456 	/* if tail call got detected across bpf2bpf calls then mark each of the
6457 	 * currently present subprog frames as tail call reachable subprogs;
6458 	 * this info will be utilized by JIT so that we will be preserving the
6459 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6460 	 */
6461 	if (tail_call_reachable)
6462 		for (j = 0; j < frame; j++) {
6463 			if (subprog[ret_prog[j]].is_exception_cb) {
6464 				verbose(env, "cannot tail call within exception cb\n");
6465 				return -EINVAL;
6466 			}
6467 			subprog[ret_prog[j]].tail_call_reachable = true;
6468 		}
6469 	if (subprog[0].tail_call_reachable)
6470 		env->prog->aux->tail_call_reachable = true;
6471 
6472 	/* end of for() loop means the last insn of the 'subprog'
6473 	 * was reached. Doesn't matter whether it was JA or EXIT
6474 	 */
6475 	if (frame == 0)
6476 		return 0;
6477 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6478 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6479 	frame--;
6480 	i = ret_insn[frame];
6481 	idx = ret_prog[frame];
6482 	goto continue_func;
6483 }
6484 
6485 static int check_max_stack_depth(struct bpf_verifier_env *env)
6486 {
6487 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6488 	struct bpf_subprog_info *si = env->subprog_info;
6489 	bool priv_stack_supported;
6490 	int ret;
6491 
6492 	for (int i = 0; i < env->subprog_cnt; i++) {
6493 		if (si[i].has_tail_call) {
6494 			priv_stack_mode = NO_PRIV_STACK;
6495 			break;
6496 		}
6497 	}
6498 
6499 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6500 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6501 
6502 	/* All async_cb subprogs use normal kernel stack. If a particular
6503 	 * subprog appears in both main prog and async_cb subtree, that
6504 	 * subprog will use normal kernel stack to avoid potential nesting.
6505 	 * The reverse subprog traversal ensures when main prog subtree is
6506 	 * checked, the subprogs appearing in async_cb subtrees are already
6507 	 * marked as using normal kernel stack, so stack size checking can
6508 	 * be done properly.
6509 	 */
6510 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6511 		if (!i || si[i].is_async_cb) {
6512 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6513 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6514 			if (ret < 0)
6515 				return ret;
6516 		}
6517 	}
6518 
6519 	for (int i = 0; i < env->subprog_cnt; i++) {
6520 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6521 			env->prog->aux->jits_use_priv_stack = true;
6522 			break;
6523 		}
6524 	}
6525 
6526 	return 0;
6527 }
6528 
6529 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6530 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6531 				  const struct bpf_insn *insn, int idx)
6532 {
6533 	int start = idx + insn->imm + 1, subprog;
6534 
6535 	subprog = find_subprog(env, start);
6536 	if (subprog < 0) {
6537 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6538 			  start);
6539 		return -EFAULT;
6540 	}
6541 	return env->subprog_info[subprog].stack_depth;
6542 }
6543 #endif
6544 
6545 static int __check_buffer_access(struct bpf_verifier_env *env,
6546 				 const char *buf_info,
6547 				 const struct bpf_reg_state *reg,
6548 				 int regno, int off, int size)
6549 {
6550 	if (off < 0) {
6551 		verbose(env,
6552 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6553 			regno, buf_info, off, size);
6554 		return -EACCES;
6555 	}
6556 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6557 		char tn_buf[48];
6558 
6559 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6560 		verbose(env,
6561 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6562 			regno, off, tn_buf);
6563 		return -EACCES;
6564 	}
6565 
6566 	return 0;
6567 }
6568 
6569 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6570 				  const struct bpf_reg_state *reg,
6571 				  int regno, int off, int size)
6572 {
6573 	int err;
6574 
6575 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6576 	if (err)
6577 		return err;
6578 
6579 	if (off + size > env->prog->aux->max_tp_access)
6580 		env->prog->aux->max_tp_access = off + size;
6581 
6582 	return 0;
6583 }
6584 
6585 static int check_buffer_access(struct bpf_verifier_env *env,
6586 			       const struct bpf_reg_state *reg,
6587 			       int regno, int off, int size,
6588 			       bool zero_size_allowed,
6589 			       u32 *max_access)
6590 {
6591 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6592 	int err;
6593 
6594 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6595 	if (err)
6596 		return err;
6597 
6598 	if (off + size > *max_access)
6599 		*max_access = off + size;
6600 
6601 	return 0;
6602 }
6603 
6604 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6605 static void zext_32_to_64(struct bpf_reg_state *reg)
6606 {
6607 	reg->var_off = tnum_subreg(reg->var_off);
6608 	__reg_assign_32_into_64(reg);
6609 }
6610 
6611 /* truncate register to smaller size (in bytes)
6612  * must be called with size < BPF_REG_SIZE
6613  */
6614 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6615 {
6616 	u64 mask;
6617 
6618 	/* clear high bits in bit representation */
6619 	reg->var_off = tnum_cast(reg->var_off, size);
6620 
6621 	/* fix arithmetic bounds */
6622 	mask = ((u64)1 << (size * 8)) - 1;
6623 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6624 		reg->umin_value &= mask;
6625 		reg->umax_value &= mask;
6626 	} else {
6627 		reg->umin_value = 0;
6628 		reg->umax_value = mask;
6629 	}
6630 	reg->smin_value = reg->umin_value;
6631 	reg->smax_value = reg->umax_value;
6632 
6633 	/* If size is smaller than 32bit register the 32bit register
6634 	 * values are also truncated so we push 64-bit bounds into
6635 	 * 32-bit bounds. Above were truncated < 32-bits already.
6636 	 */
6637 	if (size < 4)
6638 		__mark_reg32_unbounded(reg);
6639 
6640 	reg_bounds_sync(reg);
6641 }
6642 
6643 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6644 {
6645 	if (size == 1) {
6646 		reg->smin_value = reg->s32_min_value = S8_MIN;
6647 		reg->smax_value = reg->s32_max_value = S8_MAX;
6648 	} else if (size == 2) {
6649 		reg->smin_value = reg->s32_min_value = S16_MIN;
6650 		reg->smax_value = reg->s32_max_value = S16_MAX;
6651 	} else {
6652 		/* size == 4 */
6653 		reg->smin_value = reg->s32_min_value = S32_MIN;
6654 		reg->smax_value = reg->s32_max_value = S32_MAX;
6655 	}
6656 	reg->umin_value = reg->u32_min_value = 0;
6657 	reg->umax_value = U64_MAX;
6658 	reg->u32_max_value = U32_MAX;
6659 	reg->var_off = tnum_unknown;
6660 }
6661 
6662 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6663 {
6664 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6665 	u64 top_smax_value, top_smin_value;
6666 	u64 num_bits = size * 8;
6667 
6668 	if (tnum_is_const(reg->var_off)) {
6669 		u64_cval = reg->var_off.value;
6670 		if (size == 1)
6671 			reg->var_off = tnum_const((s8)u64_cval);
6672 		else if (size == 2)
6673 			reg->var_off = tnum_const((s16)u64_cval);
6674 		else
6675 			/* size == 4 */
6676 			reg->var_off = tnum_const((s32)u64_cval);
6677 
6678 		u64_cval = reg->var_off.value;
6679 		reg->smax_value = reg->smin_value = u64_cval;
6680 		reg->umax_value = reg->umin_value = u64_cval;
6681 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6682 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6683 		return;
6684 	}
6685 
6686 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6687 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6688 
6689 	if (top_smax_value != top_smin_value)
6690 		goto out;
6691 
6692 	/* find the s64_min and s64_min after sign extension */
6693 	if (size == 1) {
6694 		init_s64_max = (s8)reg->smax_value;
6695 		init_s64_min = (s8)reg->smin_value;
6696 	} else if (size == 2) {
6697 		init_s64_max = (s16)reg->smax_value;
6698 		init_s64_min = (s16)reg->smin_value;
6699 	} else {
6700 		init_s64_max = (s32)reg->smax_value;
6701 		init_s64_min = (s32)reg->smin_value;
6702 	}
6703 
6704 	s64_max = max(init_s64_max, init_s64_min);
6705 	s64_min = min(init_s64_max, init_s64_min);
6706 
6707 	/* both of s64_max/s64_min positive or negative */
6708 	if ((s64_max >= 0) == (s64_min >= 0)) {
6709 		reg->s32_min_value = reg->smin_value = s64_min;
6710 		reg->s32_max_value = reg->smax_value = s64_max;
6711 		reg->u32_min_value = reg->umin_value = s64_min;
6712 		reg->u32_max_value = reg->umax_value = s64_max;
6713 		reg->var_off = tnum_range(s64_min, s64_max);
6714 		return;
6715 	}
6716 
6717 out:
6718 	set_sext64_default_val(reg, size);
6719 }
6720 
6721 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6722 {
6723 	if (size == 1) {
6724 		reg->s32_min_value = S8_MIN;
6725 		reg->s32_max_value = S8_MAX;
6726 	} else {
6727 		/* size == 2 */
6728 		reg->s32_min_value = S16_MIN;
6729 		reg->s32_max_value = S16_MAX;
6730 	}
6731 	reg->u32_min_value = 0;
6732 	reg->u32_max_value = U32_MAX;
6733 	reg->var_off = tnum_subreg(tnum_unknown);
6734 }
6735 
6736 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6737 {
6738 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6739 	u32 top_smax_value, top_smin_value;
6740 	u32 num_bits = size * 8;
6741 
6742 	if (tnum_is_const(reg->var_off)) {
6743 		u32_val = reg->var_off.value;
6744 		if (size == 1)
6745 			reg->var_off = tnum_const((s8)u32_val);
6746 		else
6747 			reg->var_off = tnum_const((s16)u32_val);
6748 
6749 		u32_val = reg->var_off.value;
6750 		reg->s32_min_value = reg->s32_max_value = u32_val;
6751 		reg->u32_min_value = reg->u32_max_value = u32_val;
6752 		return;
6753 	}
6754 
6755 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6756 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6757 
6758 	if (top_smax_value != top_smin_value)
6759 		goto out;
6760 
6761 	/* find the s32_min and s32_min after sign extension */
6762 	if (size == 1) {
6763 		init_s32_max = (s8)reg->s32_max_value;
6764 		init_s32_min = (s8)reg->s32_min_value;
6765 	} else {
6766 		/* size == 2 */
6767 		init_s32_max = (s16)reg->s32_max_value;
6768 		init_s32_min = (s16)reg->s32_min_value;
6769 	}
6770 	s32_max = max(init_s32_max, init_s32_min);
6771 	s32_min = min(init_s32_max, init_s32_min);
6772 
6773 	if ((s32_min >= 0) == (s32_max >= 0)) {
6774 		reg->s32_min_value = s32_min;
6775 		reg->s32_max_value = s32_max;
6776 		reg->u32_min_value = (u32)s32_min;
6777 		reg->u32_max_value = (u32)s32_max;
6778 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6779 		return;
6780 	}
6781 
6782 out:
6783 	set_sext32_default_val(reg, size);
6784 }
6785 
6786 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6787 {
6788 	/* A map is considered read-only if the following condition are true:
6789 	 *
6790 	 * 1) BPF program side cannot change any of the map content. The
6791 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6792 	 *    and was set at map creation time.
6793 	 * 2) The map value(s) have been initialized from user space by a
6794 	 *    loader and then "frozen", such that no new map update/delete
6795 	 *    operations from syscall side are possible for the rest of
6796 	 *    the map's lifetime from that point onwards.
6797 	 * 3) Any parallel/pending map update/delete operations from syscall
6798 	 *    side have been completed. Only after that point, it's safe to
6799 	 *    assume that map value(s) are immutable.
6800 	 */
6801 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6802 	       READ_ONCE(map->frozen) &&
6803 	       !bpf_map_write_active(map);
6804 }
6805 
6806 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6807 			       bool is_ldsx)
6808 {
6809 	void *ptr;
6810 	u64 addr;
6811 	int err;
6812 
6813 	err = map->ops->map_direct_value_addr(map, &addr, off);
6814 	if (err)
6815 		return err;
6816 	ptr = (void *)(long)addr + off;
6817 
6818 	switch (size) {
6819 	case sizeof(u8):
6820 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6821 		break;
6822 	case sizeof(u16):
6823 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6824 		break;
6825 	case sizeof(u32):
6826 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6827 		break;
6828 	case sizeof(u64):
6829 		*val = *(u64 *)ptr;
6830 		break;
6831 	default:
6832 		return -EINVAL;
6833 	}
6834 	return 0;
6835 }
6836 
6837 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6838 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6839 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6840 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6841 
6842 /*
6843  * Allow list few fields as RCU trusted or full trusted.
6844  * This logic doesn't allow mix tagging and will be removed once GCC supports
6845  * btf_type_tag.
6846  */
6847 
6848 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6849 BTF_TYPE_SAFE_RCU(struct task_struct) {
6850 	const cpumask_t *cpus_ptr;
6851 	struct css_set __rcu *cgroups;
6852 	struct task_struct __rcu *real_parent;
6853 	struct task_struct *group_leader;
6854 };
6855 
6856 BTF_TYPE_SAFE_RCU(struct cgroup) {
6857 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6858 	struct kernfs_node *kn;
6859 };
6860 
6861 BTF_TYPE_SAFE_RCU(struct css_set) {
6862 	struct cgroup *dfl_cgrp;
6863 };
6864 
6865 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6866 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6867 	struct file __rcu *exe_file;
6868 };
6869 
6870 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6871  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6872  */
6873 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6874 	struct sock *sk;
6875 };
6876 
6877 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6878 	struct sock *sk;
6879 };
6880 
6881 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6882 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6883 	struct seq_file *seq;
6884 };
6885 
6886 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6887 	struct bpf_iter_meta *meta;
6888 	struct task_struct *task;
6889 };
6890 
6891 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6892 	struct file *file;
6893 };
6894 
6895 BTF_TYPE_SAFE_TRUSTED(struct file) {
6896 	struct inode *f_inode;
6897 };
6898 
6899 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6900 	/* no negative dentry-s in places where bpf can see it */
6901 	struct inode *d_inode;
6902 };
6903 
6904 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6905 	struct sock *sk;
6906 };
6907 
6908 static bool type_is_rcu(struct bpf_verifier_env *env,
6909 			struct bpf_reg_state *reg,
6910 			const char *field_name, u32 btf_id)
6911 {
6912 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6913 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6914 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6915 
6916 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6917 }
6918 
6919 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6920 				struct bpf_reg_state *reg,
6921 				const char *field_name, u32 btf_id)
6922 {
6923 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6924 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6925 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6926 
6927 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6928 }
6929 
6930 static bool type_is_trusted(struct bpf_verifier_env *env,
6931 			    struct bpf_reg_state *reg,
6932 			    const char *field_name, u32 btf_id)
6933 {
6934 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6935 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6936 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6937 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6938 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6939 
6940 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6941 }
6942 
6943 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6944 				    struct bpf_reg_state *reg,
6945 				    const char *field_name, u32 btf_id)
6946 {
6947 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6948 
6949 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6950 					  "__safe_trusted_or_null");
6951 }
6952 
6953 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6954 				   struct bpf_reg_state *regs,
6955 				   int regno, int off, int size,
6956 				   enum bpf_access_type atype,
6957 				   int value_regno)
6958 {
6959 	struct bpf_reg_state *reg = regs + regno;
6960 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6961 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6962 	const char *field_name = NULL;
6963 	enum bpf_type_flag flag = 0;
6964 	u32 btf_id = 0;
6965 	int ret;
6966 
6967 	if (!env->allow_ptr_leaks) {
6968 		verbose(env,
6969 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6970 			tname);
6971 		return -EPERM;
6972 	}
6973 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6974 		verbose(env,
6975 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6976 			tname);
6977 		return -EINVAL;
6978 	}
6979 	if (off < 0) {
6980 		verbose(env,
6981 			"R%d is ptr_%s invalid negative access: off=%d\n",
6982 			regno, tname, off);
6983 		return -EACCES;
6984 	}
6985 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6986 		char tn_buf[48];
6987 
6988 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6989 		verbose(env,
6990 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6991 			regno, tname, off, tn_buf);
6992 		return -EACCES;
6993 	}
6994 
6995 	if (reg->type & MEM_USER) {
6996 		verbose(env,
6997 			"R%d is ptr_%s access user memory: off=%d\n",
6998 			regno, tname, off);
6999 		return -EACCES;
7000 	}
7001 
7002 	if (reg->type & MEM_PERCPU) {
7003 		verbose(env,
7004 			"R%d is ptr_%s access percpu memory: off=%d\n",
7005 			regno, tname, off);
7006 		return -EACCES;
7007 	}
7008 
7009 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7010 		if (!btf_is_kernel(reg->btf)) {
7011 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
7012 			return -EFAULT;
7013 		}
7014 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7015 	} else {
7016 		/* Writes are permitted with default btf_struct_access for
7017 		 * program allocated objects (which always have ref_obj_id > 0),
7018 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7019 		 */
7020 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7021 			verbose(env, "only read is supported\n");
7022 			return -EACCES;
7023 		}
7024 
7025 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7026 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7027 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
7028 			return -EFAULT;
7029 		}
7030 
7031 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7032 	}
7033 
7034 	if (ret < 0)
7035 		return ret;
7036 
7037 	if (ret != PTR_TO_BTF_ID) {
7038 		/* just mark; */
7039 
7040 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7041 		/* If this is an untrusted pointer, all pointers formed by walking it
7042 		 * also inherit the untrusted flag.
7043 		 */
7044 		flag = PTR_UNTRUSTED;
7045 
7046 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7047 		/* By default any pointer obtained from walking a trusted pointer is no
7048 		 * longer trusted, unless the field being accessed has explicitly been
7049 		 * marked as inheriting its parent's state of trust (either full or RCU).
7050 		 * For example:
7051 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7052 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7053 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7054 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7055 		 *
7056 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7057 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7058 		 */
7059 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7060 			flag |= PTR_TRUSTED;
7061 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7062 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7063 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7064 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7065 				/* ignore __rcu tag and mark it MEM_RCU */
7066 				flag |= MEM_RCU;
7067 			} else if (flag & MEM_RCU ||
7068 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7069 				/* __rcu tagged pointers can be NULL */
7070 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7071 
7072 				/* We always trust them */
7073 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7074 				    flag & PTR_UNTRUSTED)
7075 					flag &= ~PTR_UNTRUSTED;
7076 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7077 				/* keep as-is */
7078 			} else {
7079 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7080 				clear_trusted_flags(&flag);
7081 			}
7082 		} else {
7083 			/*
7084 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7085 			 * aggressively mark as untrusted otherwise such
7086 			 * pointers will be plain PTR_TO_BTF_ID without flags
7087 			 * and will be allowed to be passed into helpers for
7088 			 * compat reasons.
7089 			 */
7090 			flag = PTR_UNTRUSTED;
7091 		}
7092 	} else {
7093 		/* Old compat. Deprecated */
7094 		clear_trusted_flags(&flag);
7095 	}
7096 
7097 	if (atype == BPF_READ && value_regno >= 0)
7098 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7099 
7100 	return 0;
7101 }
7102 
7103 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7104 				   struct bpf_reg_state *regs,
7105 				   int regno, int off, int size,
7106 				   enum bpf_access_type atype,
7107 				   int value_regno)
7108 {
7109 	struct bpf_reg_state *reg = regs + regno;
7110 	struct bpf_map *map = reg->map_ptr;
7111 	struct bpf_reg_state map_reg;
7112 	enum bpf_type_flag flag = 0;
7113 	const struct btf_type *t;
7114 	const char *tname;
7115 	u32 btf_id;
7116 	int ret;
7117 
7118 	if (!btf_vmlinux) {
7119 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7120 		return -ENOTSUPP;
7121 	}
7122 
7123 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7124 		verbose(env, "map_ptr access not supported for map type %d\n",
7125 			map->map_type);
7126 		return -ENOTSUPP;
7127 	}
7128 
7129 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7130 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7131 
7132 	if (!env->allow_ptr_leaks) {
7133 		verbose(env,
7134 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7135 			tname);
7136 		return -EPERM;
7137 	}
7138 
7139 	if (off < 0) {
7140 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7141 			regno, tname, off);
7142 		return -EACCES;
7143 	}
7144 
7145 	if (atype != BPF_READ) {
7146 		verbose(env, "only read from %s is supported\n", tname);
7147 		return -EACCES;
7148 	}
7149 
7150 	/* Simulate access to a PTR_TO_BTF_ID */
7151 	memset(&map_reg, 0, sizeof(map_reg));
7152 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
7153 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7154 	if (ret < 0)
7155 		return ret;
7156 
7157 	if (value_regno >= 0)
7158 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7159 
7160 	return 0;
7161 }
7162 
7163 /* Check that the stack access at the given offset is within bounds. The
7164  * maximum valid offset is -1.
7165  *
7166  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7167  * -state->allocated_stack for reads.
7168  */
7169 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7170                                           s64 off,
7171                                           struct bpf_func_state *state,
7172                                           enum bpf_access_type t)
7173 {
7174 	int min_valid_off;
7175 
7176 	if (t == BPF_WRITE || env->allow_uninit_stack)
7177 		min_valid_off = -MAX_BPF_STACK;
7178 	else
7179 		min_valid_off = -state->allocated_stack;
7180 
7181 	if (off < min_valid_off || off > -1)
7182 		return -EACCES;
7183 	return 0;
7184 }
7185 
7186 /* Check that the stack access at 'regno + off' falls within the maximum stack
7187  * bounds.
7188  *
7189  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7190  */
7191 static int check_stack_access_within_bounds(
7192 		struct bpf_verifier_env *env,
7193 		int regno, int off, int access_size,
7194 		enum bpf_access_type type)
7195 {
7196 	struct bpf_reg_state *regs = cur_regs(env);
7197 	struct bpf_reg_state *reg = regs + regno;
7198 	struct bpf_func_state *state = func(env, reg);
7199 	s64 min_off, max_off;
7200 	int err;
7201 	char *err_extra;
7202 
7203 	if (type == BPF_READ)
7204 		err_extra = " read from";
7205 	else
7206 		err_extra = " write to";
7207 
7208 	if (tnum_is_const(reg->var_off)) {
7209 		min_off = (s64)reg->var_off.value + off;
7210 		max_off = min_off + access_size;
7211 	} else {
7212 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7213 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7214 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7215 				err_extra, regno);
7216 			return -EACCES;
7217 		}
7218 		min_off = reg->smin_value + off;
7219 		max_off = reg->smax_value + off + access_size;
7220 	}
7221 
7222 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7223 	if (!err && max_off > 0)
7224 		err = -EINVAL; /* out of stack access into non-negative offsets */
7225 	if (!err && access_size < 0)
7226 		/* access_size should not be negative (or overflow an int); others checks
7227 		 * along the way should have prevented such an access.
7228 		 */
7229 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7230 
7231 	if (err) {
7232 		if (tnum_is_const(reg->var_off)) {
7233 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7234 				err_extra, regno, off, access_size);
7235 		} else {
7236 			char tn_buf[48];
7237 
7238 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7239 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7240 				err_extra, regno, tn_buf, off, access_size);
7241 		}
7242 		return err;
7243 	}
7244 
7245 	/* Note that there is no stack access with offset zero, so the needed stack
7246 	 * size is -min_off, not -min_off+1.
7247 	 */
7248 	return grow_stack_state(env, state, -min_off /* size */);
7249 }
7250 
7251 static bool get_func_retval_range(struct bpf_prog *prog,
7252 				  struct bpf_retval_range *range)
7253 {
7254 	if (prog->type == BPF_PROG_TYPE_LSM &&
7255 		prog->expected_attach_type == BPF_LSM_MAC &&
7256 		!bpf_lsm_get_retval_range(prog, range)) {
7257 		return true;
7258 	}
7259 	return false;
7260 }
7261 
7262 /* check whether memory at (regno + off) is accessible for t = (read | write)
7263  * if t==write, value_regno is a register which value is stored into memory
7264  * if t==read, value_regno is a register which will receive the value from memory
7265  * if t==write && value_regno==-1, some unknown value is stored into memory
7266  * if t==read && value_regno==-1, don't care what we read from memory
7267  */
7268 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7269 			    int off, int bpf_size, enum bpf_access_type t,
7270 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7271 {
7272 	struct bpf_reg_state *regs = cur_regs(env);
7273 	struct bpf_reg_state *reg = regs + regno;
7274 	int size, err = 0;
7275 
7276 	size = bpf_size_to_bytes(bpf_size);
7277 	if (size < 0)
7278 		return size;
7279 
7280 	/* alignment checks will add in reg->off themselves */
7281 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7282 	if (err)
7283 		return err;
7284 
7285 	/* for access checks, reg->off is just part of off */
7286 	off += reg->off;
7287 
7288 	if (reg->type == PTR_TO_MAP_KEY) {
7289 		if (t == BPF_WRITE) {
7290 			verbose(env, "write to change key R%d not allowed\n", regno);
7291 			return -EACCES;
7292 		}
7293 
7294 		err = check_mem_region_access(env, regno, off, size,
7295 					      reg->map_ptr->key_size, false);
7296 		if (err)
7297 			return err;
7298 		if (value_regno >= 0)
7299 			mark_reg_unknown(env, regs, value_regno);
7300 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7301 		struct btf_field *kptr_field = NULL;
7302 
7303 		if (t == BPF_WRITE && value_regno >= 0 &&
7304 		    is_pointer_value(env, value_regno)) {
7305 			verbose(env, "R%d leaks addr into map\n", value_regno);
7306 			return -EACCES;
7307 		}
7308 		err = check_map_access_type(env, regno, off, size, t);
7309 		if (err)
7310 			return err;
7311 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7312 		if (err)
7313 			return err;
7314 		if (tnum_is_const(reg->var_off))
7315 			kptr_field = btf_record_find(reg->map_ptr->record,
7316 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7317 		if (kptr_field) {
7318 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7319 		} else if (t == BPF_READ && value_regno >= 0) {
7320 			struct bpf_map *map = reg->map_ptr;
7321 
7322 			/* if map is read-only, track its contents as scalars */
7323 			if (tnum_is_const(reg->var_off) &&
7324 			    bpf_map_is_rdonly(map) &&
7325 			    map->ops->map_direct_value_addr) {
7326 				int map_off = off + reg->var_off.value;
7327 				u64 val = 0;
7328 
7329 				err = bpf_map_direct_read(map, map_off, size,
7330 							  &val, is_ldsx);
7331 				if (err)
7332 					return err;
7333 
7334 				regs[value_regno].type = SCALAR_VALUE;
7335 				__mark_reg_known(&regs[value_regno], val);
7336 			} else {
7337 				mark_reg_unknown(env, regs, value_regno);
7338 			}
7339 		}
7340 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7341 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7342 
7343 		if (type_may_be_null(reg->type)) {
7344 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7345 				reg_type_str(env, reg->type));
7346 			return -EACCES;
7347 		}
7348 
7349 		if (t == BPF_WRITE && rdonly_mem) {
7350 			verbose(env, "R%d cannot write into %s\n",
7351 				regno, reg_type_str(env, reg->type));
7352 			return -EACCES;
7353 		}
7354 
7355 		if (t == BPF_WRITE && value_regno >= 0 &&
7356 		    is_pointer_value(env, value_regno)) {
7357 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7358 			return -EACCES;
7359 		}
7360 
7361 		err = check_mem_region_access(env, regno, off, size,
7362 					      reg->mem_size, false);
7363 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7364 			mark_reg_unknown(env, regs, value_regno);
7365 	} else if (reg->type == PTR_TO_CTX) {
7366 		bool is_retval = false;
7367 		struct bpf_retval_range range;
7368 		enum bpf_reg_type reg_type = SCALAR_VALUE;
7369 		struct btf *btf = NULL;
7370 		u32 btf_id = 0;
7371 
7372 		if (t == BPF_WRITE && value_regno >= 0 &&
7373 		    is_pointer_value(env, value_regno)) {
7374 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7375 			return -EACCES;
7376 		}
7377 
7378 		err = check_ptr_off_reg(env, reg, regno);
7379 		if (err < 0)
7380 			return err;
7381 
7382 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
7383 				       &btf_id, &is_retval, is_ldsx);
7384 		if (err)
7385 			verbose_linfo(env, insn_idx, "; ");
7386 		if (!err && t == BPF_READ && value_regno >= 0) {
7387 			/* ctx access returns either a scalar, or a
7388 			 * PTR_TO_PACKET[_META,_END]. In the latter
7389 			 * case, we know the offset is zero.
7390 			 */
7391 			if (reg_type == SCALAR_VALUE) {
7392 				if (is_retval && get_func_retval_range(env->prog, &range)) {
7393 					err = __mark_reg_s32_range(env, regs, value_regno,
7394 								   range.minval, range.maxval);
7395 					if (err)
7396 						return err;
7397 				} else {
7398 					mark_reg_unknown(env, regs, value_regno);
7399 				}
7400 			} else {
7401 				mark_reg_known_zero(env, regs,
7402 						    value_regno);
7403 				if (type_may_be_null(reg_type))
7404 					regs[value_regno].id = ++env->id_gen;
7405 				/* A load of ctx field could have different
7406 				 * actual load size with the one encoded in the
7407 				 * insn. When the dst is PTR, it is for sure not
7408 				 * a sub-register.
7409 				 */
7410 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7411 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
7412 					regs[value_regno].btf = btf;
7413 					regs[value_regno].btf_id = btf_id;
7414 				}
7415 			}
7416 			regs[value_regno].type = reg_type;
7417 		}
7418 
7419 	} else if (reg->type == PTR_TO_STACK) {
7420 		/* Basic bounds checks. */
7421 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7422 		if (err)
7423 			return err;
7424 
7425 		if (t == BPF_READ)
7426 			err = check_stack_read(env, regno, off, size,
7427 					       value_regno);
7428 		else
7429 			err = check_stack_write(env, regno, off, size,
7430 						value_regno, insn_idx);
7431 	} else if (reg_is_pkt_pointer(reg)) {
7432 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7433 			verbose(env, "cannot write into packet\n");
7434 			return -EACCES;
7435 		}
7436 		if (t == BPF_WRITE && value_regno >= 0 &&
7437 		    is_pointer_value(env, value_regno)) {
7438 			verbose(env, "R%d leaks addr into packet\n",
7439 				value_regno);
7440 			return -EACCES;
7441 		}
7442 		err = check_packet_access(env, regno, off, size, false);
7443 		if (!err && t == BPF_READ && value_regno >= 0)
7444 			mark_reg_unknown(env, regs, value_regno);
7445 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7446 		if (t == BPF_WRITE && value_regno >= 0 &&
7447 		    is_pointer_value(env, value_regno)) {
7448 			verbose(env, "R%d leaks addr into flow keys\n",
7449 				value_regno);
7450 			return -EACCES;
7451 		}
7452 
7453 		err = check_flow_keys_access(env, off, size);
7454 		if (!err && t == BPF_READ && value_regno >= 0)
7455 			mark_reg_unknown(env, regs, value_regno);
7456 	} else if (type_is_sk_pointer(reg->type)) {
7457 		if (t == BPF_WRITE) {
7458 			verbose(env, "R%d cannot write into %s\n",
7459 				regno, reg_type_str(env, reg->type));
7460 			return -EACCES;
7461 		}
7462 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7463 		if (!err && value_regno >= 0)
7464 			mark_reg_unknown(env, regs, value_regno);
7465 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7466 		err = check_tp_buffer_access(env, reg, regno, off, size);
7467 		if (!err && t == BPF_READ && value_regno >= 0)
7468 			mark_reg_unknown(env, regs, value_regno);
7469 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7470 		   !type_may_be_null(reg->type)) {
7471 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7472 					      value_regno);
7473 	} else if (reg->type == CONST_PTR_TO_MAP) {
7474 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7475 					      value_regno);
7476 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7477 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7478 		u32 *max_access;
7479 
7480 		if (rdonly_mem) {
7481 			if (t == BPF_WRITE) {
7482 				verbose(env, "R%d cannot write into %s\n",
7483 					regno, reg_type_str(env, reg->type));
7484 				return -EACCES;
7485 			}
7486 			max_access = &env->prog->aux->max_rdonly_access;
7487 		} else {
7488 			max_access = &env->prog->aux->max_rdwr_access;
7489 		}
7490 
7491 		err = check_buffer_access(env, reg, regno, off, size, false,
7492 					  max_access);
7493 
7494 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7495 			mark_reg_unknown(env, regs, value_regno);
7496 	} else if (reg->type == PTR_TO_ARENA) {
7497 		if (t == BPF_READ && value_regno >= 0)
7498 			mark_reg_unknown(env, regs, value_regno);
7499 	} else {
7500 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7501 			reg_type_str(env, reg->type));
7502 		return -EACCES;
7503 	}
7504 
7505 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7506 	    regs[value_regno].type == SCALAR_VALUE) {
7507 		if (!is_ldsx)
7508 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7509 			coerce_reg_to_size(&regs[value_regno], size);
7510 		else
7511 			coerce_reg_to_size_sx(&regs[value_regno], size);
7512 	}
7513 	return err;
7514 }
7515 
7516 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7517 			     bool allow_trust_mismatch);
7518 
7519 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7520 {
7521 	int load_reg;
7522 	int err;
7523 
7524 	switch (insn->imm) {
7525 	case BPF_ADD:
7526 	case BPF_ADD | BPF_FETCH:
7527 	case BPF_AND:
7528 	case BPF_AND | BPF_FETCH:
7529 	case BPF_OR:
7530 	case BPF_OR | BPF_FETCH:
7531 	case BPF_XOR:
7532 	case BPF_XOR | BPF_FETCH:
7533 	case BPF_XCHG:
7534 	case BPF_CMPXCHG:
7535 		break;
7536 	default:
7537 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7538 		return -EINVAL;
7539 	}
7540 
7541 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7542 		verbose(env, "invalid atomic operand size\n");
7543 		return -EINVAL;
7544 	}
7545 
7546 	/* check src1 operand */
7547 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7548 	if (err)
7549 		return err;
7550 
7551 	/* check src2 operand */
7552 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7553 	if (err)
7554 		return err;
7555 
7556 	if (insn->imm == BPF_CMPXCHG) {
7557 		/* Check comparison of R0 with memory location */
7558 		const u32 aux_reg = BPF_REG_0;
7559 
7560 		err = check_reg_arg(env, aux_reg, SRC_OP);
7561 		if (err)
7562 			return err;
7563 
7564 		if (is_pointer_value(env, aux_reg)) {
7565 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7566 			return -EACCES;
7567 		}
7568 	}
7569 
7570 	if (is_pointer_value(env, insn->src_reg)) {
7571 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7572 		return -EACCES;
7573 	}
7574 
7575 	if (is_ctx_reg(env, insn->dst_reg) ||
7576 	    is_pkt_reg(env, insn->dst_reg) ||
7577 	    is_flow_key_reg(env, insn->dst_reg) ||
7578 	    is_sk_reg(env, insn->dst_reg) ||
7579 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7580 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7581 			insn->dst_reg,
7582 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7583 		return -EACCES;
7584 	}
7585 
7586 	if (insn->imm & BPF_FETCH) {
7587 		if (insn->imm == BPF_CMPXCHG)
7588 			load_reg = BPF_REG_0;
7589 		else
7590 			load_reg = insn->src_reg;
7591 
7592 		/* check and record load of old value */
7593 		err = check_reg_arg(env, load_reg, DST_OP);
7594 		if (err)
7595 			return err;
7596 	} else {
7597 		/* This instruction accesses a memory location but doesn't
7598 		 * actually load it into a register.
7599 		 */
7600 		load_reg = -1;
7601 	}
7602 
7603 	/* Check whether we can read the memory, with second call for fetch
7604 	 * case to simulate the register fill.
7605 	 */
7606 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7607 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7608 	if (!err && load_reg >= 0)
7609 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7610 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7611 				       true, false);
7612 	if (err)
7613 		return err;
7614 
7615 	if (is_arena_reg(env, insn->dst_reg)) {
7616 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7617 		if (err)
7618 			return err;
7619 	}
7620 	/* Check whether we can write into the same memory. */
7621 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7622 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7623 	if (err)
7624 		return err;
7625 	return 0;
7626 }
7627 
7628 /* When register 'regno' is used to read the stack (either directly or through
7629  * a helper function) make sure that it's within stack boundary and, depending
7630  * on the access type and privileges, that all elements of the stack are
7631  * initialized.
7632  *
7633  * 'off' includes 'regno->off', but not its dynamic part (if any).
7634  *
7635  * All registers that have been spilled on the stack in the slots within the
7636  * read offsets are marked as read.
7637  */
7638 static int check_stack_range_initialized(
7639 		struct bpf_verifier_env *env, int regno, int off,
7640 		int access_size, bool zero_size_allowed,
7641 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7642 {
7643 	struct bpf_reg_state *reg = reg_state(env, regno);
7644 	struct bpf_func_state *state = func(env, reg);
7645 	int err, min_off, max_off, i, j, slot, spi;
7646 	/* Some accesses can write anything into the stack, others are
7647 	 * read-only.
7648 	 */
7649 	bool clobber = false;
7650 
7651 	if (access_size == 0 && !zero_size_allowed) {
7652 		verbose(env, "invalid zero-sized read\n");
7653 		return -EACCES;
7654 	}
7655 
7656 	if (type == BPF_WRITE)
7657 		clobber = true;
7658 
7659 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7660 	if (err)
7661 		return err;
7662 
7663 
7664 	if (tnum_is_const(reg->var_off)) {
7665 		min_off = max_off = reg->var_off.value + off;
7666 	} else {
7667 		/* Variable offset is prohibited for unprivileged mode for
7668 		 * simplicity since it requires corresponding support in
7669 		 * Spectre masking for stack ALU.
7670 		 * See also retrieve_ptr_limit().
7671 		 */
7672 		if (!env->bypass_spec_v1) {
7673 			char tn_buf[48];
7674 
7675 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7676 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7677 				regno, tn_buf);
7678 			return -EACCES;
7679 		}
7680 		/* Only initialized buffer on stack is allowed to be accessed
7681 		 * with variable offset. With uninitialized buffer it's hard to
7682 		 * guarantee that whole memory is marked as initialized on
7683 		 * helper return since specific bounds are unknown what may
7684 		 * cause uninitialized stack leaking.
7685 		 */
7686 		if (meta && meta->raw_mode)
7687 			meta = NULL;
7688 
7689 		min_off = reg->smin_value + off;
7690 		max_off = reg->smax_value + off;
7691 	}
7692 
7693 	if (meta && meta->raw_mode) {
7694 		/* Ensure we won't be overwriting dynptrs when simulating byte
7695 		 * by byte access in check_helper_call using meta.access_size.
7696 		 * This would be a problem if we have a helper in the future
7697 		 * which takes:
7698 		 *
7699 		 *	helper(uninit_mem, len, dynptr)
7700 		 *
7701 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7702 		 * may end up writing to dynptr itself when touching memory from
7703 		 * arg 1. This can be relaxed on a case by case basis for known
7704 		 * safe cases, but reject due to the possibilitiy of aliasing by
7705 		 * default.
7706 		 */
7707 		for (i = min_off; i < max_off + access_size; i++) {
7708 			int stack_off = -i - 1;
7709 
7710 			spi = __get_spi(i);
7711 			/* raw_mode may write past allocated_stack */
7712 			if (state->allocated_stack <= stack_off)
7713 				continue;
7714 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7715 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7716 				return -EACCES;
7717 			}
7718 		}
7719 		meta->access_size = access_size;
7720 		meta->regno = regno;
7721 		return 0;
7722 	}
7723 
7724 	for (i = min_off; i < max_off + access_size; i++) {
7725 		u8 *stype;
7726 
7727 		slot = -i - 1;
7728 		spi = slot / BPF_REG_SIZE;
7729 		if (state->allocated_stack <= slot) {
7730 			verbose(env, "verifier bug: allocated_stack too small\n");
7731 			return -EFAULT;
7732 		}
7733 
7734 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7735 		if (*stype == STACK_MISC)
7736 			goto mark;
7737 		if ((*stype == STACK_ZERO) ||
7738 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7739 			if (clobber) {
7740 				/* helper can write anything into the stack */
7741 				*stype = STACK_MISC;
7742 			}
7743 			goto mark;
7744 		}
7745 
7746 		if (is_spilled_reg(&state->stack[spi]) &&
7747 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7748 		     env->allow_ptr_leaks)) {
7749 			if (clobber) {
7750 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7751 				for (j = 0; j < BPF_REG_SIZE; j++)
7752 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7753 			}
7754 			goto mark;
7755 		}
7756 
7757 		if (tnum_is_const(reg->var_off)) {
7758 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
7759 				regno, min_off, i - min_off, access_size);
7760 		} else {
7761 			char tn_buf[48];
7762 
7763 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7764 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
7765 				regno, tn_buf, i - min_off, access_size);
7766 		}
7767 		return -EACCES;
7768 mark:
7769 		/* reading any byte out of 8-byte 'spill_slot' will cause
7770 		 * the whole slot to be marked as 'read'
7771 		 */
7772 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7773 			      state->stack[spi].spilled_ptr.parent,
7774 			      REG_LIVE_READ64);
7775 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7776 		 * be sure that whether stack slot is written to or not. Hence,
7777 		 * we must still conservatively propagate reads upwards even if
7778 		 * helper may write to the entire memory range.
7779 		 */
7780 	}
7781 	return 0;
7782 }
7783 
7784 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7785 				   int access_size, enum bpf_access_type access_type,
7786 				   bool zero_size_allowed,
7787 				   struct bpf_call_arg_meta *meta)
7788 {
7789 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7790 	u32 *max_access;
7791 
7792 	switch (base_type(reg->type)) {
7793 	case PTR_TO_PACKET:
7794 	case PTR_TO_PACKET_META:
7795 		return check_packet_access(env, regno, reg->off, access_size,
7796 					   zero_size_allowed);
7797 	case PTR_TO_MAP_KEY:
7798 		if (access_type == BPF_WRITE) {
7799 			verbose(env, "R%d cannot write into %s\n", regno,
7800 				reg_type_str(env, reg->type));
7801 			return -EACCES;
7802 		}
7803 		return check_mem_region_access(env, regno, reg->off, access_size,
7804 					       reg->map_ptr->key_size, false);
7805 	case PTR_TO_MAP_VALUE:
7806 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7807 			return -EACCES;
7808 		return check_map_access(env, regno, reg->off, access_size,
7809 					zero_size_allowed, ACCESS_HELPER);
7810 	case PTR_TO_MEM:
7811 		if (type_is_rdonly_mem(reg->type)) {
7812 			if (access_type == BPF_WRITE) {
7813 				verbose(env, "R%d cannot write into %s\n", regno,
7814 					reg_type_str(env, reg->type));
7815 				return -EACCES;
7816 			}
7817 		}
7818 		return check_mem_region_access(env, regno, reg->off,
7819 					       access_size, reg->mem_size,
7820 					       zero_size_allowed);
7821 	case PTR_TO_BUF:
7822 		if (type_is_rdonly_mem(reg->type)) {
7823 			if (access_type == BPF_WRITE) {
7824 				verbose(env, "R%d cannot write into %s\n", regno,
7825 					reg_type_str(env, reg->type));
7826 				return -EACCES;
7827 			}
7828 
7829 			max_access = &env->prog->aux->max_rdonly_access;
7830 		} else {
7831 			max_access = &env->prog->aux->max_rdwr_access;
7832 		}
7833 		return check_buffer_access(env, reg, regno, reg->off,
7834 					   access_size, zero_size_allowed,
7835 					   max_access);
7836 	case PTR_TO_STACK:
7837 		return check_stack_range_initialized(
7838 				env,
7839 				regno, reg->off, access_size,
7840 				zero_size_allowed, access_type, meta);
7841 	case PTR_TO_BTF_ID:
7842 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7843 					       access_size, BPF_READ, -1);
7844 	case PTR_TO_CTX:
7845 		/* in case the function doesn't know how to access the context,
7846 		 * (because we are in a program of type SYSCALL for example), we
7847 		 * can not statically check its size.
7848 		 * Dynamically check it now.
7849 		 */
7850 		if (!env->ops->convert_ctx_access) {
7851 			int offset = access_size - 1;
7852 
7853 			/* Allow zero-byte read from PTR_TO_CTX */
7854 			if (access_size == 0)
7855 				return zero_size_allowed ? 0 : -EACCES;
7856 
7857 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7858 						access_type, -1, false, false);
7859 		}
7860 
7861 		fallthrough;
7862 	default: /* scalar_value or invalid ptr */
7863 		/* Allow zero-byte read from NULL, regardless of pointer type */
7864 		if (zero_size_allowed && access_size == 0 &&
7865 		    register_is_null(reg))
7866 			return 0;
7867 
7868 		verbose(env, "R%d type=%s ", regno,
7869 			reg_type_str(env, reg->type));
7870 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7871 		return -EACCES;
7872 	}
7873 }
7874 
7875 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7876  * size.
7877  *
7878  * @regno is the register containing the access size. regno-1 is the register
7879  * containing the pointer.
7880  */
7881 static int check_mem_size_reg(struct bpf_verifier_env *env,
7882 			      struct bpf_reg_state *reg, u32 regno,
7883 			      enum bpf_access_type access_type,
7884 			      bool zero_size_allowed,
7885 			      struct bpf_call_arg_meta *meta)
7886 {
7887 	int err;
7888 
7889 	/* This is used to refine r0 return value bounds for helpers
7890 	 * that enforce this value as an upper bound on return values.
7891 	 * See do_refine_retval_range() for helpers that can refine
7892 	 * the return value. C type of helper is u32 so we pull register
7893 	 * bound from umax_value however, if negative verifier errors
7894 	 * out. Only upper bounds can be learned because retval is an
7895 	 * int type and negative retvals are allowed.
7896 	 */
7897 	meta->msize_max_value = reg->umax_value;
7898 
7899 	/* The register is SCALAR_VALUE; the access check happens using
7900 	 * its boundaries. For unprivileged variable accesses, disable
7901 	 * raw mode so that the program is required to initialize all
7902 	 * the memory that the helper could just partially fill up.
7903 	 */
7904 	if (!tnum_is_const(reg->var_off))
7905 		meta = NULL;
7906 
7907 	if (reg->smin_value < 0) {
7908 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7909 			regno);
7910 		return -EACCES;
7911 	}
7912 
7913 	if (reg->umin_value == 0 && !zero_size_allowed) {
7914 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7915 			regno, reg->umin_value, reg->umax_value);
7916 		return -EACCES;
7917 	}
7918 
7919 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7920 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7921 			regno);
7922 		return -EACCES;
7923 	}
7924 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7925 				      access_type, zero_size_allowed, meta);
7926 	if (!err)
7927 		err = mark_chain_precision(env, regno);
7928 	return err;
7929 }
7930 
7931 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7932 			 u32 regno, u32 mem_size)
7933 {
7934 	bool may_be_null = type_may_be_null(reg->type);
7935 	struct bpf_reg_state saved_reg;
7936 	int err;
7937 
7938 	if (register_is_null(reg))
7939 		return 0;
7940 
7941 	/* Assuming that the register contains a value check if the memory
7942 	 * access is safe. Temporarily save and restore the register's state as
7943 	 * the conversion shouldn't be visible to a caller.
7944 	 */
7945 	if (may_be_null) {
7946 		saved_reg = *reg;
7947 		mark_ptr_not_null_reg(reg);
7948 	}
7949 
7950 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7951 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7952 
7953 	if (may_be_null)
7954 		*reg = saved_reg;
7955 
7956 	return err;
7957 }
7958 
7959 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7960 				    u32 regno)
7961 {
7962 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7963 	bool may_be_null = type_may_be_null(mem_reg->type);
7964 	struct bpf_reg_state saved_reg;
7965 	struct bpf_call_arg_meta meta;
7966 	int err;
7967 
7968 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7969 
7970 	memset(&meta, 0, sizeof(meta));
7971 
7972 	if (may_be_null) {
7973 		saved_reg = *mem_reg;
7974 		mark_ptr_not_null_reg(mem_reg);
7975 	}
7976 
7977 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7978 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7979 
7980 	if (may_be_null)
7981 		*mem_reg = saved_reg;
7982 
7983 	return err;
7984 }
7985 
7986 /* Implementation details:
7987  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7988  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7989  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7990  * Two separate bpf_obj_new will also have different reg->id.
7991  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7992  * clears reg->id after value_or_null->value transition, since the verifier only
7993  * cares about the range of access to valid map value pointer and doesn't care
7994  * about actual address of the map element.
7995  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7996  * reg->id > 0 after value_or_null->value transition. By doing so
7997  * two bpf_map_lookups will be considered two different pointers that
7998  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7999  * returned from bpf_obj_new.
8000  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8001  * dead-locks.
8002  * Since only one bpf_spin_lock is allowed the checks are simpler than
8003  * reg_is_refcounted() logic. The verifier needs to remember only
8004  * one spin_lock instead of array of acquired_refs.
8005  * env->cur_state->active_locks remembers which map value element or allocated
8006  * object got locked and clears it after bpf_spin_unlock.
8007  */
8008 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
8009 			     bool is_lock)
8010 {
8011 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8012 	struct bpf_verifier_state *cur = env->cur_state;
8013 	bool is_const = tnum_is_const(reg->var_off);
8014 	u64 val = reg->var_off.value;
8015 	struct bpf_map *map = NULL;
8016 	struct btf *btf = NULL;
8017 	struct btf_record *rec;
8018 	int err;
8019 
8020 	if (!is_const) {
8021 		verbose(env,
8022 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
8023 			regno);
8024 		return -EINVAL;
8025 	}
8026 	if (reg->type == PTR_TO_MAP_VALUE) {
8027 		map = reg->map_ptr;
8028 		if (!map->btf) {
8029 			verbose(env,
8030 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
8031 				map->name);
8032 			return -EINVAL;
8033 		}
8034 	} else {
8035 		btf = reg->btf;
8036 	}
8037 
8038 	rec = reg_btf_record(reg);
8039 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
8040 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
8041 			map ? map->name : "kptr");
8042 		return -EINVAL;
8043 	}
8044 	if (rec->spin_lock_off != val + reg->off) {
8045 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
8046 			val + reg->off, rec->spin_lock_off);
8047 		return -EINVAL;
8048 	}
8049 	if (is_lock) {
8050 		void *ptr;
8051 
8052 		if (map)
8053 			ptr = map;
8054 		else
8055 			ptr = btf;
8056 
8057 		if (cur->active_locks) {
8058 			verbose(env,
8059 				"Locking two bpf_spin_locks are not allowed\n");
8060 			return -EINVAL;
8061 		}
8062 		err = acquire_lock_state(env, env->insn_idx, REF_TYPE_LOCK, reg->id, ptr);
8063 		if (err < 0) {
8064 			verbose(env, "Failed to acquire lock state\n");
8065 			return err;
8066 		}
8067 	} else {
8068 		void *ptr;
8069 
8070 		if (map)
8071 			ptr = map;
8072 		else
8073 			ptr = btf;
8074 
8075 		if (!cur->active_locks) {
8076 			verbose(env, "bpf_spin_unlock without taking a lock\n");
8077 			return -EINVAL;
8078 		}
8079 
8080 		if (release_lock_state(env->cur_state, REF_TYPE_LOCK, reg->id, ptr)) {
8081 			verbose(env, "bpf_spin_unlock of different lock\n");
8082 			return -EINVAL;
8083 		}
8084 
8085 		invalidate_non_owning_refs(env);
8086 	}
8087 	return 0;
8088 }
8089 
8090 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8091 			      struct bpf_call_arg_meta *meta)
8092 {
8093 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8094 	bool is_const = tnum_is_const(reg->var_off);
8095 	struct bpf_map *map = reg->map_ptr;
8096 	u64 val = reg->var_off.value;
8097 
8098 	if (!is_const) {
8099 		verbose(env,
8100 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
8101 			regno);
8102 		return -EINVAL;
8103 	}
8104 	if (!map->btf) {
8105 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
8106 			map->name);
8107 		return -EINVAL;
8108 	}
8109 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
8110 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
8111 		return -EINVAL;
8112 	}
8113 	if (map->record->timer_off != val + reg->off) {
8114 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
8115 			val + reg->off, map->record->timer_off);
8116 		return -EINVAL;
8117 	}
8118 	if (meta->map_ptr) {
8119 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
8120 		return -EFAULT;
8121 	}
8122 	meta->map_uid = reg->map_uid;
8123 	meta->map_ptr = map;
8124 	return 0;
8125 }
8126 
8127 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8128 			   struct bpf_kfunc_call_arg_meta *meta)
8129 {
8130 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8131 	struct bpf_map *map = reg->map_ptr;
8132 	u64 val = reg->var_off.value;
8133 
8134 	if (map->record->wq_off != val + reg->off) {
8135 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8136 			val + reg->off, map->record->wq_off);
8137 		return -EINVAL;
8138 	}
8139 	meta->map.uid = reg->map_uid;
8140 	meta->map.ptr = map;
8141 	return 0;
8142 }
8143 
8144 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8145 			     struct bpf_call_arg_meta *meta)
8146 {
8147 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8148 	struct btf_field *kptr_field;
8149 	struct bpf_map *map_ptr;
8150 	struct btf_record *rec;
8151 	u32 kptr_off;
8152 
8153 	if (type_is_ptr_alloc_obj(reg->type)) {
8154 		rec = reg_btf_record(reg);
8155 	} else { /* PTR_TO_MAP_VALUE */
8156 		map_ptr = reg->map_ptr;
8157 		if (!map_ptr->btf) {
8158 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8159 				map_ptr->name);
8160 			return -EINVAL;
8161 		}
8162 		rec = map_ptr->record;
8163 		meta->map_ptr = map_ptr;
8164 	}
8165 
8166 	if (!tnum_is_const(reg->var_off)) {
8167 		verbose(env,
8168 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8169 			regno);
8170 		return -EINVAL;
8171 	}
8172 
8173 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8174 		verbose(env, "R%d has no valid kptr\n", regno);
8175 		return -EINVAL;
8176 	}
8177 
8178 	kptr_off = reg->off + reg->var_off.value;
8179 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8180 	if (!kptr_field) {
8181 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8182 		return -EACCES;
8183 	}
8184 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8185 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8186 		return -EACCES;
8187 	}
8188 	meta->kptr_field = kptr_field;
8189 	return 0;
8190 }
8191 
8192 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8193  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8194  *
8195  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8196  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8197  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8198  *
8199  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8200  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8201  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8202  * mutate the view of the dynptr and also possibly destroy it. In the latter
8203  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8204  * memory that dynptr points to.
8205  *
8206  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8207  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8208  * readonly dynptr view yet, hence only the first case is tracked and checked.
8209  *
8210  * This is consistent with how C applies the const modifier to a struct object,
8211  * where the pointer itself inside bpf_dynptr becomes const but not what it
8212  * points to.
8213  *
8214  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8215  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8216  */
8217 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8218 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8219 {
8220 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8221 	int err;
8222 
8223 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8224 		verbose(env,
8225 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8226 			regno - 1);
8227 		return -EINVAL;
8228 	}
8229 
8230 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8231 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8232 	 */
8233 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8234 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
8235 		return -EFAULT;
8236 	}
8237 
8238 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8239 	 *		 constructing a mutable bpf_dynptr object.
8240 	 *
8241 	 *		 Currently, this is only possible with PTR_TO_STACK
8242 	 *		 pointing to a region of at least 16 bytes which doesn't
8243 	 *		 contain an existing bpf_dynptr.
8244 	 *
8245 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8246 	 *		 mutated or destroyed. However, the memory it points to
8247 	 *		 may be mutated.
8248 	 *
8249 	 *  None       - Points to a initialized dynptr that can be mutated and
8250 	 *		 destroyed, including mutation of the memory it points
8251 	 *		 to.
8252 	 */
8253 	if (arg_type & MEM_UNINIT) {
8254 		int i;
8255 
8256 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8257 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8258 			return -EINVAL;
8259 		}
8260 
8261 		/* we write BPF_DW bits (8 bytes) at a time */
8262 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8263 			err = check_mem_access(env, insn_idx, regno,
8264 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8265 			if (err)
8266 				return err;
8267 		}
8268 
8269 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8270 	} else /* MEM_RDONLY and None case from above */ {
8271 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8272 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8273 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8274 			return -EINVAL;
8275 		}
8276 
8277 		if (!is_dynptr_reg_valid_init(env, reg)) {
8278 			verbose(env,
8279 				"Expected an initialized dynptr as arg #%d\n",
8280 				regno - 1);
8281 			return -EINVAL;
8282 		}
8283 
8284 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8285 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8286 			verbose(env,
8287 				"Expected a dynptr of type %s as arg #%d\n",
8288 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8289 			return -EINVAL;
8290 		}
8291 
8292 		err = mark_dynptr_read(env, reg);
8293 	}
8294 	return err;
8295 }
8296 
8297 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8298 {
8299 	struct bpf_func_state *state = func(env, reg);
8300 
8301 	return state->stack[spi].spilled_ptr.ref_obj_id;
8302 }
8303 
8304 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8305 {
8306 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8307 }
8308 
8309 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8310 {
8311 	return meta->kfunc_flags & KF_ITER_NEW;
8312 }
8313 
8314 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8315 {
8316 	return meta->kfunc_flags & KF_ITER_NEXT;
8317 }
8318 
8319 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8320 {
8321 	return meta->kfunc_flags & KF_ITER_DESTROY;
8322 }
8323 
8324 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8325 			      const struct btf_param *arg)
8326 {
8327 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8328 	 * kfunc is iter state pointer
8329 	 */
8330 	if (is_iter_kfunc(meta))
8331 		return arg_idx == 0;
8332 
8333 	/* iter passed as an argument to a generic kfunc */
8334 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8335 }
8336 
8337 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8338 			    struct bpf_kfunc_call_arg_meta *meta)
8339 {
8340 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8341 	const struct btf_type *t;
8342 	int spi, err, i, nr_slots, btf_id;
8343 
8344 	if (reg->type != PTR_TO_STACK) {
8345 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8346 		return -EINVAL;
8347 	}
8348 
8349 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8350 	 * ensures struct convention, so we wouldn't need to do any BTF
8351 	 * validation here. But given iter state can be passed as a parameter
8352 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8353 	 * conservative here.
8354 	 */
8355 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8356 	if (btf_id < 0) {
8357 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8358 		return -EINVAL;
8359 	}
8360 	t = btf_type_by_id(meta->btf, btf_id);
8361 	nr_slots = t->size / BPF_REG_SIZE;
8362 
8363 	if (is_iter_new_kfunc(meta)) {
8364 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8365 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8366 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8367 				iter_type_str(meta->btf, btf_id), regno - 1);
8368 			return -EINVAL;
8369 		}
8370 
8371 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8372 			err = check_mem_access(env, insn_idx, regno,
8373 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8374 			if (err)
8375 				return err;
8376 		}
8377 
8378 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8379 		if (err)
8380 			return err;
8381 	} else {
8382 		/* iter_next() or iter_destroy(), as well as any kfunc
8383 		 * accepting iter argument, expect initialized iter state
8384 		 */
8385 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8386 		switch (err) {
8387 		case 0:
8388 			break;
8389 		case -EINVAL:
8390 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8391 				iter_type_str(meta->btf, btf_id), regno - 1);
8392 			return err;
8393 		case -EPROTO:
8394 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8395 			return err;
8396 		default:
8397 			return err;
8398 		}
8399 
8400 		spi = iter_get_spi(env, reg, nr_slots);
8401 		if (spi < 0)
8402 			return spi;
8403 
8404 		err = mark_iter_read(env, reg, spi, nr_slots);
8405 		if (err)
8406 			return err;
8407 
8408 		/* remember meta->iter info for process_iter_next_call() */
8409 		meta->iter.spi = spi;
8410 		meta->iter.frameno = reg->frameno;
8411 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8412 
8413 		if (is_iter_destroy_kfunc(meta)) {
8414 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8415 			if (err)
8416 				return err;
8417 		}
8418 	}
8419 
8420 	return 0;
8421 }
8422 
8423 /* Look for a previous loop entry at insn_idx: nearest parent state
8424  * stopped at insn_idx with callsites matching those in cur->frame.
8425  */
8426 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8427 						  struct bpf_verifier_state *cur,
8428 						  int insn_idx)
8429 {
8430 	struct bpf_verifier_state_list *sl;
8431 	struct bpf_verifier_state *st;
8432 
8433 	/* Explored states are pushed in stack order, most recent states come first */
8434 	sl = *explored_state(env, insn_idx);
8435 	for (; sl; sl = sl->next) {
8436 		/* If st->branches != 0 state is a part of current DFS verification path,
8437 		 * hence cur & st for a loop.
8438 		 */
8439 		st = &sl->state;
8440 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8441 		    st->dfs_depth < cur->dfs_depth)
8442 			return st;
8443 	}
8444 
8445 	return NULL;
8446 }
8447 
8448 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8449 static bool regs_exact(const struct bpf_reg_state *rold,
8450 		       const struct bpf_reg_state *rcur,
8451 		       struct bpf_idmap *idmap);
8452 
8453 static void maybe_widen_reg(struct bpf_verifier_env *env,
8454 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8455 			    struct bpf_idmap *idmap)
8456 {
8457 	if (rold->type != SCALAR_VALUE)
8458 		return;
8459 	if (rold->type != rcur->type)
8460 		return;
8461 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8462 		return;
8463 	__mark_reg_unknown(env, rcur);
8464 }
8465 
8466 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8467 				   struct bpf_verifier_state *old,
8468 				   struct bpf_verifier_state *cur)
8469 {
8470 	struct bpf_func_state *fold, *fcur;
8471 	int i, fr;
8472 
8473 	reset_idmap_scratch(env);
8474 	for (fr = old->curframe; fr >= 0; fr--) {
8475 		fold = old->frame[fr];
8476 		fcur = cur->frame[fr];
8477 
8478 		for (i = 0; i < MAX_BPF_REG; i++)
8479 			maybe_widen_reg(env,
8480 					&fold->regs[i],
8481 					&fcur->regs[i],
8482 					&env->idmap_scratch);
8483 
8484 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8485 			if (!is_spilled_reg(&fold->stack[i]) ||
8486 			    !is_spilled_reg(&fcur->stack[i]))
8487 				continue;
8488 
8489 			maybe_widen_reg(env,
8490 					&fold->stack[i].spilled_ptr,
8491 					&fcur->stack[i].spilled_ptr,
8492 					&env->idmap_scratch);
8493 		}
8494 	}
8495 	return 0;
8496 }
8497 
8498 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8499 						 struct bpf_kfunc_call_arg_meta *meta)
8500 {
8501 	int iter_frameno = meta->iter.frameno;
8502 	int iter_spi = meta->iter.spi;
8503 
8504 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8505 }
8506 
8507 /* process_iter_next_call() is called when verifier gets to iterator's next
8508  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8509  * to it as just "iter_next()" in comments below.
8510  *
8511  * BPF verifier relies on a crucial contract for any iter_next()
8512  * implementation: it should *eventually* return NULL, and once that happens
8513  * it should keep returning NULL. That is, once iterator exhausts elements to
8514  * iterate, it should never reset or spuriously return new elements.
8515  *
8516  * With the assumption of such contract, process_iter_next_call() simulates
8517  * a fork in the verifier state to validate loop logic correctness and safety
8518  * without having to simulate infinite amount of iterations.
8519  *
8520  * In current state, we first assume that iter_next() returned NULL and
8521  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8522  * conditions we should not form an infinite loop and should eventually reach
8523  * exit.
8524  *
8525  * Besides that, we also fork current state and enqueue it for later
8526  * verification. In a forked state we keep iterator state as ACTIVE
8527  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8528  * also bump iteration depth to prevent erroneous infinite loop detection
8529  * later on (see iter_active_depths_differ() comment for details). In this
8530  * state we assume that we'll eventually loop back to another iter_next()
8531  * calls (it could be in exactly same location or in some other instruction,
8532  * it doesn't matter, we don't make any unnecessary assumptions about this,
8533  * everything revolves around iterator state in a stack slot, not which
8534  * instruction is calling iter_next()). When that happens, we either will come
8535  * to iter_next() with equivalent state and can conclude that next iteration
8536  * will proceed in exactly the same way as we just verified, so it's safe to
8537  * assume that loop converges. If not, we'll go on another iteration
8538  * simulation with a different input state, until all possible starting states
8539  * are validated or we reach maximum number of instructions limit.
8540  *
8541  * This way, we will either exhaustively discover all possible input states
8542  * that iterator loop can start with and eventually will converge, or we'll
8543  * effectively regress into bounded loop simulation logic and either reach
8544  * maximum number of instructions if loop is not provably convergent, or there
8545  * is some statically known limit on number of iterations (e.g., if there is
8546  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8547  *
8548  * Iteration convergence logic in is_state_visited() relies on exact
8549  * states comparison, which ignores read and precision marks.
8550  * This is necessary because read and precision marks are not finalized
8551  * while in the loop. Exact comparison might preclude convergence for
8552  * simple programs like below:
8553  *
8554  *     i = 0;
8555  *     while(iter_next(&it))
8556  *       i++;
8557  *
8558  * At each iteration step i++ would produce a new distinct state and
8559  * eventually instruction processing limit would be reached.
8560  *
8561  * To avoid such behavior speculatively forget (widen) range for
8562  * imprecise scalar registers, if those registers were not precise at the
8563  * end of the previous iteration and do not match exactly.
8564  *
8565  * This is a conservative heuristic that allows to verify wide range of programs,
8566  * however it precludes verification of programs that conjure an
8567  * imprecise value on the first loop iteration and use it as precise on a second.
8568  * For example, the following safe program would fail to verify:
8569  *
8570  *     struct bpf_num_iter it;
8571  *     int arr[10];
8572  *     int i = 0, a = 0;
8573  *     bpf_iter_num_new(&it, 0, 10);
8574  *     while (bpf_iter_num_next(&it)) {
8575  *       if (a == 0) {
8576  *         a = 1;
8577  *         i = 7; // Because i changed verifier would forget
8578  *                // it's range on second loop entry.
8579  *       } else {
8580  *         arr[i] = 42; // This would fail to verify.
8581  *       }
8582  *     }
8583  *     bpf_iter_num_destroy(&it);
8584  */
8585 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8586 				  struct bpf_kfunc_call_arg_meta *meta)
8587 {
8588 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8589 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8590 	struct bpf_reg_state *cur_iter, *queued_iter;
8591 
8592 	BTF_TYPE_EMIT(struct bpf_iter);
8593 
8594 	cur_iter = get_iter_from_state(cur_st, meta);
8595 
8596 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8597 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8598 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8599 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8600 		return -EFAULT;
8601 	}
8602 
8603 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8604 		/* Because iter_next() call is a checkpoint is_state_visitied()
8605 		 * should guarantee parent state with same call sites and insn_idx.
8606 		 */
8607 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8608 		    !same_callsites(cur_st->parent, cur_st)) {
8609 			verbose(env, "bug: bad parent state for iter next call");
8610 			return -EFAULT;
8611 		}
8612 		/* Note cur_st->parent in the call below, it is necessary to skip
8613 		 * checkpoint created for cur_st by is_state_visited()
8614 		 * right at this instruction.
8615 		 */
8616 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8617 		/* branch out active iter state */
8618 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8619 		if (!queued_st)
8620 			return -ENOMEM;
8621 
8622 		queued_iter = get_iter_from_state(queued_st, meta);
8623 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8624 		queued_iter->iter.depth++;
8625 		if (prev_st)
8626 			widen_imprecise_scalars(env, prev_st, queued_st);
8627 
8628 		queued_fr = queued_st->frame[queued_st->curframe];
8629 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8630 	}
8631 
8632 	/* switch to DRAINED state, but keep the depth unchanged */
8633 	/* mark current iter state as drained and assume returned NULL */
8634 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8635 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8636 
8637 	return 0;
8638 }
8639 
8640 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8641 {
8642 	return type == ARG_CONST_SIZE ||
8643 	       type == ARG_CONST_SIZE_OR_ZERO;
8644 }
8645 
8646 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8647 {
8648 	return base_type(type) == ARG_PTR_TO_MEM &&
8649 	       type & MEM_UNINIT;
8650 }
8651 
8652 static bool arg_type_is_release(enum bpf_arg_type type)
8653 {
8654 	return type & OBJ_RELEASE;
8655 }
8656 
8657 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8658 {
8659 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8660 }
8661 
8662 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8663 				 const struct bpf_call_arg_meta *meta,
8664 				 enum bpf_arg_type *arg_type)
8665 {
8666 	if (!meta->map_ptr) {
8667 		/* kernel subsystem misconfigured verifier */
8668 		verbose(env, "invalid map_ptr to access map->type\n");
8669 		return -EACCES;
8670 	}
8671 
8672 	switch (meta->map_ptr->map_type) {
8673 	case BPF_MAP_TYPE_SOCKMAP:
8674 	case BPF_MAP_TYPE_SOCKHASH:
8675 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8676 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8677 		} else {
8678 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8679 			return -EINVAL;
8680 		}
8681 		break;
8682 	case BPF_MAP_TYPE_BLOOM_FILTER:
8683 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8684 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8685 		break;
8686 	default:
8687 		break;
8688 	}
8689 	return 0;
8690 }
8691 
8692 struct bpf_reg_types {
8693 	const enum bpf_reg_type types[10];
8694 	u32 *btf_id;
8695 };
8696 
8697 static const struct bpf_reg_types sock_types = {
8698 	.types = {
8699 		PTR_TO_SOCK_COMMON,
8700 		PTR_TO_SOCKET,
8701 		PTR_TO_TCP_SOCK,
8702 		PTR_TO_XDP_SOCK,
8703 	},
8704 };
8705 
8706 #ifdef CONFIG_NET
8707 static const struct bpf_reg_types btf_id_sock_common_types = {
8708 	.types = {
8709 		PTR_TO_SOCK_COMMON,
8710 		PTR_TO_SOCKET,
8711 		PTR_TO_TCP_SOCK,
8712 		PTR_TO_XDP_SOCK,
8713 		PTR_TO_BTF_ID,
8714 		PTR_TO_BTF_ID | PTR_TRUSTED,
8715 	},
8716 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8717 };
8718 #endif
8719 
8720 static const struct bpf_reg_types mem_types = {
8721 	.types = {
8722 		PTR_TO_STACK,
8723 		PTR_TO_PACKET,
8724 		PTR_TO_PACKET_META,
8725 		PTR_TO_MAP_KEY,
8726 		PTR_TO_MAP_VALUE,
8727 		PTR_TO_MEM,
8728 		PTR_TO_MEM | MEM_RINGBUF,
8729 		PTR_TO_BUF,
8730 		PTR_TO_BTF_ID | PTR_TRUSTED,
8731 	},
8732 };
8733 
8734 static const struct bpf_reg_types spin_lock_types = {
8735 	.types = {
8736 		PTR_TO_MAP_VALUE,
8737 		PTR_TO_BTF_ID | MEM_ALLOC,
8738 	}
8739 };
8740 
8741 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8742 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8743 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8744 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8745 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8746 static const struct bpf_reg_types btf_ptr_types = {
8747 	.types = {
8748 		PTR_TO_BTF_ID,
8749 		PTR_TO_BTF_ID | PTR_TRUSTED,
8750 		PTR_TO_BTF_ID | MEM_RCU,
8751 	},
8752 };
8753 static const struct bpf_reg_types percpu_btf_ptr_types = {
8754 	.types = {
8755 		PTR_TO_BTF_ID | MEM_PERCPU,
8756 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8757 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8758 	}
8759 };
8760 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8761 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8762 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8763 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8764 static const struct bpf_reg_types kptr_xchg_dest_types = {
8765 	.types = {
8766 		PTR_TO_MAP_VALUE,
8767 		PTR_TO_BTF_ID | MEM_ALLOC
8768 	}
8769 };
8770 static const struct bpf_reg_types dynptr_types = {
8771 	.types = {
8772 		PTR_TO_STACK,
8773 		CONST_PTR_TO_DYNPTR,
8774 	}
8775 };
8776 
8777 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8778 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8779 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8780 	[ARG_CONST_SIZE]		= &scalar_types,
8781 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8782 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8783 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8784 	[ARG_PTR_TO_CTX]		= &context_types,
8785 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8786 #ifdef CONFIG_NET
8787 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8788 #endif
8789 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8790 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8791 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8792 	[ARG_PTR_TO_MEM]		= &mem_types,
8793 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8794 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8795 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8796 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8797 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8798 	[ARG_PTR_TO_TIMER]		= &timer_types,
8799 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
8800 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8801 };
8802 
8803 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8804 			  enum bpf_arg_type arg_type,
8805 			  const u32 *arg_btf_id,
8806 			  struct bpf_call_arg_meta *meta)
8807 {
8808 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8809 	enum bpf_reg_type expected, type = reg->type;
8810 	const struct bpf_reg_types *compatible;
8811 	int i, j;
8812 
8813 	compatible = compatible_reg_types[base_type(arg_type)];
8814 	if (!compatible) {
8815 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8816 		return -EFAULT;
8817 	}
8818 
8819 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8820 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8821 	 *
8822 	 * Same for MAYBE_NULL:
8823 	 *
8824 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8825 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8826 	 *
8827 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8828 	 *
8829 	 * Therefore we fold these flags depending on the arg_type before comparison.
8830 	 */
8831 	if (arg_type & MEM_RDONLY)
8832 		type &= ~MEM_RDONLY;
8833 	if (arg_type & PTR_MAYBE_NULL)
8834 		type &= ~PTR_MAYBE_NULL;
8835 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8836 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8837 
8838 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8839 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
8840 		type &= ~MEM_ALLOC;
8841 		type &= ~MEM_PERCPU;
8842 	}
8843 
8844 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8845 		expected = compatible->types[i];
8846 		if (expected == NOT_INIT)
8847 			break;
8848 
8849 		if (type == expected)
8850 			goto found;
8851 	}
8852 
8853 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8854 	for (j = 0; j + 1 < i; j++)
8855 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8856 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8857 	return -EACCES;
8858 
8859 found:
8860 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8861 		return 0;
8862 
8863 	if (compatible == &mem_types) {
8864 		if (!(arg_type & MEM_RDONLY)) {
8865 			verbose(env,
8866 				"%s() may write into memory pointed by R%d type=%s\n",
8867 				func_id_name(meta->func_id),
8868 				regno, reg_type_str(env, reg->type));
8869 			return -EACCES;
8870 		}
8871 		return 0;
8872 	}
8873 
8874 	switch ((int)reg->type) {
8875 	case PTR_TO_BTF_ID:
8876 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8877 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8878 	case PTR_TO_BTF_ID | MEM_RCU:
8879 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8880 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8881 	{
8882 		/* For bpf_sk_release, it needs to match against first member
8883 		 * 'struct sock_common', hence make an exception for it. This
8884 		 * allows bpf_sk_release to work for multiple socket types.
8885 		 */
8886 		bool strict_type_match = arg_type_is_release(arg_type) &&
8887 					 meta->func_id != BPF_FUNC_sk_release;
8888 
8889 		if (type_may_be_null(reg->type) &&
8890 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8891 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8892 			return -EACCES;
8893 		}
8894 
8895 		if (!arg_btf_id) {
8896 			if (!compatible->btf_id) {
8897 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8898 				return -EFAULT;
8899 			}
8900 			arg_btf_id = compatible->btf_id;
8901 		}
8902 
8903 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8904 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8905 				return -EACCES;
8906 		} else {
8907 			if (arg_btf_id == BPF_PTR_POISON) {
8908 				verbose(env, "verifier internal error:");
8909 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8910 					regno);
8911 				return -EACCES;
8912 			}
8913 
8914 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8915 						  btf_vmlinux, *arg_btf_id,
8916 						  strict_type_match)) {
8917 				verbose(env, "R%d is of type %s but %s is expected\n",
8918 					regno, btf_type_name(reg->btf, reg->btf_id),
8919 					btf_type_name(btf_vmlinux, *arg_btf_id));
8920 				return -EACCES;
8921 			}
8922 		}
8923 		break;
8924 	}
8925 	case PTR_TO_BTF_ID | MEM_ALLOC:
8926 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8927 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8928 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8929 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8930 			return -EFAULT;
8931 		}
8932 		/* Check if local kptr in src arg matches kptr in dst arg */
8933 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
8934 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8935 				return -EACCES;
8936 		}
8937 		break;
8938 	case PTR_TO_BTF_ID | MEM_PERCPU:
8939 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8940 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8941 		/* Handled by helper specific checks */
8942 		break;
8943 	default:
8944 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8945 		return -EFAULT;
8946 	}
8947 	return 0;
8948 }
8949 
8950 static struct btf_field *
8951 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8952 {
8953 	struct btf_field *field;
8954 	struct btf_record *rec;
8955 
8956 	rec = reg_btf_record(reg);
8957 	if (!rec)
8958 		return NULL;
8959 
8960 	field = btf_record_find(rec, off, fields);
8961 	if (!field)
8962 		return NULL;
8963 
8964 	return field;
8965 }
8966 
8967 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8968 				  const struct bpf_reg_state *reg, int regno,
8969 				  enum bpf_arg_type arg_type)
8970 {
8971 	u32 type = reg->type;
8972 
8973 	/* When referenced register is passed to release function, its fixed
8974 	 * offset must be 0.
8975 	 *
8976 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8977 	 * meta->release_regno.
8978 	 */
8979 	if (arg_type_is_release(arg_type)) {
8980 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8981 		 * may not directly point to the object being released, but to
8982 		 * dynptr pointing to such object, which might be at some offset
8983 		 * on the stack. In that case, we simply to fallback to the
8984 		 * default handling.
8985 		 */
8986 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8987 			return 0;
8988 
8989 		/* Doing check_ptr_off_reg check for the offset will catch this
8990 		 * because fixed_off_ok is false, but checking here allows us
8991 		 * to give the user a better error message.
8992 		 */
8993 		if (reg->off) {
8994 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8995 				regno);
8996 			return -EINVAL;
8997 		}
8998 		return __check_ptr_off_reg(env, reg, regno, false);
8999 	}
9000 
9001 	switch (type) {
9002 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9003 	case PTR_TO_STACK:
9004 	case PTR_TO_PACKET:
9005 	case PTR_TO_PACKET_META:
9006 	case PTR_TO_MAP_KEY:
9007 	case PTR_TO_MAP_VALUE:
9008 	case PTR_TO_MEM:
9009 	case PTR_TO_MEM | MEM_RDONLY:
9010 	case PTR_TO_MEM | MEM_RINGBUF:
9011 	case PTR_TO_BUF:
9012 	case PTR_TO_BUF | MEM_RDONLY:
9013 	case PTR_TO_ARENA:
9014 	case SCALAR_VALUE:
9015 		return 0;
9016 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9017 	 * fixed offset.
9018 	 */
9019 	case PTR_TO_BTF_ID:
9020 	case PTR_TO_BTF_ID | MEM_ALLOC:
9021 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9022 	case PTR_TO_BTF_ID | MEM_RCU:
9023 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9024 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9025 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9026 		 * its fixed offset must be 0. In the other cases, fixed offset
9027 		 * can be non-zero. This was already checked above. So pass
9028 		 * fixed_off_ok as true to allow fixed offset for all other
9029 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9030 		 * still need to do checks instead of returning.
9031 		 */
9032 		return __check_ptr_off_reg(env, reg, regno, true);
9033 	default:
9034 		return __check_ptr_off_reg(env, reg, regno, false);
9035 	}
9036 }
9037 
9038 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9039 						const struct bpf_func_proto *fn,
9040 						struct bpf_reg_state *regs)
9041 {
9042 	struct bpf_reg_state *state = NULL;
9043 	int i;
9044 
9045 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9046 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9047 			if (state) {
9048 				verbose(env, "verifier internal error: multiple dynptr args\n");
9049 				return NULL;
9050 			}
9051 			state = &regs[BPF_REG_1 + i];
9052 		}
9053 
9054 	if (!state)
9055 		verbose(env, "verifier internal error: no dynptr arg found\n");
9056 
9057 	return state;
9058 }
9059 
9060 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9061 {
9062 	struct bpf_func_state *state = func(env, reg);
9063 	int spi;
9064 
9065 	if (reg->type == CONST_PTR_TO_DYNPTR)
9066 		return reg->id;
9067 	spi = dynptr_get_spi(env, reg);
9068 	if (spi < 0)
9069 		return spi;
9070 	return state->stack[spi].spilled_ptr.id;
9071 }
9072 
9073 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9074 {
9075 	struct bpf_func_state *state = func(env, reg);
9076 	int spi;
9077 
9078 	if (reg->type == CONST_PTR_TO_DYNPTR)
9079 		return reg->ref_obj_id;
9080 	spi = dynptr_get_spi(env, reg);
9081 	if (spi < 0)
9082 		return spi;
9083 	return state->stack[spi].spilled_ptr.ref_obj_id;
9084 }
9085 
9086 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9087 					    struct bpf_reg_state *reg)
9088 {
9089 	struct bpf_func_state *state = func(env, reg);
9090 	int spi;
9091 
9092 	if (reg->type == CONST_PTR_TO_DYNPTR)
9093 		return reg->dynptr.type;
9094 
9095 	spi = __get_spi(reg->off);
9096 	if (spi < 0) {
9097 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9098 		return BPF_DYNPTR_TYPE_INVALID;
9099 	}
9100 
9101 	return state->stack[spi].spilled_ptr.dynptr.type;
9102 }
9103 
9104 static int check_reg_const_str(struct bpf_verifier_env *env,
9105 			       struct bpf_reg_state *reg, u32 regno)
9106 {
9107 	struct bpf_map *map = reg->map_ptr;
9108 	int err;
9109 	int map_off;
9110 	u64 map_addr;
9111 	char *str_ptr;
9112 
9113 	if (reg->type != PTR_TO_MAP_VALUE)
9114 		return -EINVAL;
9115 
9116 	if (!bpf_map_is_rdonly(map)) {
9117 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9118 		return -EACCES;
9119 	}
9120 
9121 	if (!tnum_is_const(reg->var_off)) {
9122 		verbose(env, "R%d is not a constant address'\n", regno);
9123 		return -EACCES;
9124 	}
9125 
9126 	if (!map->ops->map_direct_value_addr) {
9127 		verbose(env, "no direct value access support for this map type\n");
9128 		return -EACCES;
9129 	}
9130 
9131 	err = check_map_access(env, regno, reg->off,
9132 			       map->value_size - reg->off, false,
9133 			       ACCESS_HELPER);
9134 	if (err)
9135 		return err;
9136 
9137 	map_off = reg->off + reg->var_off.value;
9138 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9139 	if (err) {
9140 		verbose(env, "direct value access on string failed\n");
9141 		return err;
9142 	}
9143 
9144 	str_ptr = (char *)(long)(map_addr);
9145 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9146 		verbose(env, "string is not zero-terminated\n");
9147 		return -EINVAL;
9148 	}
9149 	return 0;
9150 }
9151 
9152 /* Returns constant key value if possible, else negative error */
9153 static s64 get_constant_map_key(struct bpf_verifier_env *env,
9154 				struct bpf_reg_state *key,
9155 				u32 key_size)
9156 {
9157 	struct bpf_func_state *state = func(env, key);
9158 	struct bpf_reg_state *reg;
9159 	int slot, spi, off;
9160 	int spill_size = 0;
9161 	int zero_size = 0;
9162 	int stack_off;
9163 	int i, err;
9164 	u8 *stype;
9165 
9166 	if (!env->bpf_capable)
9167 		return -EOPNOTSUPP;
9168 	if (key->type != PTR_TO_STACK)
9169 		return -EOPNOTSUPP;
9170 	if (!tnum_is_const(key->var_off))
9171 		return -EOPNOTSUPP;
9172 
9173 	stack_off = key->off + key->var_off.value;
9174 	slot = -stack_off - 1;
9175 	spi = slot / BPF_REG_SIZE;
9176 	off = slot % BPF_REG_SIZE;
9177 	stype = state->stack[spi].slot_type;
9178 
9179 	/* First handle precisely tracked STACK_ZERO */
9180 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9181 		zero_size++;
9182 	if (zero_size >= key_size)
9183 		return 0;
9184 
9185 	/* Check that stack contains a scalar spill of expected size */
9186 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9187 		return -EOPNOTSUPP;
9188 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9189 		spill_size++;
9190 	if (spill_size != key_size)
9191 		return -EOPNOTSUPP;
9192 
9193 	reg = &state->stack[spi].spilled_ptr;
9194 	if (!tnum_is_const(reg->var_off))
9195 		/* Stack value not statically known */
9196 		return -EOPNOTSUPP;
9197 
9198 	/* We are relying on a constant value. So mark as precise
9199 	 * to prevent pruning on it.
9200 	 */
9201 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9202 	err = mark_chain_precision_batch(env);
9203 	if (err < 0)
9204 		return err;
9205 
9206 	return reg->var_off.value;
9207 }
9208 
9209 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9210 			  struct bpf_call_arg_meta *meta,
9211 			  const struct bpf_func_proto *fn,
9212 			  int insn_idx)
9213 {
9214 	u32 regno = BPF_REG_1 + arg;
9215 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9216 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9217 	enum bpf_reg_type type = reg->type;
9218 	u32 *arg_btf_id = NULL;
9219 	u32 key_size;
9220 	int err = 0;
9221 
9222 	if (arg_type == ARG_DONTCARE)
9223 		return 0;
9224 
9225 	err = check_reg_arg(env, regno, SRC_OP);
9226 	if (err)
9227 		return err;
9228 
9229 	if (arg_type == ARG_ANYTHING) {
9230 		if (is_pointer_value(env, regno)) {
9231 			verbose(env, "R%d leaks addr into helper function\n",
9232 				regno);
9233 			return -EACCES;
9234 		}
9235 		return 0;
9236 	}
9237 
9238 	if (type_is_pkt_pointer(type) &&
9239 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9240 		verbose(env, "helper access to the packet is not allowed\n");
9241 		return -EACCES;
9242 	}
9243 
9244 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9245 		err = resolve_map_arg_type(env, meta, &arg_type);
9246 		if (err)
9247 			return err;
9248 	}
9249 
9250 	if (register_is_null(reg) && type_may_be_null(arg_type))
9251 		/* A NULL register has a SCALAR_VALUE type, so skip
9252 		 * type checking.
9253 		 */
9254 		goto skip_type_check;
9255 
9256 	/* arg_btf_id and arg_size are in a union. */
9257 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9258 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9259 		arg_btf_id = fn->arg_btf_id[arg];
9260 
9261 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9262 	if (err)
9263 		return err;
9264 
9265 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9266 	if (err)
9267 		return err;
9268 
9269 skip_type_check:
9270 	if (arg_type_is_release(arg_type)) {
9271 		if (arg_type_is_dynptr(arg_type)) {
9272 			struct bpf_func_state *state = func(env, reg);
9273 			int spi;
9274 
9275 			/* Only dynptr created on stack can be released, thus
9276 			 * the get_spi and stack state checks for spilled_ptr
9277 			 * should only be done before process_dynptr_func for
9278 			 * PTR_TO_STACK.
9279 			 */
9280 			if (reg->type == PTR_TO_STACK) {
9281 				spi = dynptr_get_spi(env, reg);
9282 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9283 					verbose(env, "arg %d is an unacquired reference\n", regno);
9284 					return -EINVAL;
9285 				}
9286 			} else {
9287 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9288 				return -EINVAL;
9289 			}
9290 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9291 			verbose(env, "R%d must be referenced when passed to release function\n",
9292 				regno);
9293 			return -EINVAL;
9294 		}
9295 		if (meta->release_regno) {
9296 			verbose(env, "verifier internal error: more than one release argument\n");
9297 			return -EFAULT;
9298 		}
9299 		meta->release_regno = regno;
9300 	}
9301 
9302 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9303 		if (meta->ref_obj_id) {
9304 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9305 				regno, reg->ref_obj_id,
9306 				meta->ref_obj_id);
9307 			return -EFAULT;
9308 		}
9309 		meta->ref_obj_id = reg->ref_obj_id;
9310 	}
9311 
9312 	switch (base_type(arg_type)) {
9313 	case ARG_CONST_MAP_PTR:
9314 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9315 		if (meta->map_ptr) {
9316 			/* Use map_uid (which is unique id of inner map) to reject:
9317 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9318 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9319 			 * if (inner_map1 && inner_map2) {
9320 			 *     timer = bpf_map_lookup_elem(inner_map1);
9321 			 *     if (timer)
9322 			 *         // mismatch would have been allowed
9323 			 *         bpf_timer_init(timer, inner_map2);
9324 			 * }
9325 			 *
9326 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9327 			 */
9328 			if (meta->map_ptr != reg->map_ptr ||
9329 			    meta->map_uid != reg->map_uid) {
9330 				verbose(env,
9331 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9332 					meta->map_uid, reg->map_uid);
9333 				return -EINVAL;
9334 			}
9335 		}
9336 		meta->map_ptr = reg->map_ptr;
9337 		meta->map_uid = reg->map_uid;
9338 		break;
9339 	case ARG_PTR_TO_MAP_KEY:
9340 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9341 		 * check that [key, key + map->key_size) are within
9342 		 * stack limits and initialized
9343 		 */
9344 		if (!meta->map_ptr) {
9345 			/* in function declaration map_ptr must come before
9346 			 * map_key, so that it's verified and known before
9347 			 * we have to check map_key here. Otherwise it means
9348 			 * that kernel subsystem misconfigured verifier
9349 			 */
9350 			verbose(env, "invalid map_ptr to access map->key\n");
9351 			return -EACCES;
9352 		}
9353 		key_size = meta->map_ptr->key_size;
9354 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9355 		if (err)
9356 			return err;
9357 		meta->const_map_key = get_constant_map_key(env, reg, key_size);
9358 		if (meta->const_map_key < 0 && meta->const_map_key != -EOPNOTSUPP)
9359 			return meta->const_map_key;
9360 		break;
9361 	case ARG_PTR_TO_MAP_VALUE:
9362 		if (type_may_be_null(arg_type) && register_is_null(reg))
9363 			return 0;
9364 
9365 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9366 		 * check [value, value + map->value_size) validity
9367 		 */
9368 		if (!meta->map_ptr) {
9369 			/* kernel subsystem misconfigured verifier */
9370 			verbose(env, "invalid map_ptr to access map->value\n");
9371 			return -EACCES;
9372 		}
9373 		meta->raw_mode = arg_type & MEM_UNINIT;
9374 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9375 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9376 					      false, meta);
9377 		break;
9378 	case ARG_PTR_TO_PERCPU_BTF_ID:
9379 		if (!reg->btf_id) {
9380 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9381 			return -EACCES;
9382 		}
9383 		meta->ret_btf = reg->btf;
9384 		meta->ret_btf_id = reg->btf_id;
9385 		break;
9386 	case ARG_PTR_TO_SPIN_LOCK:
9387 		if (in_rbtree_lock_required_cb(env)) {
9388 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9389 			return -EACCES;
9390 		}
9391 		if (meta->func_id == BPF_FUNC_spin_lock) {
9392 			err = process_spin_lock(env, regno, true);
9393 			if (err)
9394 				return err;
9395 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9396 			err = process_spin_lock(env, regno, false);
9397 			if (err)
9398 				return err;
9399 		} else {
9400 			verbose(env, "verifier internal error\n");
9401 			return -EFAULT;
9402 		}
9403 		break;
9404 	case ARG_PTR_TO_TIMER:
9405 		err = process_timer_func(env, regno, meta);
9406 		if (err)
9407 			return err;
9408 		break;
9409 	case ARG_PTR_TO_FUNC:
9410 		meta->subprogno = reg->subprogno;
9411 		break;
9412 	case ARG_PTR_TO_MEM:
9413 		/* The access to this pointer is only checked when we hit the
9414 		 * next is_mem_size argument below.
9415 		 */
9416 		meta->raw_mode = arg_type & MEM_UNINIT;
9417 		if (arg_type & MEM_FIXED_SIZE) {
9418 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9419 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9420 						      false, meta);
9421 			if (err)
9422 				return err;
9423 			if (arg_type & MEM_ALIGNED)
9424 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9425 		}
9426 		break;
9427 	case ARG_CONST_SIZE:
9428 		err = check_mem_size_reg(env, reg, regno,
9429 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9430 					 BPF_WRITE : BPF_READ,
9431 					 false, meta);
9432 		break;
9433 	case ARG_CONST_SIZE_OR_ZERO:
9434 		err = check_mem_size_reg(env, reg, regno,
9435 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9436 					 BPF_WRITE : BPF_READ,
9437 					 true, meta);
9438 		break;
9439 	case ARG_PTR_TO_DYNPTR:
9440 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9441 		if (err)
9442 			return err;
9443 		break;
9444 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9445 		if (!tnum_is_const(reg->var_off)) {
9446 			verbose(env, "R%d is not a known constant'\n",
9447 				regno);
9448 			return -EACCES;
9449 		}
9450 		meta->mem_size = reg->var_off.value;
9451 		err = mark_chain_precision(env, regno);
9452 		if (err)
9453 			return err;
9454 		break;
9455 	case ARG_PTR_TO_CONST_STR:
9456 	{
9457 		err = check_reg_const_str(env, reg, regno);
9458 		if (err)
9459 			return err;
9460 		break;
9461 	}
9462 	case ARG_KPTR_XCHG_DEST:
9463 		err = process_kptr_func(env, regno, meta);
9464 		if (err)
9465 			return err;
9466 		break;
9467 	}
9468 
9469 	return err;
9470 }
9471 
9472 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9473 {
9474 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9475 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9476 
9477 	if (func_id != BPF_FUNC_map_update_elem &&
9478 	    func_id != BPF_FUNC_map_delete_elem)
9479 		return false;
9480 
9481 	/* It's not possible to get access to a locked struct sock in these
9482 	 * contexts, so updating is safe.
9483 	 */
9484 	switch (type) {
9485 	case BPF_PROG_TYPE_TRACING:
9486 		if (eatype == BPF_TRACE_ITER)
9487 			return true;
9488 		break;
9489 	case BPF_PROG_TYPE_SOCK_OPS:
9490 		/* map_update allowed only via dedicated helpers with event type checks */
9491 		if (func_id == BPF_FUNC_map_delete_elem)
9492 			return true;
9493 		break;
9494 	case BPF_PROG_TYPE_SOCKET_FILTER:
9495 	case BPF_PROG_TYPE_SCHED_CLS:
9496 	case BPF_PROG_TYPE_SCHED_ACT:
9497 	case BPF_PROG_TYPE_XDP:
9498 	case BPF_PROG_TYPE_SK_REUSEPORT:
9499 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9500 	case BPF_PROG_TYPE_SK_LOOKUP:
9501 		return true;
9502 	default:
9503 		break;
9504 	}
9505 
9506 	verbose(env, "cannot update sockmap in this context\n");
9507 	return false;
9508 }
9509 
9510 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9511 {
9512 	return env->prog->jit_requested &&
9513 	       bpf_jit_supports_subprog_tailcalls();
9514 }
9515 
9516 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9517 					struct bpf_map *map, int func_id)
9518 {
9519 	if (!map)
9520 		return 0;
9521 
9522 	/* We need a two way check, first is from map perspective ... */
9523 	switch (map->map_type) {
9524 	case BPF_MAP_TYPE_PROG_ARRAY:
9525 		if (func_id != BPF_FUNC_tail_call)
9526 			goto error;
9527 		break;
9528 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9529 		if (func_id != BPF_FUNC_perf_event_read &&
9530 		    func_id != BPF_FUNC_perf_event_output &&
9531 		    func_id != BPF_FUNC_skb_output &&
9532 		    func_id != BPF_FUNC_perf_event_read_value &&
9533 		    func_id != BPF_FUNC_xdp_output)
9534 			goto error;
9535 		break;
9536 	case BPF_MAP_TYPE_RINGBUF:
9537 		if (func_id != BPF_FUNC_ringbuf_output &&
9538 		    func_id != BPF_FUNC_ringbuf_reserve &&
9539 		    func_id != BPF_FUNC_ringbuf_query &&
9540 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9541 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9542 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9543 			goto error;
9544 		break;
9545 	case BPF_MAP_TYPE_USER_RINGBUF:
9546 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9547 			goto error;
9548 		break;
9549 	case BPF_MAP_TYPE_STACK_TRACE:
9550 		if (func_id != BPF_FUNC_get_stackid)
9551 			goto error;
9552 		break;
9553 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9554 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9555 		    func_id != BPF_FUNC_current_task_under_cgroup)
9556 			goto error;
9557 		break;
9558 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9559 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9560 		if (func_id != BPF_FUNC_get_local_storage)
9561 			goto error;
9562 		break;
9563 	case BPF_MAP_TYPE_DEVMAP:
9564 	case BPF_MAP_TYPE_DEVMAP_HASH:
9565 		if (func_id != BPF_FUNC_redirect_map &&
9566 		    func_id != BPF_FUNC_map_lookup_elem)
9567 			goto error;
9568 		break;
9569 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9570 	 * appear.
9571 	 */
9572 	case BPF_MAP_TYPE_CPUMAP:
9573 		if (func_id != BPF_FUNC_redirect_map)
9574 			goto error;
9575 		break;
9576 	case BPF_MAP_TYPE_XSKMAP:
9577 		if (func_id != BPF_FUNC_redirect_map &&
9578 		    func_id != BPF_FUNC_map_lookup_elem)
9579 			goto error;
9580 		break;
9581 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9582 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9583 		if (func_id != BPF_FUNC_map_lookup_elem)
9584 			goto error;
9585 		break;
9586 	case BPF_MAP_TYPE_SOCKMAP:
9587 		if (func_id != BPF_FUNC_sk_redirect_map &&
9588 		    func_id != BPF_FUNC_sock_map_update &&
9589 		    func_id != BPF_FUNC_msg_redirect_map &&
9590 		    func_id != BPF_FUNC_sk_select_reuseport &&
9591 		    func_id != BPF_FUNC_map_lookup_elem &&
9592 		    !may_update_sockmap(env, func_id))
9593 			goto error;
9594 		break;
9595 	case BPF_MAP_TYPE_SOCKHASH:
9596 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9597 		    func_id != BPF_FUNC_sock_hash_update &&
9598 		    func_id != BPF_FUNC_msg_redirect_hash &&
9599 		    func_id != BPF_FUNC_sk_select_reuseport &&
9600 		    func_id != BPF_FUNC_map_lookup_elem &&
9601 		    !may_update_sockmap(env, func_id))
9602 			goto error;
9603 		break;
9604 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9605 		if (func_id != BPF_FUNC_sk_select_reuseport)
9606 			goto error;
9607 		break;
9608 	case BPF_MAP_TYPE_QUEUE:
9609 	case BPF_MAP_TYPE_STACK:
9610 		if (func_id != BPF_FUNC_map_peek_elem &&
9611 		    func_id != BPF_FUNC_map_pop_elem &&
9612 		    func_id != BPF_FUNC_map_push_elem)
9613 			goto error;
9614 		break;
9615 	case BPF_MAP_TYPE_SK_STORAGE:
9616 		if (func_id != BPF_FUNC_sk_storage_get &&
9617 		    func_id != BPF_FUNC_sk_storage_delete &&
9618 		    func_id != BPF_FUNC_kptr_xchg)
9619 			goto error;
9620 		break;
9621 	case BPF_MAP_TYPE_INODE_STORAGE:
9622 		if (func_id != BPF_FUNC_inode_storage_get &&
9623 		    func_id != BPF_FUNC_inode_storage_delete &&
9624 		    func_id != BPF_FUNC_kptr_xchg)
9625 			goto error;
9626 		break;
9627 	case BPF_MAP_TYPE_TASK_STORAGE:
9628 		if (func_id != BPF_FUNC_task_storage_get &&
9629 		    func_id != BPF_FUNC_task_storage_delete &&
9630 		    func_id != BPF_FUNC_kptr_xchg)
9631 			goto error;
9632 		break;
9633 	case BPF_MAP_TYPE_CGRP_STORAGE:
9634 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9635 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9636 		    func_id != BPF_FUNC_kptr_xchg)
9637 			goto error;
9638 		break;
9639 	case BPF_MAP_TYPE_BLOOM_FILTER:
9640 		if (func_id != BPF_FUNC_map_peek_elem &&
9641 		    func_id != BPF_FUNC_map_push_elem)
9642 			goto error;
9643 		break;
9644 	default:
9645 		break;
9646 	}
9647 
9648 	/* ... and second from the function itself. */
9649 	switch (func_id) {
9650 	case BPF_FUNC_tail_call:
9651 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9652 			goto error;
9653 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9654 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9655 			return -EINVAL;
9656 		}
9657 		break;
9658 	case BPF_FUNC_perf_event_read:
9659 	case BPF_FUNC_perf_event_output:
9660 	case BPF_FUNC_perf_event_read_value:
9661 	case BPF_FUNC_skb_output:
9662 	case BPF_FUNC_xdp_output:
9663 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9664 			goto error;
9665 		break;
9666 	case BPF_FUNC_ringbuf_output:
9667 	case BPF_FUNC_ringbuf_reserve:
9668 	case BPF_FUNC_ringbuf_query:
9669 	case BPF_FUNC_ringbuf_reserve_dynptr:
9670 	case BPF_FUNC_ringbuf_submit_dynptr:
9671 	case BPF_FUNC_ringbuf_discard_dynptr:
9672 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9673 			goto error;
9674 		break;
9675 	case BPF_FUNC_user_ringbuf_drain:
9676 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9677 			goto error;
9678 		break;
9679 	case BPF_FUNC_get_stackid:
9680 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9681 			goto error;
9682 		break;
9683 	case BPF_FUNC_current_task_under_cgroup:
9684 	case BPF_FUNC_skb_under_cgroup:
9685 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9686 			goto error;
9687 		break;
9688 	case BPF_FUNC_redirect_map:
9689 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9690 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9691 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9692 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9693 			goto error;
9694 		break;
9695 	case BPF_FUNC_sk_redirect_map:
9696 	case BPF_FUNC_msg_redirect_map:
9697 	case BPF_FUNC_sock_map_update:
9698 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9699 			goto error;
9700 		break;
9701 	case BPF_FUNC_sk_redirect_hash:
9702 	case BPF_FUNC_msg_redirect_hash:
9703 	case BPF_FUNC_sock_hash_update:
9704 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9705 			goto error;
9706 		break;
9707 	case BPF_FUNC_get_local_storage:
9708 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9709 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9710 			goto error;
9711 		break;
9712 	case BPF_FUNC_sk_select_reuseport:
9713 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9714 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9715 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9716 			goto error;
9717 		break;
9718 	case BPF_FUNC_map_pop_elem:
9719 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9720 		    map->map_type != BPF_MAP_TYPE_STACK)
9721 			goto error;
9722 		break;
9723 	case BPF_FUNC_map_peek_elem:
9724 	case BPF_FUNC_map_push_elem:
9725 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9726 		    map->map_type != BPF_MAP_TYPE_STACK &&
9727 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9728 			goto error;
9729 		break;
9730 	case BPF_FUNC_map_lookup_percpu_elem:
9731 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9732 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9733 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9734 			goto error;
9735 		break;
9736 	case BPF_FUNC_sk_storage_get:
9737 	case BPF_FUNC_sk_storage_delete:
9738 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9739 			goto error;
9740 		break;
9741 	case BPF_FUNC_inode_storage_get:
9742 	case BPF_FUNC_inode_storage_delete:
9743 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9744 			goto error;
9745 		break;
9746 	case BPF_FUNC_task_storage_get:
9747 	case BPF_FUNC_task_storage_delete:
9748 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9749 			goto error;
9750 		break;
9751 	case BPF_FUNC_cgrp_storage_get:
9752 	case BPF_FUNC_cgrp_storage_delete:
9753 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9754 			goto error;
9755 		break;
9756 	default:
9757 		break;
9758 	}
9759 
9760 	return 0;
9761 error:
9762 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9763 		map->map_type, func_id_name(func_id), func_id);
9764 	return -EINVAL;
9765 }
9766 
9767 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9768 {
9769 	int count = 0;
9770 
9771 	if (arg_type_is_raw_mem(fn->arg1_type))
9772 		count++;
9773 	if (arg_type_is_raw_mem(fn->arg2_type))
9774 		count++;
9775 	if (arg_type_is_raw_mem(fn->arg3_type))
9776 		count++;
9777 	if (arg_type_is_raw_mem(fn->arg4_type))
9778 		count++;
9779 	if (arg_type_is_raw_mem(fn->arg5_type))
9780 		count++;
9781 
9782 	/* We only support one arg being in raw mode at the moment,
9783 	 * which is sufficient for the helper functions we have
9784 	 * right now.
9785 	 */
9786 	return count <= 1;
9787 }
9788 
9789 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9790 {
9791 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9792 	bool has_size = fn->arg_size[arg] != 0;
9793 	bool is_next_size = false;
9794 
9795 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9796 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9797 
9798 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9799 		return is_next_size;
9800 
9801 	return has_size == is_next_size || is_next_size == is_fixed;
9802 }
9803 
9804 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9805 {
9806 	/* bpf_xxx(..., buf, len) call will access 'len'
9807 	 * bytes from memory 'buf'. Both arg types need
9808 	 * to be paired, so make sure there's no buggy
9809 	 * helper function specification.
9810 	 */
9811 	if (arg_type_is_mem_size(fn->arg1_type) ||
9812 	    check_args_pair_invalid(fn, 0) ||
9813 	    check_args_pair_invalid(fn, 1) ||
9814 	    check_args_pair_invalid(fn, 2) ||
9815 	    check_args_pair_invalid(fn, 3) ||
9816 	    check_args_pair_invalid(fn, 4))
9817 		return false;
9818 
9819 	return true;
9820 }
9821 
9822 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9823 {
9824 	int i;
9825 
9826 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9827 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9828 			return !!fn->arg_btf_id[i];
9829 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9830 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9831 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9832 		    /* arg_btf_id and arg_size are in a union. */
9833 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9834 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9835 			return false;
9836 	}
9837 
9838 	return true;
9839 }
9840 
9841 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9842 {
9843 	return check_raw_mode_ok(fn) &&
9844 	       check_arg_pair_ok(fn) &&
9845 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9846 }
9847 
9848 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9849  * are now invalid, so turn them into unknown SCALAR_VALUE.
9850  *
9851  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9852  * since these slices point to packet data.
9853  */
9854 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9855 {
9856 	struct bpf_func_state *state;
9857 	struct bpf_reg_state *reg;
9858 
9859 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9860 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9861 			mark_reg_invalid(env, reg);
9862 	}));
9863 }
9864 
9865 enum {
9866 	AT_PKT_END = -1,
9867 	BEYOND_PKT_END = -2,
9868 };
9869 
9870 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9871 {
9872 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9873 	struct bpf_reg_state *reg = &state->regs[regn];
9874 
9875 	if (reg->type != PTR_TO_PACKET)
9876 		/* PTR_TO_PACKET_META is not supported yet */
9877 		return;
9878 
9879 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9880 	 * How far beyond pkt_end it goes is unknown.
9881 	 * if (!range_open) it's the case of pkt >= pkt_end
9882 	 * if (range_open) it's the case of pkt > pkt_end
9883 	 * hence this pointer is at least 1 byte bigger than pkt_end
9884 	 */
9885 	if (range_open)
9886 		reg->range = BEYOND_PKT_END;
9887 	else
9888 		reg->range = AT_PKT_END;
9889 }
9890 
9891 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
9892 {
9893 	int i;
9894 
9895 	for (i = 0; i < state->acquired_refs; i++) {
9896 		if (state->refs[i].type != REF_TYPE_PTR)
9897 			continue;
9898 		if (state->refs[i].id == ref_obj_id) {
9899 			release_reference_state(state, i);
9900 			return 0;
9901 		}
9902 	}
9903 	return -EINVAL;
9904 }
9905 
9906 /* The pointer with the specified id has released its reference to kernel
9907  * resources. Identify all copies of the same pointer and clear the reference.
9908  *
9909  * This is the release function corresponding to acquire_reference(). Idempotent.
9910  */
9911 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
9912 {
9913 	struct bpf_verifier_state *vstate = env->cur_state;
9914 	struct bpf_func_state *state;
9915 	struct bpf_reg_state *reg;
9916 	int err;
9917 
9918 	err = release_reference_nomark(vstate, ref_obj_id);
9919 	if (err)
9920 		return err;
9921 
9922 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9923 		if (reg->ref_obj_id == ref_obj_id)
9924 			mark_reg_invalid(env, reg);
9925 	}));
9926 
9927 	return 0;
9928 }
9929 
9930 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9931 {
9932 	struct bpf_func_state *unused;
9933 	struct bpf_reg_state *reg;
9934 
9935 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9936 		if (type_is_non_owning_ref(reg->type))
9937 			mark_reg_invalid(env, reg);
9938 	}));
9939 }
9940 
9941 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9942 				    struct bpf_reg_state *regs)
9943 {
9944 	int i;
9945 
9946 	/* after the call registers r0 - r5 were scratched */
9947 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9948 		mark_reg_not_init(env, regs, caller_saved[i]);
9949 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9950 	}
9951 }
9952 
9953 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9954 				   struct bpf_func_state *caller,
9955 				   struct bpf_func_state *callee,
9956 				   int insn_idx);
9957 
9958 static int set_callee_state(struct bpf_verifier_env *env,
9959 			    struct bpf_func_state *caller,
9960 			    struct bpf_func_state *callee, int insn_idx);
9961 
9962 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9963 			    set_callee_state_fn set_callee_state_cb,
9964 			    struct bpf_verifier_state *state)
9965 {
9966 	struct bpf_func_state *caller, *callee;
9967 	int err;
9968 
9969 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9970 		verbose(env, "the call stack of %d frames is too deep\n",
9971 			state->curframe + 2);
9972 		return -E2BIG;
9973 	}
9974 
9975 	if (state->frame[state->curframe + 1]) {
9976 		verbose(env, "verifier bug. Frame %d already allocated\n",
9977 			state->curframe + 1);
9978 		return -EFAULT;
9979 	}
9980 
9981 	caller = state->frame[state->curframe];
9982 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9983 	if (!callee)
9984 		return -ENOMEM;
9985 	state->frame[state->curframe + 1] = callee;
9986 
9987 	/* callee cannot access r0, r6 - r9 for reading and has to write
9988 	 * into its own stack before reading from it.
9989 	 * callee can read/write into caller's stack
9990 	 */
9991 	init_func_state(env, callee,
9992 			/* remember the callsite, it will be used by bpf_exit */
9993 			callsite,
9994 			state->curframe + 1 /* frameno within this callchain */,
9995 			subprog /* subprog number within this prog */);
9996 	err = set_callee_state_cb(env, caller, callee, callsite);
9997 	if (err)
9998 		goto err_out;
9999 
10000 	/* only increment it after check_reg_arg() finished */
10001 	state->curframe++;
10002 
10003 	return 0;
10004 
10005 err_out:
10006 	free_func_state(callee);
10007 	state->frame[state->curframe + 1] = NULL;
10008 	return err;
10009 }
10010 
10011 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10012 				    const struct btf *btf,
10013 				    struct bpf_reg_state *regs)
10014 {
10015 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10016 	struct bpf_verifier_log *log = &env->log;
10017 	u32 i;
10018 	int ret;
10019 
10020 	ret = btf_prepare_func_args(env, subprog);
10021 	if (ret)
10022 		return ret;
10023 
10024 	/* check that BTF function arguments match actual types that the
10025 	 * verifier sees.
10026 	 */
10027 	for (i = 0; i < sub->arg_cnt; i++) {
10028 		u32 regno = i + 1;
10029 		struct bpf_reg_state *reg = &regs[regno];
10030 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10031 
10032 		if (arg->arg_type == ARG_ANYTHING) {
10033 			if (reg->type != SCALAR_VALUE) {
10034 				bpf_log(log, "R%d is not a scalar\n", regno);
10035 				return -EINVAL;
10036 			}
10037 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10038 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10039 			if (ret < 0)
10040 				return ret;
10041 			/* If function expects ctx type in BTF check that caller
10042 			 * is passing PTR_TO_CTX.
10043 			 */
10044 			if (reg->type != PTR_TO_CTX) {
10045 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10046 				return -EINVAL;
10047 			}
10048 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10049 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10050 			if (ret < 0)
10051 				return ret;
10052 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10053 				return -EINVAL;
10054 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10055 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10056 				return -EINVAL;
10057 			}
10058 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10059 			/*
10060 			 * Can pass any value and the kernel won't crash, but
10061 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10062 			 * else is a bug in the bpf program. Point it out to
10063 			 * the user at the verification time instead of
10064 			 * run-time debug nightmare.
10065 			 */
10066 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10067 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10068 				return -EINVAL;
10069 			}
10070 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10071 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10072 			if (ret)
10073 				return ret;
10074 
10075 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10076 			if (ret)
10077 				return ret;
10078 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10079 			struct bpf_call_arg_meta meta;
10080 			int err;
10081 
10082 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10083 				continue;
10084 
10085 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10086 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10087 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10088 			if (err)
10089 				return err;
10090 		} else {
10091 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
10092 				i, arg->arg_type);
10093 			return -EFAULT;
10094 		}
10095 	}
10096 
10097 	return 0;
10098 }
10099 
10100 /* Compare BTF of a function call with given bpf_reg_state.
10101  * Returns:
10102  * EFAULT - there is a verifier bug. Abort verification.
10103  * EINVAL - there is a type mismatch or BTF is not available.
10104  * 0 - BTF matches with what bpf_reg_state expects.
10105  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10106  */
10107 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10108 				  struct bpf_reg_state *regs)
10109 {
10110 	struct bpf_prog *prog = env->prog;
10111 	struct btf *btf = prog->aux->btf;
10112 	u32 btf_id;
10113 	int err;
10114 
10115 	if (!prog->aux->func_info)
10116 		return -EINVAL;
10117 
10118 	btf_id = prog->aux->func_info[subprog].type_id;
10119 	if (!btf_id)
10120 		return -EFAULT;
10121 
10122 	if (prog->aux->func_info_aux[subprog].unreliable)
10123 		return -EINVAL;
10124 
10125 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10126 	/* Compiler optimizations can remove arguments from static functions
10127 	 * or mismatched type can be passed into a global function.
10128 	 * In such cases mark the function as unreliable from BTF point of view.
10129 	 */
10130 	if (err)
10131 		prog->aux->func_info_aux[subprog].unreliable = true;
10132 	return err;
10133 }
10134 
10135 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10136 			      int insn_idx, int subprog,
10137 			      set_callee_state_fn set_callee_state_cb)
10138 {
10139 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10140 	struct bpf_func_state *caller, *callee;
10141 	int err;
10142 
10143 	caller = state->frame[state->curframe];
10144 	err = btf_check_subprog_call(env, subprog, caller->regs);
10145 	if (err == -EFAULT)
10146 		return err;
10147 
10148 	/* set_callee_state is used for direct subprog calls, but we are
10149 	 * interested in validating only BPF helpers that can call subprogs as
10150 	 * callbacks
10151 	 */
10152 	env->subprog_info[subprog].is_cb = true;
10153 	if (bpf_pseudo_kfunc_call(insn) &&
10154 	    !is_callback_calling_kfunc(insn->imm)) {
10155 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
10156 			func_id_name(insn->imm), insn->imm);
10157 		return -EFAULT;
10158 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10159 		   !is_callback_calling_function(insn->imm)) { /* helper */
10160 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
10161 			func_id_name(insn->imm), insn->imm);
10162 		return -EFAULT;
10163 	}
10164 
10165 	if (is_async_callback_calling_insn(insn)) {
10166 		struct bpf_verifier_state *async_cb;
10167 
10168 		/* there is no real recursion here. timer and workqueue callbacks are async */
10169 		env->subprog_info[subprog].is_async_cb = true;
10170 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10171 					 insn_idx, subprog,
10172 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
10173 		if (!async_cb)
10174 			return -EFAULT;
10175 		callee = async_cb->frame[0];
10176 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10177 
10178 		/* Convert bpf_timer_set_callback() args into timer callback args */
10179 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10180 		if (err)
10181 			return err;
10182 
10183 		return 0;
10184 	}
10185 
10186 	/* for callback functions enqueue entry to callback and
10187 	 * proceed with next instruction within current frame.
10188 	 */
10189 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10190 	if (!callback_state)
10191 		return -ENOMEM;
10192 
10193 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10194 			       callback_state);
10195 	if (err)
10196 		return err;
10197 
10198 	callback_state->callback_unroll_depth++;
10199 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10200 	caller->callback_depth = 0;
10201 	return 0;
10202 }
10203 
10204 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10205 			   int *insn_idx)
10206 {
10207 	struct bpf_verifier_state *state = env->cur_state;
10208 	struct bpf_func_state *caller;
10209 	int err, subprog, target_insn;
10210 
10211 	target_insn = *insn_idx + insn->imm + 1;
10212 	subprog = find_subprog(env, target_insn);
10213 	if (subprog < 0) {
10214 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
10215 		return -EFAULT;
10216 	}
10217 
10218 	caller = state->frame[state->curframe];
10219 	err = btf_check_subprog_call(env, subprog, caller->regs);
10220 	if (err == -EFAULT)
10221 		return err;
10222 	if (subprog_is_global(env, subprog)) {
10223 		const char *sub_name = subprog_name(env, subprog);
10224 
10225 		/* Only global subprogs cannot be called with a lock held. */
10226 		if (env->cur_state->active_locks) {
10227 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10228 				     "use static function instead\n");
10229 			return -EINVAL;
10230 		}
10231 
10232 		/* Only global subprogs cannot be called with preemption disabled. */
10233 		if (env->cur_state->active_preempt_locks) {
10234 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
10235 				     "use static function instead\n");
10236 			return -EINVAL;
10237 		}
10238 
10239 		if (env->cur_state->active_irq_id) {
10240 			verbose(env, "global function calls are not allowed with IRQs disabled,\n"
10241 				     "use static function instead\n");
10242 			return -EINVAL;
10243 		}
10244 
10245 		if (err) {
10246 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10247 				subprog, sub_name);
10248 			return err;
10249 		}
10250 
10251 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10252 			subprog, sub_name);
10253 		if (env->subprog_info[subprog].changes_pkt_data)
10254 			clear_all_pkt_pointers(env);
10255 		/* mark global subprog for verifying after main prog */
10256 		subprog_aux(env, subprog)->called = true;
10257 		clear_caller_saved_regs(env, caller->regs);
10258 
10259 		/* All global functions return a 64-bit SCALAR_VALUE */
10260 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10261 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10262 
10263 		/* continue with next insn after call */
10264 		return 0;
10265 	}
10266 
10267 	/* for regular function entry setup new frame and continue
10268 	 * from that frame.
10269 	 */
10270 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10271 	if (err)
10272 		return err;
10273 
10274 	clear_caller_saved_regs(env, caller->regs);
10275 
10276 	/* and go analyze first insn of the callee */
10277 	*insn_idx = env->subprog_info[subprog].start - 1;
10278 
10279 	if (env->log.level & BPF_LOG_LEVEL) {
10280 		verbose(env, "caller:\n");
10281 		print_verifier_state(env, state, caller->frameno, true);
10282 		verbose(env, "callee:\n");
10283 		print_verifier_state(env, state, state->curframe, true);
10284 	}
10285 
10286 	return 0;
10287 }
10288 
10289 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10290 				   struct bpf_func_state *caller,
10291 				   struct bpf_func_state *callee)
10292 {
10293 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10294 	 *      void *callback_ctx, u64 flags);
10295 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10296 	 *      void *callback_ctx);
10297 	 */
10298 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10299 
10300 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10301 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10302 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10303 
10304 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10305 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10306 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10307 
10308 	/* pointer to stack or null */
10309 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10310 
10311 	/* unused */
10312 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10313 	return 0;
10314 }
10315 
10316 static int set_callee_state(struct bpf_verifier_env *env,
10317 			    struct bpf_func_state *caller,
10318 			    struct bpf_func_state *callee, int insn_idx)
10319 {
10320 	int i;
10321 
10322 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10323 	 * pointers, which connects us up to the liveness chain
10324 	 */
10325 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10326 		callee->regs[i] = caller->regs[i];
10327 	return 0;
10328 }
10329 
10330 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10331 				       struct bpf_func_state *caller,
10332 				       struct bpf_func_state *callee,
10333 				       int insn_idx)
10334 {
10335 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10336 	struct bpf_map *map;
10337 	int err;
10338 
10339 	/* valid map_ptr and poison value does not matter */
10340 	map = insn_aux->map_ptr_state.map_ptr;
10341 	if (!map->ops->map_set_for_each_callback_args ||
10342 	    !map->ops->map_for_each_callback) {
10343 		verbose(env, "callback function not allowed for map\n");
10344 		return -ENOTSUPP;
10345 	}
10346 
10347 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10348 	if (err)
10349 		return err;
10350 
10351 	callee->in_callback_fn = true;
10352 	callee->callback_ret_range = retval_range(0, 1);
10353 	return 0;
10354 }
10355 
10356 static int set_loop_callback_state(struct bpf_verifier_env *env,
10357 				   struct bpf_func_state *caller,
10358 				   struct bpf_func_state *callee,
10359 				   int insn_idx)
10360 {
10361 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10362 	 *	    u64 flags);
10363 	 * callback_fn(u64 index, void *callback_ctx);
10364 	 */
10365 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10366 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10367 
10368 	/* unused */
10369 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10370 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10371 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10372 
10373 	callee->in_callback_fn = true;
10374 	callee->callback_ret_range = retval_range(0, 1);
10375 	return 0;
10376 }
10377 
10378 static int set_timer_callback_state(struct bpf_verifier_env *env,
10379 				    struct bpf_func_state *caller,
10380 				    struct bpf_func_state *callee,
10381 				    int insn_idx)
10382 {
10383 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10384 
10385 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10386 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10387 	 */
10388 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10389 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10390 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10391 
10392 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10393 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10394 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10395 
10396 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10397 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10398 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10399 
10400 	/* unused */
10401 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10402 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10403 	callee->in_async_callback_fn = true;
10404 	callee->callback_ret_range = retval_range(0, 1);
10405 	return 0;
10406 }
10407 
10408 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10409 				       struct bpf_func_state *caller,
10410 				       struct bpf_func_state *callee,
10411 				       int insn_idx)
10412 {
10413 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10414 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10415 	 * (callback_fn)(struct task_struct *task,
10416 	 *               struct vm_area_struct *vma, void *callback_ctx);
10417 	 */
10418 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10419 
10420 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10421 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10422 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10423 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10424 
10425 	/* pointer to stack or null */
10426 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10427 
10428 	/* unused */
10429 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10430 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10431 	callee->in_callback_fn = true;
10432 	callee->callback_ret_range = retval_range(0, 1);
10433 	return 0;
10434 }
10435 
10436 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10437 					   struct bpf_func_state *caller,
10438 					   struct bpf_func_state *callee,
10439 					   int insn_idx)
10440 {
10441 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10442 	 *			  callback_ctx, u64 flags);
10443 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10444 	 */
10445 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10446 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10447 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10448 
10449 	/* unused */
10450 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10451 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10452 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10453 
10454 	callee->in_callback_fn = true;
10455 	callee->callback_ret_range = retval_range(0, 1);
10456 	return 0;
10457 }
10458 
10459 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10460 					 struct bpf_func_state *caller,
10461 					 struct bpf_func_state *callee,
10462 					 int insn_idx)
10463 {
10464 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10465 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10466 	 *
10467 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10468 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10469 	 * by this point, so look at 'root'
10470 	 */
10471 	struct btf_field *field;
10472 
10473 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10474 				      BPF_RB_ROOT);
10475 	if (!field || !field->graph_root.value_btf_id)
10476 		return -EFAULT;
10477 
10478 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10479 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10480 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10481 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10482 
10483 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10484 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10485 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10486 	callee->in_callback_fn = true;
10487 	callee->callback_ret_range = retval_range(0, 1);
10488 	return 0;
10489 }
10490 
10491 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10492 
10493 /* Are we currently verifying the callback for a rbtree helper that must
10494  * be called with lock held? If so, no need to complain about unreleased
10495  * lock
10496  */
10497 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10498 {
10499 	struct bpf_verifier_state *state = env->cur_state;
10500 	struct bpf_insn *insn = env->prog->insnsi;
10501 	struct bpf_func_state *callee;
10502 	int kfunc_btf_id;
10503 
10504 	if (!state->curframe)
10505 		return false;
10506 
10507 	callee = state->frame[state->curframe];
10508 
10509 	if (!callee->in_callback_fn)
10510 		return false;
10511 
10512 	kfunc_btf_id = insn[callee->callsite].imm;
10513 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10514 }
10515 
10516 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10517 				bool return_32bit)
10518 {
10519 	if (return_32bit)
10520 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10521 	else
10522 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10523 }
10524 
10525 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10526 {
10527 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10528 	struct bpf_func_state *caller, *callee;
10529 	struct bpf_reg_state *r0;
10530 	bool in_callback_fn;
10531 	int err;
10532 
10533 	callee = state->frame[state->curframe];
10534 	r0 = &callee->regs[BPF_REG_0];
10535 	if (r0->type == PTR_TO_STACK) {
10536 		/* technically it's ok to return caller's stack pointer
10537 		 * (or caller's caller's pointer) back to the caller,
10538 		 * since these pointers are valid. Only current stack
10539 		 * pointer will be invalid as soon as function exits,
10540 		 * but let's be conservative
10541 		 */
10542 		verbose(env, "cannot return stack pointer to the caller\n");
10543 		return -EINVAL;
10544 	}
10545 
10546 	caller = state->frame[state->curframe - 1];
10547 	if (callee->in_callback_fn) {
10548 		if (r0->type != SCALAR_VALUE) {
10549 			verbose(env, "R0 not a scalar value\n");
10550 			return -EACCES;
10551 		}
10552 
10553 		/* we are going to rely on register's precise value */
10554 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10555 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10556 		if (err)
10557 			return err;
10558 
10559 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10560 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10561 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10562 					       "At callback return", "R0");
10563 			return -EINVAL;
10564 		}
10565 		if (!calls_callback(env, callee->callsite)) {
10566 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10567 				*insn_idx, callee->callsite);
10568 			return -EFAULT;
10569 		}
10570 	} else {
10571 		/* return to the caller whatever r0 had in the callee */
10572 		caller->regs[BPF_REG_0] = *r0;
10573 	}
10574 
10575 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10576 	 * there function call logic would reschedule callback visit. If iteration
10577 	 * converges is_state_visited() would prune that visit eventually.
10578 	 */
10579 	in_callback_fn = callee->in_callback_fn;
10580 	if (in_callback_fn)
10581 		*insn_idx = callee->callsite;
10582 	else
10583 		*insn_idx = callee->callsite + 1;
10584 
10585 	if (env->log.level & BPF_LOG_LEVEL) {
10586 		verbose(env, "returning from callee:\n");
10587 		print_verifier_state(env, state, callee->frameno, true);
10588 		verbose(env, "to caller at %d:\n", *insn_idx);
10589 		print_verifier_state(env, state, caller->frameno, true);
10590 	}
10591 	/* clear everything in the callee. In case of exceptional exits using
10592 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10593 	free_func_state(callee);
10594 	state->frame[state->curframe--] = NULL;
10595 
10596 	/* for callbacks widen imprecise scalars to make programs like below verify:
10597 	 *
10598 	 *   struct ctx { int i; }
10599 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10600 	 *   ...
10601 	 *   struct ctx = { .i = 0; }
10602 	 *   bpf_loop(100, cb, &ctx, 0);
10603 	 *
10604 	 * This is similar to what is done in process_iter_next_call() for open
10605 	 * coded iterators.
10606 	 */
10607 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10608 	if (prev_st) {
10609 		err = widen_imprecise_scalars(env, prev_st, state);
10610 		if (err)
10611 			return err;
10612 	}
10613 	return 0;
10614 }
10615 
10616 static int do_refine_retval_range(struct bpf_verifier_env *env,
10617 				  struct bpf_reg_state *regs, int ret_type,
10618 				  int func_id,
10619 				  struct bpf_call_arg_meta *meta)
10620 {
10621 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10622 
10623 	if (ret_type != RET_INTEGER)
10624 		return 0;
10625 
10626 	switch (func_id) {
10627 	case BPF_FUNC_get_stack:
10628 	case BPF_FUNC_get_task_stack:
10629 	case BPF_FUNC_probe_read_str:
10630 	case BPF_FUNC_probe_read_kernel_str:
10631 	case BPF_FUNC_probe_read_user_str:
10632 		ret_reg->smax_value = meta->msize_max_value;
10633 		ret_reg->s32_max_value = meta->msize_max_value;
10634 		ret_reg->smin_value = -MAX_ERRNO;
10635 		ret_reg->s32_min_value = -MAX_ERRNO;
10636 		reg_bounds_sync(ret_reg);
10637 		break;
10638 	case BPF_FUNC_get_smp_processor_id:
10639 		ret_reg->umax_value = nr_cpu_ids - 1;
10640 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10641 		ret_reg->smax_value = nr_cpu_ids - 1;
10642 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10643 		ret_reg->umin_value = 0;
10644 		ret_reg->u32_min_value = 0;
10645 		ret_reg->smin_value = 0;
10646 		ret_reg->s32_min_value = 0;
10647 		reg_bounds_sync(ret_reg);
10648 		break;
10649 	}
10650 
10651 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10652 }
10653 
10654 static int
10655 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10656 		int func_id, int insn_idx)
10657 {
10658 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10659 	struct bpf_map *map = meta->map_ptr;
10660 
10661 	if (func_id != BPF_FUNC_tail_call &&
10662 	    func_id != BPF_FUNC_map_lookup_elem &&
10663 	    func_id != BPF_FUNC_map_update_elem &&
10664 	    func_id != BPF_FUNC_map_delete_elem &&
10665 	    func_id != BPF_FUNC_map_push_elem &&
10666 	    func_id != BPF_FUNC_map_pop_elem &&
10667 	    func_id != BPF_FUNC_map_peek_elem &&
10668 	    func_id != BPF_FUNC_for_each_map_elem &&
10669 	    func_id != BPF_FUNC_redirect_map &&
10670 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10671 		return 0;
10672 
10673 	if (map == NULL) {
10674 		verbose(env, "kernel subsystem misconfigured verifier\n");
10675 		return -EINVAL;
10676 	}
10677 
10678 	/* In case of read-only, some additional restrictions
10679 	 * need to be applied in order to prevent altering the
10680 	 * state of the map from program side.
10681 	 */
10682 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10683 	    (func_id == BPF_FUNC_map_delete_elem ||
10684 	     func_id == BPF_FUNC_map_update_elem ||
10685 	     func_id == BPF_FUNC_map_push_elem ||
10686 	     func_id == BPF_FUNC_map_pop_elem)) {
10687 		verbose(env, "write into map forbidden\n");
10688 		return -EACCES;
10689 	}
10690 
10691 	if (!aux->map_ptr_state.map_ptr)
10692 		bpf_map_ptr_store(aux, meta->map_ptr,
10693 				  !meta->map_ptr->bypass_spec_v1, false);
10694 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10695 		bpf_map_ptr_store(aux, meta->map_ptr,
10696 				  !meta->map_ptr->bypass_spec_v1, true);
10697 	return 0;
10698 }
10699 
10700 static int
10701 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10702 		int func_id, int insn_idx)
10703 {
10704 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10705 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10706 	struct bpf_map *map = meta->map_ptr;
10707 	u64 val, max;
10708 	int err;
10709 
10710 	if (func_id != BPF_FUNC_tail_call)
10711 		return 0;
10712 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10713 		verbose(env, "kernel subsystem misconfigured verifier\n");
10714 		return -EINVAL;
10715 	}
10716 
10717 	reg = &regs[BPF_REG_3];
10718 	val = reg->var_off.value;
10719 	max = map->max_entries;
10720 
10721 	if (!(is_reg_const(reg, false) && val < max)) {
10722 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10723 		return 0;
10724 	}
10725 
10726 	err = mark_chain_precision(env, BPF_REG_3);
10727 	if (err)
10728 		return err;
10729 	if (bpf_map_key_unseen(aux))
10730 		bpf_map_key_store(aux, val);
10731 	else if (!bpf_map_key_poisoned(aux) &&
10732 		  bpf_map_key_immediate(aux) != val)
10733 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10734 	return 0;
10735 }
10736 
10737 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10738 {
10739 	struct bpf_verifier_state *state = env->cur_state;
10740 	bool refs_lingering = false;
10741 	int i;
10742 
10743 	if (!exception_exit && cur_func(env)->frameno)
10744 		return 0;
10745 
10746 	for (i = 0; i < state->acquired_refs; i++) {
10747 		if (state->refs[i].type != REF_TYPE_PTR)
10748 			continue;
10749 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10750 			state->refs[i].id, state->refs[i].insn_idx);
10751 		refs_lingering = true;
10752 	}
10753 	return refs_lingering ? -EINVAL : 0;
10754 }
10755 
10756 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
10757 {
10758 	int err;
10759 
10760 	if (check_lock && env->cur_state->active_locks) {
10761 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
10762 		return -EINVAL;
10763 	}
10764 
10765 	err = check_reference_leak(env, exception_exit);
10766 	if (err) {
10767 		verbose(env, "%s would lead to reference leak\n", prefix);
10768 		return err;
10769 	}
10770 
10771 	if (check_lock && env->cur_state->active_irq_id) {
10772 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
10773 		return -EINVAL;
10774 	}
10775 
10776 	if (check_lock && env->cur_state->active_rcu_lock) {
10777 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
10778 		return -EINVAL;
10779 	}
10780 
10781 	if (check_lock && env->cur_state->active_preempt_locks) {
10782 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
10783 		return -EINVAL;
10784 	}
10785 
10786 	return 0;
10787 }
10788 
10789 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10790 				   struct bpf_reg_state *regs)
10791 {
10792 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10793 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10794 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10795 	struct bpf_bprintf_data data = {};
10796 	int err, fmt_map_off, num_args;
10797 	u64 fmt_addr;
10798 	char *fmt;
10799 
10800 	/* data must be an array of u64 */
10801 	if (data_len_reg->var_off.value % 8)
10802 		return -EINVAL;
10803 	num_args = data_len_reg->var_off.value / 8;
10804 
10805 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10806 	 * and map_direct_value_addr is set.
10807 	 */
10808 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10809 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10810 						  fmt_map_off);
10811 	if (err) {
10812 		verbose(env, "verifier bug\n");
10813 		return -EFAULT;
10814 	}
10815 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10816 
10817 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10818 	 * can focus on validating the format specifiers.
10819 	 */
10820 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10821 	if (err < 0)
10822 		verbose(env, "Invalid format string\n");
10823 
10824 	return err;
10825 }
10826 
10827 static int check_get_func_ip(struct bpf_verifier_env *env)
10828 {
10829 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10830 	int func_id = BPF_FUNC_get_func_ip;
10831 
10832 	if (type == BPF_PROG_TYPE_TRACING) {
10833 		if (!bpf_prog_has_trampoline(env->prog)) {
10834 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10835 				func_id_name(func_id), func_id);
10836 			return -ENOTSUPP;
10837 		}
10838 		return 0;
10839 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10840 		return 0;
10841 	}
10842 
10843 	verbose(env, "func %s#%d not supported for program type %d\n",
10844 		func_id_name(func_id), func_id, type);
10845 	return -ENOTSUPP;
10846 }
10847 
10848 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10849 {
10850 	return &env->insn_aux_data[env->insn_idx];
10851 }
10852 
10853 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10854 {
10855 	struct bpf_reg_state *regs = cur_regs(env);
10856 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10857 	bool reg_is_null = register_is_null(reg);
10858 
10859 	if (reg_is_null)
10860 		mark_chain_precision(env, BPF_REG_4);
10861 
10862 	return reg_is_null;
10863 }
10864 
10865 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10866 {
10867 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10868 
10869 	if (!state->initialized) {
10870 		state->initialized = 1;
10871 		state->fit_for_inline = loop_flag_is_zero(env);
10872 		state->callback_subprogno = subprogno;
10873 		return;
10874 	}
10875 
10876 	if (!state->fit_for_inline)
10877 		return;
10878 
10879 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10880 				 state->callback_subprogno == subprogno);
10881 }
10882 
10883 /* Returns whether or not the given map type can potentially elide
10884  * lookup return value nullness check. This is possible if the key
10885  * is statically known.
10886  */
10887 static bool can_elide_value_nullness(enum bpf_map_type type)
10888 {
10889 	switch (type) {
10890 	case BPF_MAP_TYPE_ARRAY:
10891 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10892 		return true;
10893 	default:
10894 		return false;
10895 	}
10896 }
10897 
10898 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
10899 			    const struct bpf_func_proto **ptr)
10900 {
10901 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10902 		return -ERANGE;
10903 
10904 	if (!env->ops->get_func_proto)
10905 		return -EINVAL;
10906 
10907 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10908 	return *ptr ? 0 : -EINVAL;
10909 }
10910 
10911 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10912 			     int *insn_idx_p)
10913 {
10914 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10915 	bool returns_cpu_specific_alloc_ptr = false;
10916 	const struct bpf_func_proto *fn = NULL;
10917 	enum bpf_return_type ret_type;
10918 	enum bpf_type_flag ret_flag;
10919 	struct bpf_reg_state *regs;
10920 	struct bpf_call_arg_meta meta;
10921 	int insn_idx = *insn_idx_p;
10922 	bool changes_data;
10923 	int i, err, func_id;
10924 
10925 	/* find function prototype */
10926 	func_id = insn->imm;
10927 	err = get_helper_proto(env, insn->imm, &fn);
10928 	if (err == -ERANGE) {
10929 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10930 		return -EINVAL;
10931 	}
10932 
10933 	if (err) {
10934 		verbose(env, "program of this type cannot use helper %s#%d\n",
10935 			func_id_name(func_id), func_id);
10936 		return err;
10937 	}
10938 
10939 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10940 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10941 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10942 		return -EINVAL;
10943 	}
10944 
10945 	if (fn->allowed && !fn->allowed(env->prog)) {
10946 		verbose(env, "helper call is not allowed in probe\n");
10947 		return -EINVAL;
10948 	}
10949 
10950 	if (!in_sleepable(env) && fn->might_sleep) {
10951 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10952 		return -EINVAL;
10953 	}
10954 
10955 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10956 	changes_data = bpf_helper_changes_pkt_data(func_id);
10957 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10958 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10959 			func_id_name(func_id), func_id);
10960 		return -EINVAL;
10961 	}
10962 
10963 	memset(&meta, 0, sizeof(meta));
10964 	meta.pkt_access = fn->pkt_access;
10965 
10966 	err = check_func_proto(fn, func_id);
10967 	if (err) {
10968 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10969 			func_id_name(func_id), func_id);
10970 		return err;
10971 	}
10972 
10973 	if (env->cur_state->active_rcu_lock) {
10974 		if (fn->might_sleep) {
10975 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10976 				func_id_name(func_id), func_id);
10977 			return -EINVAL;
10978 		}
10979 
10980 		if (in_sleepable(env) && is_storage_get_function(func_id))
10981 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10982 	}
10983 
10984 	if (env->cur_state->active_preempt_locks) {
10985 		if (fn->might_sleep) {
10986 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10987 				func_id_name(func_id), func_id);
10988 			return -EINVAL;
10989 		}
10990 
10991 		if (in_sleepable(env) && is_storage_get_function(func_id))
10992 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10993 	}
10994 
10995 	if (env->cur_state->active_irq_id) {
10996 		if (fn->might_sleep) {
10997 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
10998 				func_id_name(func_id), func_id);
10999 			return -EINVAL;
11000 		}
11001 
11002 		if (in_sleepable(env) && is_storage_get_function(func_id))
11003 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11004 	}
11005 
11006 	meta.func_id = func_id;
11007 	/* check args */
11008 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11009 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11010 		if (err)
11011 			return err;
11012 	}
11013 
11014 	err = record_func_map(env, &meta, func_id, insn_idx);
11015 	if (err)
11016 		return err;
11017 
11018 	err = record_func_key(env, &meta, func_id, insn_idx);
11019 	if (err)
11020 		return err;
11021 
11022 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11023 	 * is inferred from register state.
11024 	 */
11025 	for (i = 0; i < meta.access_size; i++) {
11026 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11027 				       BPF_WRITE, -1, false, false);
11028 		if (err)
11029 			return err;
11030 	}
11031 
11032 	regs = cur_regs(env);
11033 
11034 	if (meta.release_regno) {
11035 		err = -EINVAL;
11036 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11037 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11038 		 * is safe to do directly.
11039 		 */
11040 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11041 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11042 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
11043 				return -EFAULT;
11044 			}
11045 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11046 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11047 			u32 ref_obj_id = meta.ref_obj_id;
11048 			bool in_rcu = in_rcu_cs(env);
11049 			struct bpf_func_state *state;
11050 			struct bpf_reg_state *reg;
11051 
11052 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11053 			if (!err) {
11054 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11055 					if (reg->ref_obj_id == ref_obj_id) {
11056 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11057 							reg->ref_obj_id = 0;
11058 							reg->type &= ~MEM_ALLOC;
11059 							reg->type |= MEM_RCU;
11060 						} else {
11061 							mark_reg_invalid(env, reg);
11062 						}
11063 					}
11064 				}));
11065 			}
11066 		} else if (meta.ref_obj_id) {
11067 			err = release_reference(env, meta.ref_obj_id);
11068 		} else if (register_is_null(&regs[meta.release_regno])) {
11069 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11070 			 * released is NULL, which must be > R0.
11071 			 */
11072 			err = 0;
11073 		}
11074 		if (err) {
11075 			verbose(env, "func %s#%d reference has not been acquired before\n",
11076 				func_id_name(func_id), func_id);
11077 			return err;
11078 		}
11079 	}
11080 
11081 	switch (func_id) {
11082 	case BPF_FUNC_tail_call:
11083 		err = check_resource_leak(env, false, true, "tail_call");
11084 		if (err)
11085 			return err;
11086 		break;
11087 	case BPF_FUNC_get_local_storage:
11088 		/* check that flags argument in get_local_storage(map, flags) is 0,
11089 		 * this is required because get_local_storage() can't return an error.
11090 		 */
11091 		if (!register_is_null(&regs[BPF_REG_2])) {
11092 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11093 			return -EINVAL;
11094 		}
11095 		break;
11096 	case BPF_FUNC_for_each_map_elem:
11097 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11098 					 set_map_elem_callback_state);
11099 		break;
11100 	case BPF_FUNC_timer_set_callback:
11101 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11102 					 set_timer_callback_state);
11103 		break;
11104 	case BPF_FUNC_find_vma:
11105 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11106 					 set_find_vma_callback_state);
11107 		break;
11108 	case BPF_FUNC_snprintf:
11109 		err = check_bpf_snprintf_call(env, regs);
11110 		break;
11111 	case BPF_FUNC_loop:
11112 		update_loop_inline_state(env, meta.subprogno);
11113 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11114 		 * is finished, thus mark it precise.
11115 		 */
11116 		err = mark_chain_precision(env, BPF_REG_1);
11117 		if (err)
11118 			return err;
11119 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11120 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11121 						 set_loop_callback_state);
11122 		} else {
11123 			cur_func(env)->callback_depth = 0;
11124 			if (env->log.level & BPF_LOG_LEVEL2)
11125 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11126 					env->cur_state->curframe);
11127 		}
11128 		break;
11129 	case BPF_FUNC_dynptr_from_mem:
11130 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11131 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11132 				reg_type_str(env, regs[BPF_REG_1].type));
11133 			return -EACCES;
11134 		}
11135 		break;
11136 	case BPF_FUNC_set_retval:
11137 		if (prog_type == BPF_PROG_TYPE_LSM &&
11138 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11139 			if (!env->prog->aux->attach_func_proto->type) {
11140 				/* Make sure programs that attach to void
11141 				 * hooks don't try to modify return value.
11142 				 */
11143 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11144 				return -EINVAL;
11145 			}
11146 		}
11147 		break;
11148 	case BPF_FUNC_dynptr_data:
11149 	{
11150 		struct bpf_reg_state *reg;
11151 		int id, ref_obj_id;
11152 
11153 		reg = get_dynptr_arg_reg(env, fn, regs);
11154 		if (!reg)
11155 			return -EFAULT;
11156 
11157 
11158 		if (meta.dynptr_id) {
11159 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
11160 			return -EFAULT;
11161 		}
11162 		if (meta.ref_obj_id) {
11163 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
11164 			return -EFAULT;
11165 		}
11166 
11167 		id = dynptr_id(env, reg);
11168 		if (id < 0) {
11169 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11170 			return id;
11171 		}
11172 
11173 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11174 		if (ref_obj_id < 0) {
11175 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
11176 			return ref_obj_id;
11177 		}
11178 
11179 		meta.dynptr_id = id;
11180 		meta.ref_obj_id = ref_obj_id;
11181 
11182 		break;
11183 	}
11184 	case BPF_FUNC_dynptr_write:
11185 	{
11186 		enum bpf_dynptr_type dynptr_type;
11187 		struct bpf_reg_state *reg;
11188 
11189 		reg = get_dynptr_arg_reg(env, fn, regs);
11190 		if (!reg)
11191 			return -EFAULT;
11192 
11193 		dynptr_type = dynptr_get_type(env, reg);
11194 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11195 			return -EFAULT;
11196 
11197 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
11198 			/* this will trigger clear_all_pkt_pointers(), which will
11199 			 * invalidate all dynptr slices associated with the skb
11200 			 */
11201 			changes_data = true;
11202 
11203 		break;
11204 	}
11205 	case BPF_FUNC_per_cpu_ptr:
11206 	case BPF_FUNC_this_cpu_ptr:
11207 	{
11208 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11209 		const struct btf_type *type;
11210 
11211 		if (reg->type & MEM_RCU) {
11212 			type = btf_type_by_id(reg->btf, reg->btf_id);
11213 			if (!type || !btf_type_is_struct(type)) {
11214 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11215 				return -EFAULT;
11216 			}
11217 			returns_cpu_specific_alloc_ptr = true;
11218 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11219 		}
11220 		break;
11221 	}
11222 	case BPF_FUNC_user_ringbuf_drain:
11223 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11224 					 set_user_ringbuf_callback_state);
11225 		break;
11226 	}
11227 
11228 	if (err)
11229 		return err;
11230 
11231 	/* reset caller saved regs */
11232 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11233 		mark_reg_not_init(env, regs, caller_saved[i]);
11234 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11235 	}
11236 
11237 	/* helper call returns 64-bit value. */
11238 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11239 
11240 	/* update return register (already marked as written above) */
11241 	ret_type = fn->ret_type;
11242 	ret_flag = type_flag(ret_type);
11243 
11244 	switch (base_type(ret_type)) {
11245 	case RET_INTEGER:
11246 		/* sets type to SCALAR_VALUE */
11247 		mark_reg_unknown(env, regs, BPF_REG_0);
11248 		break;
11249 	case RET_VOID:
11250 		regs[BPF_REG_0].type = NOT_INIT;
11251 		break;
11252 	case RET_PTR_TO_MAP_VALUE:
11253 		/* There is no offset yet applied, variable or fixed */
11254 		mark_reg_known_zero(env, regs, BPF_REG_0);
11255 		/* remember map_ptr, so that check_map_access()
11256 		 * can check 'value_size' boundary of memory access
11257 		 * to map element returned from bpf_map_lookup_elem()
11258 		 */
11259 		if (meta.map_ptr == NULL) {
11260 			verbose(env,
11261 				"kernel subsystem misconfigured verifier\n");
11262 			return -EINVAL;
11263 		}
11264 
11265 		if (func_id == BPF_FUNC_map_lookup_elem &&
11266 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11267 		    meta.const_map_key >= 0 &&
11268 		    meta.const_map_key < meta.map_ptr->max_entries)
11269 			ret_flag &= ~PTR_MAYBE_NULL;
11270 
11271 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11272 		regs[BPF_REG_0].map_uid = meta.map_uid;
11273 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11274 		if (!type_may_be_null(ret_flag) &&
11275 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
11276 			regs[BPF_REG_0].id = ++env->id_gen;
11277 		}
11278 		break;
11279 	case RET_PTR_TO_SOCKET:
11280 		mark_reg_known_zero(env, regs, BPF_REG_0);
11281 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11282 		break;
11283 	case RET_PTR_TO_SOCK_COMMON:
11284 		mark_reg_known_zero(env, regs, BPF_REG_0);
11285 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11286 		break;
11287 	case RET_PTR_TO_TCP_SOCK:
11288 		mark_reg_known_zero(env, regs, BPF_REG_0);
11289 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11290 		break;
11291 	case RET_PTR_TO_MEM:
11292 		mark_reg_known_zero(env, regs, BPF_REG_0);
11293 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11294 		regs[BPF_REG_0].mem_size = meta.mem_size;
11295 		break;
11296 	case RET_PTR_TO_MEM_OR_BTF_ID:
11297 	{
11298 		const struct btf_type *t;
11299 
11300 		mark_reg_known_zero(env, regs, BPF_REG_0);
11301 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11302 		if (!btf_type_is_struct(t)) {
11303 			u32 tsize;
11304 			const struct btf_type *ret;
11305 			const char *tname;
11306 
11307 			/* resolve the type size of ksym. */
11308 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11309 			if (IS_ERR(ret)) {
11310 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11311 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11312 					tname, PTR_ERR(ret));
11313 				return -EINVAL;
11314 			}
11315 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11316 			regs[BPF_REG_0].mem_size = tsize;
11317 		} else {
11318 			if (returns_cpu_specific_alloc_ptr) {
11319 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11320 			} else {
11321 				/* MEM_RDONLY may be carried from ret_flag, but it
11322 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11323 				 * it will confuse the check of PTR_TO_BTF_ID in
11324 				 * check_mem_access().
11325 				 */
11326 				ret_flag &= ~MEM_RDONLY;
11327 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11328 			}
11329 
11330 			regs[BPF_REG_0].btf = meta.ret_btf;
11331 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11332 		}
11333 		break;
11334 	}
11335 	case RET_PTR_TO_BTF_ID:
11336 	{
11337 		struct btf *ret_btf;
11338 		int ret_btf_id;
11339 
11340 		mark_reg_known_zero(env, regs, BPF_REG_0);
11341 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11342 		if (func_id == BPF_FUNC_kptr_xchg) {
11343 			ret_btf = meta.kptr_field->kptr.btf;
11344 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11345 			if (!btf_is_kernel(ret_btf)) {
11346 				regs[BPF_REG_0].type |= MEM_ALLOC;
11347 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11348 					regs[BPF_REG_0].type |= MEM_PERCPU;
11349 			}
11350 		} else {
11351 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11352 				verbose(env, "verifier internal error:");
11353 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
11354 					func_id_name(func_id));
11355 				return -EINVAL;
11356 			}
11357 			ret_btf = btf_vmlinux;
11358 			ret_btf_id = *fn->ret_btf_id;
11359 		}
11360 		if (ret_btf_id == 0) {
11361 			verbose(env, "invalid return type %u of func %s#%d\n",
11362 				base_type(ret_type), func_id_name(func_id),
11363 				func_id);
11364 			return -EINVAL;
11365 		}
11366 		regs[BPF_REG_0].btf = ret_btf;
11367 		regs[BPF_REG_0].btf_id = ret_btf_id;
11368 		break;
11369 	}
11370 	default:
11371 		verbose(env, "unknown return type %u of func %s#%d\n",
11372 			base_type(ret_type), func_id_name(func_id), func_id);
11373 		return -EINVAL;
11374 	}
11375 
11376 	if (type_may_be_null(regs[BPF_REG_0].type))
11377 		regs[BPF_REG_0].id = ++env->id_gen;
11378 
11379 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11380 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
11381 			func_id_name(func_id), func_id);
11382 		return -EFAULT;
11383 	}
11384 
11385 	if (is_dynptr_ref_function(func_id))
11386 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11387 
11388 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11389 		/* For release_reference() */
11390 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11391 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11392 		int id = acquire_reference(env, insn_idx);
11393 
11394 		if (id < 0)
11395 			return id;
11396 		/* For mark_ptr_or_null_reg() */
11397 		regs[BPF_REG_0].id = id;
11398 		/* For release_reference() */
11399 		regs[BPF_REG_0].ref_obj_id = id;
11400 	}
11401 
11402 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11403 	if (err)
11404 		return err;
11405 
11406 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11407 	if (err)
11408 		return err;
11409 
11410 	if ((func_id == BPF_FUNC_get_stack ||
11411 	     func_id == BPF_FUNC_get_task_stack) &&
11412 	    !env->prog->has_callchain_buf) {
11413 		const char *err_str;
11414 
11415 #ifdef CONFIG_PERF_EVENTS
11416 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11417 		err_str = "cannot get callchain buffer for func %s#%d\n";
11418 #else
11419 		err = -ENOTSUPP;
11420 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11421 #endif
11422 		if (err) {
11423 			verbose(env, err_str, func_id_name(func_id), func_id);
11424 			return err;
11425 		}
11426 
11427 		env->prog->has_callchain_buf = true;
11428 	}
11429 
11430 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11431 		env->prog->call_get_stack = true;
11432 
11433 	if (func_id == BPF_FUNC_get_func_ip) {
11434 		if (check_get_func_ip(env))
11435 			return -ENOTSUPP;
11436 		env->prog->call_get_func_ip = true;
11437 	}
11438 
11439 	if (changes_data)
11440 		clear_all_pkt_pointers(env);
11441 	return 0;
11442 }
11443 
11444 /* mark_btf_func_reg_size() is used when the reg size is determined by
11445  * the BTF func_proto's return value size and argument.
11446  */
11447 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11448 				   size_t reg_size)
11449 {
11450 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
11451 
11452 	if (regno == BPF_REG_0) {
11453 		/* Function return value */
11454 		reg->live |= REG_LIVE_WRITTEN;
11455 		reg->subreg_def = reg_size == sizeof(u64) ?
11456 			DEF_NOT_SUBREG : env->insn_idx + 1;
11457 	} else {
11458 		/* Function argument */
11459 		if (reg_size == sizeof(u64)) {
11460 			mark_insn_zext(env, reg);
11461 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11462 		} else {
11463 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11464 		}
11465 	}
11466 }
11467 
11468 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11469 {
11470 	return meta->kfunc_flags & KF_ACQUIRE;
11471 }
11472 
11473 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11474 {
11475 	return meta->kfunc_flags & KF_RELEASE;
11476 }
11477 
11478 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11479 {
11480 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11481 }
11482 
11483 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11484 {
11485 	return meta->kfunc_flags & KF_SLEEPABLE;
11486 }
11487 
11488 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11489 {
11490 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11491 }
11492 
11493 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11494 {
11495 	return meta->kfunc_flags & KF_RCU;
11496 }
11497 
11498 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11499 {
11500 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11501 }
11502 
11503 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11504 				  const struct btf_param *arg,
11505 				  const struct bpf_reg_state *reg)
11506 {
11507 	const struct btf_type *t;
11508 
11509 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11510 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11511 		return false;
11512 
11513 	return btf_param_match_suffix(btf, arg, "__sz");
11514 }
11515 
11516 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11517 					const struct btf_param *arg,
11518 					const struct bpf_reg_state *reg)
11519 {
11520 	const struct btf_type *t;
11521 
11522 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11523 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11524 		return false;
11525 
11526 	return btf_param_match_suffix(btf, arg, "__szk");
11527 }
11528 
11529 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11530 {
11531 	return btf_param_match_suffix(btf, arg, "__opt");
11532 }
11533 
11534 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11535 {
11536 	return btf_param_match_suffix(btf, arg, "__k");
11537 }
11538 
11539 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11540 {
11541 	return btf_param_match_suffix(btf, arg, "__ign");
11542 }
11543 
11544 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11545 {
11546 	return btf_param_match_suffix(btf, arg, "__map");
11547 }
11548 
11549 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11550 {
11551 	return btf_param_match_suffix(btf, arg, "__alloc");
11552 }
11553 
11554 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11555 {
11556 	return btf_param_match_suffix(btf, arg, "__uninit");
11557 }
11558 
11559 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11560 {
11561 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11562 }
11563 
11564 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11565 {
11566 	return btf_param_match_suffix(btf, arg, "__nullable");
11567 }
11568 
11569 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11570 {
11571 	return btf_param_match_suffix(btf, arg, "__str");
11572 }
11573 
11574 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
11575 {
11576 	return btf_param_match_suffix(btf, arg, "__irq_flag");
11577 }
11578 
11579 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11580 					  const struct btf_param *arg,
11581 					  const char *name)
11582 {
11583 	int len, target_len = strlen(name);
11584 	const char *param_name;
11585 
11586 	param_name = btf_name_by_offset(btf, arg->name_off);
11587 	if (str_is_empty(param_name))
11588 		return false;
11589 	len = strlen(param_name);
11590 	if (len != target_len)
11591 		return false;
11592 	if (strcmp(param_name, name))
11593 		return false;
11594 
11595 	return true;
11596 }
11597 
11598 enum {
11599 	KF_ARG_DYNPTR_ID,
11600 	KF_ARG_LIST_HEAD_ID,
11601 	KF_ARG_LIST_NODE_ID,
11602 	KF_ARG_RB_ROOT_ID,
11603 	KF_ARG_RB_NODE_ID,
11604 	KF_ARG_WORKQUEUE_ID,
11605 };
11606 
11607 BTF_ID_LIST(kf_arg_btf_ids)
11608 BTF_ID(struct, bpf_dynptr)
11609 BTF_ID(struct, bpf_list_head)
11610 BTF_ID(struct, bpf_list_node)
11611 BTF_ID(struct, bpf_rb_root)
11612 BTF_ID(struct, bpf_rb_node)
11613 BTF_ID(struct, bpf_wq)
11614 
11615 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11616 				    const struct btf_param *arg, int type)
11617 {
11618 	const struct btf_type *t;
11619 	u32 res_id;
11620 
11621 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11622 	if (!t)
11623 		return false;
11624 	if (!btf_type_is_ptr(t))
11625 		return false;
11626 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11627 	if (!t)
11628 		return false;
11629 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11630 }
11631 
11632 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11633 {
11634 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11635 }
11636 
11637 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11638 {
11639 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11640 }
11641 
11642 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11643 {
11644 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11645 }
11646 
11647 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11648 {
11649 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11650 }
11651 
11652 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11653 {
11654 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11655 }
11656 
11657 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11658 {
11659 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11660 }
11661 
11662 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11663 				  const struct btf_param *arg)
11664 {
11665 	const struct btf_type *t;
11666 
11667 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11668 	if (!t)
11669 		return false;
11670 
11671 	return true;
11672 }
11673 
11674 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11675 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11676 					const struct btf *btf,
11677 					const struct btf_type *t, int rec)
11678 {
11679 	const struct btf_type *member_type;
11680 	const struct btf_member *member;
11681 	u32 i;
11682 
11683 	if (!btf_type_is_struct(t))
11684 		return false;
11685 
11686 	for_each_member(i, t, member) {
11687 		const struct btf_array *array;
11688 
11689 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11690 		if (btf_type_is_struct(member_type)) {
11691 			if (rec >= 3) {
11692 				verbose(env, "max struct nesting depth exceeded\n");
11693 				return false;
11694 			}
11695 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11696 				return false;
11697 			continue;
11698 		}
11699 		if (btf_type_is_array(member_type)) {
11700 			array = btf_array(member_type);
11701 			if (!array->nelems)
11702 				return false;
11703 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11704 			if (!btf_type_is_scalar(member_type))
11705 				return false;
11706 			continue;
11707 		}
11708 		if (!btf_type_is_scalar(member_type))
11709 			return false;
11710 	}
11711 	return true;
11712 }
11713 
11714 enum kfunc_ptr_arg_type {
11715 	KF_ARG_PTR_TO_CTX,
11716 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11717 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11718 	KF_ARG_PTR_TO_DYNPTR,
11719 	KF_ARG_PTR_TO_ITER,
11720 	KF_ARG_PTR_TO_LIST_HEAD,
11721 	KF_ARG_PTR_TO_LIST_NODE,
11722 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11723 	KF_ARG_PTR_TO_MEM,
11724 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11725 	KF_ARG_PTR_TO_CALLBACK,
11726 	KF_ARG_PTR_TO_RB_ROOT,
11727 	KF_ARG_PTR_TO_RB_NODE,
11728 	KF_ARG_PTR_TO_NULL,
11729 	KF_ARG_PTR_TO_CONST_STR,
11730 	KF_ARG_PTR_TO_MAP,
11731 	KF_ARG_PTR_TO_WORKQUEUE,
11732 	KF_ARG_PTR_TO_IRQ_FLAG,
11733 };
11734 
11735 enum special_kfunc_type {
11736 	KF_bpf_obj_new_impl,
11737 	KF_bpf_obj_drop_impl,
11738 	KF_bpf_refcount_acquire_impl,
11739 	KF_bpf_list_push_front_impl,
11740 	KF_bpf_list_push_back_impl,
11741 	KF_bpf_list_pop_front,
11742 	KF_bpf_list_pop_back,
11743 	KF_bpf_cast_to_kern_ctx,
11744 	KF_bpf_rdonly_cast,
11745 	KF_bpf_rcu_read_lock,
11746 	KF_bpf_rcu_read_unlock,
11747 	KF_bpf_rbtree_remove,
11748 	KF_bpf_rbtree_add_impl,
11749 	KF_bpf_rbtree_first,
11750 	KF_bpf_dynptr_from_skb,
11751 	KF_bpf_dynptr_from_xdp,
11752 	KF_bpf_dynptr_slice,
11753 	KF_bpf_dynptr_slice_rdwr,
11754 	KF_bpf_dynptr_clone,
11755 	KF_bpf_percpu_obj_new_impl,
11756 	KF_bpf_percpu_obj_drop_impl,
11757 	KF_bpf_throw,
11758 	KF_bpf_wq_set_callback_impl,
11759 	KF_bpf_preempt_disable,
11760 	KF_bpf_preempt_enable,
11761 	KF_bpf_iter_css_task_new,
11762 	KF_bpf_session_cookie,
11763 	KF_bpf_get_kmem_cache,
11764 	KF_bpf_local_irq_save,
11765 	KF_bpf_local_irq_restore,
11766 	KF_bpf_iter_num_new,
11767 	KF_bpf_iter_num_next,
11768 	KF_bpf_iter_num_destroy,
11769 };
11770 
11771 BTF_SET_START(special_kfunc_set)
11772 BTF_ID(func, bpf_obj_new_impl)
11773 BTF_ID(func, bpf_obj_drop_impl)
11774 BTF_ID(func, bpf_refcount_acquire_impl)
11775 BTF_ID(func, bpf_list_push_front_impl)
11776 BTF_ID(func, bpf_list_push_back_impl)
11777 BTF_ID(func, bpf_list_pop_front)
11778 BTF_ID(func, bpf_list_pop_back)
11779 BTF_ID(func, bpf_cast_to_kern_ctx)
11780 BTF_ID(func, bpf_rdonly_cast)
11781 BTF_ID(func, bpf_rbtree_remove)
11782 BTF_ID(func, bpf_rbtree_add_impl)
11783 BTF_ID(func, bpf_rbtree_first)
11784 #ifdef CONFIG_NET
11785 BTF_ID(func, bpf_dynptr_from_skb)
11786 BTF_ID(func, bpf_dynptr_from_xdp)
11787 #endif
11788 BTF_ID(func, bpf_dynptr_slice)
11789 BTF_ID(func, bpf_dynptr_slice_rdwr)
11790 BTF_ID(func, bpf_dynptr_clone)
11791 BTF_ID(func, bpf_percpu_obj_new_impl)
11792 BTF_ID(func, bpf_percpu_obj_drop_impl)
11793 BTF_ID(func, bpf_throw)
11794 BTF_ID(func, bpf_wq_set_callback_impl)
11795 #ifdef CONFIG_CGROUPS
11796 BTF_ID(func, bpf_iter_css_task_new)
11797 #endif
11798 BTF_SET_END(special_kfunc_set)
11799 
11800 BTF_ID_LIST(special_kfunc_list)
11801 BTF_ID(func, bpf_obj_new_impl)
11802 BTF_ID(func, bpf_obj_drop_impl)
11803 BTF_ID(func, bpf_refcount_acquire_impl)
11804 BTF_ID(func, bpf_list_push_front_impl)
11805 BTF_ID(func, bpf_list_push_back_impl)
11806 BTF_ID(func, bpf_list_pop_front)
11807 BTF_ID(func, bpf_list_pop_back)
11808 BTF_ID(func, bpf_cast_to_kern_ctx)
11809 BTF_ID(func, bpf_rdonly_cast)
11810 BTF_ID(func, bpf_rcu_read_lock)
11811 BTF_ID(func, bpf_rcu_read_unlock)
11812 BTF_ID(func, bpf_rbtree_remove)
11813 BTF_ID(func, bpf_rbtree_add_impl)
11814 BTF_ID(func, bpf_rbtree_first)
11815 #ifdef CONFIG_NET
11816 BTF_ID(func, bpf_dynptr_from_skb)
11817 BTF_ID(func, bpf_dynptr_from_xdp)
11818 #else
11819 BTF_ID_UNUSED
11820 BTF_ID_UNUSED
11821 #endif
11822 BTF_ID(func, bpf_dynptr_slice)
11823 BTF_ID(func, bpf_dynptr_slice_rdwr)
11824 BTF_ID(func, bpf_dynptr_clone)
11825 BTF_ID(func, bpf_percpu_obj_new_impl)
11826 BTF_ID(func, bpf_percpu_obj_drop_impl)
11827 BTF_ID(func, bpf_throw)
11828 BTF_ID(func, bpf_wq_set_callback_impl)
11829 BTF_ID(func, bpf_preempt_disable)
11830 BTF_ID(func, bpf_preempt_enable)
11831 #ifdef CONFIG_CGROUPS
11832 BTF_ID(func, bpf_iter_css_task_new)
11833 #else
11834 BTF_ID_UNUSED
11835 #endif
11836 #ifdef CONFIG_BPF_EVENTS
11837 BTF_ID(func, bpf_session_cookie)
11838 #else
11839 BTF_ID_UNUSED
11840 #endif
11841 BTF_ID(func, bpf_get_kmem_cache)
11842 BTF_ID(func, bpf_local_irq_save)
11843 BTF_ID(func, bpf_local_irq_restore)
11844 BTF_ID(func, bpf_iter_num_new)
11845 BTF_ID(func, bpf_iter_num_next)
11846 BTF_ID(func, bpf_iter_num_destroy)
11847 
11848 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11849 {
11850 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11851 	    meta->arg_owning_ref) {
11852 		return false;
11853 	}
11854 
11855 	return meta->kfunc_flags & KF_RET_NULL;
11856 }
11857 
11858 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11859 {
11860 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11861 }
11862 
11863 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11864 {
11865 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11866 }
11867 
11868 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11869 {
11870 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11871 }
11872 
11873 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11874 {
11875 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11876 }
11877 
11878 static enum kfunc_ptr_arg_type
11879 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11880 		       struct bpf_kfunc_call_arg_meta *meta,
11881 		       const struct btf_type *t, const struct btf_type *ref_t,
11882 		       const char *ref_tname, const struct btf_param *args,
11883 		       int argno, int nargs)
11884 {
11885 	u32 regno = argno + 1;
11886 	struct bpf_reg_state *regs = cur_regs(env);
11887 	struct bpf_reg_state *reg = &regs[regno];
11888 	bool arg_mem_size = false;
11889 
11890 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11891 		return KF_ARG_PTR_TO_CTX;
11892 
11893 	/* In this function, we verify the kfunc's BTF as per the argument type,
11894 	 * leaving the rest of the verification with respect to the register
11895 	 * type to our caller. When a set of conditions hold in the BTF type of
11896 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11897 	 */
11898 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11899 		return KF_ARG_PTR_TO_CTX;
11900 
11901 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11902 		return KF_ARG_PTR_TO_NULL;
11903 
11904 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11905 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11906 
11907 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11908 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11909 
11910 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11911 		return KF_ARG_PTR_TO_DYNPTR;
11912 
11913 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
11914 		return KF_ARG_PTR_TO_ITER;
11915 
11916 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11917 		return KF_ARG_PTR_TO_LIST_HEAD;
11918 
11919 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11920 		return KF_ARG_PTR_TO_LIST_NODE;
11921 
11922 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11923 		return KF_ARG_PTR_TO_RB_ROOT;
11924 
11925 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11926 		return KF_ARG_PTR_TO_RB_NODE;
11927 
11928 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11929 		return KF_ARG_PTR_TO_CONST_STR;
11930 
11931 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11932 		return KF_ARG_PTR_TO_MAP;
11933 
11934 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11935 		return KF_ARG_PTR_TO_WORKQUEUE;
11936 
11937 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
11938 		return KF_ARG_PTR_TO_IRQ_FLAG;
11939 
11940 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11941 		if (!btf_type_is_struct(ref_t)) {
11942 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11943 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11944 			return -EINVAL;
11945 		}
11946 		return KF_ARG_PTR_TO_BTF_ID;
11947 	}
11948 
11949 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11950 		return KF_ARG_PTR_TO_CALLBACK;
11951 
11952 	if (argno + 1 < nargs &&
11953 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11954 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11955 		arg_mem_size = true;
11956 
11957 	/* This is the catch all argument type of register types supported by
11958 	 * check_helper_mem_access. However, we only allow when argument type is
11959 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11960 	 * arg_mem_size is true, the pointer can be void *.
11961 	 */
11962 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11963 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11964 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11965 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11966 		return -EINVAL;
11967 	}
11968 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11969 }
11970 
11971 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11972 					struct bpf_reg_state *reg,
11973 					const struct btf_type *ref_t,
11974 					const char *ref_tname, u32 ref_id,
11975 					struct bpf_kfunc_call_arg_meta *meta,
11976 					int argno)
11977 {
11978 	const struct btf_type *reg_ref_t;
11979 	bool strict_type_match = false;
11980 	const struct btf *reg_btf;
11981 	const char *reg_ref_tname;
11982 	bool taking_projection;
11983 	bool struct_same;
11984 	u32 reg_ref_id;
11985 
11986 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11987 		reg_btf = reg->btf;
11988 		reg_ref_id = reg->btf_id;
11989 	} else {
11990 		reg_btf = btf_vmlinux;
11991 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11992 	}
11993 
11994 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11995 	 * or releasing a reference, or are no-cast aliases. We do _not_
11996 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11997 	 * as we want to enable BPF programs to pass types that are bitwise
11998 	 * equivalent without forcing them to explicitly cast with something
11999 	 * like bpf_cast_to_kern_ctx().
12000 	 *
12001 	 * For example, say we had a type like the following:
12002 	 *
12003 	 * struct bpf_cpumask {
12004 	 *	cpumask_t cpumask;
12005 	 *	refcount_t usage;
12006 	 * };
12007 	 *
12008 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12009 	 * to a struct cpumask, so it would be safe to pass a struct
12010 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12011 	 *
12012 	 * The philosophy here is similar to how we allow scalars of different
12013 	 * types to be passed to kfuncs as long as the size is the same. The
12014 	 * only difference here is that we're simply allowing
12015 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12016 	 * resolve types.
12017 	 */
12018 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12019 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12020 		strict_type_match = true;
12021 
12022 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12023 		     (reg->off || !tnum_is_const(reg->var_off) ||
12024 		      reg->var_off.value));
12025 
12026 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12027 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12028 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12029 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12030 	 * actually use it -- it must cast to the underlying type. So we allow
12031 	 * caller to pass in the underlying type.
12032 	 */
12033 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12034 	if (!taking_projection && !struct_same) {
12035 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12036 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12037 			btf_type_str(reg_ref_t), reg_ref_tname);
12038 		return -EINVAL;
12039 	}
12040 	return 0;
12041 }
12042 
12043 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12044 			     struct bpf_kfunc_call_arg_meta *meta)
12045 {
12046 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12047 	bool irq_save;
12048 	int err;
12049 
12050 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save]) {
12051 		irq_save = true;
12052 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore]) {
12053 		irq_save = false;
12054 	} else {
12055 		verbose(env, "verifier internal error: unknown irq flags kfunc\n");
12056 		return -EFAULT;
12057 	}
12058 
12059 	if (irq_save) {
12060 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12061 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12062 			return -EINVAL;
12063 		}
12064 
12065 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12066 		if (err)
12067 			return err;
12068 
12069 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx);
12070 		if (err)
12071 			return err;
12072 	} else {
12073 		err = is_irq_flag_reg_valid_init(env, reg);
12074 		if (err) {
12075 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12076 			return err;
12077 		}
12078 
12079 		err = mark_irq_flag_read(env, reg);
12080 		if (err)
12081 			return err;
12082 
12083 		err = unmark_stack_slot_irq_flag(env, reg);
12084 		if (err)
12085 			return err;
12086 	}
12087 	return 0;
12088 }
12089 
12090 
12091 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12092 {
12093 	struct btf_record *rec = reg_btf_record(reg);
12094 
12095 	if (!env->cur_state->active_locks) {
12096 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
12097 		return -EFAULT;
12098 	}
12099 
12100 	if (type_flag(reg->type) & NON_OWN_REF) {
12101 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
12102 		return -EFAULT;
12103 	}
12104 
12105 	reg->type |= NON_OWN_REF;
12106 	if (rec->refcount_off >= 0)
12107 		reg->type |= MEM_RCU;
12108 
12109 	return 0;
12110 }
12111 
12112 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12113 {
12114 	struct bpf_verifier_state *state = env->cur_state;
12115 	struct bpf_func_state *unused;
12116 	struct bpf_reg_state *reg;
12117 	int i;
12118 
12119 	if (!ref_obj_id) {
12120 		verbose(env, "verifier internal error: ref_obj_id is zero for "
12121 			     "owning -> non-owning conversion\n");
12122 		return -EFAULT;
12123 	}
12124 
12125 	for (i = 0; i < state->acquired_refs; i++) {
12126 		if (state->refs[i].id != ref_obj_id)
12127 			continue;
12128 
12129 		/* Clear ref_obj_id here so release_reference doesn't clobber
12130 		 * the whole reg
12131 		 */
12132 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12133 			if (reg->ref_obj_id == ref_obj_id) {
12134 				reg->ref_obj_id = 0;
12135 				ref_set_non_owning(env, reg);
12136 			}
12137 		}));
12138 		return 0;
12139 	}
12140 
12141 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
12142 	return -EFAULT;
12143 }
12144 
12145 /* Implementation details:
12146  *
12147  * Each register points to some region of memory, which we define as an
12148  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12149  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12150  * allocation. The lock and the data it protects are colocated in the same
12151  * memory region.
12152  *
12153  * Hence, everytime a register holds a pointer value pointing to such
12154  * allocation, the verifier preserves a unique reg->id for it.
12155  *
12156  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12157  * bpf_spin_lock is called.
12158  *
12159  * To enable this, lock state in the verifier captures two values:
12160  *	active_lock.ptr = Register's type specific pointer
12161  *	active_lock.id  = A unique ID for each register pointer value
12162  *
12163  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12164  * supported register types.
12165  *
12166  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12167  * allocated objects is the reg->btf pointer.
12168  *
12169  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12170  * can establish the provenance of the map value statically for each distinct
12171  * lookup into such maps. They always contain a single map value hence unique
12172  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12173  *
12174  * So, in case of global variables, they use array maps with max_entries = 1,
12175  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12176  * into the same map value as max_entries is 1, as described above).
12177  *
12178  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12179  * outer map pointer (in verifier context), but each lookup into an inner map
12180  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12181  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12182  * will get different reg->id assigned to each lookup, hence different
12183  * active_lock.id.
12184  *
12185  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12186  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12187  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12188  */
12189 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12190 {
12191 	struct bpf_reference_state *s;
12192 	void *ptr;
12193 	u32 id;
12194 
12195 	switch ((int)reg->type) {
12196 	case PTR_TO_MAP_VALUE:
12197 		ptr = reg->map_ptr;
12198 		break;
12199 	case PTR_TO_BTF_ID | MEM_ALLOC:
12200 		ptr = reg->btf;
12201 		break;
12202 	default:
12203 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
12204 		return -EFAULT;
12205 	}
12206 	id = reg->id;
12207 
12208 	if (!env->cur_state->active_locks)
12209 		return -EINVAL;
12210 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK, id, ptr);
12211 	if (!s) {
12212 		verbose(env, "held lock and object are not in the same allocation\n");
12213 		return -EINVAL;
12214 	}
12215 	return 0;
12216 }
12217 
12218 static bool is_bpf_list_api_kfunc(u32 btf_id)
12219 {
12220 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12221 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12222 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12223 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
12224 }
12225 
12226 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12227 {
12228 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12229 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12230 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
12231 }
12232 
12233 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12234 {
12235 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12236 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12237 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12238 }
12239 
12240 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12241 {
12242 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12243 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12244 }
12245 
12246 static bool kfunc_spin_allowed(u32 btf_id)
12247 {
12248 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id);
12249 }
12250 
12251 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12252 {
12253 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12254 }
12255 
12256 static bool is_async_callback_calling_kfunc(u32 btf_id)
12257 {
12258 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12259 }
12260 
12261 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12262 {
12263 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12264 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12265 }
12266 
12267 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12268 {
12269 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12270 }
12271 
12272 static bool is_callback_calling_kfunc(u32 btf_id)
12273 {
12274 	return is_sync_callback_calling_kfunc(btf_id) ||
12275 	       is_async_callback_calling_kfunc(btf_id);
12276 }
12277 
12278 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12279 {
12280 	return is_bpf_rbtree_api_kfunc(btf_id);
12281 }
12282 
12283 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12284 					  enum btf_field_type head_field_type,
12285 					  u32 kfunc_btf_id)
12286 {
12287 	bool ret;
12288 
12289 	switch (head_field_type) {
12290 	case BPF_LIST_HEAD:
12291 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12292 		break;
12293 	case BPF_RB_ROOT:
12294 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12295 		break;
12296 	default:
12297 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12298 			btf_field_type_name(head_field_type));
12299 		return false;
12300 	}
12301 
12302 	if (!ret)
12303 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12304 			btf_field_type_name(head_field_type));
12305 	return ret;
12306 }
12307 
12308 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12309 					  enum btf_field_type node_field_type,
12310 					  u32 kfunc_btf_id)
12311 {
12312 	bool ret;
12313 
12314 	switch (node_field_type) {
12315 	case BPF_LIST_NODE:
12316 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12317 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12318 		break;
12319 	case BPF_RB_NODE:
12320 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12321 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
12322 		break;
12323 	default:
12324 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12325 			btf_field_type_name(node_field_type));
12326 		return false;
12327 	}
12328 
12329 	if (!ret)
12330 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12331 			btf_field_type_name(node_field_type));
12332 	return ret;
12333 }
12334 
12335 static int
12336 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12337 				   struct bpf_reg_state *reg, u32 regno,
12338 				   struct bpf_kfunc_call_arg_meta *meta,
12339 				   enum btf_field_type head_field_type,
12340 				   struct btf_field **head_field)
12341 {
12342 	const char *head_type_name;
12343 	struct btf_field *field;
12344 	struct btf_record *rec;
12345 	u32 head_off;
12346 
12347 	if (meta->btf != btf_vmlinux) {
12348 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12349 		return -EFAULT;
12350 	}
12351 
12352 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12353 		return -EFAULT;
12354 
12355 	head_type_name = btf_field_type_name(head_field_type);
12356 	if (!tnum_is_const(reg->var_off)) {
12357 		verbose(env,
12358 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12359 			regno, head_type_name);
12360 		return -EINVAL;
12361 	}
12362 
12363 	rec = reg_btf_record(reg);
12364 	head_off = reg->off + reg->var_off.value;
12365 	field = btf_record_find(rec, head_off, head_field_type);
12366 	if (!field) {
12367 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12368 		return -EINVAL;
12369 	}
12370 
12371 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12372 	if (check_reg_allocation_locked(env, reg)) {
12373 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12374 			rec->spin_lock_off, head_type_name);
12375 		return -EINVAL;
12376 	}
12377 
12378 	if (*head_field) {
12379 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
12380 		return -EFAULT;
12381 	}
12382 	*head_field = field;
12383 	return 0;
12384 }
12385 
12386 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12387 					   struct bpf_reg_state *reg, u32 regno,
12388 					   struct bpf_kfunc_call_arg_meta *meta)
12389 {
12390 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12391 							  &meta->arg_list_head.field);
12392 }
12393 
12394 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12395 					     struct bpf_reg_state *reg, u32 regno,
12396 					     struct bpf_kfunc_call_arg_meta *meta)
12397 {
12398 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12399 							  &meta->arg_rbtree_root.field);
12400 }
12401 
12402 static int
12403 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12404 				   struct bpf_reg_state *reg, u32 regno,
12405 				   struct bpf_kfunc_call_arg_meta *meta,
12406 				   enum btf_field_type head_field_type,
12407 				   enum btf_field_type node_field_type,
12408 				   struct btf_field **node_field)
12409 {
12410 	const char *node_type_name;
12411 	const struct btf_type *et, *t;
12412 	struct btf_field *field;
12413 	u32 node_off;
12414 
12415 	if (meta->btf != btf_vmlinux) {
12416 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12417 		return -EFAULT;
12418 	}
12419 
12420 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12421 		return -EFAULT;
12422 
12423 	node_type_name = btf_field_type_name(node_field_type);
12424 	if (!tnum_is_const(reg->var_off)) {
12425 		verbose(env,
12426 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12427 			regno, node_type_name);
12428 		return -EINVAL;
12429 	}
12430 
12431 	node_off = reg->off + reg->var_off.value;
12432 	field = reg_find_field_offset(reg, node_off, node_field_type);
12433 	if (!field) {
12434 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12435 		return -EINVAL;
12436 	}
12437 
12438 	field = *node_field;
12439 
12440 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12441 	t = btf_type_by_id(reg->btf, reg->btf_id);
12442 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12443 				  field->graph_root.value_btf_id, true)) {
12444 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12445 			"in struct %s, but arg is at offset=%d in struct %s\n",
12446 			btf_field_type_name(head_field_type),
12447 			btf_field_type_name(node_field_type),
12448 			field->graph_root.node_offset,
12449 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12450 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12451 		return -EINVAL;
12452 	}
12453 	meta->arg_btf = reg->btf;
12454 	meta->arg_btf_id = reg->btf_id;
12455 
12456 	if (node_off != field->graph_root.node_offset) {
12457 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12458 			node_off, btf_field_type_name(node_field_type),
12459 			field->graph_root.node_offset,
12460 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12461 		return -EINVAL;
12462 	}
12463 
12464 	return 0;
12465 }
12466 
12467 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12468 					   struct bpf_reg_state *reg, u32 regno,
12469 					   struct bpf_kfunc_call_arg_meta *meta)
12470 {
12471 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12472 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12473 						  &meta->arg_list_head.field);
12474 }
12475 
12476 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12477 					     struct bpf_reg_state *reg, u32 regno,
12478 					     struct bpf_kfunc_call_arg_meta *meta)
12479 {
12480 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12481 						  BPF_RB_ROOT, BPF_RB_NODE,
12482 						  &meta->arg_rbtree_root.field);
12483 }
12484 
12485 /*
12486  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12487  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12488  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12489  * them can only be attached to some specific hook points.
12490  */
12491 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12492 {
12493 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12494 
12495 	switch (prog_type) {
12496 	case BPF_PROG_TYPE_LSM:
12497 		return true;
12498 	case BPF_PROG_TYPE_TRACING:
12499 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12500 			return true;
12501 		fallthrough;
12502 	default:
12503 		return in_sleepable(env);
12504 	}
12505 }
12506 
12507 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12508 			    int insn_idx)
12509 {
12510 	const char *func_name = meta->func_name, *ref_tname;
12511 	const struct btf *btf = meta->btf;
12512 	const struct btf_param *args;
12513 	struct btf_record *rec;
12514 	u32 i, nargs;
12515 	int ret;
12516 
12517 	args = (const struct btf_param *)(meta->func_proto + 1);
12518 	nargs = btf_type_vlen(meta->func_proto);
12519 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
12520 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
12521 			MAX_BPF_FUNC_REG_ARGS);
12522 		return -EINVAL;
12523 	}
12524 
12525 	/* Check that BTF function arguments match actual types that the
12526 	 * verifier sees.
12527 	 */
12528 	for (i = 0; i < nargs; i++) {
12529 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
12530 		const struct btf_type *t, *ref_t, *resolve_ret;
12531 		enum bpf_arg_type arg_type = ARG_DONTCARE;
12532 		u32 regno = i + 1, ref_id, type_size;
12533 		bool is_ret_buf_sz = false;
12534 		int kf_arg_type;
12535 
12536 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
12537 
12538 		if (is_kfunc_arg_ignore(btf, &args[i]))
12539 			continue;
12540 
12541 		if (btf_type_is_scalar(t)) {
12542 			if (reg->type != SCALAR_VALUE) {
12543 				verbose(env, "R%d is not a scalar\n", regno);
12544 				return -EINVAL;
12545 			}
12546 
12547 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
12548 				if (meta->arg_constant.found) {
12549 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12550 					return -EFAULT;
12551 				}
12552 				if (!tnum_is_const(reg->var_off)) {
12553 					verbose(env, "R%d must be a known constant\n", regno);
12554 					return -EINVAL;
12555 				}
12556 				ret = mark_chain_precision(env, regno);
12557 				if (ret < 0)
12558 					return ret;
12559 				meta->arg_constant.found = true;
12560 				meta->arg_constant.value = reg->var_off.value;
12561 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12562 				meta->r0_rdonly = true;
12563 				is_ret_buf_sz = true;
12564 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12565 				is_ret_buf_sz = true;
12566 			}
12567 
12568 			if (is_ret_buf_sz) {
12569 				if (meta->r0_size) {
12570 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12571 					return -EINVAL;
12572 				}
12573 
12574 				if (!tnum_is_const(reg->var_off)) {
12575 					verbose(env, "R%d is not a const\n", regno);
12576 					return -EINVAL;
12577 				}
12578 
12579 				meta->r0_size = reg->var_off.value;
12580 				ret = mark_chain_precision(env, regno);
12581 				if (ret)
12582 					return ret;
12583 			}
12584 			continue;
12585 		}
12586 
12587 		if (!btf_type_is_ptr(t)) {
12588 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12589 			return -EINVAL;
12590 		}
12591 
12592 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12593 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
12594 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
12595 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12596 			return -EACCES;
12597 		}
12598 
12599 		if (reg->ref_obj_id) {
12600 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
12601 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12602 					regno, reg->ref_obj_id,
12603 					meta->ref_obj_id);
12604 				return -EFAULT;
12605 			}
12606 			meta->ref_obj_id = reg->ref_obj_id;
12607 			if (is_kfunc_release(meta))
12608 				meta->release_regno = regno;
12609 		}
12610 
12611 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12612 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12613 
12614 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12615 		if (kf_arg_type < 0)
12616 			return kf_arg_type;
12617 
12618 		switch (kf_arg_type) {
12619 		case KF_ARG_PTR_TO_NULL:
12620 			continue;
12621 		case KF_ARG_PTR_TO_MAP:
12622 			if (!reg->map_ptr) {
12623 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
12624 				return -EINVAL;
12625 			}
12626 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12627 				/* Use map_uid (which is unique id of inner map) to reject:
12628 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12629 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12630 				 * if (inner_map1 && inner_map2) {
12631 				 *     wq = bpf_map_lookup_elem(inner_map1);
12632 				 *     if (wq)
12633 				 *         // mismatch would have been allowed
12634 				 *         bpf_wq_init(wq, inner_map2);
12635 				 * }
12636 				 *
12637 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12638 				 */
12639 				if (meta->map.ptr != reg->map_ptr ||
12640 				    meta->map.uid != reg->map_uid) {
12641 					verbose(env,
12642 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12643 						meta->map.uid, reg->map_uid);
12644 					return -EINVAL;
12645 				}
12646 			}
12647 			meta->map.ptr = reg->map_ptr;
12648 			meta->map.uid = reg->map_uid;
12649 			fallthrough;
12650 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12651 		case KF_ARG_PTR_TO_BTF_ID:
12652 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
12653 				break;
12654 
12655 			if (!is_trusted_reg(reg)) {
12656 				if (!is_kfunc_rcu(meta)) {
12657 					verbose(env, "R%d must be referenced or trusted\n", regno);
12658 					return -EINVAL;
12659 				}
12660 				if (!is_rcu_reg(reg)) {
12661 					verbose(env, "R%d must be a rcu pointer\n", regno);
12662 					return -EINVAL;
12663 				}
12664 			}
12665 			fallthrough;
12666 		case KF_ARG_PTR_TO_CTX:
12667 		case KF_ARG_PTR_TO_DYNPTR:
12668 		case KF_ARG_PTR_TO_ITER:
12669 		case KF_ARG_PTR_TO_LIST_HEAD:
12670 		case KF_ARG_PTR_TO_LIST_NODE:
12671 		case KF_ARG_PTR_TO_RB_ROOT:
12672 		case KF_ARG_PTR_TO_RB_NODE:
12673 		case KF_ARG_PTR_TO_MEM:
12674 		case KF_ARG_PTR_TO_MEM_SIZE:
12675 		case KF_ARG_PTR_TO_CALLBACK:
12676 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12677 		case KF_ARG_PTR_TO_CONST_STR:
12678 		case KF_ARG_PTR_TO_WORKQUEUE:
12679 		case KF_ARG_PTR_TO_IRQ_FLAG:
12680 			break;
12681 		default:
12682 			WARN_ON_ONCE(1);
12683 			return -EFAULT;
12684 		}
12685 
12686 		if (is_kfunc_release(meta) && reg->ref_obj_id)
12687 			arg_type |= OBJ_RELEASE;
12688 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
12689 		if (ret < 0)
12690 			return ret;
12691 
12692 		switch (kf_arg_type) {
12693 		case KF_ARG_PTR_TO_CTX:
12694 			if (reg->type != PTR_TO_CTX) {
12695 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
12696 					i, reg_type_str(env, reg->type));
12697 				return -EINVAL;
12698 			}
12699 
12700 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12701 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12702 				if (ret < 0)
12703 					return -EINVAL;
12704 				meta->ret_btf_id  = ret;
12705 			}
12706 			break;
12707 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12708 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12709 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
12710 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
12711 					return -EINVAL;
12712 				}
12713 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12714 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12715 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
12716 					return -EINVAL;
12717 				}
12718 			} else {
12719 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12720 				return -EINVAL;
12721 			}
12722 			if (!reg->ref_obj_id) {
12723 				verbose(env, "allocated object must be referenced\n");
12724 				return -EINVAL;
12725 			}
12726 			if (meta->btf == btf_vmlinux) {
12727 				meta->arg_btf = reg->btf;
12728 				meta->arg_btf_id = reg->btf_id;
12729 			}
12730 			break;
12731 		case KF_ARG_PTR_TO_DYNPTR:
12732 		{
12733 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12734 			int clone_ref_obj_id = 0;
12735 
12736 			if (reg->type == CONST_PTR_TO_DYNPTR)
12737 				dynptr_arg_type |= MEM_RDONLY;
12738 
12739 			if (is_kfunc_arg_uninit(btf, &args[i]))
12740 				dynptr_arg_type |= MEM_UNINIT;
12741 
12742 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12743 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12744 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12745 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12746 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12747 				   (dynptr_arg_type & MEM_UNINIT)) {
12748 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12749 
12750 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12751 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12752 					return -EFAULT;
12753 				}
12754 
12755 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12756 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12757 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12758 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12759 					return -EFAULT;
12760 				}
12761 			}
12762 
12763 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12764 			if (ret < 0)
12765 				return ret;
12766 
12767 			if (!(dynptr_arg_type & MEM_UNINIT)) {
12768 				int id = dynptr_id(env, reg);
12769 
12770 				if (id < 0) {
12771 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12772 					return id;
12773 				}
12774 				meta->initialized_dynptr.id = id;
12775 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12776 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12777 			}
12778 
12779 			break;
12780 		}
12781 		case KF_ARG_PTR_TO_ITER:
12782 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12783 				if (!check_css_task_iter_allowlist(env)) {
12784 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12785 					return -EINVAL;
12786 				}
12787 			}
12788 			ret = process_iter_arg(env, regno, insn_idx, meta);
12789 			if (ret < 0)
12790 				return ret;
12791 			break;
12792 		case KF_ARG_PTR_TO_LIST_HEAD:
12793 			if (reg->type != PTR_TO_MAP_VALUE &&
12794 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12795 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12796 				return -EINVAL;
12797 			}
12798 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12799 				verbose(env, "allocated object must be referenced\n");
12800 				return -EINVAL;
12801 			}
12802 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12803 			if (ret < 0)
12804 				return ret;
12805 			break;
12806 		case KF_ARG_PTR_TO_RB_ROOT:
12807 			if (reg->type != PTR_TO_MAP_VALUE &&
12808 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12809 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12810 				return -EINVAL;
12811 			}
12812 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12813 				verbose(env, "allocated object must be referenced\n");
12814 				return -EINVAL;
12815 			}
12816 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12817 			if (ret < 0)
12818 				return ret;
12819 			break;
12820 		case KF_ARG_PTR_TO_LIST_NODE:
12821 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12822 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12823 				return -EINVAL;
12824 			}
12825 			if (!reg->ref_obj_id) {
12826 				verbose(env, "allocated object must be referenced\n");
12827 				return -EINVAL;
12828 			}
12829 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12830 			if (ret < 0)
12831 				return ret;
12832 			break;
12833 		case KF_ARG_PTR_TO_RB_NODE:
12834 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12835 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12836 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12837 					return -EINVAL;
12838 				}
12839 				if (in_rbtree_lock_required_cb(env)) {
12840 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12841 					return -EINVAL;
12842 				}
12843 			} else {
12844 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12845 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12846 					return -EINVAL;
12847 				}
12848 				if (!reg->ref_obj_id) {
12849 					verbose(env, "allocated object must be referenced\n");
12850 					return -EINVAL;
12851 				}
12852 			}
12853 
12854 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12855 			if (ret < 0)
12856 				return ret;
12857 			break;
12858 		case KF_ARG_PTR_TO_MAP:
12859 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12860 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12861 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12862 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12863 			fallthrough;
12864 		case KF_ARG_PTR_TO_BTF_ID:
12865 			/* Only base_type is checked, further checks are done here */
12866 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12867 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12868 			    !reg2btf_ids[base_type(reg->type)]) {
12869 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12870 				verbose(env, "expected %s or socket\n",
12871 					reg_type_str(env, base_type(reg->type) |
12872 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12873 				return -EINVAL;
12874 			}
12875 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12876 			if (ret < 0)
12877 				return ret;
12878 			break;
12879 		case KF_ARG_PTR_TO_MEM:
12880 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12881 			if (IS_ERR(resolve_ret)) {
12882 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12883 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12884 				return -EINVAL;
12885 			}
12886 			ret = check_mem_reg(env, reg, regno, type_size);
12887 			if (ret < 0)
12888 				return ret;
12889 			break;
12890 		case KF_ARG_PTR_TO_MEM_SIZE:
12891 		{
12892 			struct bpf_reg_state *buff_reg = &regs[regno];
12893 			const struct btf_param *buff_arg = &args[i];
12894 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12895 			const struct btf_param *size_arg = &args[i + 1];
12896 
12897 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12898 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12899 				if (ret < 0) {
12900 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12901 					return ret;
12902 				}
12903 			}
12904 
12905 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12906 				if (meta->arg_constant.found) {
12907 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12908 					return -EFAULT;
12909 				}
12910 				if (!tnum_is_const(size_reg->var_off)) {
12911 					verbose(env, "R%d must be a known constant\n", regno + 1);
12912 					return -EINVAL;
12913 				}
12914 				meta->arg_constant.found = true;
12915 				meta->arg_constant.value = size_reg->var_off.value;
12916 			}
12917 
12918 			/* Skip next '__sz' or '__szk' argument */
12919 			i++;
12920 			break;
12921 		}
12922 		case KF_ARG_PTR_TO_CALLBACK:
12923 			if (reg->type != PTR_TO_FUNC) {
12924 				verbose(env, "arg%d expected pointer to func\n", i);
12925 				return -EINVAL;
12926 			}
12927 			meta->subprogno = reg->subprogno;
12928 			break;
12929 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12930 			if (!type_is_ptr_alloc_obj(reg->type)) {
12931 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12932 				return -EINVAL;
12933 			}
12934 			if (!type_is_non_owning_ref(reg->type))
12935 				meta->arg_owning_ref = true;
12936 
12937 			rec = reg_btf_record(reg);
12938 			if (!rec) {
12939 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12940 				return -EFAULT;
12941 			}
12942 
12943 			if (rec->refcount_off < 0) {
12944 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12945 				return -EINVAL;
12946 			}
12947 
12948 			meta->arg_btf = reg->btf;
12949 			meta->arg_btf_id = reg->btf_id;
12950 			break;
12951 		case KF_ARG_PTR_TO_CONST_STR:
12952 			if (reg->type != PTR_TO_MAP_VALUE) {
12953 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12954 				return -EINVAL;
12955 			}
12956 			ret = check_reg_const_str(env, reg, regno);
12957 			if (ret)
12958 				return ret;
12959 			break;
12960 		case KF_ARG_PTR_TO_WORKQUEUE:
12961 			if (reg->type != PTR_TO_MAP_VALUE) {
12962 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12963 				return -EINVAL;
12964 			}
12965 			ret = process_wq_func(env, regno, meta);
12966 			if (ret < 0)
12967 				return ret;
12968 			break;
12969 		case KF_ARG_PTR_TO_IRQ_FLAG:
12970 			if (reg->type != PTR_TO_STACK) {
12971 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
12972 				return -EINVAL;
12973 			}
12974 			ret = process_irq_flag(env, regno, meta);
12975 			if (ret < 0)
12976 				return ret;
12977 			break;
12978 		}
12979 	}
12980 
12981 	if (is_kfunc_release(meta) && !meta->release_regno) {
12982 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12983 			func_name);
12984 		return -EINVAL;
12985 	}
12986 
12987 	return 0;
12988 }
12989 
12990 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12991 			    struct bpf_insn *insn,
12992 			    struct bpf_kfunc_call_arg_meta *meta,
12993 			    const char **kfunc_name)
12994 {
12995 	const struct btf_type *func, *func_proto;
12996 	u32 func_id, *kfunc_flags;
12997 	const char *func_name;
12998 	struct btf *desc_btf;
12999 
13000 	if (kfunc_name)
13001 		*kfunc_name = NULL;
13002 
13003 	if (!insn->imm)
13004 		return -EINVAL;
13005 
13006 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13007 	if (IS_ERR(desc_btf))
13008 		return PTR_ERR(desc_btf);
13009 
13010 	func_id = insn->imm;
13011 	func = btf_type_by_id(desc_btf, func_id);
13012 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13013 	if (kfunc_name)
13014 		*kfunc_name = func_name;
13015 	func_proto = btf_type_by_id(desc_btf, func->type);
13016 
13017 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13018 	if (!kfunc_flags) {
13019 		return -EACCES;
13020 	}
13021 
13022 	memset(meta, 0, sizeof(*meta));
13023 	meta->btf = desc_btf;
13024 	meta->func_id = func_id;
13025 	meta->kfunc_flags = *kfunc_flags;
13026 	meta->func_proto = func_proto;
13027 	meta->func_name = func_name;
13028 
13029 	return 0;
13030 }
13031 
13032 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13033 
13034 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13035 			    int *insn_idx_p)
13036 {
13037 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13038 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13039 	struct bpf_reg_state *regs = cur_regs(env);
13040 	const char *func_name, *ptr_type_name;
13041 	const struct btf_type *t, *ptr_type;
13042 	struct bpf_kfunc_call_arg_meta meta;
13043 	struct bpf_insn_aux_data *insn_aux;
13044 	int err, insn_idx = *insn_idx_p;
13045 	const struct btf_param *args;
13046 	const struct btf_type *ret_t;
13047 	struct btf *desc_btf;
13048 
13049 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13050 	if (!insn->imm)
13051 		return 0;
13052 
13053 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13054 	if (err == -EACCES && func_name)
13055 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13056 	if (err)
13057 		return err;
13058 	desc_btf = meta.btf;
13059 	insn_aux = &env->insn_aux_data[insn_idx];
13060 
13061 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13062 
13063 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13064 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13065 		return -EACCES;
13066 	}
13067 
13068 	sleepable = is_kfunc_sleepable(&meta);
13069 	if (sleepable && !in_sleepable(env)) {
13070 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13071 		return -EACCES;
13072 	}
13073 
13074 	/* Check the arguments */
13075 	err = check_kfunc_args(env, &meta, insn_idx);
13076 	if (err < 0)
13077 		return err;
13078 
13079 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13080 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13081 					 set_rbtree_add_callback_state);
13082 		if (err) {
13083 			verbose(env, "kfunc %s#%d failed callback verification\n",
13084 				func_name, meta.func_id);
13085 			return err;
13086 		}
13087 	}
13088 
13089 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13090 		meta.r0_size = sizeof(u64);
13091 		meta.r0_rdonly = false;
13092 	}
13093 
13094 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13095 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13096 					 set_timer_callback_state);
13097 		if (err) {
13098 			verbose(env, "kfunc %s#%d failed callback verification\n",
13099 				func_name, meta.func_id);
13100 			return err;
13101 		}
13102 	}
13103 
13104 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13105 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13106 
13107 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13108 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13109 
13110 	if (env->cur_state->active_rcu_lock) {
13111 		struct bpf_func_state *state;
13112 		struct bpf_reg_state *reg;
13113 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13114 
13115 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13116 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13117 			return -EACCES;
13118 		}
13119 
13120 		if (rcu_lock) {
13121 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13122 			return -EINVAL;
13123 		} else if (rcu_unlock) {
13124 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13125 				if (reg->type & MEM_RCU) {
13126 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13127 					reg->type |= PTR_UNTRUSTED;
13128 				}
13129 			}));
13130 			env->cur_state->active_rcu_lock = false;
13131 		} else if (sleepable) {
13132 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13133 			return -EACCES;
13134 		}
13135 	} else if (rcu_lock) {
13136 		env->cur_state->active_rcu_lock = true;
13137 	} else if (rcu_unlock) {
13138 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13139 		return -EINVAL;
13140 	}
13141 
13142 	if (env->cur_state->active_preempt_locks) {
13143 		if (preempt_disable) {
13144 			env->cur_state->active_preempt_locks++;
13145 		} else if (preempt_enable) {
13146 			env->cur_state->active_preempt_locks--;
13147 		} else if (sleepable) {
13148 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13149 			return -EACCES;
13150 		}
13151 	} else if (preempt_disable) {
13152 		env->cur_state->active_preempt_locks++;
13153 	} else if (preempt_enable) {
13154 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13155 		return -EINVAL;
13156 	}
13157 
13158 	if (env->cur_state->active_irq_id && sleepable) {
13159 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13160 		return -EACCES;
13161 	}
13162 
13163 	/* In case of release function, we get register number of refcounted
13164 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13165 	 */
13166 	if (meta.release_regno) {
13167 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13168 		if (err) {
13169 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13170 				func_name, meta.func_id);
13171 			return err;
13172 		}
13173 	}
13174 
13175 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13176 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13177 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13178 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13179 		insn_aux->insert_off = regs[BPF_REG_2].off;
13180 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13181 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13182 		if (err) {
13183 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13184 				func_name, meta.func_id);
13185 			return err;
13186 		}
13187 
13188 		err = release_reference(env, release_ref_obj_id);
13189 		if (err) {
13190 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13191 				func_name, meta.func_id);
13192 			return err;
13193 		}
13194 	}
13195 
13196 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13197 		if (!bpf_jit_supports_exceptions()) {
13198 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13199 				func_name, meta.func_id);
13200 			return -ENOTSUPP;
13201 		}
13202 		env->seen_exception = true;
13203 
13204 		/* In the case of the default callback, the cookie value passed
13205 		 * to bpf_throw becomes the return value of the program.
13206 		 */
13207 		if (!env->exception_callback_subprog) {
13208 			err = check_return_code(env, BPF_REG_1, "R1");
13209 			if (err < 0)
13210 				return err;
13211 		}
13212 	}
13213 
13214 	for (i = 0; i < CALLER_SAVED_REGS; i++)
13215 		mark_reg_not_init(env, regs, caller_saved[i]);
13216 
13217 	/* Check return type */
13218 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13219 
13220 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13221 		/* Only exception is bpf_obj_new_impl */
13222 		if (meta.btf != btf_vmlinux ||
13223 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
13224 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
13225 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
13226 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13227 			return -EINVAL;
13228 		}
13229 	}
13230 
13231 	if (btf_type_is_scalar(t)) {
13232 		mark_reg_unknown(env, regs, BPF_REG_0);
13233 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13234 	} else if (btf_type_is_ptr(t)) {
13235 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13236 
13237 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
13238 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13239 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13240 				struct btf_struct_meta *struct_meta;
13241 				struct btf *ret_btf;
13242 				u32 ret_btf_id;
13243 
13244 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13245 					return -ENOMEM;
13246 
13247 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
13248 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13249 					return -EINVAL;
13250 				}
13251 
13252 				ret_btf = env->prog->aux->btf;
13253 				ret_btf_id = meta.arg_constant.value;
13254 
13255 				/* This may be NULL due to user not supplying a BTF */
13256 				if (!ret_btf) {
13257 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13258 					return -EINVAL;
13259 				}
13260 
13261 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13262 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
13263 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13264 					return -EINVAL;
13265 				}
13266 
13267 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13268 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13269 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13270 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13271 						return -EINVAL;
13272 					}
13273 
13274 					if (!bpf_global_percpu_ma_set) {
13275 						mutex_lock(&bpf_percpu_ma_lock);
13276 						if (!bpf_global_percpu_ma_set) {
13277 							/* Charge memory allocated with bpf_global_percpu_ma to
13278 							 * root memcg. The obj_cgroup for root memcg is NULL.
13279 							 */
13280 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13281 							if (!err)
13282 								bpf_global_percpu_ma_set = true;
13283 						}
13284 						mutex_unlock(&bpf_percpu_ma_lock);
13285 						if (err)
13286 							return err;
13287 					}
13288 
13289 					mutex_lock(&bpf_percpu_ma_lock);
13290 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13291 					mutex_unlock(&bpf_percpu_ma_lock);
13292 					if (err)
13293 						return err;
13294 				}
13295 
13296 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13297 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13298 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13299 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13300 						return -EINVAL;
13301 					}
13302 
13303 					if (struct_meta) {
13304 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13305 						return -EINVAL;
13306 					}
13307 				}
13308 
13309 				mark_reg_known_zero(env, regs, BPF_REG_0);
13310 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13311 				regs[BPF_REG_0].btf = ret_btf;
13312 				regs[BPF_REG_0].btf_id = ret_btf_id;
13313 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13314 					regs[BPF_REG_0].type |= MEM_PERCPU;
13315 
13316 				insn_aux->obj_new_size = ret_t->size;
13317 				insn_aux->kptr_struct_meta = struct_meta;
13318 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13319 				mark_reg_known_zero(env, regs, BPF_REG_0);
13320 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13321 				regs[BPF_REG_0].btf = meta.arg_btf;
13322 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
13323 
13324 				insn_aux->kptr_struct_meta =
13325 					btf_find_struct_meta(meta.arg_btf,
13326 							     meta.arg_btf_id);
13327 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
13328 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
13329 				struct btf_field *field = meta.arg_list_head.field;
13330 
13331 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13332 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
13333 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
13334 				struct btf_field *field = meta.arg_rbtree_root.field;
13335 
13336 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13337 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13338 				mark_reg_known_zero(env, regs, BPF_REG_0);
13339 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13340 				regs[BPF_REG_0].btf = desc_btf;
13341 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
13342 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13343 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
13344 				if (!ret_t || !btf_type_is_struct(ret_t)) {
13345 					verbose(env,
13346 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
13347 					return -EINVAL;
13348 				}
13349 
13350 				mark_reg_known_zero(env, regs, BPF_REG_0);
13351 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13352 				regs[BPF_REG_0].btf = desc_btf;
13353 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
13354 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13355 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13356 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
13357 
13358 				mark_reg_known_zero(env, regs, BPF_REG_0);
13359 
13360 				if (!meta.arg_constant.found) {
13361 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
13362 					return -EFAULT;
13363 				}
13364 
13365 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
13366 
13367 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13368 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13369 
13370 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13371 					regs[BPF_REG_0].type |= MEM_RDONLY;
13372 				} else {
13373 					/* this will set env->seen_direct_write to true */
13374 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13375 						verbose(env, "the prog does not allow writes to packet data\n");
13376 						return -EINVAL;
13377 					}
13378 				}
13379 
13380 				if (!meta.initialized_dynptr.id) {
13381 					verbose(env, "verifier internal error: no dynptr id\n");
13382 					return -EFAULT;
13383 				}
13384 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
13385 
13386 				/* we don't need to set BPF_REG_0's ref obj id
13387 				 * because packet slices are not refcounted (see
13388 				 * dynptr_type_refcounted)
13389 				 */
13390 			} else {
13391 				verbose(env, "kernel function %s unhandled dynamic return type\n",
13392 					meta.func_name);
13393 				return -EFAULT;
13394 			}
13395 		} else if (btf_type_is_void(ptr_type)) {
13396 			/* kfunc returning 'void *' is equivalent to returning scalar */
13397 			mark_reg_unknown(env, regs, BPF_REG_0);
13398 		} else if (!__btf_type_is_struct(ptr_type)) {
13399 			if (!meta.r0_size) {
13400 				__u32 sz;
13401 
13402 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13403 					meta.r0_size = sz;
13404 					meta.r0_rdonly = true;
13405 				}
13406 			}
13407 			if (!meta.r0_size) {
13408 				ptr_type_name = btf_name_by_offset(desc_btf,
13409 								   ptr_type->name_off);
13410 				verbose(env,
13411 					"kernel function %s returns pointer type %s %s is not supported\n",
13412 					func_name,
13413 					btf_type_str(ptr_type),
13414 					ptr_type_name);
13415 				return -EINVAL;
13416 			}
13417 
13418 			mark_reg_known_zero(env, regs, BPF_REG_0);
13419 			regs[BPF_REG_0].type = PTR_TO_MEM;
13420 			regs[BPF_REG_0].mem_size = meta.r0_size;
13421 
13422 			if (meta.r0_rdonly)
13423 				regs[BPF_REG_0].type |= MEM_RDONLY;
13424 
13425 			/* Ensures we don't access the memory after a release_reference() */
13426 			if (meta.ref_obj_id)
13427 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
13428 		} else {
13429 			mark_reg_known_zero(env, regs, BPF_REG_0);
13430 			regs[BPF_REG_0].btf = desc_btf;
13431 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
13432 			regs[BPF_REG_0].btf_id = ptr_type_id;
13433 
13434 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13435 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
13436 
13437 			if (is_iter_next_kfunc(&meta)) {
13438 				struct bpf_reg_state *cur_iter;
13439 
13440 				cur_iter = get_iter_from_state(env->cur_state, &meta);
13441 
13442 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
13443 					regs[BPF_REG_0].type |= MEM_RCU;
13444 				else
13445 					regs[BPF_REG_0].type |= PTR_TRUSTED;
13446 			}
13447 		}
13448 
13449 		if (is_kfunc_ret_null(&meta)) {
13450 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13451 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13452 			regs[BPF_REG_0].id = ++env->id_gen;
13453 		}
13454 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13455 		if (is_kfunc_acquire(&meta)) {
13456 			int id = acquire_reference(env, insn_idx);
13457 
13458 			if (id < 0)
13459 				return id;
13460 			if (is_kfunc_ret_null(&meta))
13461 				regs[BPF_REG_0].id = id;
13462 			regs[BPF_REG_0].ref_obj_id = id;
13463 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
13464 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13465 		}
13466 
13467 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13468 			regs[BPF_REG_0].id = ++env->id_gen;
13469 	} else if (btf_type_is_void(t)) {
13470 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
13471 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
13472 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13473 				insn_aux->kptr_struct_meta =
13474 					btf_find_struct_meta(meta.arg_btf,
13475 							     meta.arg_btf_id);
13476 			}
13477 		}
13478 	}
13479 
13480 	nargs = btf_type_vlen(meta.func_proto);
13481 	args = (const struct btf_param *)(meta.func_proto + 1);
13482 	for (i = 0; i < nargs; i++) {
13483 		u32 regno = i + 1;
13484 
13485 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13486 		if (btf_type_is_ptr(t))
13487 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13488 		else
13489 			/* scalar. ensured by btf_check_kfunc_arg_match() */
13490 			mark_btf_func_reg_size(env, regno, t->size);
13491 	}
13492 
13493 	if (is_iter_next_kfunc(&meta)) {
13494 		err = process_iter_next_call(env, insn_idx, &meta);
13495 		if (err)
13496 			return err;
13497 	}
13498 
13499 	return 0;
13500 }
13501 
13502 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
13503 				  const struct bpf_reg_state *reg,
13504 				  enum bpf_reg_type type)
13505 {
13506 	bool known = tnum_is_const(reg->var_off);
13507 	s64 val = reg->var_off.value;
13508 	s64 smin = reg->smin_value;
13509 
13510 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13511 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13512 			reg_type_str(env, type), val);
13513 		return false;
13514 	}
13515 
13516 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
13517 		verbose(env, "%s pointer offset %d is not allowed\n",
13518 			reg_type_str(env, type), reg->off);
13519 		return false;
13520 	}
13521 
13522 	if (smin == S64_MIN) {
13523 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13524 			reg_type_str(env, type));
13525 		return false;
13526 	}
13527 
13528 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13529 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13530 			smin, reg_type_str(env, type));
13531 		return false;
13532 	}
13533 
13534 	return true;
13535 }
13536 
13537 enum {
13538 	REASON_BOUNDS	= -1,
13539 	REASON_TYPE	= -2,
13540 	REASON_PATHS	= -3,
13541 	REASON_LIMIT	= -4,
13542 	REASON_STACK	= -5,
13543 };
13544 
13545 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13546 			      u32 *alu_limit, bool mask_to_left)
13547 {
13548 	u32 max = 0, ptr_limit = 0;
13549 
13550 	switch (ptr_reg->type) {
13551 	case PTR_TO_STACK:
13552 		/* Offset 0 is out-of-bounds, but acceptable start for the
13553 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13554 		 * offset where we would need to deal with min/max bounds is
13555 		 * currently prohibited for unprivileged.
13556 		 */
13557 		max = MAX_BPF_STACK + mask_to_left;
13558 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
13559 		break;
13560 	case PTR_TO_MAP_VALUE:
13561 		max = ptr_reg->map_ptr->value_size;
13562 		ptr_limit = (mask_to_left ?
13563 			     ptr_reg->smin_value :
13564 			     ptr_reg->umax_value) + ptr_reg->off;
13565 		break;
13566 	default:
13567 		return REASON_TYPE;
13568 	}
13569 
13570 	if (ptr_limit >= max)
13571 		return REASON_LIMIT;
13572 	*alu_limit = ptr_limit;
13573 	return 0;
13574 }
13575 
13576 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
13577 				    const struct bpf_insn *insn)
13578 {
13579 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
13580 }
13581 
13582 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
13583 				       u32 alu_state, u32 alu_limit)
13584 {
13585 	/* If we arrived here from different branches with different
13586 	 * state or limits to sanitize, then this won't work.
13587 	 */
13588 	if (aux->alu_state &&
13589 	    (aux->alu_state != alu_state ||
13590 	     aux->alu_limit != alu_limit))
13591 		return REASON_PATHS;
13592 
13593 	/* Corresponding fixup done in do_misc_fixups(). */
13594 	aux->alu_state = alu_state;
13595 	aux->alu_limit = alu_limit;
13596 	return 0;
13597 }
13598 
13599 static int sanitize_val_alu(struct bpf_verifier_env *env,
13600 			    struct bpf_insn *insn)
13601 {
13602 	struct bpf_insn_aux_data *aux = cur_aux(env);
13603 
13604 	if (can_skip_alu_sanitation(env, insn))
13605 		return 0;
13606 
13607 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13608 }
13609 
13610 static bool sanitize_needed(u8 opcode)
13611 {
13612 	return opcode == BPF_ADD || opcode == BPF_SUB;
13613 }
13614 
13615 struct bpf_sanitize_info {
13616 	struct bpf_insn_aux_data aux;
13617 	bool mask_to_left;
13618 };
13619 
13620 static struct bpf_verifier_state *
13621 sanitize_speculative_path(struct bpf_verifier_env *env,
13622 			  const struct bpf_insn *insn,
13623 			  u32 next_idx, u32 curr_idx)
13624 {
13625 	struct bpf_verifier_state *branch;
13626 	struct bpf_reg_state *regs;
13627 
13628 	branch = push_stack(env, next_idx, curr_idx, true);
13629 	if (branch && insn) {
13630 		regs = branch->frame[branch->curframe]->regs;
13631 		if (BPF_SRC(insn->code) == BPF_K) {
13632 			mark_reg_unknown(env, regs, insn->dst_reg);
13633 		} else if (BPF_SRC(insn->code) == BPF_X) {
13634 			mark_reg_unknown(env, regs, insn->dst_reg);
13635 			mark_reg_unknown(env, regs, insn->src_reg);
13636 		}
13637 	}
13638 	return branch;
13639 }
13640 
13641 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13642 			    struct bpf_insn *insn,
13643 			    const struct bpf_reg_state *ptr_reg,
13644 			    const struct bpf_reg_state *off_reg,
13645 			    struct bpf_reg_state *dst_reg,
13646 			    struct bpf_sanitize_info *info,
13647 			    const bool commit_window)
13648 {
13649 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13650 	struct bpf_verifier_state *vstate = env->cur_state;
13651 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13652 	bool off_is_neg = off_reg->smin_value < 0;
13653 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13654 	u8 opcode = BPF_OP(insn->code);
13655 	u32 alu_state, alu_limit;
13656 	struct bpf_reg_state tmp;
13657 	bool ret;
13658 	int err;
13659 
13660 	if (can_skip_alu_sanitation(env, insn))
13661 		return 0;
13662 
13663 	/* We already marked aux for masking from non-speculative
13664 	 * paths, thus we got here in the first place. We only care
13665 	 * to explore bad access from here.
13666 	 */
13667 	if (vstate->speculative)
13668 		goto do_sim;
13669 
13670 	if (!commit_window) {
13671 		if (!tnum_is_const(off_reg->var_off) &&
13672 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
13673 			return REASON_BOUNDS;
13674 
13675 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13676 				     (opcode == BPF_SUB && !off_is_neg);
13677 	}
13678 
13679 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13680 	if (err < 0)
13681 		return err;
13682 
13683 	if (commit_window) {
13684 		/* In commit phase we narrow the masking window based on
13685 		 * the observed pointer move after the simulated operation.
13686 		 */
13687 		alu_state = info->aux.alu_state;
13688 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13689 	} else {
13690 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13691 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13692 		alu_state |= ptr_is_dst_reg ?
13693 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13694 
13695 		/* Limit pruning on unknown scalars to enable deep search for
13696 		 * potential masking differences from other program paths.
13697 		 */
13698 		if (!off_is_imm)
13699 			env->explore_alu_limits = true;
13700 	}
13701 
13702 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13703 	if (err < 0)
13704 		return err;
13705 do_sim:
13706 	/* If we're in commit phase, we're done here given we already
13707 	 * pushed the truncated dst_reg into the speculative verification
13708 	 * stack.
13709 	 *
13710 	 * Also, when register is a known constant, we rewrite register-based
13711 	 * operation to immediate-based, and thus do not need masking (and as
13712 	 * a consequence, do not need to simulate the zero-truncation either).
13713 	 */
13714 	if (commit_window || off_is_imm)
13715 		return 0;
13716 
13717 	/* Simulate and find potential out-of-bounds access under
13718 	 * speculative execution from truncation as a result of
13719 	 * masking when off was not within expected range. If off
13720 	 * sits in dst, then we temporarily need to move ptr there
13721 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13722 	 * for cases where we use K-based arithmetic in one direction
13723 	 * and truncated reg-based in the other in order to explore
13724 	 * bad access.
13725 	 */
13726 	if (!ptr_is_dst_reg) {
13727 		tmp = *dst_reg;
13728 		copy_register_state(dst_reg, ptr_reg);
13729 	}
13730 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
13731 					env->insn_idx);
13732 	if (!ptr_is_dst_reg && ret)
13733 		*dst_reg = tmp;
13734 	return !ret ? REASON_STACK : 0;
13735 }
13736 
13737 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13738 {
13739 	struct bpf_verifier_state *vstate = env->cur_state;
13740 
13741 	/* If we simulate paths under speculation, we don't update the
13742 	 * insn as 'seen' such that when we verify unreachable paths in
13743 	 * the non-speculative domain, sanitize_dead_code() can still
13744 	 * rewrite/sanitize them.
13745 	 */
13746 	if (!vstate->speculative)
13747 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13748 }
13749 
13750 static int sanitize_err(struct bpf_verifier_env *env,
13751 			const struct bpf_insn *insn, int reason,
13752 			const struct bpf_reg_state *off_reg,
13753 			const struct bpf_reg_state *dst_reg)
13754 {
13755 	static const char *err = "pointer arithmetic with it prohibited for !root";
13756 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13757 	u32 dst = insn->dst_reg, src = insn->src_reg;
13758 
13759 	switch (reason) {
13760 	case REASON_BOUNDS:
13761 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13762 			off_reg == dst_reg ? dst : src, err);
13763 		break;
13764 	case REASON_TYPE:
13765 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13766 			off_reg == dst_reg ? src : dst, err);
13767 		break;
13768 	case REASON_PATHS:
13769 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13770 			dst, op, err);
13771 		break;
13772 	case REASON_LIMIT:
13773 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13774 			dst, op, err);
13775 		break;
13776 	case REASON_STACK:
13777 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13778 			dst, err);
13779 		break;
13780 	default:
13781 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13782 			reason);
13783 		break;
13784 	}
13785 
13786 	return -EACCES;
13787 }
13788 
13789 /* check that stack access falls within stack limits and that 'reg' doesn't
13790  * have a variable offset.
13791  *
13792  * Variable offset is prohibited for unprivileged mode for simplicity since it
13793  * requires corresponding support in Spectre masking for stack ALU.  See also
13794  * retrieve_ptr_limit().
13795  *
13796  *
13797  * 'off' includes 'reg->off'.
13798  */
13799 static int check_stack_access_for_ptr_arithmetic(
13800 				struct bpf_verifier_env *env,
13801 				int regno,
13802 				const struct bpf_reg_state *reg,
13803 				int off)
13804 {
13805 	if (!tnum_is_const(reg->var_off)) {
13806 		char tn_buf[48];
13807 
13808 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13809 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13810 			regno, tn_buf, off);
13811 		return -EACCES;
13812 	}
13813 
13814 	if (off >= 0 || off < -MAX_BPF_STACK) {
13815 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13816 			"prohibited for !root; off=%d\n", regno, off);
13817 		return -EACCES;
13818 	}
13819 
13820 	return 0;
13821 }
13822 
13823 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13824 				 const struct bpf_insn *insn,
13825 				 const struct bpf_reg_state *dst_reg)
13826 {
13827 	u32 dst = insn->dst_reg;
13828 
13829 	/* For unprivileged we require that resulting offset must be in bounds
13830 	 * in order to be able to sanitize access later on.
13831 	 */
13832 	if (env->bypass_spec_v1)
13833 		return 0;
13834 
13835 	switch (dst_reg->type) {
13836 	case PTR_TO_STACK:
13837 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13838 					dst_reg->off + dst_reg->var_off.value))
13839 			return -EACCES;
13840 		break;
13841 	case PTR_TO_MAP_VALUE:
13842 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13843 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13844 				"prohibited for !root\n", dst);
13845 			return -EACCES;
13846 		}
13847 		break;
13848 	default:
13849 		break;
13850 	}
13851 
13852 	return 0;
13853 }
13854 
13855 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13856  * Caller should also handle BPF_MOV case separately.
13857  * If we return -EACCES, caller may want to try again treating pointer as a
13858  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13859  */
13860 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13861 				   struct bpf_insn *insn,
13862 				   const struct bpf_reg_state *ptr_reg,
13863 				   const struct bpf_reg_state *off_reg)
13864 {
13865 	struct bpf_verifier_state *vstate = env->cur_state;
13866 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13867 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13868 	bool known = tnum_is_const(off_reg->var_off);
13869 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13870 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13871 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13872 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13873 	struct bpf_sanitize_info info = {};
13874 	u8 opcode = BPF_OP(insn->code);
13875 	u32 dst = insn->dst_reg;
13876 	int ret;
13877 
13878 	dst_reg = &regs[dst];
13879 
13880 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13881 	    smin_val > smax_val || umin_val > umax_val) {
13882 		/* Taint dst register if offset had invalid bounds derived from
13883 		 * e.g. dead branches.
13884 		 */
13885 		__mark_reg_unknown(env, dst_reg);
13886 		return 0;
13887 	}
13888 
13889 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13890 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13891 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13892 			__mark_reg_unknown(env, dst_reg);
13893 			return 0;
13894 		}
13895 
13896 		verbose(env,
13897 			"R%d 32-bit pointer arithmetic prohibited\n",
13898 			dst);
13899 		return -EACCES;
13900 	}
13901 
13902 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13903 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13904 			dst, reg_type_str(env, ptr_reg->type));
13905 		return -EACCES;
13906 	}
13907 
13908 	switch (base_type(ptr_reg->type)) {
13909 	case PTR_TO_CTX:
13910 	case PTR_TO_MAP_VALUE:
13911 	case PTR_TO_MAP_KEY:
13912 	case PTR_TO_STACK:
13913 	case PTR_TO_PACKET_META:
13914 	case PTR_TO_PACKET:
13915 	case PTR_TO_TP_BUFFER:
13916 	case PTR_TO_BTF_ID:
13917 	case PTR_TO_MEM:
13918 	case PTR_TO_BUF:
13919 	case PTR_TO_FUNC:
13920 	case CONST_PTR_TO_DYNPTR:
13921 		break;
13922 	case PTR_TO_FLOW_KEYS:
13923 		if (known)
13924 			break;
13925 		fallthrough;
13926 	case CONST_PTR_TO_MAP:
13927 		/* smin_val represents the known value */
13928 		if (known && smin_val == 0 && opcode == BPF_ADD)
13929 			break;
13930 		fallthrough;
13931 	default:
13932 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13933 			dst, reg_type_str(env, ptr_reg->type));
13934 		return -EACCES;
13935 	}
13936 
13937 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13938 	 * The id may be overwritten later if we create a new variable offset.
13939 	 */
13940 	dst_reg->type = ptr_reg->type;
13941 	dst_reg->id = ptr_reg->id;
13942 
13943 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13944 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13945 		return -EINVAL;
13946 
13947 	/* pointer types do not carry 32-bit bounds at the moment. */
13948 	__mark_reg32_unbounded(dst_reg);
13949 
13950 	if (sanitize_needed(opcode)) {
13951 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13952 				       &info, false);
13953 		if (ret < 0)
13954 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13955 	}
13956 
13957 	switch (opcode) {
13958 	case BPF_ADD:
13959 		/* We can take a fixed offset as long as it doesn't overflow
13960 		 * the s32 'off' field
13961 		 */
13962 		if (known && (ptr_reg->off + smin_val ==
13963 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13964 			/* pointer += K.  Accumulate it into fixed offset */
13965 			dst_reg->smin_value = smin_ptr;
13966 			dst_reg->smax_value = smax_ptr;
13967 			dst_reg->umin_value = umin_ptr;
13968 			dst_reg->umax_value = umax_ptr;
13969 			dst_reg->var_off = ptr_reg->var_off;
13970 			dst_reg->off = ptr_reg->off + smin_val;
13971 			dst_reg->raw = ptr_reg->raw;
13972 			break;
13973 		}
13974 		/* A new variable offset is created.  Note that off_reg->off
13975 		 * == 0, since it's a scalar.
13976 		 * dst_reg gets the pointer type and since some positive
13977 		 * integer value was added to the pointer, give it a new 'id'
13978 		 * if it's a PTR_TO_PACKET.
13979 		 * this creates a new 'base' pointer, off_reg (variable) gets
13980 		 * added into the variable offset, and we copy the fixed offset
13981 		 * from ptr_reg.
13982 		 */
13983 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13984 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13985 			dst_reg->smin_value = S64_MIN;
13986 			dst_reg->smax_value = S64_MAX;
13987 		}
13988 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13989 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13990 			dst_reg->umin_value = 0;
13991 			dst_reg->umax_value = U64_MAX;
13992 		}
13993 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13994 		dst_reg->off = ptr_reg->off;
13995 		dst_reg->raw = ptr_reg->raw;
13996 		if (reg_is_pkt_pointer(ptr_reg)) {
13997 			dst_reg->id = ++env->id_gen;
13998 			/* something was added to pkt_ptr, set range to zero */
13999 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14000 		}
14001 		break;
14002 	case BPF_SUB:
14003 		if (dst_reg == off_reg) {
14004 			/* scalar -= pointer.  Creates an unknown scalar */
14005 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14006 				dst);
14007 			return -EACCES;
14008 		}
14009 		/* We don't allow subtraction from FP, because (according to
14010 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14011 		 * be able to deal with it.
14012 		 */
14013 		if (ptr_reg->type == PTR_TO_STACK) {
14014 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14015 				dst);
14016 			return -EACCES;
14017 		}
14018 		if (known && (ptr_reg->off - smin_val ==
14019 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14020 			/* pointer -= K.  Subtract it from fixed offset */
14021 			dst_reg->smin_value = smin_ptr;
14022 			dst_reg->smax_value = smax_ptr;
14023 			dst_reg->umin_value = umin_ptr;
14024 			dst_reg->umax_value = umax_ptr;
14025 			dst_reg->var_off = ptr_reg->var_off;
14026 			dst_reg->id = ptr_reg->id;
14027 			dst_reg->off = ptr_reg->off - smin_val;
14028 			dst_reg->raw = ptr_reg->raw;
14029 			break;
14030 		}
14031 		/* A new variable offset is created.  If the subtrahend is known
14032 		 * nonnegative, then any reg->range we had before is still good.
14033 		 */
14034 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14035 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14036 			/* Overflow possible, we know nothing */
14037 			dst_reg->smin_value = S64_MIN;
14038 			dst_reg->smax_value = S64_MAX;
14039 		}
14040 		if (umin_ptr < umax_val) {
14041 			/* Overflow possible, we know nothing */
14042 			dst_reg->umin_value = 0;
14043 			dst_reg->umax_value = U64_MAX;
14044 		} else {
14045 			/* Cannot overflow (as long as bounds are consistent) */
14046 			dst_reg->umin_value = umin_ptr - umax_val;
14047 			dst_reg->umax_value = umax_ptr - umin_val;
14048 		}
14049 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14050 		dst_reg->off = ptr_reg->off;
14051 		dst_reg->raw = ptr_reg->raw;
14052 		if (reg_is_pkt_pointer(ptr_reg)) {
14053 			dst_reg->id = ++env->id_gen;
14054 			/* something was added to pkt_ptr, set range to zero */
14055 			if (smin_val < 0)
14056 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14057 		}
14058 		break;
14059 	case BPF_AND:
14060 	case BPF_OR:
14061 	case BPF_XOR:
14062 		/* bitwise ops on pointers are troublesome, prohibit. */
14063 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14064 			dst, bpf_alu_string[opcode >> 4]);
14065 		return -EACCES;
14066 	default:
14067 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14068 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14069 			dst, bpf_alu_string[opcode >> 4]);
14070 		return -EACCES;
14071 	}
14072 
14073 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14074 		return -EINVAL;
14075 	reg_bounds_sync(dst_reg);
14076 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
14077 		return -EACCES;
14078 	if (sanitize_needed(opcode)) {
14079 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14080 				       &info, true);
14081 		if (ret < 0)
14082 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14083 	}
14084 
14085 	return 0;
14086 }
14087 
14088 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14089 				 struct bpf_reg_state *src_reg)
14090 {
14091 	s32 *dst_smin = &dst_reg->s32_min_value;
14092 	s32 *dst_smax = &dst_reg->s32_max_value;
14093 	u32 *dst_umin = &dst_reg->u32_min_value;
14094 	u32 *dst_umax = &dst_reg->u32_max_value;
14095 
14096 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14097 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14098 		*dst_smin = S32_MIN;
14099 		*dst_smax = S32_MAX;
14100 	}
14101 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
14102 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
14103 		*dst_umin = 0;
14104 		*dst_umax = U32_MAX;
14105 	}
14106 }
14107 
14108 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14109 			       struct bpf_reg_state *src_reg)
14110 {
14111 	s64 *dst_smin = &dst_reg->smin_value;
14112 	s64 *dst_smax = &dst_reg->smax_value;
14113 	u64 *dst_umin = &dst_reg->umin_value;
14114 	u64 *dst_umax = &dst_reg->umax_value;
14115 
14116 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14117 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14118 		*dst_smin = S64_MIN;
14119 		*dst_smax = S64_MAX;
14120 	}
14121 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
14122 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
14123 		*dst_umin = 0;
14124 		*dst_umax = U64_MAX;
14125 	}
14126 }
14127 
14128 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14129 				 struct bpf_reg_state *src_reg)
14130 {
14131 	s32 *dst_smin = &dst_reg->s32_min_value;
14132 	s32 *dst_smax = &dst_reg->s32_max_value;
14133 	u32 umin_val = src_reg->u32_min_value;
14134 	u32 umax_val = src_reg->u32_max_value;
14135 
14136 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14137 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14138 		/* Overflow possible, we know nothing */
14139 		*dst_smin = S32_MIN;
14140 		*dst_smax = S32_MAX;
14141 	}
14142 	if (dst_reg->u32_min_value < umax_val) {
14143 		/* Overflow possible, we know nothing */
14144 		dst_reg->u32_min_value = 0;
14145 		dst_reg->u32_max_value = U32_MAX;
14146 	} else {
14147 		/* Cannot overflow (as long as bounds are consistent) */
14148 		dst_reg->u32_min_value -= umax_val;
14149 		dst_reg->u32_max_value -= umin_val;
14150 	}
14151 }
14152 
14153 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14154 			       struct bpf_reg_state *src_reg)
14155 {
14156 	s64 *dst_smin = &dst_reg->smin_value;
14157 	s64 *dst_smax = &dst_reg->smax_value;
14158 	u64 umin_val = src_reg->umin_value;
14159 	u64 umax_val = src_reg->umax_value;
14160 
14161 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14162 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14163 		/* Overflow possible, we know nothing */
14164 		*dst_smin = S64_MIN;
14165 		*dst_smax = S64_MAX;
14166 	}
14167 	if (dst_reg->umin_value < umax_val) {
14168 		/* Overflow possible, we know nothing */
14169 		dst_reg->umin_value = 0;
14170 		dst_reg->umax_value = U64_MAX;
14171 	} else {
14172 		/* Cannot overflow (as long as bounds are consistent) */
14173 		dst_reg->umin_value -= umax_val;
14174 		dst_reg->umax_value -= umin_val;
14175 	}
14176 }
14177 
14178 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14179 				 struct bpf_reg_state *src_reg)
14180 {
14181 	s32 *dst_smin = &dst_reg->s32_min_value;
14182 	s32 *dst_smax = &dst_reg->s32_max_value;
14183 	u32 *dst_umin = &dst_reg->u32_min_value;
14184 	u32 *dst_umax = &dst_reg->u32_max_value;
14185 	s32 tmp_prod[4];
14186 
14187 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14188 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14189 		/* Overflow possible, we know nothing */
14190 		*dst_umin = 0;
14191 		*dst_umax = U32_MAX;
14192 	}
14193 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14194 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14195 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14196 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14197 		/* Overflow possible, we know nothing */
14198 		*dst_smin = S32_MIN;
14199 		*dst_smax = S32_MAX;
14200 	} else {
14201 		*dst_smin = min_array(tmp_prod, 4);
14202 		*dst_smax = max_array(tmp_prod, 4);
14203 	}
14204 }
14205 
14206 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14207 			       struct bpf_reg_state *src_reg)
14208 {
14209 	s64 *dst_smin = &dst_reg->smin_value;
14210 	s64 *dst_smax = &dst_reg->smax_value;
14211 	u64 *dst_umin = &dst_reg->umin_value;
14212 	u64 *dst_umax = &dst_reg->umax_value;
14213 	s64 tmp_prod[4];
14214 
14215 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14216 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14217 		/* Overflow possible, we know nothing */
14218 		*dst_umin = 0;
14219 		*dst_umax = U64_MAX;
14220 	}
14221 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14222 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14223 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14224 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14225 		/* Overflow possible, we know nothing */
14226 		*dst_smin = S64_MIN;
14227 		*dst_smax = S64_MAX;
14228 	} else {
14229 		*dst_smin = min_array(tmp_prod, 4);
14230 		*dst_smax = max_array(tmp_prod, 4);
14231 	}
14232 }
14233 
14234 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14235 				 struct bpf_reg_state *src_reg)
14236 {
14237 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14238 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14239 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14240 	u32 umax_val = src_reg->u32_max_value;
14241 
14242 	if (src_known && dst_known) {
14243 		__mark_reg32_known(dst_reg, var32_off.value);
14244 		return;
14245 	}
14246 
14247 	/* We get our minimum from the var_off, since that's inherently
14248 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14249 	 */
14250 	dst_reg->u32_min_value = var32_off.value;
14251 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14252 
14253 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14254 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14255 	 */
14256 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14257 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14258 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14259 	} else {
14260 		dst_reg->s32_min_value = S32_MIN;
14261 		dst_reg->s32_max_value = S32_MAX;
14262 	}
14263 }
14264 
14265 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14266 			       struct bpf_reg_state *src_reg)
14267 {
14268 	bool src_known = tnum_is_const(src_reg->var_off);
14269 	bool dst_known = tnum_is_const(dst_reg->var_off);
14270 	u64 umax_val = src_reg->umax_value;
14271 
14272 	if (src_known && dst_known) {
14273 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14274 		return;
14275 	}
14276 
14277 	/* We get our minimum from the var_off, since that's inherently
14278 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14279 	 */
14280 	dst_reg->umin_value = dst_reg->var_off.value;
14281 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14282 
14283 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14284 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14285 	 */
14286 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14287 		dst_reg->smin_value = dst_reg->umin_value;
14288 		dst_reg->smax_value = dst_reg->umax_value;
14289 	} else {
14290 		dst_reg->smin_value = S64_MIN;
14291 		dst_reg->smax_value = S64_MAX;
14292 	}
14293 	/* We may learn something more from the var_off */
14294 	__update_reg_bounds(dst_reg);
14295 }
14296 
14297 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14298 				struct bpf_reg_state *src_reg)
14299 {
14300 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14301 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14302 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14303 	u32 umin_val = src_reg->u32_min_value;
14304 
14305 	if (src_known && dst_known) {
14306 		__mark_reg32_known(dst_reg, var32_off.value);
14307 		return;
14308 	}
14309 
14310 	/* We get our maximum from the var_off, and our minimum is the
14311 	 * maximum of the operands' minima
14312 	 */
14313 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
14314 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14315 
14316 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14317 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14318 	 */
14319 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14320 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14321 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14322 	} else {
14323 		dst_reg->s32_min_value = S32_MIN;
14324 		dst_reg->s32_max_value = S32_MAX;
14325 	}
14326 }
14327 
14328 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14329 			      struct bpf_reg_state *src_reg)
14330 {
14331 	bool src_known = tnum_is_const(src_reg->var_off);
14332 	bool dst_known = tnum_is_const(dst_reg->var_off);
14333 	u64 umin_val = src_reg->umin_value;
14334 
14335 	if (src_known && dst_known) {
14336 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14337 		return;
14338 	}
14339 
14340 	/* We get our maximum from the var_off, and our minimum is the
14341 	 * maximum of the operands' minima
14342 	 */
14343 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14344 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14345 
14346 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14347 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14348 	 */
14349 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14350 		dst_reg->smin_value = dst_reg->umin_value;
14351 		dst_reg->smax_value = dst_reg->umax_value;
14352 	} else {
14353 		dst_reg->smin_value = S64_MIN;
14354 		dst_reg->smax_value = S64_MAX;
14355 	}
14356 	/* We may learn something more from the var_off */
14357 	__update_reg_bounds(dst_reg);
14358 }
14359 
14360 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14361 				 struct bpf_reg_state *src_reg)
14362 {
14363 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14364 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14365 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14366 
14367 	if (src_known && dst_known) {
14368 		__mark_reg32_known(dst_reg, var32_off.value);
14369 		return;
14370 	}
14371 
14372 	/* We get both minimum and maximum from the var32_off. */
14373 	dst_reg->u32_min_value = var32_off.value;
14374 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14375 
14376 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14377 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14378 	 */
14379 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14380 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14381 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14382 	} else {
14383 		dst_reg->s32_min_value = S32_MIN;
14384 		dst_reg->s32_max_value = S32_MAX;
14385 	}
14386 }
14387 
14388 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14389 			       struct bpf_reg_state *src_reg)
14390 {
14391 	bool src_known = tnum_is_const(src_reg->var_off);
14392 	bool dst_known = tnum_is_const(dst_reg->var_off);
14393 
14394 	if (src_known && dst_known) {
14395 		/* dst_reg->var_off.value has been updated earlier */
14396 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14397 		return;
14398 	}
14399 
14400 	/* We get both minimum and maximum from the var_off. */
14401 	dst_reg->umin_value = dst_reg->var_off.value;
14402 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14403 
14404 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14405 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14406 	 */
14407 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14408 		dst_reg->smin_value = dst_reg->umin_value;
14409 		dst_reg->smax_value = dst_reg->umax_value;
14410 	} else {
14411 		dst_reg->smin_value = S64_MIN;
14412 		dst_reg->smax_value = S64_MAX;
14413 	}
14414 
14415 	__update_reg_bounds(dst_reg);
14416 }
14417 
14418 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14419 				   u64 umin_val, u64 umax_val)
14420 {
14421 	/* We lose all sign bit information (except what we can pick
14422 	 * up from var_off)
14423 	 */
14424 	dst_reg->s32_min_value = S32_MIN;
14425 	dst_reg->s32_max_value = S32_MAX;
14426 	/* If we might shift our top bit out, then we know nothing */
14427 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
14428 		dst_reg->u32_min_value = 0;
14429 		dst_reg->u32_max_value = U32_MAX;
14430 	} else {
14431 		dst_reg->u32_min_value <<= umin_val;
14432 		dst_reg->u32_max_value <<= umax_val;
14433 	}
14434 }
14435 
14436 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14437 				 struct bpf_reg_state *src_reg)
14438 {
14439 	u32 umax_val = src_reg->u32_max_value;
14440 	u32 umin_val = src_reg->u32_min_value;
14441 	/* u32 alu operation will zext upper bits */
14442 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14443 
14444 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14445 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14446 	/* Not required but being careful mark reg64 bounds as unknown so
14447 	 * that we are forced to pick them up from tnum and zext later and
14448 	 * if some path skips this step we are still safe.
14449 	 */
14450 	__mark_reg64_unbounded(dst_reg);
14451 	__update_reg32_bounds(dst_reg);
14452 }
14453 
14454 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14455 				   u64 umin_val, u64 umax_val)
14456 {
14457 	/* Special case <<32 because it is a common compiler pattern to sign
14458 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
14459 	 * positive we know this shift will also be positive so we can track
14460 	 * bounds correctly. Otherwise we lose all sign bit information except
14461 	 * what we can pick up from var_off. Perhaps we can generalize this
14462 	 * later to shifts of any length.
14463 	 */
14464 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
14465 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
14466 	else
14467 		dst_reg->smax_value = S64_MAX;
14468 
14469 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
14470 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
14471 	else
14472 		dst_reg->smin_value = S64_MIN;
14473 
14474 	/* If we might shift our top bit out, then we know nothing */
14475 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
14476 		dst_reg->umin_value = 0;
14477 		dst_reg->umax_value = U64_MAX;
14478 	} else {
14479 		dst_reg->umin_value <<= umin_val;
14480 		dst_reg->umax_value <<= umax_val;
14481 	}
14482 }
14483 
14484 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14485 			       struct bpf_reg_state *src_reg)
14486 {
14487 	u64 umax_val = src_reg->umax_value;
14488 	u64 umin_val = src_reg->umin_value;
14489 
14490 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14491 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14492 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14493 
14494 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14495 	/* We may learn something more from the var_off */
14496 	__update_reg_bounds(dst_reg);
14497 }
14498 
14499 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14500 				 struct bpf_reg_state *src_reg)
14501 {
14502 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14503 	u32 umax_val = src_reg->u32_max_value;
14504 	u32 umin_val = src_reg->u32_min_value;
14505 
14506 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14507 	 * be negative, then either:
14508 	 * 1) src_reg might be zero, so the sign bit of the result is
14509 	 *    unknown, so we lose our signed bounds
14510 	 * 2) it's known negative, thus the unsigned bounds capture the
14511 	 *    signed bounds
14512 	 * 3) the signed bounds cross zero, so they tell us nothing
14513 	 *    about the result
14514 	 * If the value in dst_reg is known nonnegative, then again the
14515 	 * unsigned bounds capture the signed bounds.
14516 	 * Thus, in all cases it suffices to blow away our signed bounds
14517 	 * and rely on inferring new ones from the unsigned bounds and
14518 	 * var_off of the result.
14519 	 */
14520 	dst_reg->s32_min_value = S32_MIN;
14521 	dst_reg->s32_max_value = S32_MAX;
14522 
14523 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14524 	dst_reg->u32_min_value >>= umax_val;
14525 	dst_reg->u32_max_value >>= umin_val;
14526 
14527 	__mark_reg64_unbounded(dst_reg);
14528 	__update_reg32_bounds(dst_reg);
14529 }
14530 
14531 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14532 			       struct bpf_reg_state *src_reg)
14533 {
14534 	u64 umax_val = src_reg->umax_value;
14535 	u64 umin_val = src_reg->umin_value;
14536 
14537 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14538 	 * be negative, then either:
14539 	 * 1) src_reg might be zero, so the sign bit of the result is
14540 	 *    unknown, so we lose our signed bounds
14541 	 * 2) it's known negative, thus the unsigned bounds capture the
14542 	 *    signed bounds
14543 	 * 3) the signed bounds cross zero, so they tell us nothing
14544 	 *    about the result
14545 	 * If the value in dst_reg is known nonnegative, then again the
14546 	 * unsigned bounds capture the signed bounds.
14547 	 * Thus, in all cases it suffices to blow away our signed bounds
14548 	 * and rely on inferring new ones from the unsigned bounds and
14549 	 * var_off of the result.
14550 	 */
14551 	dst_reg->smin_value = S64_MIN;
14552 	dst_reg->smax_value = S64_MAX;
14553 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14554 	dst_reg->umin_value >>= umax_val;
14555 	dst_reg->umax_value >>= umin_val;
14556 
14557 	/* Its not easy to operate on alu32 bounds here because it depends
14558 	 * on bits being shifted in. Take easy way out and mark unbounded
14559 	 * so we can recalculate later from tnum.
14560 	 */
14561 	__mark_reg32_unbounded(dst_reg);
14562 	__update_reg_bounds(dst_reg);
14563 }
14564 
14565 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
14566 				  struct bpf_reg_state *src_reg)
14567 {
14568 	u64 umin_val = src_reg->u32_min_value;
14569 
14570 	/* Upon reaching here, src_known is true and
14571 	 * umax_val is equal to umin_val.
14572 	 */
14573 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
14574 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
14575 
14576 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
14577 
14578 	/* blow away the dst_reg umin_value/umax_value and rely on
14579 	 * dst_reg var_off to refine the result.
14580 	 */
14581 	dst_reg->u32_min_value = 0;
14582 	dst_reg->u32_max_value = U32_MAX;
14583 
14584 	__mark_reg64_unbounded(dst_reg);
14585 	__update_reg32_bounds(dst_reg);
14586 }
14587 
14588 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14589 				struct bpf_reg_state *src_reg)
14590 {
14591 	u64 umin_val = src_reg->umin_value;
14592 
14593 	/* Upon reaching here, src_known is true and umax_val is equal
14594 	 * to umin_val.
14595 	 */
14596 	dst_reg->smin_value >>= umin_val;
14597 	dst_reg->smax_value >>= umin_val;
14598 
14599 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14600 
14601 	/* blow away the dst_reg umin_value/umax_value and rely on
14602 	 * dst_reg var_off to refine the result.
14603 	 */
14604 	dst_reg->umin_value = 0;
14605 	dst_reg->umax_value = U64_MAX;
14606 
14607 	/* Its not easy to operate on alu32 bounds here because it depends
14608 	 * on bits being shifted in from upper 32-bits. Take easy way out
14609 	 * and mark unbounded so we can recalculate later from tnum.
14610 	 */
14611 	__mark_reg32_unbounded(dst_reg);
14612 	__update_reg_bounds(dst_reg);
14613 }
14614 
14615 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14616 					     const struct bpf_reg_state *src_reg)
14617 {
14618 	bool src_is_const = false;
14619 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14620 
14621 	if (insn_bitness == 32) {
14622 		if (tnum_subreg_is_const(src_reg->var_off)
14623 		    && src_reg->s32_min_value == src_reg->s32_max_value
14624 		    && src_reg->u32_min_value == src_reg->u32_max_value)
14625 			src_is_const = true;
14626 	} else {
14627 		if (tnum_is_const(src_reg->var_off)
14628 		    && src_reg->smin_value == src_reg->smax_value
14629 		    && src_reg->umin_value == src_reg->umax_value)
14630 			src_is_const = true;
14631 	}
14632 
14633 	switch (BPF_OP(insn->code)) {
14634 	case BPF_ADD:
14635 	case BPF_SUB:
14636 	case BPF_AND:
14637 	case BPF_XOR:
14638 	case BPF_OR:
14639 	case BPF_MUL:
14640 		return true;
14641 
14642 	/* Shift operators range is only computable if shift dimension operand
14643 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14644 	 * includes shifts by a negative number.
14645 	 */
14646 	case BPF_LSH:
14647 	case BPF_RSH:
14648 	case BPF_ARSH:
14649 		return (src_is_const && src_reg->umax_value < insn_bitness);
14650 	default:
14651 		return false;
14652 	}
14653 }
14654 
14655 /* WARNING: This function does calculations on 64-bit values, but the actual
14656  * execution may occur on 32-bit values. Therefore, things like bitshifts
14657  * need extra checks in the 32-bit case.
14658  */
14659 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14660 				      struct bpf_insn *insn,
14661 				      struct bpf_reg_state *dst_reg,
14662 				      struct bpf_reg_state src_reg)
14663 {
14664 	u8 opcode = BPF_OP(insn->code);
14665 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14666 	int ret;
14667 
14668 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14669 		__mark_reg_unknown(env, dst_reg);
14670 		return 0;
14671 	}
14672 
14673 	if (sanitize_needed(opcode)) {
14674 		ret = sanitize_val_alu(env, insn);
14675 		if (ret < 0)
14676 			return sanitize_err(env, insn, ret, NULL, NULL);
14677 	}
14678 
14679 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14680 	 * There are two classes of instructions: The first class we track both
14681 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14682 	 * greatest amount of precision when alu operations are mixed with jmp32
14683 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14684 	 * and BPF_OR. This is possible because these ops have fairly easy to
14685 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14686 	 * See alu32 verifier tests for examples. The second class of
14687 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14688 	 * with regards to tracking sign/unsigned bounds because the bits may
14689 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14690 	 * the reg unbounded in the subreg bound space and use the resulting
14691 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14692 	 */
14693 	switch (opcode) {
14694 	case BPF_ADD:
14695 		scalar32_min_max_add(dst_reg, &src_reg);
14696 		scalar_min_max_add(dst_reg, &src_reg);
14697 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14698 		break;
14699 	case BPF_SUB:
14700 		scalar32_min_max_sub(dst_reg, &src_reg);
14701 		scalar_min_max_sub(dst_reg, &src_reg);
14702 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14703 		break;
14704 	case BPF_MUL:
14705 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14706 		scalar32_min_max_mul(dst_reg, &src_reg);
14707 		scalar_min_max_mul(dst_reg, &src_reg);
14708 		break;
14709 	case BPF_AND:
14710 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14711 		scalar32_min_max_and(dst_reg, &src_reg);
14712 		scalar_min_max_and(dst_reg, &src_reg);
14713 		break;
14714 	case BPF_OR:
14715 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14716 		scalar32_min_max_or(dst_reg, &src_reg);
14717 		scalar_min_max_or(dst_reg, &src_reg);
14718 		break;
14719 	case BPF_XOR:
14720 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14721 		scalar32_min_max_xor(dst_reg, &src_reg);
14722 		scalar_min_max_xor(dst_reg, &src_reg);
14723 		break;
14724 	case BPF_LSH:
14725 		if (alu32)
14726 			scalar32_min_max_lsh(dst_reg, &src_reg);
14727 		else
14728 			scalar_min_max_lsh(dst_reg, &src_reg);
14729 		break;
14730 	case BPF_RSH:
14731 		if (alu32)
14732 			scalar32_min_max_rsh(dst_reg, &src_reg);
14733 		else
14734 			scalar_min_max_rsh(dst_reg, &src_reg);
14735 		break;
14736 	case BPF_ARSH:
14737 		if (alu32)
14738 			scalar32_min_max_arsh(dst_reg, &src_reg);
14739 		else
14740 			scalar_min_max_arsh(dst_reg, &src_reg);
14741 		break;
14742 	default:
14743 		break;
14744 	}
14745 
14746 	/* ALU32 ops are zero extended into 64bit register */
14747 	if (alu32)
14748 		zext_32_to_64(dst_reg);
14749 	reg_bounds_sync(dst_reg);
14750 	return 0;
14751 }
14752 
14753 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14754  * and var_off.
14755  */
14756 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14757 				   struct bpf_insn *insn)
14758 {
14759 	struct bpf_verifier_state *vstate = env->cur_state;
14760 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14761 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14762 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14763 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14764 	u8 opcode = BPF_OP(insn->code);
14765 	int err;
14766 
14767 	dst_reg = &regs[insn->dst_reg];
14768 	src_reg = NULL;
14769 
14770 	if (dst_reg->type == PTR_TO_ARENA) {
14771 		struct bpf_insn_aux_data *aux = cur_aux(env);
14772 
14773 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14774 			/*
14775 			 * 32-bit operations zero upper bits automatically.
14776 			 * 64-bit operations need to be converted to 32.
14777 			 */
14778 			aux->needs_zext = true;
14779 
14780 		/* Any arithmetic operations are allowed on arena pointers */
14781 		return 0;
14782 	}
14783 
14784 	if (dst_reg->type != SCALAR_VALUE)
14785 		ptr_reg = dst_reg;
14786 
14787 	if (BPF_SRC(insn->code) == BPF_X) {
14788 		src_reg = &regs[insn->src_reg];
14789 		if (src_reg->type != SCALAR_VALUE) {
14790 			if (dst_reg->type != SCALAR_VALUE) {
14791 				/* Combining two pointers by any ALU op yields
14792 				 * an arbitrary scalar. Disallow all math except
14793 				 * pointer subtraction
14794 				 */
14795 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14796 					mark_reg_unknown(env, regs, insn->dst_reg);
14797 					return 0;
14798 				}
14799 				verbose(env, "R%d pointer %s pointer prohibited\n",
14800 					insn->dst_reg,
14801 					bpf_alu_string[opcode >> 4]);
14802 				return -EACCES;
14803 			} else {
14804 				/* scalar += pointer
14805 				 * This is legal, but we have to reverse our
14806 				 * src/dest handling in computing the range
14807 				 */
14808 				err = mark_chain_precision(env, insn->dst_reg);
14809 				if (err)
14810 					return err;
14811 				return adjust_ptr_min_max_vals(env, insn,
14812 							       src_reg, dst_reg);
14813 			}
14814 		} else if (ptr_reg) {
14815 			/* pointer += scalar */
14816 			err = mark_chain_precision(env, insn->src_reg);
14817 			if (err)
14818 				return err;
14819 			return adjust_ptr_min_max_vals(env, insn,
14820 						       dst_reg, src_reg);
14821 		} else if (dst_reg->precise) {
14822 			/* if dst_reg is precise, src_reg should be precise as well */
14823 			err = mark_chain_precision(env, insn->src_reg);
14824 			if (err)
14825 				return err;
14826 		}
14827 	} else {
14828 		/* Pretend the src is a reg with a known value, since we only
14829 		 * need to be able to read from this state.
14830 		 */
14831 		off_reg.type = SCALAR_VALUE;
14832 		__mark_reg_known(&off_reg, insn->imm);
14833 		src_reg = &off_reg;
14834 		if (ptr_reg) /* pointer += K */
14835 			return adjust_ptr_min_max_vals(env, insn,
14836 						       ptr_reg, src_reg);
14837 	}
14838 
14839 	/* Got here implies adding two SCALAR_VALUEs */
14840 	if (WARN_ON_ONCE(ptr_reg)) {
14841 		print_verifier_state(env, vstate, vstate->curframe, true);
14842 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14843 		return -EINVAL;
14844 	}
14845 	if (WARN_ON(!src_reg)) {
14846 		print_verifier_state(env, vstate, vstate->curframe, true);
14847 		verbose(env, "verifier internal error: no src_reg\n");
14848 		return -EINVAL;
14849 	}
14850 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14851 	if (err)
14852 		return err;
14853 	/*
14854 	 * Compilers can generate the code
14855 	 * r1 = r2
14856 	 * r1 += 0x1
14857 	 * if r2 < 1000 goto ...
14858 	 * use r1 in memory access
14859 	 * So for 64-bit alu remember constant delta between r2 and r1 and
14860 	 * update r1 after 'if' condition.
14861 	 */
14862 	if (env->bpf_capable &&
14863 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
14864 	    dst_reg->id && is_reg_const(src_reg, false)) {
14865 		u64 val = reg_const_value(src_reg, false);
14866 
14867 		if ((dst_reg->id & BPF_ADD_CONST) ||
14868 		    /* prevent overflow in sync_linked_regs() later */
14869 		    val > (u32)S32_MAX) {
14870 			/*
14871 			 * If the register already went through rX += val
14872 			 * we cannot accumulate another val into rx->off.
14873 			 */
14874 			dst_reg->off = 0;
14875 			dst_reg->id = 0;
14876 		} else {
14877 			dst_reg->id |= BPF_ADD_CONST;
14878 			dst_reg->off = val;
14879 		}
14880 	} else {
14881 		/*
14882 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14883 		 * incorrectly propagated into other registers by sync_linked_regs()
14884 		 */
14885 		dst_reg->id = 0;
14886 	}
14887 	return 0;
14888 }
14889 
14890 /* check validity of 32-bit and 64-bit arithmetic operations */
14891 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14892 {
14893 	struct bpf_reg_state *regs = cur_regs(env);
14894 	u8 opcode = BPF_OP(insn->code);
14895 	int err;
14896 
14897 	if (opcode == BPF_END || opcode == BPF_NEG) {
14898 		if (opcode == BPF_NEG) {
14899 			if (BPF_SRC(insn->code) != BPF_K ||
14900 			    insn->src_reg != BPF_REG_0 ||
14901 			    insn->off != 0 || insn->imm != 0) {
14902 				verbose(env, "BPF_NEG uses reserved fields\n");
14903 				return -EINVAL;
14904 			}
14905 		} else {
14906 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14907 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14908 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14909 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14910 				verbose(env, "BPF_END uses reserved fields\n");
14911 				return -EINVAL;
14912 			}
14913 		}
14914 
14915 		/* check src operand */
14916 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14917 		if (err)
14918 			return err;
14919 
14920 		if (is_pointer_value(env, insn->dst_reg)) {
14921 			verbose(env, "R%d pointer arithmetic prohibited\n",
14922 				insn->dst_reg);
14923 			return -EACCES;
14924 		}
14925 
14926 		/* check dest operand */
14927 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14928 		if (err)
14929 			return err;
14930 
14931 	} else if (opcode == BPF_MOV) {
14932 
14933 		if (BPF_SRC(insn->code) == BPF_X) {
14934 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14935 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14936 				    insn->imm) {
14937 					verbose(env, "BPF_MOV uses reserved fields\n");
14938 					return -EINVAL;
14939 				}
14940 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14941 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14942 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14943 					return -EINVAL;
14944 				}
14945 				if (!env->prog->aux->arena) {
14946 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14947 					return -EINVAL;
14948 				}
14949 			} else {
14950 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14951 				     insn->off != 32) || insn->imm) {
14952 					verbose(env, "BPF_MOV uses reserved fields\n");
14953 					return -EINVAL;
14954 				}
14955 			}
14956 
14957 			/* check src operand */
14958 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14959 			if (err)
14960 				return err;
14961 		} else {
14962 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14963 				verbose(env, "BPF_MOV uses reserved fields\n");
14964 				return -EINVAL;
14965 			}
14966 		}
14967 
14968 		/* check dest operand, mark as required later */
14969 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14970 		if (err)
14971 			return err;
14972 
14973 		if (BPF_SRC(insn->code) == BPF_X) {
14974 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14975 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14976 
14977 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14978 				if (insn->imm) {
14979 					/* off == BPF_ADDR_SPACE_CAST */
14980 					mark_reg_unknown(env, regs, insn->dst_reg);
14981 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14982 						dst_reg->type = PTR_TO_ARENA;
14983 						/* PTR_TO_ARENA is 32-bit */
14984 						dst_reg->subreg_def = env->insn_idx + 1;
14985 					}
14986 				} else if (insn->off == 0) {
14987 					/* case: R1 = R2
14988 					 * copy register state to dest reg
14989 					 */
14990 					assign_scalar_id_before_mov(env, src_reg);
14991 					copy_register_state(dst_reg, src_reg);
14992 					dst_reg->live |= REG_LIVE_WRITTEN;
14993 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14994 				} else {
14995 					/* case: R1 = (s8, s16 s32)R2 */
14996 					if (is_pointer_value(env, insn->src_reg)) {
14997 						verbose(env,
14998 							"R%d sign-extension part of pointer\n",
14999 							insn->src_reg);
15000 						return -EACCES;
15001 					} else if (src_reg->type == SCALAR_VALUE) {
15002 						bool no_sext;
15003 
15004 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15005 						if (no_sext)
15006 							assign_scalar_id_before_mov(env, src_reg);
15007 						copy_register_state(dst_reg, src_reg);
15008 						if (!no_sext)
15009 							dst_reg->id = 0;
15010 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15011 						dst_reg->live |= REG_LIVE_WRITTEN;
15012 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15013 					} else {
15014 						mark_reg_unknown(env, regs, insn->dst_reg);
15015 					}
15016 				}
15017 			} else {
15018 				/* R1 = (u32) R2 */
15019 				if (is_pointer_value(env, insn->src_reg)) {
15020 					verbose(env,
15021 						"R%d partial copy of pointer\n",
15022 						insn->src_reg);
15023 					return -EACCES;
15024 				} else if (src_reg->type == SCALAR_VALUE) {
15025 					if (insn->off == 0) {
15026 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15027 
15028 						if (is_src_reg_u32)
15029 							assign_scalar_id_before_mov(env, src_reg);
15030 						copy_register_state(dst_reg, src_reg);
15031 						/* Make sure ID is cleared if src_reg is not in u32
15032 						 * range otherwise dst_reg min/max could be incorrectly
15033 						 * propagated into src_reg by sync_linked_regs()
15034 						 */
15035 						if (!is_src_reg_u32)
15036 							dst_reg->id = 0;
15037 						dst_reg->live |= REG_LIVE_WRITTEN;
15038 						dst_reg->subreg_def = env->insn_idx + 1;
15039 					} else {
15040 						/* case: W1 = (s8, s16)W2 */
15041 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15042 
15043 						if (no_sext)
15044 							assign_scalar_id_before_mov(env, src_reg);
15045 						copy_register_state(dst_reg, src_reg);
15046 						if (!no_sext)
15047 							dst_reg->id = 0;
15048 						dst_reg->live |= REG_LIVE_WRITTEN;
15049 						dst_reg->subreg_def = env->insn_idx + 1;
15050 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15051 					}
15052 				} else {
15053 					mark_reg_unknown(env, regs,
15054 							 insn->dst_reg);
15055 				}
15056 				zext_32_to_64(dst_reg);
15057 				reg_bounds_sync(dst_reg);
15058 			}
15059 		} else {
15060 			/* case: R = imm
15061 			 * remember the value we stored into this reg
15062 			 */
15063 			/* clear any state __mark_reg_known doesn't set */
15064 			mark_reg_unknown(env, regs, insn->dst_reg);
15065 			regs[insn->dst_reg].type = SCALAR_VALUE;
15066 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15067 				__mark_reg_known(regs + insn->dst_reg,
15068 						 insn->imm);
15069 			} else {
15070 				__mark_reg_known(regs + insn->dst_reg,
15071 						 (u32)insn->imm);
15072 			}
15073 		}
15074 
15075 	} else if (opcode > BPF_END) {
15076 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15077 		return -EINVAL;
15078 
15079 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15080 
15081 		if (BPF_SRC(insn->code) == BPF_X) {
15082 			if (insn->imm != 0 || insn->off > 1 ||
15083 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15084 				verbose(env, "BPF_ALU uses reserved fields\n");
15085 				return -EINVAL;
15086 			}
15087 			/* check src1 operand */
15088 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15089 			if (err)
15090 				return err;
15091 		} else {
15092 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15093 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15094 				verbose(env, "BPF_ALU uses reserved fields\n");
15095 				return -EINVAL;
15096 			}
15097 		}
15098 
15099 		/* check src2 operand */
15100 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15101 		if (err)
15102 			return err;
15103 
15104 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15105 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15106 			verbose(env, "div by zero\n");
15107 			return -EINVAL;
15108 		}
15109 
15110 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15111 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15112 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15113 
15114 			if (insn->imm < 0 || insn->imm >= size) {
15115 				verbose(env, "invalid shift %d\n", insn->imm);
15116 				return -EINVAL;
15117 			}
15118 		}
15119 
15120 		/* check dest operand */
15121 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15122 		err = err ?: adjust_reg_min_max_vals(env, insn);
15123 		if (err)
15124 			return err;
15125 	}
15126 
15127 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15128 }
15129 
15130 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15131 				   struct bpf_reg_state *dst_reg,
15132 				   enum bpf_reg_type type,
15133 				   bool range_right_open)
15134 {
15135 	struct bpf_func_state *state;
15136 	struct bpf_reg_state *reg;
15137 	int new_range;
15138 
15139 	if (dst_reg->off < 0 ||
15140 	    (dst_reg->off == 0 && range_right_open))
15141 		/* This doesn't give us any range */
15142 		return;
15143 
15144 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15145 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15146 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15147 		 * than pkt_end, but that's because it's also less than pkt.
15148 		 */
15149 		return;
15150 
15151 	new_range = dst_reg->off;
15152 	if (range_right_open)
15153 		new_range++;
15154 
15155 	/* Examples for register markings:
15156 	 *
15157 	 * pkt_data in dst register:
15158 	 *
15159 	 *   r2 = r3;
15160 	 *   r2 += 8;
15161 	 *   if (r2 > pkt_end) goto <handle exception>
15162 	 *   <access okay>
15163 	 *
15164 	 *   r2 = r3;
15165 	 *   r2 += 8;
15166 	 *   if (r2 < pkt_end) goto <access okay>
15167 	 *   <handle exception>
15168 	 *
15169 	 *   Where:
15170 	 *     r2 == dst_reg, pkt_end == src_reg
15171 	 *     r2=pkt(id=n,off=8,r=0)
15172 	 *     r3=pkt(id=n,off=0,r=0)
15173 	 *
15174 	 * pkt_data in src register:
15175 	 *
15176 	 *   r2 = r3;
15177 	 *   r2 += 8;
15178 	 *   if (pkt_end >= r2) goto <access okay>
15179 	 *   <handle exception>
15180 	 *
15181 	 *   r2 = r3;
15182 	 *   r2 += 8;
15183 	 *   if (pkt_end <= r2) goto <handle exception>
15184 	 *   <access okay>
15185 	 *
15186 	 *   Where:
15187 	 *     pkt_end == dst_reg, r2 == src_reg
15188 	 *     r2=pkt(id=n,off=8,r=0)
15189 	 *     r3=pkt(id=n,off=0,r=0)
15190 	 *
15191 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15192 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15193 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15194 	 * the check.
15195 	 */
15196 
15197 	/* If our ids match, then we must have the same max_value.  And we
15198 	 * don't care about the other reg's fixed offset, since if it's too big
15199 	 * the range won't allow anything.
15200 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15201 	 */
15202 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15203 		if (reg->type == type && reg->id == dst_reg->id)
15204 			/* keep the maximum range already checked */
15205 			reg->range = max(reg->range, new_range);
15206 	}));
15207 }
15208 
15209 /*
15210  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15211  */
15212 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15213 				  u8 opcode, bool is_jmp32)
15214 {
15215 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15216 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15217 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15218 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15219 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15220 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15221 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15222 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15223 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15224 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15225 
15226 	switch (opcode) {
15227 	case BPF_JEQ:
15228 		/* constants, umin/umax and smin/smax checks would be
15229 		 * redundant in this case because they all should match
15230 		 */
15231 		if (tnum_is_const(t1) && tnum_is_const(t2))
15232 			return t1.value == t2.value;
15233 		/* non-overlapping ranges */
15234 		if (umin1 > umax2 || umax1 < umin2)
15235 			return 0;
15236 		if (smin1 > smax2 || smax1 < smin2)
15237 			return 0;
15238 		if (!is_jmp32) {
15239 			/* if 64-bit ranges are inconclusive, see if we can
15240 			 * utilize 32-bit subrange knowledge to eliminate
15241 			 * branches that can't be taken a priori
15242 			 */
15243 			if (reg1->u32_min_value > reg2->u32_max_value ||
15244 			    reg1->u32_max_value < reg2->u32_min_value)
15245 				return 0;
15246 			if (reg1->s32_min_value > reg2->s32_max_value ||
15247 			    reg1->s32_max_value < reg2->s32_min_value)
15248 				return 0;
15249 		}
15250 		break;
15251 	case BPF_JNE:
15252 		/* constants, umin/umax and smin/smax checks would be
15253 		 * redundant in this case because they all should match
15254 		 */
15255 		if (tnum_is_const(t1) && tnum_is_const(t2))
15256 			return t1.value != t2.value;
15257 		/* non-overlapping ranges */
15258 		if (umin1 > umax2 || umax1 < umin2)
15259 			return 1;
15260 		if (smin1 > smax2 || smax1 < smin2)
15261 			return 1;
15262 		if (!is_jmp32) {
15263 			/* if 64-bit ranges are inconclusive, see if we can
15264 			 * utilize 32-bit subrange knowledge to eliminate
15265 			 * branches that can't be taken a priori
15266 			 */
15267 			if (reg1->u32_min_value > reg2->u32_max_value ||
15268 			    reg1->u32_max_value < reg2->u32_min_value)
15269 				return 1;
15270 			if (reg1->s32_min_value > reg2->s32_max_value ||
15271 			    reg1->s32_max_value < reg2->s32_min_value)
15272 				return 1;
15273 		}
15274 		break;
15275 	case BPF_JSET:
15276 		if (!is_reg_const(reg2, is_jmp32)) {
15277 			swap(reg1, reg2);
15278 			swap(t1, t2);
15279 		}
15280 		if (!is_reg_const(reg2, is_jmp32))
15281 			return -1;
15282 		if ((~t1.mask & t1.value) & t2.value)
15283 			return 1;
15284 		if (!((t1.mask | t1.value) & t2.value))
15285 			return 0;
15286 		break;
15287 	case BPF_JGT:
15288 		if (umin1 > umax2)
15289 			return 1;
15290 		else if (umax1 <= umin2)
15291 			return 0;
15292 		break;
15293 	case BPF_JSGT:
15294 		if (smin1 > smax2)
15295 			return 1;
15296 		else if (smax1 <= smin2)
15297 			return 0;
15298 		break;
15299 	case BPF_JLT:
15300 		if (umax1 < umin2)
15301 			return 1;
15302 		else if (umin1 >= umax2)
15303 			return 0;
15304 		break;
15305 	case BPF_JSLT:
15306 		if (smax1 < smin2)
15307 			return 1;
15308 		else if (smin1 >= smax2)
15309 			return 0;
15310 		break;
15311 	case BPF_JGE:
15312 		if (umin1 >= umax2)
15313 			return 1;
15314 		else if (umax1 < umin2)
15315 			return 0;
15316 		break;
15317 	case BPF_JSGE:
15318 		if (smin1 >= smax2)
15319 			return 1;
15320 		else if (smax1 < smin2)
15321 			return 0;
15322 		break;
15323 	case BPF_JLE:
15324 		if (umax1 <= umin2)
15325 			return 1;
15326 		else if (umin1 > umax2)
15327 			return 0;
15328 		break;
15329 	case BPF_JSLE:
15330 		if (smax1 <= smin2)
15331 			return 1;
15332 		else if (smin1 > smax2)
15333 			return 0;
15334 		break;
15335 	}
15336 
15337 	return -1;
15338 }
15339 
15340 static int flip_opcode(u32 opcode)
15341 {
15342 	/* How can we transform "a <op> b" into "b <op> a"? */
15343 	static const u8 opcode_flip[16] = {
15344 		/* these stay the same */
15345 		[BPF_JEQ  >> 4] = BPF_JEQ,
15346 		[BPF_JNE  >> 4] = BPF_JNE,
15347 		[BPF_JSET >> 4] = BPF_JSET,
15348 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15349 		[BPF_JGE  >> 4] = BPF_JLE,
15350 		[BPF_JGT  >> 4] = BPF_JLT,
15351 		[BPF_JLE  >> 4] = BPF_JGE,
15352 		[BPF_JLT  >> 4] = BPF_JGT,
15353 		[BPF_JSGE >> 4] = BPF_JSLE,
15354 		[BPF_JSGT >> 4] = BPF_JSLT,
15355 		[BPF_JSLE >> 4] = BPF_JSGE,
15356 		[BPF_JSLT >> 4] = BPF_JSGT
15357 	};
15358 	return opcode_flip[opcode >> 4];
15359 }
15360 
15361 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15362 				   struct bpf_reg_state *src_reg,
15363 				   u8 opcode)
15364 {
15365 	struct bpf_reg_state *pkt;
15366 
15367 	if (src_reg->type == PTR_TO_PACKET_END) {
15368 		pkt = dst_reg;
15369 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15370 		pkt = src_reg;
15371 		opcode = flip_opcode(opcode);
15372 	} else {
15373 		return -1;
15374 	}
15375 
15376 	if (pkt->range >= 0)
15377 		return -1;
15378 
15379 	switch (opcode) {
15380 	case BPF_JLE:
15381 		/* pkt <= pkt_end */
15382 		fallthrough;
15383 	case BPF_JGT:
15384 		/* pkt > pkt_end */
15385 		if (pkt->range == BEYOND_PKT_END)
15386 			/* pkt has at last one extra byte beyond pkt_end */
15387 			return opcode == BPF_JGT;
15388 		break;
15389 	case BPF_JLT:
15390 		/* pkt < pkt_end */
15391 		fallthrough;
15392 	case BPF_JGE:
15393 		/* pkt >= pkt_end */
15394 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15395 			return opcode == BPF_JGE;
15396 		break;
15397 	}
15398 	return -1;
15399 }
15400 
15401 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15402  * and return:
15403  *  1 - branch will be taken and "goto target" will be executed
15404  *  0 - branch will not be taken and fall-through to next insn
15405  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15406  *      range [0,10]
15407  */
15408 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15409 			   u8 opcode, bool is_jmp32)
15410 {
15411 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15412 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15413 
15414 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15415 		u64 val;
15416 
15417 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15418 		if (!is_reg_const(reg2, is_jmp32)) {
15419 			opcode = flip_opcode(opcode);
15420 			swap(reg1, reg2);
15421 		}
15422 		/* and ensure that reg2 is a constant */
15423 		if (!is_reg_const(reg2, is_jmp32))
15424 			return -1;
15425 
15426 		if (!reg_not_null(reg1))
15427 			return -1;
15428 
15429 		/* If pointer is valid tests against zero will fail so we can
15430 		 * use this to direct branch taken.
15431 		 */
15432 		val = reg_const_value(reg2, is_jmp32);
15433 		if (val != 0)
15434 			return -1;
15435 
15436 		switch (opcode) {
15437 		case BPF_JEQ:
15438 			return 0;
15439 		case BPF_JNE:
15440 			return 1;
15441 		default:
15442 			return -1;
15443 		}
15444 	}
15445 
15446 	/* now deal with two scalars, but not necessarily constants */
15447 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
15448 }
15449 
15450 /* Opcode that corresponds to a *false* branch condition.
15451  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15452  */
15453 static u8 rev_opcode(u8 opcode)
15454 {
15455 	switch (opcode) {
15456 	case BPF_JEQ:		return BPF_JNE;
15457 	case BPF_JNE:		return BPF_JEQ;
15458 	/* JSET doesn't have it's reverse opcode in BPF, so add
15459 	 * BPF_X flag to denote the reverse of that operation
15460 	 */
15461 	case BPF_JSET:		return BPF_JSET | BPF_X;
15462 	case BPF_JSET | BPF_X:	return BPF_JSET;
15463 	case BPF_JGE:		return BPF_JLT;
15464 	case BPF_JGT:		return BPF_JLE;
15465 	case BPF_JLE:		return BPF_JGT;
15466 	case BPF_JLT:		return BPF_JGE;
15467 	case BPF_JSGE:		return BPF_JSLT;
15468 	case BPF_JSGT:		return BPF_JSLE;
15469 	case BPF_JSLE:		return BPF_JSGT;
15470 	case BPF_JSLT:		return BPF_JSGE;
15471 	default:		return 0;
15472 	}
15473 }
15474 
15475 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15476 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15477 				u8 opcode, bool is_jmp32)
15478 {
15479 	struct tnum t;
15480 	u64 val;
15481 
15482 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15483 	switch (opcode) {
15484 	case BPF_JGE:
15485 	case BPF_JGT:
15486 	case BPF_JSGE:
15487 	case BPF_JSGT:
15488 		opcode = flip_opcode(opcode);
15489 		swap(reg1, reg2);
15490 		break;
15491 	default:
15492 		break;
15493 	}
15494 
15495 	switch (opcode) {
15496 	case BPF_JEQ:
15497 		if (is_jmp32) {
15498 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15499 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15500 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15501 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15502 			reg2->u32_min_value = reg1->u32_min_value;
15503 			reg2->u32_max_value = reg1->u32_max_value;
15504 			reg2->s32_min_value = reg1->s32_min_value;
15505 			reg2->s32_max_value = reg1->s32_max_value;
15506 
15507 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15508 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15509 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15510 		} else {
15511 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
15512 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15513 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
15514 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15515 			reg2->umin_value = reg1->umin_value;
15516 			reg2->umax_value = reg1->umax_value;
15517 			reg2->smin_value = reg1->smin_value;
15518 			reg2->smax_value = reg1->smax_value;
15519 
15520 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15521 			reg2->var_off = reg1->var_off;
15522 		}
15523 		break;
15524 	case BPF_JNE:
15525 		if (!is_reg_const(reg2, is_jmp32))
15526 			swap(reg1, reg2);
15527 		if (!is_reg_const(reg2, is_jmp32))
15528 			break;
15529 
15530 		/* try to recompute the bound of reg1 if reg2 is a const and
15531 		 * is exactly the edge of reg1.
15532 		 */
15533 		val = reg_const_value(reg2, is_jmp32);
15534 		if (is_jmp32) {
15535 			/* u32_min_value is not equal to 0xffffffff at this point,
15536 			 * because otherwise u32_max_value is 0xffffffff as well,
15537 			 * in such a case both reg1 and reg2 would be constants,
15538 			 * jump would be predicted and reg_set_min_max() won't
15539 			 * be called.
15540 			 *
15541 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
15542 			 * below.
15543 			 */
15544 			if (reg1->u32_min_value == (u32)val)
15545 				reg1->u32_min_value++;
15546 			if (reg1->u32_max_value == (u32)val)
15547 				reg1->u32_max_value--;
15548 			if (reg1->s32_min_value == (s32)val)
15549 				reg1->s32_min_value++;
15550 			if (reg1->s32_max_value == (s32)val)
15551 				reg1->s32_max_value--;
15552 		} else {
15553 			if (reg1->umin_value == (u64)val)
15554 				reg1->umin_value++;
15555 			if (reg1->umax_value == (u64)val)
15556 				reg1->umax_value--;
15557 			if (reg1->smin_value == (s64)val)
15558 				reg1->smin_value++;
15559 			if (reg1->smax_value == (s64)val)
15560 				reg1->smax_value--;
15561 		}
15562 		break;
15563 	case BPF_JSET:
15564 		if (!is_reg_const(reg2, is_jmp32))
15565 			swap(reg1, reg2);
15566 		if (!is_reg_const(reg2, is_jmp32))
15567 			break;
15568 		val = reg_const_value(reg2, is_jmp32);
15569 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
15570 		 * requires single bit to learn something useful. E.g., if we
15571 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
15572 		 * are actually set? We can learn something definite only if
15573 		 * it's a single-bit value to begin with.
15574 		 *
15575 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
15576 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
15577 		 * bit 1 is set, which we can readily use in adjustments.
15578 		 */
15579 		if (!is_power_of_2(val))
15580 			break;
15581 		if (is_jmp32) {
15582 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
15583 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15584 		} else {
15585 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15586 		}
15587 		break;
15588 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15589 		if (!is_reg_const(reg2, is_jmp32))
15590 			swap(reg1, reg2);
15591 		if (!is_reg_const(reg2, is_jmp32))
15592 			break;
15593 		val = reg_const_value(reg2, is_jmp32);
15594 		if (is_jmp32) {
15595 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15596 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15597 		} else {
15598 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15599 		}
15600 		break;
15601 	case BPF_JLE:
15602 		if (is_jmp32) {
15603 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15604 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15605 		} else {
15606 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15607 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
15608 		}
15609 		break;
15610 	case BPF_JLT:
15611 		if (is_jmp32) {
15612 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
15613 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
15614 		} else {
15615 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
15616 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
15617 		}
15618 		break;
15619 	case BPF_JSLE:
15620 		if (is_jmp32) {
15621 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15622 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15623 		} else {
15624 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15625 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
15626 		}
15627 		break;
15628 	case BPF_JSLT:
15629 		if (is_jmp32) {
15630 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
15631 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
15632 		} else {
15633 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
15634 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
15635 		}
15636 		break;
15637 	default:
15638 		return;
15639 	}
15640 }
15641 
15642 /* Adjusts the register min/max values in the case that the dst_reg and
15643  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
15644  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
15645  * Technically we can do similar adjustments for pointers to the same object,
15646  * but we don't support that right now.
15647  */
15648 static int reg_set_min_max(struct bpf_verifier_env *env,
15649 			   struct bpf_reg_state *true_reg1,
15650 			   struct bpf_reg_state *true_reg2,
15651 			   struct bpf_reg_state *false_reg1,
15652 			   struct bpf_reg_state *false_reg2,
15653 			   u8 opcode, bool is_jmp32)
15654 {
15655 	int err;
15656 
15657 	/* If either register is a pointer, we can't learn anything about its
15658 	 * variable offset from the compare (unless they were a pointer into
15659 	 * the same object, but we don't bother with that).
15660 	 */
15661 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
15662 		return 0;
15663 
15664 	/* fallthrough (FALSE) branch */
15665 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
15666 	reg_bounds_sync(false_reg1);
15667 	reg_bounds_sync(false_reg2);
15668 
15669 	/* jump (TRUE) branch */
15670 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
15671 	reg_bounds_sync(true_reg1);
15672 	reg_bounds_sync(true_reg2);
15673 
15674 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
15675 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
15676 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
15677 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
15678 	return err;
15679 }
15680 
15681 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15682 				 struct bpf_reg_state *reg, u32 id,
15683 				 bool is_null)
15684 {
15685 	if (type_may_be_null(reg->type) && reg->id == id &&
15686 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15687 		/* Old offset (both fixed and variable parts) should have been
15688 		 * known-zero, because we don't allow pointer arithmetic on
15689 		 * pointers that might be NULL. If we see this happening, don't
15690 		 * convert the register.
15691 		 *
15692 		 * But in some cases, some helpers that return local kptrs
15693 		 * advance offset for the returned pointer. In those cases, it
15694 		 * is fine to expect to see reg->off.
15695 		 */
15696 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
15697 			return;
15698 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15699 		    WARN_ON_ONCE(reg->off))
15700 			return;
15701 
15702 		if (is_null) {
15703 			reg->type = SCALAR_VALUE;
15704 			/* We don't need id and ref_obj_id from this point
15705 			 * onwards anymore, thus we should better reset it,
15706 			 * so that state pruning has chances to take effect.
15707 			 */
15708 			reg->id = 0;
15709 			reg->ref_obj_id = 0;
15710 
15711 			return;
15712 		}
15713 
15714 		mark_ptr_not_null_reg(reg);
15715 
15716 		if (!reg_may_point_to_spin_lock(reg)) {
15717 			/* For not-NULL ptr, reg->ref_obj_id will be reset
15718 			 * in release_reference().
15719 			 *
15720 			 * reg->id is still used by spin_lock ptr. Other
15721 			 * than spin_lock ptr type, reg->id can be reset.
15722 			 */
15723 			reg->id = 0;
15724 		}
15725 	}
15726 }
15727 
15728 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15729  * be folded together at some point.
15730  */
15731 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15732 				  bool is_null)
15733 {
15734 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15735 	struct bpf_reg_state *regs = state->regs, *reg;
15736 	u32 ref_obj_id = regs[regno].ref_obj_id;
15737 	u32 id = regs[regno].id;
15738 
15739 	if (ref_obj_id && ref_obj_id == id && is_null)
15740 		/* regs[regno] is in the " == NULL" branch.
15741 		 * No one could have freed the reference state before
15742 		 * doing the NULL check.
15743 		 */
15744 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
15745 
15746 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15747 		mark_ptr_or_null_reg(state, reg, id, is_null);
15748 	}));
15749 }
15750 
15751 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15752 				   struct bpf_reg_state *dst_reg,
15753 				   struct bpf_reg_state *src_reg,
15754 				   struct bpf_verifier_state *this_branch,
15755 				   struct bpf_verifier_state *other_branch)
15756 {
15757 	if (BPF_SRC(insn->code) != BPF_X)
15758 		return false;
15759 
15760 	/* Pointers are always 64-bit. */
15761 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15762 		return false;
15763 
15764 	switch (BPF_OP(insn->code)) {
15765 	case BPF_JGT:
15766 		if ((dst_reg->type == PTR_TO_PACKET &&
15767 		     src_reg->type == PTR_TO_PACKET_END) ||
15768 		    (dst_reg->type == PTR_TO_PACKET_META &&
15769 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15770 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15771 			find_good_pkt_pointers(this_branch, dst_reg,
15772 					       dst_reg->type, false);
15773 			mark_pkt_end(other_branch, insn->dst_reg, true);
15774 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15775 			    src_reg->type == PTR_TO_PACKET) ||
15776 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15777 			    src_reg->type == PTR_TO_PACKET_META)) {
15778 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15779 			find_good_pkt_pointers(other_branch, src_reg,
15780 					       src_reg->type, true);
15781 			mark_pkt_end(this_branch, insn->src_reg, false);
15782 		} else {
15783 			return false;
15784 		}
15785 		break;
15786 	case BPF_JLT:
15787 		if ((dst_reg->type == PTR_TO_PACKET &&
15788 		     src_reg->type == PTR_TO_PACKET_END) ||
15789 		    (dst_reg->type == PTR_TO_PACKET_META &&
15790 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15791 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15792 			find_good_pkt_pointers(other_branch, dst_reg,
15793 					       dst_reg->type, true);
15794 			mark_pkt_end(this_branch, insn->dst_reg, false);
15795 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15796 			    src_reg->type == PTR_TO_PACKET) ||
15797 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15798 			    src_reg->type == PTR_TO_PACKET_META)) {
15799 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15800 			find_good_pkt_pointers(this_branch, src_reg,
15801 					       src_reg->type, false);
15802 			mark_pkt_end(other_branch, insn->src_reg, true);
15803 		} else {
15804 			return false;
15805 		}
15806 		break;
15807 	case BPF_JGE:
15808 		if ((dst_reg->type == PTR_TO_PACKET &&
15809 		     src_reg->type == PTR_TO_PACKET_END) ||
15810 		    (dst_reg->type == PTR_TO_PACKET_META &&
15811 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15812 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15813 			find_good_pkt_pointers(this_branch, dst_reg,
15814 					       dst_reg->type, true);
15815 			mark_pkt_end(other_branch, insn->dst_reg, false);
15816 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15817 			    src_reg->type == PTR_TO_PACKET) ||
15818 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15819 			    src_reg->type == PTR_TO_PACKET_META)) {
15820 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15821 			find_good_pkt_pointers(other_branch, src_reg,
15822 					       src_reg->type, false);
15823 			mark_pkt_end(this_branch, insn->src_reg, true);
15824 		} else {
15825 			return false;
15826 		}
15827 		break;
15828 	case BPF_JLE:
15829 		if ((dst_reg->type == PTR_TO_PACKET &&
15830 		     src_reg->type == PTR_TO_PACKET_END) ||
15831 		    (dst_reg->type == PTR_TO_PACKET_META &&
15832 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15833 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15834 			find_good_pkt_pointers(other_branch, dst_reg,
15835 					       dst_reg->type, false);
15836 			mark_pkt_end(this_branch, insn->dst_reg, true);
15837 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15838 			    src_reg->type == PTR_TO_PACKET) ||
15839 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15840 			    src_reg->type == PTR_TO_PACKET_META)) {
15841 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15842 			find_good_pkt_pointers(this_branch, src_reg,
15843 					       src_reg->type, true);
15844 			mark_pkt_end(other_branch, insn->src_reg, false);
15845 		} else {
15846 			return false;
15847 		}
15848 		break;
15849 	default:
15850 		return false;
15851 	}
15852 
15853 	return true;
15854 }
15855 
15856 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15857 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15858 {
15859 	struct linked_reg *e;
15860 
15861 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15862 		return;
15863 
15864 	e = linked_regs_push(reg_set);
15865 	if (e) {
15866 		e->frameno = frameno;
15867 		e->is_reg = is_reg;
15868 		e->regno = spi_or_reg;
15869 	} else {
15870 		reg->id = 0;
15871 	}
15872 }
15873 
15874 /* For all R being scalar registers or spilled scalar registers
15875  * in verifier state, save R in linked_regs if R->id == id.
15876  * If there are too many Rs sharing same id, reset id for leftover Rs.
15877  */
15878 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
15879 				struct linked_regs *linked_regs)
15880 {
15881 	struct bpf_func_state *func;
15882 	struct bpf_reg_state *reg;
15883 	int i, j;
15884 
15885 	id = id & ~BPF_ADD_CONST;
15886 	for (i = vstate->curframe; i >= 0; i--) {
15887 		func = vstate->frame[i];
15888 		for (j = 0; j < BPF_REG_FP; j++) {
15889 			reg = &func->regs[j];
15890 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15891 		}
15892 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15893 			if (!is_spilled_reg(&func->stack[j]))
15894 				continue;
15895 			reg = &func->stack[j].spilled_ptr;
15896 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15897 		}
15898 	}
15899 }
15900 
15901 /* For all R in linked_regs, copy known_reg range into R
15902  * if R->id == known_reg->id.
15903  */
15904 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
15905 			     struct linked_regs *linked_regs)
15906 {
15907 	struct bpf_reg_state fake_reg;
15908 	struct bpf_reg_state *reg;
15909 	struct linked_reg *e;
15910 	int i;
15911 
15912 	for (i = 0; i < linked_regs->cnt; ++i) {
15913 		e = &linked_regs->entries[i];
15914 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15915 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15916 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15917 			continue;
15918 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15919 			continue;
15920 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15921 		    reg->off == known_reg->off) {
15922 			s32 saved_subreg_def = reg->subreg_def;
15923 
15924 			copy_register_state(reg, known_reg);
15925 			reg->subreg_def = saved_subreg_def;
15926 		} else {
15927 			s32 saved_subreg_def = reg->subreg_def;
15928 			s32 saved_off = reg->off;
15929 
15930 			fake_reg.type = SCALAR_VALUE;
15931 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15932 
15933 			/* reg = known_reg; reg += delta */
15934 			copy_register_state(reg, known_reg);
15935 			/*
15936 			 * Must preserve off, id and add_const flag,
15937 			 * otherwise another sync_linked_regs() will be incorrect.
15938 			 */
15939 			reg->off = saved_off;
15940 			reg->subreg_def = saved_subreg_def;
15941 
15942 			scalar32_min_max_add(reg, &fake_reg);
15943 			scalar_min_max_add(reg, &fake_reg);
15944 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15945 		}
15946 	}
15947 }
15948 
15949 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15950 			     struct bpf_insn *insn, int *insn_idx)
15951 {
15952 	struct bpf_verifier_state *this_branch = env->cur_state;
15953 	struct bpf_verifier_state *other_branch;
15954 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15955 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15956 	struct bpf_reg_state *eq_branch_regs;
15957 	struct linked_regs linked_regs = {};
15958 	u8 opcode = BPF_OP(insn->code);
15959 	bool is_jmp32;
15960 	int pred = -1;
15961 	int err;
15962 
15963 	/* Only conditional jumps are expected to reach here. */
15964 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15965 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15966 		return -EINVAL;
15967 	}
15968 
15969 	if (opcode == BPF_JCOND) {
15970 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15971 		int idx = *insn_idx;
15972 
15973 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15974 		    insn->src_reg != BPF_MAY_GOTO ||
15975 		    insn->dst_reg || insn->imm) {
15976 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
15977 			return -EINVAL;
15978 		}
15979 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15980 
15981 		/* branch out 'fallthrough' insn as a new state to explore */
15982 		queued_st = push_stack(env, idx + 1, idx, false);
15983 		if (!queued_st)
15984 			return -ENOMEM;
15985 
15986 		queued_st->may_goto_depth++;
15987 		if (prev_st)
15988 			widen_imprecise_scalars(env, prev_st, queued_st);
15989 		*insn_idx += insn->off;
15990 		return 0;
15991 	}
15992 
15993 	/* check src2 operand */
15994 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15995 	if (err)
15996 		return err;
15997 
15998 	dst_reg = &regs[insn->dst_reg];
15999 	if (BPF_SRC(insn->code) == BPF_X) {
16000 		if (insn->imm != 0) {
16001 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16002 			return -EINVAL;
16003 		}
16004 
16005 		/* check src1 operand */
16006 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16007 		if (err)
16008 			return err;
16009 
16010 		src_reg = &regs[insn->src_reg];
16011 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16012 		    is_pointer_value(env, insn->src_reg)) {
16013 			verbose(env, "R%d pointer comparison prohibited\n",
16014 				insn->src_reg);
16015 			return -EACCES;
16016 		}
16017 	} else {
16018 		if (insn->src_reg != BPF_REG_0) {
16019 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16020 			return -EINVAL;
16021 		}
16022 		src_reg = &env->fake_reg[0];
16023 		memset(src_reg, 0, sizeof(*src_reg));
16024 		src_reg->type = SCALAR_VALUE;
16025 		__mark_reg_known(src_reg, insn->imm);
16026 	}
16027 
16028 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16029 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16030 	if (pred >= 0) {
16031 		/* If we get here with a dst_reg pointer type it is because
16032 		 * above is_branch_taken() special cased the 0 comparison.
16033 		 */
16034 		if (!__is_pointer_value(false, dst_reg))
16035 			err = mark_chain_precision(env, insn->dst_reg);
16036 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16037 		    !__is_pointer_value(false, src_reg))
16038 			err = mark_chain_precision(env, insn->src_reg);
16039 		if (err)
16040 			return err;
16041 	}
16042 
16043 	if (pred == 1) {
16044 		/* Only follow the goto, ignore fall-through. If needed, push
16045 		 * the fall-through branch for simulation under speculative
16046 		 * execution.
16047 		 */
16048 		if (!env->bypass_spec_v1 &&
16049 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16050 					       *insn_idx))
16051 			return -EFAULT;
16052 		if (env->log.level & BPF_LOG_LEVEL)
16053 			print_insn_state(env, this_branch, this_branch->curframe);
16054 		*insn_idx += insn->off;
16055 		return 0;
16056 	} else if (pred == 0) {
16057 		/* Only follow the fall-through branch, since that's where the
16058 		 * program will go. If needed, push the goto branch for
16059 		 * simulation under speculative execution.
16060 		 */
16061 		if (!env->bypass_spec_v1 &&
16062 		    !sanitize_speculative_path(env, insn,
16063 					       *insn_idx + insn->off + 1,
16064 					       *insn_idx))
16065 			return -EFAULT;
16066 		if (env->log.level & BPF_LOG_LEVEL)
16067 			print_insn_state(env, this_branch, this_branch->curframe);
16068 		return 0;
16069 	}
16070 
16071 	/* Push scalar registers sharing same ID to jump history,
16072 	 * do this before creating 'other_branch', so that both
16073 	 * 'this_branch' and 'other_branch' share this history
16074 	 * if parent state is created.
16075 	 */
16076 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16077 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16078 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16079 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16080 	if (linked_regs.cnt > 1) {
16081 		err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16082 		if (err)
16083 			return err;
16084 	}
16085 
16086 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16087 				  false);
16088 	if (!other_branch)
16089 		return -EFAULT;
16090 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16091 
16092 	if (BPF_SRC(insn->code) == BPF_X) {
16093 		err = reg_set_min_max(env,
16094 				      &other_branch_regs[insn->dst_reg],
16095 				      &other_branch_regs[insn->src_reg],
16096 				      dst_reg, src_reg, opcode, is_jmp32);
16097 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16098 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16099 		 * so that these are two different memory locations. The
16100 		 * src_reg is not used beyond here in context of K.
16101 		 */
16102 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16103 		       sizeof(env->fake_reg[0]));
16104 		err = reg_set_min_max(env,
16105 				      &other_branch_regs[insn->dst_reg],
16106 				      &env->fake_reg[0],
16107 				      dst_reg, &env->fake_reg[1],
16108 				      opcode, is_jmp32);
16109 	}
16110 	if (err)
16111 		return err;
16112 
16113 	if (BPF_SRC(insn->code) == BPF_X &&
16114 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16115 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16116 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16117 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16118 	}
16119 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16120 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16121 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16122 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16123 	}
16124 
16125 	/* if one pointer register is compared to another pointer
16126 	 * register check if PTR_MAYBE_NULL could be lifted.
16127 	 * E.g. register A - maybe null
16128 	 *      register B - not null
16129 	 * for JNE A, B, ... - A is not null in the false branch;
16130 	 * for JEQ A, B, ... - A is not null in the true branch.
16131 	 *
16132 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16133 	 * not need to be null checked by the BPF program, i.e.,
16134 	 * could be null even without PTR_MAYBE_NULL marking, so
16135 	 * only propagate nullness when neither reg is that type.
16136 	 */
16137 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16138 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16139 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16140 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16141 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16142 		eq_branch_regs = NULL;
16143 		switch (opcode) {
16144 		case BPF_JEQ:
16145 			eq_branch_regs = other_branch_regs;
16146 			break;
16147 		case BPF_JNE:
16148 			eq_branch_regs = regs;
16149 			break;
16150 		default:
16151 			/* do nothing */
16152 			break;
16153 		}
16154 		if (eq_branch_regs) {
16155 			if (type_may_be_null(src_reg->type))
16156 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16157 			else
16158 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16159 		}
16160 	}
16161 
16162 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16163 	 * NOTE: these optimizations below are related with pointer comparison
16164 	 *       which will never be JMP32.
16165 	 */
16166 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16167 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16168 	    type_may_be_null(dst_reg->type)) {
16169 		/* Mark all identical registers in each branch as either
16170 		 * safe or unknown depending R == 0 or R != 0 conditional.
16171 		 */
16172 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16173 				      opcode == BPF_JNE);
16174 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16175 				      opcode == BPF_JEQ);
16176 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16177 					   this_branch, other_branch) &&
16178 		   is_pointer_value(env, insn->dst_reg)) {
16179 		verbose(env, "R%d pointer comparison prohibited\n",
16180 			insn->dst_reg);
16181 		return -EACCES;
16182 	}
16183 	if (env->log.level & BPF_LOG_LEVEL)
16184 		print_insn_state(env, this_branch, this_branch->curframe);
16185 	return 0;
16186 }
16187 
16188 /* verify BPF_LD_IMM64 instruction */
16189 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16190 {
16191 	struct bpf_insn_aux_data *aux = cur_aux(env);
16192 	struct bpf_reg_state *regs = cur_regs(env);
16193 	struct bpf_reg_state *dst_reg;
16194 	struct bpf_map *map;
16195 	int err;
16196 
16197 	if (BPF_SIZE(insn->code) != BPF_DW) {
16198 		verbose(env, "invalid BPF_LD_IMM insn\n");
16199 		return -EINVAL;
16200 	}
16201 	if (insn->off != 0) {
16202 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16203 		return -EINVAL;
16204 	}
16205 
16206 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16207 	if (err)
16208 		return err;
16209 
16210 	dst_reg = &regs[insn->dst_reg];
16211 	if (insn->src_reg == 0) {
16212 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16213 
16214 		dst_reg->type = SCALAR_VALUE;
16215 		__mark_reg_known(&regs[insn->dst_reg], imm);
16216 		return 0;
16217 	}
16218 
16219 	/* All special src_reg cases are listed below. From this point onwards
16220 	 * we either succeed and assign a corresponding dst_reg->type after
16221 	 * zeroing the offset, or fail and reject the program.
16222 	 */
16223 	mark_reg_known_zero(env, regs, insn->dst_reg);
16224 
16225 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16226 		dst_reg->type = aux->btf_var.reg_type;
16227 		switch (base_type(dst_reg->type)) {
16228 		case PTR_TO_MEM:
16229 			dst_reg->mem_size = aux->btf_var.mem_size;
16230 			break;
16231 		case PTR_TO_BTF_ID:
16232 			dst_reg->btf = aux->btf_var.btf;
16233 			dst_reg->btf_id = aux->btf_var.btf_id;
16234 			break;
16235 		default:
16236 			verbose(env, "bpf verifier is misconfigured\n");
16237 			return -EFAULT;
16238 		}
16239 		return 0;
16240 	}
16241 
16242 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16243 		struct bpf_prog_aux *aux = env->prog->aux;
16244 		u32 subprogno = find_subprog(env,
16245 					     env->insn_idx + insn->imm + 1);
16246 
16247 		if (!aux->func_info) {
16248 			verbose(env, "missing btf func_info\n");
16249 			return -EINVAL;
16250 		}
16251 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16252 			verbose(env, "callback function not static\n");
16253 			return -EINVAL;
16254 		}
16255 
16256 		dst_reg->type = PTR_TO_FUNC;
16257 		dst_reg->subprogno = subprogno;
16258 		return 0;
16259 	}
16260 
16261 	map = env->used_maps[aux->map_index];
16262 	dst_reg->map_ptr = map;
16263 
16264 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16265 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16266 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16267 			__mark_reg_unknown(env, dst_reg);
16268 			return 0;
16269 		}
16270 		dst_reg->type = PTR_TO_MAP_VALUE;
16271 		dst_reg->off = aux->map_off;
16272 		WARN_ON_ONCE(map->max_entries != 1);
16273 		/* We want reg->id to be same (0) as map_value is not distinct */
16274 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16275 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16276 		dst_reg->type = CONST_PTR_TO_MAP;
16277 	} else {
16278 		verbose(env, "bpf verifier is misconfigured\n");
16279 		return -EINVAL;
16280 	}
16281 
16282 	return 0;
16283 }
16284 
16285 static bool may_access_skb(enum bpf_prog_type type)
16286 {
16287 	switch (type) {
16288 	case BPF_PROG_TYPE_SOCKET_FILTER:
16289 	case BPF_PROG_TYPE_SCHED_CLS:
16290 	case BPF_PROG_TYPE_SCHED_ACT:
16291 		return true;
16292 	default:
16293 		return false;
16294 	}
16295 }
16296 
16297 /* verify safety of LD_ABS|LD_IND instructions:
16298  * - they can only appear in the programs where ctx == skb
16299  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16300  *   preserve R6-R9, and store return value into R0
16301  *
16302  * Implicit input:
16303  *   ctx == skb == R6 == CTX
16304  *
16305  * Explicit input:
16306  *   SRC == any register
16307  *   IMM == 32-bit immediate
16308  *
16309  * Output:
16310  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16311  */
16312 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16313 {
16314 	struct bpf_reg_state *regs = cur_regs(env);
16315 	static const int ctx_reg = BPF_REG_6;
16316 	u8 mode = BPF_MODE(insn->code);
16317 	int i, err;
16318 
16319 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16320 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16321 		return -EINVAL;
16322 	}
16323 
16324 	if (!env->ops->gen_ld_abs) {
16325 		verbose(env, "bpf verifier is misconfigured\n");
16326 		return -EINVAL;
16327 	}
16328 
16329 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
16330 	    BPF_SIZE(insn->code) == BPF_DW ||
16331 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
16332 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
16333 		return -EINVAL;
16334 	}
16335 
16336 	/* check whether implicit source operand (register R6) is readable */
16337 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16338 	if (err)
16339 		return err;
16340 
16341 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16342 	 * gen_ld_abs() may terminate the program at runtime, leading to
16343 	 * reference leak.
16344 	 */
16345 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16346 	if (err)
16347 		return err;
16348 
16349 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16350 		verbose(env,
16351 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16352 		return -EINVAL;
16353 	}
16354 
16355 	if (mode == BPF_IND) {
16356 		/* check explicit source operand */
16357 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16358 		if (err)
16359 			return err;
16360 	}
16361 
16362 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16363 	if (err < 0)
16364 		return err;
16365 
16366 	/* reset caller saved regs to unreadable */
16367 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16368 		mark_reg_not_init(env, regs, caller_saved[i]);
16369 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16370 	}
16371 
16372 	/* mark destination R0 register as readable, since it contains
16373 	 * the value fetched from the packet.
16374 	 * Already marked as written above.
16375 	 */
16376 	mark_reg_unknown(env, regs, BPF_REG_0);
16377 	/* ld_abs load up to 32-bit skb data. */
16378 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16379 	return 0;
16380 }
16381 
16382 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16383 {
16384 	const char *exit_ctx = "At program exit";
16385 	struct tnum enforce_attach_type_range = tnum_unknown;
16386 	const struct bpf_prog *prog = env->prog;
16387 	struct bpf_reg_state *reg;
16388 	struct bpf_retval_range range = retval_range(0, 1);
16389 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16390 	int err;
16391 	struct bpf_func_state *frame = env->cur_state->frame[0];
16392 	const bool is_subprog = frame->subprogno;
16393 	bool return_32bit = false;
16394 
16395 	/* LSM and struct_ops func-ptr's return type could be "void" */
16396 	if (!is_subprog || frame->in_exception_callback_fn) {
16397 		switch (prog_type) {
16398 		case BPF_PROG_TYPE_LSM:
16399 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
16400 				/* See below, can be 0 or 0-1 depending on hook. */
16401 				break;
16402 			fallthrough;
16403 		case BPF_PROG_TYPE_STRUCT_OPS:
16404 			if (!prog->aux->attach_func_proto->type)
16405 				return 0;
16406 			break;
16407 		default:
16408 			break;
16409 		}
16410 	}
16411 
16412 	/* eBPF calling convention is such that R0 is used
16413 	 * to return the value from eBPF program.
16414 	 * Make sure that it's readable at this time
16415 	 * of bpf_exit, which means that program wrote
16416 	 * something into it earlier
16417 	 */
16418 	err = check_reg_arg(env, regno, SRC_OP);
16419 	if (err)
16420 		return err;
16421 
16422 	if (is_pointer_value(env, regno)) {
16423 		verbose(env, "R%d leaks addr as return value\n", regno);
16424 		return -EACCES;
16425 	}
16426 
16427 	reg = cur_regs(env) + regno;
16428 
16429 	if (frame->in_async_callback_fn) {
16430 		/* enforce return zero from async callbacks like timer */
16431 		exit_ctx = "At async callback return";
16432 		range = retval_range(0, 0);
16433 		goto enforce_retval;
16434 	}
16435 
16436 	if (is_subprog && !frame->in_exception_callback_fn) {
16437 		if (reg->type != SCALAR_VALUE) {
16438 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
16439 				regno, reg_type_str(env, reg->type));
16440 			return -EINVAL;
16441 		}
16442 		return 0;
16443 	}
16444 
16445 	switch (prog_type) {
16446 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16447 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
16448 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
16449 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
16450 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
16451 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
16452 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
16453 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
16454 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
16455 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
16456 			range = retval_range(1, 1);
16457 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
16458 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
16459 			range = retval_range(0, 3);
16460 		break;
16461 	case BPF_PROG_TYPE_CGROUP_SKB:
16462 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
16463 			range = retval_range(0, 3);
16464 			enforce_attach_type_range = tnum_range(2, 3);
16465 		}
16466 		break;
16467 	case BPF_PROG_TYPE_CGROUP_SOCK:
16468 	case BPF_PROG_TYPE_SOCK_OPS:
16469 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16470 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16471 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16472 		break;
16473 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16474 		if (!env->prog->aux->attach_btf_id)
16475 			return 0;
16476 		range = retval_range(0, 0);
16477 		break;
16478 	case BPF_PROG_TYPE_TRACING:
16479 		switch (env->prog->expected_attach_type) {
16480 		case BPF_TRACE_FENTRY:
16481 		case BPF_TRACE_FEXIT:
16482 			range = retval_range(0, 0);
16483 			break;
16484 		case BPF_TRACE_RAW_TP:
16485 		case BPF_MODIFY_RETURN:
16486 			return 0;
16487 		case BPF_TRACE_ITER:
16488 			break;
16489 		default:
16490 			return -ENOTSUPP;
16491 		}
16492 		break;
16493 	case BPF_PROG_TYPE_KPROBE:
16494 		switch (env->prog->expected_attach_type) {
16495 		case BPF_TRACE_KPROBE_SESSION:
16496 		case BPF_TRACE_UPROBE_SESSION:
16497 			range = retval_range(0, 1);
16498 			break;
16499 		default:
16500 			return 0;
16501 		}
16502 		break;
16503 	case BPF_PROG_TYPE_SK_LOOKUP:
16504 		range = retval_range(SK_DROP, SK_PASS);
16505 		break;
16506 
16507 	case BPF_PROG_TYPE_LSM:
16508 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16509 			/* no range found, any return value is allowed */
16510 			if (!get_func_retval_range(env->prog, &range))
16511 				return 0;
16512 			/* no restricted range, any return value is allowed */
16513 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
16514 				return 0;
16515 			return_32bit = true;
16516 		} else if (!env->prog->aux->attach_func_proto->type) {
16517 			/* Make sure programs that attach to void
16518 			 * hooks don't try to modify return value.
16519 			 */
16520 			range = retval_range(1, 1);
16521 		}
16522 		break;
16523 
16524 	case BPF_PROG_TYPE_NETFILTER:
16525 		range = retval_range(NF_DROP, NF_ACCEPT);
16526 		break;
16527 	case BPF_PROG_TYPE_EXT:
16528 		/* freplace program can return anything as its return value
16529 		 * depends on the to-be-replaced kernel func or bpf program.
16530 		 */
16531 	default:
16532 		return 0;
16533 	}
16534 
16535 enforce_retval:
16536 	if (reg->type != SCALAR_VALUE) {
16537 		verbose(env, "%s the register R%d is not a known value (%s)\n",
16538 			exit_ctx, regno, reg_type_str(env, reg->type));
16539 		return -EINVAL;
16540 	}
16541 
16542 	err = mark_chain_precision(env, regno);
16543 	if (err)
16544 		return err;
16545 
16546 	if (!retval_range_within(range, reg, return_32bit)) {
16547 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
16548 		if (!is_subprog &&
16549 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
16550 		    prog_type == BPF_PROG_TYPE_LSM &&
16551 		    !prog->aux->attach_func_proto->type)
16552 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
16553 		return -EINVAL;
16554 	}
16555 
16556 	if (!tnum_is_unknown(enforce_attach_type_range) &&
16557 	    tnum_in(enforce_attach_type_range, reg->var_off))
16558 		env->prog->enforce_expected_attach_type = 1;
16559 	return 0;
16560 }
16561 
16562 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
16563 {
16564 	struct bpf_subprog_info *subprog;
16565 
16566 	subprog = find_containing_subprog(env, off);
16567 	subprog->changes_pkt_data = true;
16568 }
16569 
16570 /* 't' is an index of a call-site.
16571  * 'w' is a callee entry point.
16572  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
16573  * Rely on DFS traversal order and absence of recursive calls to guarantee that
16574  * callee's change_pkt_data marks would be correct at that moment.
16575  */
16576 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
16577 {
16578 	struct bpf_subprog_info *caller, *callee;
16579 
16580 	caller = find_containing_subprog(env, t);
16581 	callee = find_containing_subprog(env, w);
16582 	caller->changes_pkt_data |= callee->changes_pkt_data;
16583 }
16584 
16585 /* non-recursive DFS pseudo code
16586  * 1  procedure DFS-iterative(G,v):
16587  * 2      label v as discovered
16588  * 3      let S be a stack
16589  * 4      S.push(v)
16590  * 5      while S is not empty
16591  * 6            t <- S.peek()
16592  * 7            if t is what we're looking for:
16593  * 8                return t
16594  * 9            for all edges e in G.adjacentEdges(t) do
16595  * 10               if edge e is already labelled
16596  * 11                   continue with the next edge
16597  * 12               w <- G.adjacentVertex(t,e)
16598  * 13               if vertex w is not discovered and not explored
16599  * 14                   label e as tree-edge
16600  * 15                   label w as discovered
16601  * 16                   S.push(w)
16602  * 17                   continue at 5
16603  * 18               else if vertex w is discovered
16604  * 19                   label e as back-edge
16605  * 20               else
16606  * 21                   // vertex w is explored
16607  * 22                   label e as forward- or cross-edge
16608  * 23           label t as explored
16609  * 24           S.pop()
16610  *
16611  * convention:
16612  * 0x10 - discovered
16613  * 0x11 - discovered and fall-through edge labelled
16614  * 0x12 - discovered and fall-through and branch edges labelled
16615  * 0x20 - explored
16616  */
16617 
16618 enum {
16619 	DISCOVERED = 0x10,
16620 	EXPLORED = 0x20,
16621 	FALLTHROUGH = 1,
16622 	BRANCH = 2,
16623 };
16624 
16625 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
16626 {
16627 	env->insn_aux_data[idx].prune_point = true;
16628 }
16629 
16630 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
16631 {
16632 	return env->insn_aux_data[insn_idx].prune_point;
16633 }
16634 
16635 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
16636 {
16637 	env->insn_aux_data[idx].force_checkpoint = true;
16638 }
16639 
16640 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
16641 {
16642 	return env->insn_aux_data[insn_idx].force_checkpoint;
16643 }
16644 
16645 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
16646 {
16647 	env->insn_aux_data[idx].calls_callback = true;
16648 }
16649 
16650 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
16651 {
16652 	return env->insn_aux_data[insn_idx].calls_callback;
16653 }
16654 
16655 enum {
16656 	DONE_EXPLORING = 0,
16657 	KEEP_EXPLORING = 1,
16658 };
16659 
16660 /* t, w, e - match pseudo-code above:
16661  * t - index of current instruction
16662  * w - next instruction
16663  * e - edge
16664  */
16665 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
16666 {
16667 	int *insn_stack = env->cfg.insn_stack;
16668 	int *insn_state = env->cfg.insn_state;
16669 
16670 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
16671 		return DONE_EXPLORING;
16672 
16673 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
16674 		return DONE_EXPLORING;
16675 
16676 	if (w < 0 || w >= env->prog->len) {
16677 		verbose_linfo(env, t, "%d: ", t);
16678 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
16679 		return -EINVAL;
16680 	}
16681 
16682 	if (e == BRANCH) {
16683 		/* mark branch target for state pruning */
16684 		mark_prune_point(env, w);
16685 		mark_jmp_point(env, w);
16686 	}
16687 
16688 	if (insn_state[w] == 0) {
16689 		/* tree-edge */
16690 		insn_state[t] = DISCOVERED | e;
16691 		insn_state[w] = DISCOVERED;
16692 		if (env->cfg.cur_stack >= env->prog->len)
16693 			return -E2BIG;
16694 		insn_stack[env->cfg.cur_stack++] = w;
16695 		return KEEP_EXPLORING;
16696 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
16697 		if (env->bpf_capable)
16698 			return DONE_EXPLORING;
16699 		verbose_linfo(env, t, "%d: ", t);
16700 		verbose_linfo(env, w, "%d: ", w);
16701 		verbose(env, "back-edge from insn %d to %d\n", t, w);
16702 		return -EINVAL;
16703 	} else if (insn_state[w] == EXPLORED) {
16704 		/* forward- or cross-edge */
16705 		insn_state[t] = DISCOVERED | e;
16706 	} else {
16707 		verbose(env, "insn state internal bug\n");
16708 		return -EFAULT;
16709 	}
16710 	return DONE_EXPLORING;
16711 }
16712 
16713 static int visit_func_call_insn(int t, struct bpf_insn *insns,
16714 				struct bpf_verifier_env *env,
16715 				bool visit_callee)
16716 {
16717 	int ret, insn_sz;
16718 	int w;
16719 
16720 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
16721 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
16722 	if (ret)
16723 		return ret;
16724 
16725 	mark_prune_point(env, t + insn_sz);
16726 	/* when we exit from subprog, we need to record non-linear history */
16727 	mark_jmp_point(env, t + insn_sz);
16728 
16729 	if (visit_callee) {
16730 		w = t + insns[t].imm + 1;
16731 		mark_prune_point(env, t);
16732 		merge_callee_effects(env, t, w);
16733 		ret = push_insn(t, w, BRANCH, env);
16734 	}
16735 	return ret;
16736 }
16737 
16738 /* Bitmask with 1s for all caller saved registers */
16739 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16740 
16741 /* Return a bitmask specifying which caller saved registers are
16742  * clobbered by a call to a helper *as if* this helper follows
16743  * bpf_fastcall contract:
16744  * - includes R0 if function is non-void;
16745  * - includes R1-R5 if corresponding parameter has is described
16746  *   in the function prototype.
16747  */
16748 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
16749 {
16750 	u32 mask;
16751 	int i;
16752 
16753 	mask = 0;
16754 	if (fn->ret_type != RET_VOID)
16755 		mask |= BIT(BPF_REG_0);
16756 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
16757 		if (fn->arg_type[i] != ARG_DONTCARE)
16758 			mask |= BIT(BPF_REG_1 + i);
16759 	return mask;
16760 }
16761 
16762 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16763  * replacement patch is presumed to follow bpf_fastcall contract
16764  * (see mark_fastcall_pattern_for_call() below).
16765  */
16766 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16767 {
16768 	switch (imm) {
16769 #ifdef CONFIG_X86_64
16770 	case BPF_FUNC_get_smp_processor_id:
16771 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16772 #endif
16773 	default:
16774 		return false;
16775 	}
16776 }
16777 
16778 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
16779 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
16780 {
16781 	u32 vlen, i, mask;
16782 
16783 	vlen = btf_type_vlen(meta->func_proto);
16784 	mask = 0;
16785 	if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
16786 		mask |= BIT(BPF_REG_0);
16787 	for (i = 0; i < vlen; ++i)
16788 		mask |= BIT(BPF_REG_1 + i);
16789 	return mask;
16790 }
16791 
16792 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
16793 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
16794 {
16795 	return meta->kfunc_flags & KF_FASTCALL;
16796 }
16797 
16798 /* LLVM define a bpf_fastcall function attribute.
16799  * This attribute means that function scratches only some of
16800  * the caller saved registers defined by ABI.
16801  * For BPF the set of such registers could be defined as follows:
16802  * - R0 is scratched only if function is non-void;
16803  * - R1-R5 are scratched only if corresponding parameter type is defined
16804  *   in the function prototype.
16805  *
16806  * The contract between kernel and clang allows to simultaneously use
16807  * such functions and maintain backwards compatibility with old
16808  * kernels that don't understand bpf_fastcall calls:
16809  *
16810  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16811  *   registers are not scratched by the call;
16812  *
16813  * - as a post-processing step, clang visits each bpf_fastcall call and adds
16814  *   spill/fill for every live r0-r5;
16815  *
16816  * - stack offsets used for the spill/fill are allocated as lowest
16817  *   stack offsets in whole function and are not used for any other
16818  *   purposes;
16819  *
16820  * - when kernel loads a program, it looks for such patterns
16821  *   (bpf_fastcall function surrounded by spills/fills) and checks if
16822  *   spill/fill stack offsets are used exclusively in fastcall patterns;
16823  *
16824  * - if so, and if verifier or current JIT inlines the call to the
16825  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16826  *   spill/fill pairs;
16827  *
16828  * - when old kernel loads a program, presence of spill/fill pairs
16829  *   keeps BPF program valid, albeit slightly less efficient.
16830  *
16831  * For example:
16832  *
16833  *   r1 = 1;
16834  *   r2 = 2;
16835  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16836  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
16837  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16838  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
16839  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
16840  *   r0 = r1;                            exit;
16841  *   r0 += r2;
16842  *   exit;
16843  *
16844  * The purpose of mark_fastcall_pattern_for_call is to:
16845  * - look for such patterns;
16846  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16847  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16848  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16849  *   at which bpf_fastcall spill/fill stack slots start;
16850  * - update env->subprog_info[*]->keep_fastcall_stack.
16851  *
16852  * The .fastcall_pattern and .fastcall_stack_off are used by
16853  * check_fastcall_stack_contract() to check if every stack access to
16854  * fastcall spill/fill stack slot originates from spill/fill
16855  * instructions, members of fastcall patterns.
16856  *
16857  * If such condition holds true for a subprogram, fastcall patterns could
16858  * be rewritten by remove_fastcall_spills_fills().
16859  * Otherwise bpf_fastcall patterns are not changed in the subprogram
16860  * (code, presumably, generated by an older clang version).
16861  *
16862  * For example, it is *not* safe to remove spill/fill below:
16863  *
16864  *   r1 = 1;
16865  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16866  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16867  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
16868  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
16869  *   r0 += r1;                           exit;
16870  *   exit;
16871  */
16872 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16873 					   struct bpf_subprog_info *subprog,
16874 					   int insn_idx, s16 lowest_off)
16875 {
16876 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16877 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16878 	const struct bpf_func_proto *fn;
16879 	u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
16880 	u32 expected_regs_mask;
16881 	bool can_be_inlined = false;
16882 	s16 off;
16883 	int i;
16884 
16885 	if (bpf_helper_call(call)) {
16886 		if (get_helper_proto(env, call->imm, &fn) < 0)
16887 			/* error would be reported later */
16888 			return;
16889 		clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
16890 		can_be_inlined = fn->allow_fastcall &&
16891 				 (verifier_inlines_helper_call(env, call->imm) ||
16892 				  bpf_jit_inlines_helper_call(call->imm));
16893 	}
16894 
16895 	if (bpf_pseudo_kfunc_call(call)) {
16896 		struct bpf_kfunc_call_arg_meta meta;
16897 		int err;
16898 
16899 		err = fetch_kfunc_meta(env, call, &meta, NULL);
16900 		if (err < 0)
16901 			/* error would be reported later */
16902 			return;
16903 
16904 		clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
16905 		can_be_inlined = is_fastcall_kfunc_call(&meta);
16906 	}
16907 
16908 	if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
16909 		return;
16910 
16911 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16912 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16913 
16914 	/* match pairs of form:
16915 	 *
16916 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16917 	 * ...
16918 	 * call %[to_be_inlined]
16919 	 * ...
16920 	 * rX = *(u64 *)(r10 - Y)
16921 	 */
16922 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16923 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16924 			break;
16925 		stx = &insns[insn_idx - i];
16926 		ldx = &insns[insn_idx + i];
16927 		/* must be a stack spill/fill pair */
16928 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16929 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16930 		    stx->dst_reg != BPF_REG_10 ||
16931 		    ldx->src_reg != BPF_REG_10)
16932 			break;
16933 		/* must be a spill/fill for the same reg */
16934 		if (stx->src_reg != ldx->dst_reg)
16935 			break;
16936 		/* must be one of the previously unseen registers */
16937 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16938 			break;
16939 		/* must be a spill/fill for the same expected offset,
16940 		 * no need to check offset alignment, BPF_DW stack access
16941 		 * is always 8-byte aligned.
16942 		 */
16943 		if (stx->off != off || ldx->off != off)
16944 			break;
16945 		expected_regs_mask &= ~BIT(stx->src_reg);
16946 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16947 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16948 	}
16949 	if (i == 1)
16950 		return;
16951 
16952 	/* Conditionally set 'fastcall_spills_num' to allow forward
16953 	 * compatibility when more helper functions are marked as
16954 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16955 	 *
16956 	 *   1: *(u64 *)(r10 - 8) = r1
16957 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16958 	 *   3: r1 = *(u64 *)(r10 - 8)
16959 	 *   4: *(u64 *)(r10 - 8) = r1
16960 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16961 	 *   6: r1 = *(u64 *)(r10 - 8)
16962 	 *
16963 	 * There is no need to block bpf_fastcall rewrite for such program.
16964 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16965 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16966 	 * does not remove spill/fill pair {4,6}.
16967 	 */
16968 	if (can_be_inlined)
16969 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16970 	else
16971 		subprog->keep_fastcall_stack = 1;
16972 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16973 }
16974 
16975 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16976 {
16977 	struct bpf_subprog_info *subprog = env->subprog_info;
16978 	struct bpf_insn *insn;
16979 	s16 lowest_off;
16980 	int s, i;
16981 
16982 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16983 		/* find lowest stack spill offset used in this subprog */
16984 		lowest_off = 0;
16985 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16986 			insn = env->prog->insnsi + i;
16987 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16988 			    insn->dst_reg != BPF_REG_10)
16989 				continue;
16990 			lowest_off = min(lowest_off, insn->off);
16991 		}
16992 		/* use this offset to find fastcall patterns */
16993 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16994 			insn = env->prog->insnsi + i;
16995 			if (insn->code != (BPF_JMP | BPF_CALL))
16996 				continue;
16997 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16998 		}
16999 	}
17000 	return 0;
17001 }
17002 
17003 /* Visits the instruction at index t and returns one of the following:
17004  *  < 0 - an error occurred
17005  *  DONE_EXPLORING - the instruction was fully explored
17006  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17007  */
17008 static int visit_insn(int t, struct bpf_verifier_env *env)
17009 {
17010 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17011 	int ret, off, insn_sz;
17012 
17013 	if (bpf_pseudo_func(insn))
17014 		return visit_func_call_insn(t, insns, env, true);
17015 
17016 	/* All non-branch instructions have a single fall-through edge. */
17017 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17018 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17019 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17020 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17021 	}
17022 
17023 	switch (BPF_OP(insn->code)) {
17024 	case BPF_EXIT:
17025 		return DONE_EXPLORING;
17026 
17027 	case BPF_CALL:
17028 		if (is_async_callback_calling_insn(insn))
17029 			/* Mark this call insn as a prune point to trigger
17030 			 * is_state_visited() check before call itself is
17031 			 * processed by __check_func_call(). Otherwise new
17032 			 * async state will be pushed for further exploration.
17033 			 */
17034 			mark_prune_point(env, t);
17035 		/* For functions that invoke callbacks it is not known how many times
17036 		 * callback would be called. Verifier models callback calling functions
17037 		 * by repeatedly visiting callback bodies and returning to origin call
17038 		 * instruction.
17039 		 * In order to stop such iteration verifier needs to identify when a
17040 		 * state identical some state from a previous iteration is reached.
17041 		 * Check below forces creation of checkpoint before callback calling
17042 		 * instruction to allow search for such identical states.
17043 		 */
17044 		if (is_sync_callback_calling_insn(insn)) {
17045 			mark_calls_callback(env, t);
17046 			mark_force_checkpoint(env, t);
17047 			mark_prune_point(env, t);
17048 			mark_jmp_point(env, t);
17049 		}
17050 		if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm))
17051 			mark_subprog_changes_pkt_data(env, t);
17052 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17053 			struct bpf_kfunc_call_arg_meta meta;
17054 
17055 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17056 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17057 				mark_prune_point(env, t);
17058 				/* Checking and saving state checkpoints at iter_next() call
17059 				 * is crucial for fast convergence of open-coded iterator loop
17060 				 * logic, so we need to force it. If we don't do that,
17061 				 * is_state_visited() might skip saving a checkpoint, causing
17062 				 * unnecessarily long sequence of not checkpointed
17063 				 * instructions and jumps, leading to exhaustion of jump
17064 				 * history buffer, and potentially other undesired outcomes.
17065 				 * It is expected that with correct open-coded iterators
17066 				 * convergence will happen quickly, so we don't run a risk of
17067 				 * exhausting memory.
17068 				 */
17069 				mark_force_checkpoint(env, t);
17070 			}
17071 		}
17072 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17073 
17074 	case BPF_JA:
17075 		if (BPF_SRC(insn->code) != BPF_K)
17076 			return -EINVAL;
17077 
17078 		if (BPF_CLASS(insn->code) == BPF_JMP)
17079 			off = insn->off;
17080 		else
17081 			off = insn->imm;
17082 
17083 		/* unconditional jump with single edge */
17084 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17085 		if (ret)
17086 			return ret;
17087 
17088 		mark_prune_point(env, t + off + 1);
17089 		mark_jmp_point(env, t + off + 1);
17090 
17091 		return ret;
17092 
17093 	default:
17094 		/* conditional jump with two edges */
17095 		mark_prune_point(env, t);
17096 		if (is_may_goto_insn(insn))
17097 			mark_force_checkpoint(env, t);
17098 
17099 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17100 		if (ret)
17101 			return ret;
17102 
17103 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17104 	}
17105 }
17106 
17107 /* non-recursive depth-first-search to detect loops in BPF program
17108  * loop == back-edge in directed graph
17109  */
17110 static int check_cfg(struct bpf_verifier_env *env)
17111 {
17112 	int insn_cnt = env->prog->len;
17113 	int *insn_stack, *insn_state;
17114 	int ex_insn_beg, i, ret = 0;
17115 	bool ex_done = false;
17116 
17117 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17118 	if (!insn_state)
17119 		return -ENOMEM;
17120 
17121 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17122 	if (!insn_stack) {
17123 		kvfree(insn_state);
17124 		return -ENOMEM;
17125 	}
17126 
17127 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17128 	insn_stack[0] = 0; /* 0 is the first instruction */
17129 	env->cfg.cur_stack = 1;
17130 
17131 walk_cfg:
17132 	while (env->cfg.cur_stack > 0) {
17133 		int t = insn_stack[env->cfg.cur_stack - 1];
17134 
17135 		ret = visit_insn(t, env);
17136 		switch (ret) {
17137 		case DONE_EXPLORING:
17138 			insn_state[t] = EXPLORED;
17139 			env->cfg.cur_stack--;
17140 			break;
17141 		case KEEP_EXPLORING:
17142 			break;
17143 		default:
17144 			if (ret > 0) {
17145 				verbose(env, "visit_insn internal bug\n");
17146 				ret = -EFAULT;
17147 			}
17148 			goto err_free;
17149 		}
17150 	}
17151 
17152 	if (env->cfg.cur_stack < 0) {
17153 		verbose(env, "pop stack internal bug\n");
17154 		ret = -EFAULT;
17155 		goto err_free;
17156 	}
17157 
17158 	if (env->exception_callback_subprog && !ex_done) {
17159 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
17160 
17161 		insn_state[ex_insn_beg] = DISCOVERED;
17162 		insn_stack[0] = ex_insn_beg;
17163 		env->cfg.cur_stack = 1;
17164 		ex_done = true;
17165 		goto walk_cfg;
17166 	}
17167 
17168 	for (i = 0; i < insn_cnt; i++) {
17169 		struct bpf_insn *insn = &env->prog->insnsi[i];
17170 
17171 		if (insn_state[i] != EXPLORED) {
17172 			verbose(env, "unreachable insn %d\n", i);
17173 			ret = -EINVAL;
17174 			goto err_free;
17175 		}
17176 		if (bpf_is_ldimm64(insn)) {
17177 			if (insn_state[i + 1] != 0) {
17178 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17179 				ret = -EINVAL;
17180 				goto err_free;
17181 			}
17182 			i++; /* skip second half of ldimm64 */
17183 		}
17184 	}
17185 	ret = 0; /* cfg looks good */
17186 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17187 
17188 err_free:
17189 	kvfree(insn_state);
17190 	kvfree(insn_stack);
17191 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17192 	return ret;
17193 }
17194 
17195 static int check_abnormal_return(struct bpf_verifier_env *env)
17196 {
17197 	int i;
17198 
17199 	for (i = 1; i < env->subprog_cnt; i++) {
17200 		if (env->subprog_info[i].has_ld_abs) {
17201 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
17202 			return -EINVAL;
17203 		}
17204 		if (env->subprog_info[i].has_tail_call) {
17205 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
17206 			return -EINVAL;
17207 		}
17208 	}
17209 	return 0;
17210 }
17211 
17212 /* The minimum supported BTF func info size */
17213 #define MIN_BPF_FUNCINFO_SIZE	8
17214 #define MAX_FUNCINFO_REC_SIZE	252
17215 
17216 static int check_btf_func_early(struct bpf_verifier_env *env,
17217 				const union bpf_attr *attr,
17218 				bpfptr_t uattr)
17219 {
17220 	u32 krec_size = sizeof(struct bpf_func_info);
17221 	const struct btf_type *type, *func_proto;
17222 	u32 i, nfuncs, urec_size, min_size;
17223 	struct bpf_func_info *krecord;
17224 	struct bpf_prog *prog;
17225 	const struct btf *btf;
17226 	u32 prev_offset = 0;
17227 	bpfptr_t urecord;
17228 	int ret = -ENOMEM;
17229 
17230 	nfuncs = attr->func_info_cnt;
17231 	if (!nfuncs) {
17232 		if (check_abnormal_return(env))
17233 			return -EINVAL;
17234 		return 0;
17235 	}
17236 
17237 	urec_size = attr->func_info_rec_size;
17238 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
17239 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
17240 	    urec_size % sizeof(u32)) {
17241 		verbose(env, "invalid func info rec size %u\n", urec_size);
17242 		return -EINVAL;
17243 	}
17244 
17245 	prog = env->prog;
17246 	btf = prog->aux->btf;
17247 
17248 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17249 	min_size = min_t(u32, krec_size, urec_size);
17250 
17251 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
17252 	if (!krecord)
17253 		return -ENOMEM;
17254 
17255 	for (i = 0; i < nfuncs; i++) {
17256 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
17257 		if (ret) {
17258 			if (ret == -E2BIG) {
17259 				verbose(env, "nonzero tailing record in func info");
17260 				/* set the size kernel expects so loader can zero
17261 				 * out the rest of the record.
17262 				 */
17263 				if (copy_to_bpfptr_offset(uattr,
17264 							  offsetof(union bpf_attr, func_info_rec_size),
17265 							  &min_size, sizeof(min_size)))
17266 					ret = -EFAULT;
17267 			}
17268 			goto err_free;
17269 		}
17270 
17271 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
17272 			ret = -EFAULT;
17273 			goto err_free;
17274 		}
17275 
17276 		/* check insn_off */
17277 		ret = -EINVAL;
17278 		if (i == 0) {
17279 			if (krecord[i].insn_off) {
17280 				verbose(env,
17281 					"nonzero insn_off %u for the first func info record",
17282 					krecord[i].insn_off);
17283 				goto err_free;
17284 			}
17285 		} else if (krecord[i].insn_off <= prev_offset) {
17286 			verbose(env,
17287 				"same or smaller insn offset (%u) than previous func info record (%u)",
17288 				krecord[i].insn_off, prev_offset);
17289 			goto err_free;
17290 		}
17291 
17292 		/* check type_id */
17293 		type = btf_type_by_id(btf, krecord[i].type_id);
17294 		if (!type || !btf_type_is_func(type)) {
17295 			verbose(env, "invalid type id %d in func info",
17296 				krecord[i].type_id);
17297 			goto err_free;
17298 		}
17299 
17300 		func_proto = btf_type_by_id(btf, type->type);
17301 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
17302 			/* btf_func_check() already verified it during BTF load */
17303 			goto err_free;
17304 
17305 		prev_offset = krecord[i].insn_off;
17306 		bpfptr_add(&urecord, urec_size);
17307 	}
17308 
17309 	prog->aux->func_info = krecord;
17310 	prog->aux->func_info_cnt = nfuncs;
17311 	return 0;
17312 
17313 err_free:
17314 	kvfree(krecord);
17315 	return ret;
17316 }
17317 
17318 static int check_btf_func(struct bpf_verifier_env *env,
17319 			  const union bpf_attr *attr,
17320 			  bpfptr_t uattr)
17321 {
17322 	const struct btf_type *type, *func_proto, *ret_type;
17323 	u32 i, nfuncs, urec_size;
17324 	struct bpf_func_info *krecord;
17325 	struct bpf_func_info_aux *info_aux = NULL;
17326 	struct bpf_prog *prog;
17327 	const struct btf *btf;
17328 	bpfptr_t urecord;
17329 	bool scalar_return;
17330 	int ret = -ENOMEM;
17331 
17332 	nfuncs = attr->func_info_cnt;
17333 	if (!nfuncs) {
17334 		if (check_abnormal_return(env))
17335 			return -EINVAL;
17336 		return 0;
17337 	}
17338 	if (nfuncs != env->subprog_cnt) {
17339 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
17340 		return -EINVAL;
17341 	}
17342 
17343 	urec_size = attr->func_info_rec_size;
17344 
17345 	prog = env->prog;
17346 	btf = prog->aux->btf;
17347 
17348 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17349 
17350 	krecord = prog->aux->func_info;
17351 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
17352 	if (!info_aux)
17353 		return -ENOMEM;
17354 
17355 	for (i = 0; i < nfuncs; i++) {
17356 		/* check insn_off */
17357 		ret = -EINVAL;
17358 
17359 		if (env->subprog_info[i].start != krecord[i].insn_off) {
17360 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
17361 			goto err_free;
17362 		}
17363 
17364 		/* Already checked type_id */
17365 		type = btf_type_by_id(btf, krecord[i].type_id);
17366 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
17367 		/* Already checked func_proto */
17368 		func_proto = btf_type_by_id(btf, type->type);
17369 
17370 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
17371 		scalar_return =
17372 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
17373 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
17374 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
17375 			goto err_free;
17376 		}
17377 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
17378 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
17379 			goto err_free;
17380 		}
17381 
17382 		bpfptr_add(&urecord, urec_size);
17383 	}
17384 
17385 	prog->aux->func_info_aux = info_aux;
17386 	return 0;
17387 
17388 err_free:
17389 	kfree(info_aux);
17390 	return ret;
17391 }
17392 
17393 static void adjust_btf_func(struct bpf_verifier_env *env)
17394 {
17395 	struct bpf_prog_aux *aux = env->prog->aux;
17396 	int i;
17397 
17398 	if (!aux->func_info)
17399 		return;
17400 
17401 	/* func_info is not available for hidden subprogs */
17402 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
17403 		aux->func_info[i].insn_off = env->subprog_info[i].start;
17404 }
17405 
17406 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
17407 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
17408 
17409 static int check_btf_line(struct bpf_verifier_env *env,
17410 			  const union bpf_attr *attr,
17411 			  bpfptr_t uattr)
17412 {
17413 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
17414 	struct bpf_subprog_info *sub;
17415 	struct bpf_line_info *linfo;
17416 	struct bpf_prog *prog;
17417 	const struct btf *btf;
17418 	bpfptr_t ulinfo;
17419 	int err;
17420 
17421 	nr_linfo = attr->line_info_cnt;
17422 	if (!nr_linfo)
17423 		return 0;
17424 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
17425 		return -EINVAL;
17426 
17427 	rec_size = attr->line_info_rec_size;
17428 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
17429 	    rec_size > MAX_LINEINFO_REC_SIZE ||
17430 	    rec_size & (sizeof(u32) - 1))
17431 		return -EINVAL;
17432 
17433 	/* Need to zero it in case the userspace may
17434 	 * pass in a smaller bpf_line_info object.
17435 	 */
17436 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
17437 			 GFP_KERNEL | __GFP_NOWARN);
17438 	if (!linfo)
17439 		return -ENOMEM;
17440 
17441 	prog = env->prog;
17442 	btf = prog->aux->btf;
17443 
17444 	s = 0;
17445 	sub = env->subprog_info;
17446 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
17447 	expected_size = sizeof(struct bpf_line_info);
17448 	ncopy = min_t(u32, expected_size, rec_size);
17449 	for (i = 0; i < nr_linfo; i++) {
17450 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
17451 		if (err) {
17452 			if (err == -E2BIG) {
17453 				verbose(env, "nonzero tailing record in line_info");
17454 				if (copy_to_bpfptr_offset(uattr,
17455 							  offsetof(union bpf_attr, line_info_rec_size),
17456 							  &expected_size, sizeof(expected_size)))
17457 					err = -EFAULT;
17458 			}
17459 			goto err_free;
17460 		}
17461 
17462 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
17463 			err = -EFAULT;
17464 			goto err_free;
17465 		}
17466 
17467 		/*
17468 		 * Check insn_off to ensure
17469 		 * 1) strictly increasing AND
17470 		 * 2) bounded by prog->len
17471 		 *
17472 		 * The linfo[0].insn_off == 0 check logically falls into
17473 		 * the later "missing bpf_line_info for func..." case
17474 		 * because the first linfo[0].insn_off must be the
17475 		 * first sub also and the first sub must have
17476 		 * subprog_info[0].start == 0.
17477 		 */
17478 		if ((i && linfo[i].insn_off <= prev_offset) ||
17479 		    linfo[i].insn_off >= prog->len) {
17480 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
17481 				i, linfo[i].insn_off, prev_offset,
17482 				prog->len);
17483 			err = -EINVAL;
17484 			goto err_free;
17485 		}
17486 
17487 		if (!prog->insnsi[linfo[i].insn_off].code) {
17488 			verbose(env,
17489 				"Invalid insn code at line_info[%u].insn_off\n",
17490 				i);
17491 			err = -EINVAL;
17492 			goto err_free;
17493 		}
17494 
17495 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
17496 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
17497 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
17498 			err = -EINVAL;
17499 			goto err_free;
17500 		}
17501 
17502 		if (s != env->subprog_cnt) {
17503 			if (linfo[i].insn_off == sub[s].start) {
17504 				sub[s].linfo_idx = i;
17505 				s++;
17506 			} else if (sub[s].start < linfo[i].insn_off) {
17507 				verbose(env, "missing bpf_line_info for func#%u\n", s);
17508 				err = -EINVAL;
17509 				goto err_free;
17510 			}
17511 		}
17512 
17513 		prev_offset = linfo[i].insn_off;
17514 		bpfptr_add(&ulinfo, rec_size);
17515 	}
17516 
17517 	if (s != env->subprog_cnt) {
17518 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
17519 			env->subprog_cnt - s, s);
17520 		err = -EINVAL;
17521 		goto err_free;
17522 	}
17523 
17524 	prog->aux->linfo = linfo;
17525 	prog->aux->nr_linfo = nr_linfo;
17526 
17527 	return 0;
17528 
17529 err_free:
17530 	kvfree(linfo);
17531 	return err;
17532 }
17533 
17534 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
17535 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
17536 
17537 static int check_core_relo(struct bpf_verifier_env *env,
17538 			   const union bpf_attr *attr,
17539 			   bpfptr_t uattr)
17540 {
17541 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
17542 	struct bpf_core_relo core_relo = {};
17543 	struct bpf_prog *prog = env->prog;
17544 	const struct btf *btf = prog->aux->btf;
17545 	struct bpf_core_ctx ctx = {
17546 		.log = &env->log,
17547 		.btf = btf,
17548 	};
17549 	bpfptr_t u_core_relo;
17550 	int err;
17551 
17552 	nr_core_relo = attr->core_relo_cnt;
17553 	if (!nr_core_relo)
17554 		return 0;
17555 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
17556 		return -EINVAL;
17557 
17558 	rec_size = attr->core_relo_rec_size;
17559 	if (rec_size < MIN_CORE_RELO_SIZE ||
17560 	    rec_size > MAX_CORE_RELO_SIZE ||
17561 	    rec_size % sizeof(u32))
17562 		return -EINVAL;
17563 
17564 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
17565 	expected_size = sizeof(struct bpf_core_relo);
17566 	ncopy = min_t(u32, expected_size, rec_size);
17567 
17568 	/* Unlike func_info and line_info, copy and apply each CO-RE
17569 	 * relocation record one at a time.
17570 	 */
17571 	for (i = 0; i < nr_core_relo; i++) {
17572 		/* future proofing when sizeof(bpf_core_relo) changes */
17573 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
17574 		if (err) {
17575 			if (err == -E2BIG) {
17576 				verbose(env, "nonzero tailing record in core_relo");
17577 				if (copy_to_bpfptr_offset(uattr,
17578 							  offsetof(union bpf_attr, core_relo_rec_size),
17579 							  &expected_size, sizeof(expected_size)))
17580 					err = -EFAULT;
17581 			}
17582 			break;
17583 		}
17584 
17585 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
17586 			err = -EFAULT;
17587 			break;
17588 		}
17589 
17590 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
17591 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
17592 				i, core_relo.insn_off, prog->len);
17593 			err = -EINVAL;
17594 			break;
17595 		}
17596 
17597 		err = bpf_core_apply(&ctx, &core_relo, i,
17598 				     &prog->insnsi[core_relo.insn_off / 8]);
17599 		if (err)
17600 			break;
17601 		bpfptr_add(&u_core_relo, rec_size);
17602 	}
17603 	return err;
17604 }
17605 
17606 static int check_btf_info_early(struct bpf_verifier_env *env,
17607 				const union bpf_attr *attr,
17608 				bpfptr_t uattr)
17609 {
17610 	struct btf *btf;
17611 	int err;
17612 
17613 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17614 		if (check_abnormal_return(env))
17615 			return -EINVAL;
17616 		return 0;
17617 	}
17618 
17619 	btf = btf_get_by_fd(attr->prog_btf_fd);
17620 	if (IS_ERR(btf))
17621 		return PTR_ERR(btf);
17622 	if (btf_is_kernel(btf)) {
17623 		btf_put(btf);
17624 		return -EACCES;
17625 	}
17626 	env->prog->aux->btf = btf;
17627 
17628 	err = check_btf_func_early(env, attr, uattr);
17629 	if (err)
17630 		return err;
17631 	return 0;
17632 }
17633 
17634 static int check_btf_info(struct bpf_verifier_env *env,
17635 			  const union bpf_attr *attr,
17636 			  bpfptr_t uattr)
17637 {
17638 	int err;
17639 
17640 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17641 		if (check_abnormal_return(env))
17642 			return -EINVAL;
17643 		return 0;
17644 	}
17645 
17646 	err = check_btf_func(env, attr, uattr);
17647 	if (err)
17648 		return err;
17649 
17650 	err = check_btf_line(env, attr, uattr);
17651 	if (err)
17652 		return err;
17653 
17654 	err = check_core_relo(env, attr, uattr);
17655 	if (err)
17656 		return err;
17657 
17658 	return 0;
17659 }
17660 
17661 /* check %cur's range satisfies %old's */
17662 static bool range_within(const struct bpf_reg_state *old,
17663 			 const struct bpf_reg_state *cur)
17664 {
17665 	return old->umin_value <= cur->umin_value &&
17666 	       old->umax_value >= cur->umax_value &&
17667 	       old->smin_value <= cur->smin_value &&
17668 	       old->smax_value >= cur->smax_value &&
17669 	       old->u32_min_value <= cur->u32_min_value &&
17670 	       old->u32_max_value >= cur->u32_max_value &&
17671 	       old->s32_min_value <= cur->s32_min_value &&
17672 	       old->s32_max_value >= cur->s32_max_value;
17673 }
17674 
17675 /* If in the old state two registers had the same id, then they need to have
17676  * the same id in the new state as well.  But that id could be different from
17677  * the old state, so we need to track the mapping from old to new ids.
17678  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
17679  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
17680  * regs with a different old id could still have new id 9, we don't care about
17681  * that.
17682  * So we look through our idmap to see if this old id has been seen before.  If
17683  * so, we require the new id to match; otherwise, we add the id pair to the map.
17684  */
17685 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17686 {
17687 	struct bpf_id_pair *map = idmap->map;
17688 	unsigned int i;
17689 
17690 	/* either both IDs should be set or both should be zero */
17691 	if (!!old_id != !!cur_id)
17692 		return false;
17693 
17694 	if (old_id == 0) /* cur_id == 0 as well */
17695 		return true;
17696 
17697 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
17698 		if (!map[i].old) {
17699 			/* Reached an empty slot; haven't seen this id before */
17700 			map[i].old = old_id;
17701 			map[i].cur = cur_id;
17702 			return true;
17703 		}
17704 		if (map[i].old == old_id)
17705 			return map[i].cur == cur_id;
17706 		if (map[i].cur == cur_id)
17707 			return false;
17708 	}
17709 	/* We ran out of idmap slots, which should be impossible */
17710 	WARN_ON_ONCE(1);
17711 	return false;
17712 }
17713 
17714 /* Similar to check_ids(), but allocate a unique temporary ID
17715  * for 'old_id' or 'cur_id' of zero.
17716  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
17717  */
17718 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17719 {
17720 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
17721 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
17722 
17723 	return check_ids(old_id, cur_id, idmap);
17724 }
17725 
17726 static void clean_func_state(struct bpf_verifier_env *env,
17727 			     struct bpf_func_state *st)
17728 {
17729 	enum bpf_reg_liveness live;
17730 	int i, j;
17731 
17732 	for (i = 0; i < BPF_REG_FP; i++) {
17733 		live = st->regs[i].live;
17734 		/* liveness must not touch this register anymore */
17735 		st->regs[i].live |= REG_LIVE_DONE;
17736 		if (!(live & REG_LIVE_READ))
17737 			/* since the register is unused, clear its state
17738 			 * to make further comparison simpler
17739 			 */
17740 			__mark_reg_not_init(env, &st->regs[i]);
17741 	}
17742 
17743 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
17744 		live = st->stack[i].spilled_ptr.live;
17745 		/* liveness must not touch this stack slot anymore */
17746 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
17747 		if (!(live & REG_LIVE_READ)) {
17748 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
17749 			for (j = 0; j < BPF_REG_SIZE; j++)
17750 				st->stack[i].slot_type[j] = STACK_INVALID;
17751 		}
17752 	}
17753 }
17754 
17755 static void clean_verifier_state(struct bpf_verifier_env *env,
17756 				 struct bpf_verifier_state *st)
17757 {
17758 	int i;
17759 
17760 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
17761 		/* all regs in this state in all frames were already marked */
17762 		return;
17763 
17764 	for (i = 0; i <= st->curframe; i++)
17765 		clean_func_state(env, st->frame[i]);
17766 }
17767 
17768 /* the parentage chains form a tree.
17769  * the verifier states are added to state lists at given insn and
17770  * pushed into state stack for future exploration.
17771  * when the verifier reaches bpf_exit insn some of the verifer states
17772  * stored in the state lists have their final liveness state already,
17773  * but a lot of states will get revised from liveness point of view when
17774  * the verifier explores other branches.
17775  * Example:
17776  * 1: r0 = 1
17777  * 2: if r1 == 100 goto pc+1
17778  * 3: r0 = 2
17779  * 4: exit
17780  * when the verifier reaches exit insn the register r0 in the state list of
17781  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
17782  * of insn 2 and goes exploring further. At the insn 4 it will walk the
17783  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
17784  *
17785  * Since the verifier pushes the branch states as it sees them while exploring
17786  * the program the condition of walking the branch instruction for the second
17787  * time means that all states below this branch were already explored and
17788  * their final liveness marks are already propagated.
17789  * Hence when the verifier completes the search of state list in is_state_visited()
17790  * we can call this clean_live_states() function to mark all liveness states
17791  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
17792  * will not be used.
17793  * This function also clears the registers and stack for states that !READ
17794  * to simplify state merging.
17795  *
17796  * Important note here that walking the same branch instruction in the callee
17797  * doesn't meant that the states are DONE. The verifier has to compare
17798  * the callsites
17799  */
17800 static void clean_live_states(struct bpf_verifier_env *env, int insn,
17801 			      struct bpf_verifier_state *cur)
17802 {
17803 	struct bpf_verifier_state_list *sl;
17804 
17805 	sl = *explored_state(env, insn);
17806 	while (sl) {
17807 		if (sl->state.branches)
17808 			goto next;
17809 		if (sl->state.insn_idx != insn ||
17810 		    !same_callsites(&sl->state, cur))
17811 			goto next;
17812 		clean_verifier_state(env, &sl->state);
17813 next:
17814 		sl = sl->next;
17815 	}
17816 }
17817 
17818 static bool regs_exact(const struct bpf_reg_state *rold,
17819 		       const struct bpf_reg_state *rcur,
17820 		       struct bpf_idmap *idmap)
17821 {
17822 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17823 	       check_ids(rold->id, rcur->id, idmap) &&
17824 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17825 }
17826 
17827 enum exact_level {
17828 	NOT_EXACT,
17829 	EXACT,
17830 	RANGE_WITHIN
17831 };
17832 
17833 /* Returns true if (rold safe implies rcur safe) */
17834 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
17835 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
17836 		    enum exact_level exact)
17837 {
17838 	if (exact == EXACT)
17839 		return regs_exact(rold, rcur, idmap);
17840 
17841 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
17842 		/* explored state didn't use this */
17843 		return true;
17844 	if (rold->type == NOT_INIT) {
17845 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
17846 			/* explored state can't have used this */
17847 			return true;
17848 	}
17849 
17850 	/* Enforce that register types have to match exactly, including their
17851 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
17852 	 * rule.
17853 	 *
17854 	 * One can make a point that using a pointer register as unbounded
17855 	 * SCALAR would be technically acceptable, but this could lead to
17856 	 * pointer leaks because scalars are allowed to leak while pointers
17857 	 * are not. We could make this safe in special cases if root is
17858 	 * calling us, but it's probably not worth the hassle.
17859 	 *
17860 	 * Also, register types that are *not* MAYBE_NULL could technically be
17861 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
17862 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
17863 	 * to the same map).
17864 	 * However, if the old MAYBE_NULL register then got NULL checked,
17865 	 * doing so could have affected others with the same id, and we can't
17866 	 * check for that because we lost the id when we converted to
17867 	 * a non-MAYBE_NULL variant.
17868 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
17869 	 * non-MAYBE_NULL registers as well.
17870 	 */
17871 	if (rold->type != rcur->type)
17872 		return false;
17873 
17874 	switch (base_type(rold->type)) {
17875 	case SCALAR_VALUE:
17876 		if (env->explore_alu_limits) {
17877 			/* explore_alu_limits disables tnum_in() and range_within()
17878 			 * logic and requires everything to be strict
17879 			 */
17880 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17881 			       check_scalar_ids(rold->id, rcur->id, idmap);
17882 		}
17883 		if (!rold->precise && exact == NOT_EXACT)
17884 			return true;
17885 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
17886 			return false;
17887 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
17888 			return false;
17889 		/* Why check_ids() for scalar registers?
17890 		 *
17891 		 * Consider the following BPF code:
17892 		 *   1: r6 = ... unbound scalar, ID=a ...
17893 		 *   2: r7 = ... unbound scalar, ID=b ...
17894 		 *   3: if (r6 > r7) goto +1
17895 		 *   4: r6 = r7
17896 		 *   5: if (r6 > X) goto ...
17897 		 *   6: ... memory operation using r7 ...
17898 		 *
17899 		 * First verification path is [1-6]:
17900 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
17901 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
17902 		 *   r7 <= X, because r6 and r7 share same id.
17903 		 * Next verification path is [1-4, 6].
17904 		 *
17905 		 * Instruction (6) would be reached in two states:
17906 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
17907 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
17908 		 *
17909 		 * Use check_ids() to distinguish these states.
17910 		 * ---
17911 		 * Also verify that new value satisfies old value range knowledge.
17912 		 */
17913 		return range_within(rold, rcur) &&
17914 		       tnum_in(rold->var_off, rcur->var_off) &&
17915 		       check_scalar_ids(rold->id, rcur->id, idmap);
17916 	case PTR_TO_MAP_KEY:
17917 	case PTR_TO_MAP_VALUE:
17918 	case PTR_TO_MEM:
17919 	case PTR_TO_BUF:
17920 	case PTR_TO_TP_BUFFER:
17921 		/* If the new min/max/var_off satisfy the old ones and
17922 		 * everything else matches, we are OK.
17923 		 */
17924 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
17925 		       range_within(rold, rcur) &&
17926 		       tnum_in(rold->var_off, rcur->var_off) &&
17927 		       check_ids(rold->id, rcur->id, idmap) &&
17928 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17929 	case PTR_TO_PACKET_META:
17930 	case PTR_TO_PACKET:
17931 		/* We must have at least as much range as the old ptr
17932 		 * did, so that any accesses which were safe before are
17933 		 * still safe.  This is true even if old range < old off,
17934 		 * since someone could have accessed through (ptr - k), or
17935 		 * even done ptr -= k in a register, to get a safe access.
17936 		 */
17937 		if (rold->range > rcur->range)
17938 			return false;
17939 		/* If the offsets don't match, we can't trust our alignment;
17940 		 * nor can we be sure that we won't fall out of range.
17941 		 */
17942 		if (rold->off != rcur->off)
17943 			return false;
17944 		/* id relations must be preserved */
17945 		if (!check_ids(rold->id, rcur->id, idmap))
17946 			return false;
17947 		/* new val must satisfy old val knowledge */
17948 		return range_within(rold, rcur) &&
17949 		       tnum_in(rold->var_off, rcur->var_off);
17950 	case PTR_TO_STACK:
17951 		/* two stack pointers are equal only if they're pointing to
17952 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
17953 		 */
17954 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
17955 	case PTR_TO_ARENA:
17956 		return true;
17957 	default:
17958 		return regs_exact(rold, rcur, idmap);
17959 	}
17960 }
17961 
17962 static struct bpf_reg_state unbound_reg;
17963 
17964 static __init int unbound_reg_init(void)
17965 {
17966 	__mark_reg_unknown_imprecise(&unbound_reg);
17967 	unbound_reg.live |= REG_LIVE_READ;
17968 	return 0;
17969 }
17970 late_initcall(unbound_reg_init);
17971 
17972 static bool is_stack_all_misc(struct bpf_verifier_env *env,
17973 			      struct bpf_stack_state *stack)
17974 {
17975 	u32 i;
17976 
17977 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
17978 		if ((stack->slot_type[i] == STACK_MISC) ||
17979 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
17980 			continue;
17981 		return false;
17982 	}
17983 
17984 	return true;
17985 }
17986 
17987 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
17988 						  struct bpf_stack_state *stack)
17989 {
17990 	if (is_spilled_scalar_reg64(stack))
17991 		return &stack->spilled_ptr;
17992 
17993 	if (is_stack_all_misc(env, stack))
17994 		return &unbound_reg;
17995 
17996 	return NULL;
17997 }
17998 
17999 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18000 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18001 		      enum exact_level exact)
18002 {
18003 	int i, spi;
18004 
18005 	/* walk slots of the explored stack and ignore any additional
18006 	 * slots in the current stack, since explored(safe) state
18007 	 * didn't use them
18008 	 */
18009 	for (i = 0; i < old->allocated_stack; i++) {
18010 		struct bpf_reg_state *old_reg, *cur_reg;
18011 
18012 		spi = i / BPF_REG_SIZE;
18013 
18014 		if (exact != NOT_EXACT &&
18015 		    (i >= cur->allocated_stack ||
18016 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18017 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18018 			return false;
18019 
18020 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
18021 		    && exact == NOT_EXACT) {
18022 			i += BPF_REG_SIZE - 1;
18023 			/* explored state didn't use this */
18024 			continue;
18025 		}
18026 
18027 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18028 			continue;
18029 
18030 		if (env->allow_uninit_stack &&
18031 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18032 			continue;
18033 
18034 		/* explored stack has more populated slots than current stack
18035 		 * and these slots were used
18036 		 */
18037 		if (i >= cur->allocated_stack)
18038 			return false;
18039 
18040 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18041 		 * Load from all slots MISC produces unbound scalar.
18042 		 * Construct a fake register for such stack and call
18043 		 * regsafe() to ensure scalar ids are compared.
18044 		 */
18045 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18046 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18047 		if (old_reg && cur_reg) {
18048 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18049 				return false;
18050 			i += BPF_REG_SIZE - 1;
18051 			continue;
18052 		}
18053 
18054 		/* if old state was safe with misc data in the stack
18055 		 * it will be safe with zero-initialized stack.
18056 		 * The opposite is not true
18057 		 */
18058 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18059 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18060 			continue;
18061 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18062 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18063 			/* Ex: old explored (safe) state has STACK_SPILL in
18064 			 * this stack slot, but current has STACK_MISC ->
18065 			 * this verifier states are not equivalent,
18066 			 * return false to continue verification of this path
18067 			 */
18068 			return false;
18069 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18070 			continue;
18071 		/* Both old and cur are having same slot_type */
18072 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18073 		case STACK_SPILL:
18074 			/* when explored and current stack slot are both storing
18075 			 * spilled registers, check that stored pointers types
18076 			 * are the same as well.
18077 			 * Ex: explored safe path could have stored
18078 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18079 			 * but current path has stored:
18080 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18081 			 * such verifier states are not equivalent.
18082 			 * return false to continue verification of this path
18083 			 */
18084 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18085 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18086 				return false;
18087 			break;
18088 		case STACK_DYNPTR:
18089 			old_reg = &old->stack[spi].spilled_ptr;
18090 			cur_reg = &cur->stack[spi].spilled_ptr;
18091 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18092 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18093 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18094 				return false;
18095 			break;
18096 		case STACK_ITER:
18097 			old_reg = &old->stack[spi].spilled_ptr;
18098 			cur_reg = &cur->stack[spi].spilled_ptr;
18099 			/* iter.depth is not compared between states as it
18100 			 * doesn't matter for correctness and would otherwise
18101 			 * prevent convergence; we maintain it only to prevent
18102 			 * infinite loop check triggering, see
18103 			 * iter_active_depths_differ()
18104 			 */
18105 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18106 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18107 			    old_reg->iter.state != cur_reg->iter.state ||
18108 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18109 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18110 				return false;
18111 			break;
18112 		case STACK_IRQ_FLAG:
18113 			old_reg = &old->stack[spi].spilled_ptr;
18114 			cur_reg = &cur->stack[spi].spilled_ptr;
18115 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18116 				return false;
18117 			break;
18118 		case STACK_MISC:
18119 		case STACK_ZERO:
18120 		case STACK_INVALID:
18121 			continue;
18122 		/* Ensure that new unhandled slot types return false by default */
18123 		default:
18124 			return false;
18125 		}
18126 	}
18127 	return true;
18128 }
18129 
18130 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18131 		    struct bpf_idmap *idmap)
18132 {
18133 	int i;
18134 
18135 	if (old->acquired_refs != cur->acquired_refs)
18136 		return false;
18137 
18138 	if (old->active_locks != cur->active_locks)
18139 		return false;
18140 
18141 	if (old->active_preempt_locks != cur->active_preempt_locks)
18142 		return false;
18143 
18144 	if (old->active_rcu_lock != cur->active_rcu_lock)
18145 		return false;
18146 
18147 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18148 		return false;
18149 
18150 	for (i = 0; i < old->acquired_refs; i++) {
18151 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18152 		    old->refs[i].type != cur->refs[i].type)
18153 			return false;
18154 		switch (old->refs[i].type) {
18155 		case REF_TYPE_PTR:
18156 		case REF_TYPE_IRQ:
18157 			break;
18158 		case REF_TYPE_LOCK:
18159 			if (old->refs[i].ptr != cur->refs[i].ptr)
18160 				return false;
18161 			break;
18162 		default:
18163 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18164 			return false;
18165 		}
18166 	}
18167 
18168 	return true;
18169 }
18170 
18171 /* compare two verifier states
18172  *
18173  * all states stored in state_list are known to be valid, since
18174  * verifier reached 'bpf_exit' instruction through them
18175  *
18176  * this function is called when verifier exploring different branches of
18177  * execution popped from the state stack. If it sees an old state that has
18178  * more strict register state and more strict stack state then this execution
18179  * branch doesn't need to be explored further, since verifier already
18180  * concluded that more strict state leads to valid finish.
18181  *
18182  * Therefore two states are equivalent if register state is more conservative
18183  * and explored stack state is more conservative than the current one.
18184  * Example:
18185  *       explored                   current
18186  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
18187  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
18188  *
18189  * In other words if current stack state (one being explored) has more
18190  * valid slots than old one that already passed validation, it means
18191  * the verifier can stop exploring and conclude that current state is valid too
18192  *
18193  * Similarly with registers. If explored state has register type as invalid
18194  * whereas register type in current state is meaningful, it means that
18195  * the current state will reach 'bpf_exit' instruction safely
18196  */
18197 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
18198 			      struct bpf_func_state *cur, enum exact_level exact)
18199 {
18200 	int i;
18201 
18202 	if (old->callback_depth > cur->callback_depth)
18203 		return false;
18204 
18205 	for (i = 0; i < MAX_BPF_REG; i++)
18206 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
18207 			     &env->idmap_scratch, exact))
18208 			return false;
18209 
18210 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
18211 		return false;
18212 
18213 	return true;
18214 }
18215 
18216 static void reset_idmap_scratch(struct bpf_verifier_env *env)
18217 {
18218 	env->idmap_scratch.tmp_id_gen = env->id_gen;
18219 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
18220 }
18221 
18222 static bool states_equal(struct bpf_verifier_env *env,
18223 			 struct bpf_verifier_state *old,
18224 			 struct bpf_verifier_state *cur,
18225 			 enum exact_level exact)
18226 {
18227 	int i;
18228 
18229 	if (old->curframe != cur->curframe)
18230 		return false;
18231 
18232 	reset_idmap_scratch(env);
18233 
18234 	/* Verification state from speculative execution simulation
18235 	 * must never prune a non-speculative execution one.
18236 	 */
18237 	if (old->speculative && !cur->speculative)
18238 		return false;
18239 
18240 	if (old->in_sleepable != cur->in_sleepable)
18241 		return false;
18242 
18243 	if (!refsafe(old, cur, &env->idmap_scratch))
18244 		return false;
18245 
18246 	/* for states to be equal callsites have to be the same
18247 	 * and all frame states need to be equivalent
18248 	 */
18249 	for (i = 0; i <= old->curframe; i++) {
18250 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
18251 			return false;
18252 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
18253 			return false;
18254 	}
18255 	return true;
18256 }
18257 
18258 /* Return 0 if no propagation happened. Return negative error code if error
18259  * happened. Otherwise, return the propagated bit.
18260  */
18261 static int propagate_liveness_reg(struct bpf_verifier_env *env,
18262 				  struct bpf_reg_state *reg,
18263 				  struct bpf_reg_state *parent_reg)
18264 {
18265 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
18266 	u8 flag = reg->live & REG_LIVE_READ;
18267 	int err;
18268 
18269 	/* When comes here, read flags of PARENT_REG or REG could be any of
18270 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
18271 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
18272 	 */
18273 	if (parent_flag == REG_LIVE_READ64 ||
18274 	    /* Or if there is no read flag from REG. */
18275 	    !flag ||
18276 	    /* Or if the read flag from REG is the same as PARENT_REG. */
18277 	    parent_flag == flag)
18278 		return 0;
18279 
18280 	err = mark_reg_read(env, reg, parent_reg, flag);
18281 	if (err)
18282 		return err;
18283 
18284 	return flag;
18285 }
18286 
18287 /* A write screens off any subsequent reads; but write marks come from the
18288  * straight-line code between a state and its parent.  When we arrive at an
18289  * equivalent state (jump target or such) we didn't arrive by the straight-line
18290  * code, so read marks in the state must propagate to the parent regardless
18291  * of the state's write marks. That's what 'parent == state->parent' comparison
18292  * in mark_reg_read() is for.
18293  */
18294 static int propagate_liveness(struct bpf_verifier_env *env,
18295 			      const struct bpf_verifier_state *vstate,
18296 			      struct bpf_verifier_state *vparent)
18297 {
18298 	struct bpf_reg_state *state_reg, *parent_reg;
18299 	struct bpf_func_state *state, *parent;
18300 	int i, frame, err = 0;
18301 
18302 	if (vparent->curframe != vstate->curframe) {
18303 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
18304 		     vparent->curframe, vstate->curframe);
18305 		return -EFAULT;
18306 	}
18307 	/* Propagate read liveness of registers... */
18308 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
18309 	for (frame = 0; frame <= vstate->curframe; frame++) {
18310 		parent = vparent->frame[frame];
18311 		state = vstate->frame[frame];
18312 		parent_reg = parent->regs;
18313 		state_reg = state->regs;
18314 		/* We don't need to worry about FP liveness, it's read-only */
18315 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
18316 			err = propagate_liveness_reg(env, &state_reg[i],
18317 						     &parent_reg[i]);
18318 			if (err < 0)
18319 				return err;
18320 			if (err == REG_LIVE_READ64)
18321 				mark_insn_zext(env, &parent_reg[i]);
18322 		}
18323 
18324 		/* Propagate stack slots. */
18325 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
18326 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
18327 			parent_reg = &parent->stack[i].spilled_ptr;
18328 			state_reg = &state->stack[i].spilled_ptr;
18329 			err = propagate_liveness_reg(env, state_reg,
18330 						     parent_reg);
18331 			if (err < 0)
18332 				return err;
18333 		}
18334 	}
18335 	return 0;
18336 }
18337 
18338 /* find precise scalars in the previous equivalent state and
18339  * propagate them into the current state
18340  */
18341 static int propagate_precision(struct bpf_verifier_env *env,
18342 			       const struct bpf_verifier_state *old)
18343 {
18344 	struct bpf_reg_state *state_reg;
18345 	struct bpf_func_state *state;
18346 	int i, err = 0, fr;
18347 	bool first;
18348 
18349 	for (fr = old->curframe; fr >= 0; fr--) {
18350 		state = old->frame[fr];
18351 		state_reg = state->regs;
18352 		first = true;
18353 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
18354 			if (state_reg->type != SCALAR_VALUE ||
18355 			    !state_reg->precise ||
18356 			    !(state_reg->live & REG_LIVE_READ))
18357 				continue;
18358 			if (env->log.level & BPF_LOG_LEVEL2) {
18359 				if (first)
18360 					verbose(env, "frame %d: propagating r%d", fr, i);
18361 				else
18362 					verbose(env, ",r%d", i);
18363 			}
18364 			bt_set_frame_reg(&env->bt, fr, i);
18365 			first = false;
18366 		}
18367 
18368 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18369 			if (!is_spilled_reg(&state->stack[i]))
18370 				continue;
18371 			state_reg = &state->stack[i].spilled_ptr;
18372 			if (state_reg->type != SCALAR_VALUE ||
18373 			    !state_reg->precise ||
18374 			    !(state_reg->live & REG_LIVE_READ))
18375 				continue;
18376 			if (env->log.level & BPF_LOG_LEVEL2) {
18377 				if (first)
18378 					verbose(env, "frame %d: propagating fp%d",
18379 						fr, (-i - 1) * BPF_REG_SIZE);
18380 				else
18381 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
18382 			}
18383 			bt_set_frame_slot(&env->bt, fr, i);
18384 			first = false;
18385 		}
18386 		if (!first)
18387 			verbose(env, "\n");
18388 	}
18389 
18390 	err = mark_chain_precision_batch(env);
18391 	if (err < 0)
18392 		return err;
18393 
18394 	return 0;
18395 }
18396 
18397 static bool states_maybe_looping(struct bpf_verifier_state *old,
18398 				 struct bpf_verifier_state *cur)
18399 {
18400 	struct bpf_func_state *fold, *fcur;
18401 	int i, fr = cur->curframe;
18402 
18403 	if (old->curframe != fr)
18404 		return false;
18405 
18406 	fold = old->frame[fr];
18407 	fcur = cur->frame[fr];
18408 	for (i = 0; i < MAX_BPF_REG; i++)
18409 		if (memcmp(&fold->regs[i], &fcur->regs[i],
18410 			   offsetof(struct bpf_reg_state, parent)))
18411 			return false;
18412 	return true;
18413 }
18414 
18415 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
18416 {
18417 	return env->insn_aux_data[insn_idx].is_iter_next;
18418 }
18419 
18420 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
18421  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
18422  * states to match, which otherwise would look like an infinite loop. So while
18423  * iter_next() calls are taken care of, we still need to be careful and
18424  * prevent erroneous and too eager declaration of "ininite loop", when
18425  * iterators are involved.
18426  *
18427  * Here's a situation in pseudo-BPF assembly form:
18428  *
18429  *   0: again:                          ; set up iter_next() call args
18430  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
18431  *   2:   call bpf_iter_num_next        ; this is iter_next() call
18432  *   3:   if r0 == 0 goto done
18433  *   4:   ... something useful here ...
18434  *   5:   goto again                    ; another iteration
18435  *   6: done:
18436  *   7:   r1 = &it
18437  *   8:   call bpf_iter_num_destroy     ; clean up iter state
18438  *   9:   exit
18439  *
18440  * This is a typical loop. Let's assume that we have a prune point at 1:,
18441  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
18442  * again`, assuming other heuristics don't get in a way).
18443  *
18444  * When we first time come to 1:, let's say we have some state X. We proceed
18445  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
18446  * Now we come back to validate that forked ACTIVE state. We proceed through
18447  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
18448  * are converging. But the problem is that we don't know that yet, as this
18449  * convergence has to happen at iter_next() call site only. So if nothing is
18450  * done, at 1: verifier will use bounded loop logic and declare infinite
18451  * looping (and would be *technically* correct, if not for iterator's
18452  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
18453  * don't want that. So what we do in process_iter_next_call() when we go on
18454  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
18455  * a different iteration. So when we suspect an infinite loop, we additionally
18456  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
18457  * pretend we are not looping and wait for next iter_next() call.
18458  *
18459  * This only applies to ACTIVE state. In DRAINED state we don't expect to
18460  * loop, because that would actually mean infinite loop, as DRAINED state is
18461  * "sticky", and so we'll keep returning into the same instruction with the
18462  * same state (at least in one of possible code paths).
18463  *
18464  * This approach allows to keep infinite loop heuristic even in the face of
18465  * active iterator. E.g., C snippet below is and will be detected as
18466  * inifintely looping:
18467  *
18468  *   struct bpf_iter_num it;
18469  *   int *p, x;
18470  *
18471  *   bpf_iter_num_new(&it, 0, 10);
18472  *   while ((p = bpf_iter_num_next(&t))) {
18473  *       x = p;
18474  *       while (x--) {} // <<-- infinite loop here
18475  *   }
18476  *
18477  */
18478 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
18479 {
18480 	struct bpf_reg_state *slot, *cur_slot;
18481 	struct bpf_func_state *state;
18482 	int i, fr;
18483 
18484 	for (fr = old->curframe; fr >= 0; fr--) {
18485 		state = old->frame[fr];
18486 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18487 			if (state->stack[i].slot_type[0] != STACK_ITER)
18488 				continue;
18489 
18490 			slot = &state->stack[i].spilled_ptr;
18491 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
18492 				continue;
18493 
18494 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
18495 			if (cur_slot->iter.depth != slot->iter.depth)
18496 				return true;
18497 		}
18498 	}
18499 	return false;
18500 }
18501 
18502 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
18503 {
18504 	struct bpf_verifier_state_list *new_sl;
18505 	struct bpf_verifier_state_list *sl, **pprev;
18506 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
18507 	int i, j, n, err, states_cnt = 0;
18508 	bool force_new_state, add_new_state, force_exact;
18509 
18510 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
18511 			  /* Avoid accumulating infinitely long jmp history */
18512 			  cur->insn_hist_end - cur->insn_hist_start > 40;
18513 
18514 	/* bpf progs typically have pruning point every 4 instructions
18515 	 * http://vger.kernel.org/bpfconf2019.html#session-1
18516 	 * Do not add new state for future pruning if the verifier hasn't seen
18517 	 * at least 2 jumps and at least 8 instructions.
18518 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
18519 	 * In tests that amounts to up to 50% reduction into total verifier
18520 	 * memory consumption and 20% verifier time speedup.
18521 	 */
18522 	add_new_state = force_new_state;
18523 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
18524 	    env->insn_processed - env->prev_insn_processed >= 8)
18525 		add_new_state = true;
18526 
18527 	pprev = explored_state(env, insn_idx);
18528 	sl = *pprev;
18529 
18530 	clean_live_states(env, insn_idx, cur);
18531 
18532 	while (sl) {
18533 		states_cnt++;
18534 		if (sl->state.insn_idx != insn_idx)
18535 			goto next;
18536 
18537 		if (sl->state.branches) {
18538 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
18539 
18540 			if (frame->in_async_callback_fn &&
18541 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
18542 				/* Different async_entry_cnt means that the verifier is
18543 				 * processing another entry into async callback.
18544 				 * Seeing the same state is not an indication of infinite
18545 				 * loop or infinite recursion.
18546 				 * But finding the same state doesn't mean that it's safe
18547 				 * to stop processing the current state. The previous state
18548 				 * hasn't yet reached bpf_exit, since state.branches > 0.
18549 				 * Checking in_async_callback_fn alone is not enough either.
18550 				 * Since the verifier still needs to catch infinite loops
18551 				 * inside async callbacks.
18552 				 */
18553 				goto skip_inf_loop_check;
18554 			}
18555 			/* BPF open-coded iterators loop detection is special.
18556 			 * states_maybe_looping() logic is too simplistic in detecting
18557 			 * states that *might* be equivalent, because it doesn't know
18558 			 * about ID remapping, so don't even perform it.
18559 			 * See process_iter_next_call() and iter_active_depths_differ()
18560 			 * for overview of the logic. When current and one of parent
18561 			 * states are detected as equivalent, it's a good thing: we prove
18562 			 * convergence and can stop simulating further iterations.
18563 			 * It's safe to assume that iterator loop will finish, taking into
18564 			 * account iter_next() contract of eventually returning
18565 			 * sticky NULL result.
18566 			 *
18567 			 * Note, that states have to be compared exactly in this case because
18568 			 * read and precision marks might not be finalized inside the loop.
18569 			 * E.g. as in the program below:
18570 			 *
18571 			 *     1. r7 = -16
18572 			 *     2. r6 = bpf_get_prandom_u32()
18573 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
18574 			 *     4.   if (r6 != 42) {
18575 			 *     5.     r7 = -32
18576 			 *     6.     r6 = bpf_get_prandom_u32()
18577 			 *     7.     continue
18578 			 *     8.   }
18579 			 *     9.   r0 = r10
18580 			 *    10.   r0 += r7
18581 			 *    11.   r8 = *(u64 *)(r0 + 0)
18582 			 *    12.   r6 = bpf_get_prandom_u32()
18583 			 *    13. }
18584 			 *
18585 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
18586 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
18587 			 * not have read or precision mark for r7 yet, thus inexact states
18588 			 * comparison would discard current state with r7=-32
18589 			 * => unsafe memory access at 11 would not be caught.
18590 			 */
18591 			if (is_iter_next_insn(env, insn_idx)) {
18592 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18593 					struct bpf_func_state *cur_frame;
18594 					struct bpf_reg_state *iter_state, *iter_reg;
18595 					int spi;
18596 
18597 					cur_frame = cur->frame[cur->curframe];
18598 					/* btf_check_iter_kfuncs() enforces that
18599 					 * iter state pointer is always the first arg
18600 					 */
18601 					iter_reg = &cur_frame->regs[BPF_REG_1];
18602 					/* current state is valid due to states_equal(),
18603 					 * so we can assume valid iter and reg state,
18604 					 * no need for extra (re-)validations
18605 					 */
18606 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
18607 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
18608 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
18609 						update_loop_entry(cur, &sl->state);
18610 						goto hit;
18611 					}
18612 				}
18613 				goto skip_inf_loop_check;
18614 			}
18615 			if (is_may_goto_insn_at(env, insn_idx)) {
18616 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
18617 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18618 					update_loop_entry(cur, &sl->state);
18619 					goto hit;
18620 				}
18621 			}
18622 			if (calls_callback(env, insn_idx)) {
18623 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
18624 					goto hit;
18625 				goto skip_inf_loop_check;
18626 			}
18627 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
18628 			if (states_maybe_looping(&sl->state, cur) &&
18629 			    states_equal(env, &sl->state, cur, EXACT) &&
18630 			    !iter_active_depths_differ(&sl->state, cur) &&
18631 			    sl->state.may_goto_depth == cur->may_goto_depth &&
18632 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
18633 				verbose_linfo(env, insn_idx, "; ");
18634 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
18635 				verbose(env, "cur state:");
18636 				print_verifier_state(env, cur, cur->curframe, true);
18637 				verbose(env, "old state:");
18638 				print_verifier_state(env, &sl->state, cur->curframe, true);
18639 				return -EINVAL;
18640 			}
18641 			/* if the verifier is processing a loop, avoid adding new state
18642 			 * too often, since different loop iterations have distinct
18643 			 * states and may not help future pruning.
18644 			 * This threshold shouldn't be too low to make sure that
18645 			 * a loop with large bound will be rejected quickly.
18646 			 * The most abusive loop will be:
18647 			 * r1 += 1
18648 			 * if r1 < 1000000 goto pc-2
18649 			 * 1M insn_procssed limit / 100 == 10k peak states.
18650 			 * This threshold shouldn't be too high either, since states
18651 			 * at the end of the loop are likely to be useful in pruning.
18652 			 */
18653 skip_inf_loop_check:
18654 			if (!force_new_state &&
18655 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
18656 			    env->insn_processed - env->prev_insn_processed < 100)
18657 				add_new_state = false;
18658 			goto miss;
18659 		}
18660 		/* If sl->state is a part of a loop and this loop's entry is a part of
18661 		 * current verification path then states have to be compared exactly.
18662 		 * 'force_exact' is needed to catch the following case:
18663 		 *
18664 		 *                initial     Here state 'succ' was processed first,
18665 		 *                  |         it was eventually tracked to produce a
18666 		 *                  V         state identical to 'hdr'.
18667 		 *     .---------> hdr        All branches from 'succ' had been explored
18668 		 *     |            |         and thus 'succ' has its .branches == 0.
18669 		 *     |            V
18670 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
18671 		 *     |    |       |         to the same instruction + callsites.
18672 		 *     |    V       V         In such case it is necessary to check
18673 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
18674 		 *     |    |       |         If 'succ' and 'cur' are a part of the
18675 		 *     |    V       V         same loop exact flag has to be set.
18676 		 *     |   succ <- cur        To check if that is the case, verify
18677 		 *     |    |                 if loop entry of 'succ' is in current
18678 		 *     |    V                 DFS path.
18679 		 *     |   ...
18680 		 *     |    |
18681 		 *     '----'
18682 		 *
18683 		 * Additional details are in the comment before get_loop_entry().
18684 		 */
18685 		loop_entry = get_loop_entry(&sl->state);
18686 		force_exact = loop_entry && loop_entry->branches > 0;
18687 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
18688 			if (force_exact)
18689 				update_loop_entry(cur, loop_entry);
18690 hit:
18691 			sl->hit_cnt++;
18692 			/* reached equivalent register/stack state,
18693 			 * prune the search.
18694 			 * Registers read by the continuation are read by us.
18695 			 * If we have any write marks in env->cur_state, they
18696 			 * will prevent corresponding reads in the continuation
18697 			 * from reaching our parent (an explored_state).  Our
18698 			 * own state will get the read marks recorded, but
18699 			 * they'll be immediately forgotten as we're pruning
18700 			 * this state and will pop a new one.
18701 			 */
18702 			err = propagate_liveness(env, &sl->state, cur);
18703 
18704 			/* if previous state reached the exit with precision and
18705 			 * current state is equivalent to it (except precision marks)
18706 			 * the precision needs to be propagated back in
18707 			 * the current state.
18708 			 */
18709 			if (is_jmp_point(env, env->insn_idx))
18710 				err = err ? : push_insn_history(env, cur, 0, 0);
18711 			err = err ? : propagate_precision(env, &sl->state);
18712 			if (err)
18713 				return err;
18714 			return 1;
18715 		}
18716 miss:
18717 		/* when new state is not going to be added do not increase miss count.
18718 		 * Otherwise several loop iterations will remove the state
18719 		 * recorded earlier. The goal of these heuristics is to have
18720 		 * states from some iterations of the loop (some in the beginning
18721 		 * and some at the end) to help pruning.
18722 		 */
18723 		if (add_new_state)
18724 			sl->miss_cnt++;
18725 		/* heuristic to determine whether this state is beneficial
18726 		 * to keep checking from state equivalence point of view.
18727 		 * Higher numbers increase max_states_per_insn and verification time,
18728 		 * but do not meaningfully decrease insn_processed.
18729 		 * 'n' controls how many times state could miss before eviction.
18730 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
18731 		 * too early would hinder iterator convergence.
18732 		 */
18733 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
18734 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
18735 			/* the state is unlikely to be useful. Remove it to
18736 			 * speed up verification
18737 			 */
18738 			*pprev = sl->next;
18739 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
18740 			    !sl->state.used_as_loop_entry) {
18741 				u32 br = sl->state.branches;
18742 
18743 				WARN_ONCE(br,
18744 					  "BUG live_done but branches_to_explore %d\n",
18745 					  br);
18746 				free_verifier_state(&sl->state, false);
18747 				kfree(sl);
18748 				env->peak_states--;
18749 			} else {
18750 				/* cannot free this state, since parentage chain may
18751 				 * walk it later. Add it for free_list instead to
18752 				 * be freed at the end of verification
18753 				 */
18754 				sl->next = env->free_list;
18755 				env->free_list = sl;
18756 			}
18757 			sl = *pprev;
18758 			continue;
18759 		}
18760 next:
18761 		pprev = &sl->next;
18762 		sl = *pprev;
18763 	}
18764 
18765 	if (env->max_states_per_insn < states_cnt)
18766 		env->max_states_per_insn = states_cnt;
18767 
18768 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
18769 		return 0;
18770 
18771 	if (!add_new_state)
18772 		return 0;
18773 
18774 	/* There were no equivalent states, remember the current one.
18775 	 * Technically the current state is not proven to be safe yet,
18776 	 * but it will either reach outer most bpf_exit (which means it's safe)
18777 	 * or it will be rejected. When there are no loops the verifier won't be
18778 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
18779 	 * again on the way to bpf_exit.
18780 	 * When looping the sl->state.branches will be > 0 and this state
18781 	 * will not be considered for equivalence until branches == 0.
18782 	 */
18783 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
18784 	if (!new_sl)
18785 		return -ENOMEM;
18786 	env->total_states++;
18787 	env->peak_states++;
18788 	env->prev_jmps_processed = env->jmps_processed;
18789 	env->prev_insn_processed = env->insn_processed;
18790 
18791 	/* forget precise markings we inherited, see __mark_chain_precision */
18792 	if (env->bpf_capable)
18793 		mark_all_scalars_imprecise(env, cur);
18794 
18795 	/* add new state to the head of linked list */
18796 	new = &new_sl->state;
18797 	err = copy_verifier_state(new, cur);
18798 	if (err) {
18799 		free_verifier_state(new, false);
18800 		kfree(new_sl);
18801 		return err;
18802 	}
18803 	new->insn_idx = insn_idx;
18804 	WARN_ONCE(new->branches != 1,
18805 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
18806 
18807 	cur->parent = new;
18808 	cur->first_insn_idx = insn_idx;
18809 	cur->insn_hist_start = cur->insn_hist_end;
18810 	cur->dfs_depth = new->dfs_depth + 1;
18811 	new_sl->next = *explored_state(env, insn_idx);
18812 	*explored_state(env, insn_idx) = new_sl;
18813 	/* connect new state to parentage chain. Current frame needs all
18814 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
18815 	 * to the stack implicitly by JITs) so in callers' frames connect just
18816 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
18817 	 * the state of the call instruction (with WRITTEN set), and r0 comes
18818 	 * from callee with its full parentage chain, anyway.
18819 	 */
18820 	/* clear write marks in current state: the writes we did are not writes
18821 	 * our child did, so they don't screen off its reads from us.
18822 	 * (There are no read marks in current state, because reads always mark
18823 	 * their parent and current state never has children yet.  Only
18824 	 * explored_states can get read marks.)
18825 	 */
18826 	for (j = 0; j <= cur->curframe; j++) {
18827 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
18828 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
18829 		for (i = 0; i < BPF_REG_FP; i++)
18830 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
18831 	}
18832 
18833 	/* all stack frames are accessible from callee, clear them all */
18834 	for (j = 0; j <= cur->curframe; j++) {
18835 		struct bpf_func_state *frame = cur->frame[j];
18836 		struct bpf_func_state *newframe = new->frame[j];
18837 
18838 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
18839 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
18840 			frame->stack[i].spilled_ptr.parent =
18841 						&newframe->stack[i].spilled_ptr;
18842 		}
18843 	}
18844 	return 0;
18845 }
18846 
18847 /* Return true if it's OK to have the same insn return a different type. */
18848 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
18849 {
18850 	switch (base_type(type)) {
18851 	case PTR_TO_CTX:
18852 	case PTR_TO_SOCKET:
18853 	case PTR_TO_SOCK_COMMON:
18854 	case PTR_TO_TCP_SOCK:
18855 	case PTR_TO_XDP_SOCK:
18856 	case PTR_TO_BTF_ID:
18857 	case PTR_TO_ARENA:
18858 		return false;
18859 	default:
18860 		return true;
18861 	}
18862 }
18863 
18864 /* If an instruction was previously used with particular pointer types, then we
18865  * need to be careful to avoid cases such as the below, where it may be ok
18866  * for one branch accessing the pointer, but not ok for the other branch:
18867  *
18868  * R1 = sock_ptr
18869  * goto X;
18870  * ...
18871  * R1 = some_other_valid_ptr;
18872  * goto X;
18873  * ...
18874  * R2 = *(u32 *)(R1 + 0);
18875  */
18876 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18877 {
18878 	return src != prev && (!reg_type_mismatch_ok(src) ||
18879 			       !reg_type_mismatch_ok(prev));
18880 }
18881 
18882 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18883 			     bool allow_trust_mismatch)
18884 {
18885 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18886 
18887 	if (*prev_type == NOT_INIT) {
18888 		/* Saw a valid insn
18889 		 * dst_reg = *(u32 *)(src_reg + off)
18890 		 * save type to validate intersecting paths
18891 		 */
18892 		*prev_type = type;
18893 	} else if (reg_type_mismatch(type, *prev_type)) {
18894 		/* Abuser program is trying to use the same insn
18895 		 * dst_reg = *(u32*) (src_reg + off)
18896 		 * with different pointer types:
18897 		 * src_reg == ctx in one branch and
18898 		 * src_reg == stack|map in some other branch.
18899 		 * Reject it.
18900 		 */
18901 		if (allow_trust_mismatch &&
18902 		    base_type(type) == PTR_TO_BTF_ID &&
18903 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
18904 			/*
18905 			 * Have to support a use case when one path through
18906 			 * the program yields TRUSTED pointer while another
18907 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
18908 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
18909 			 */
18910 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
18911 		} else {
18912 			verbose(env, "same insn cannot be used with different pointers\n");
18913 			return -EINVAL;
18914 		}
18915 	}
18916 
18917 	return 0;
18918 }
18919 
18920 static int do_check(struct bpf_verifier_env *env)
18921 {
18922 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18923 	struct bpf_verifier_state *state = env->cur_state;
18924 	struct bpf_insn *insns = env->prog->insnsi;
18925 	struct bpf_reg_state *regs;
18926 	int insn_cnt = env->prog->len;
18927 	bool do_print_state = false;
18928 	int prev_insn_idx = -1;
18929 
18930 	for (;;) {
18931 		bool exception_exit = false;
18932 		struct bpf_insn *insn;
18933 		u8 class;
18934 		int err;
18935 
18936 		/* reset current history entry on each new instruction */
18937 		env->cur_hist_ent = NULL;
18938 
18939 		env->prev_insn_idx = prev_insn_idx;
18940 		if (env->insn_idx >= insn_cnt) {
18941 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
18942 				env->insn_idx, insn_cnt);
18943 			return -EFAULT;
18944 		}
18945 
18946 		insn = &insns[env->insn_idx];
18947 		class = BPF_CLASS(insn->code);
18948 
18949 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18950 			verbose(env,
18951 				"BPF program is too large. Processed %d insn\n",
18952 				env->insn_processed);
18953 			return -E2BIG;
18954 		}
18955 
18956 		state->last_insn_idx = env->prev_insn_idx;
18957 
18958 		if (is_prune_point(env, env->insn_idx)) {
18959 			err = is_state_visited(env, env->insn_idx);
18960 			if (err < 0)
18961 				return err;
18962 			if (err == 1) {
18963 				/* found equivalent state, can prune the search */
18964 				if (env->log.level & BPF_LOG_LEVEL) {
18965 					if (do_print_state)
18966 						verbose(env, "\nfrom %d to %d%s: safe\n",
18967 							env->prev_insn_idx, env->insn_idx,
18968 							env->cur_state->speculative ?
18969 							" (speculative execution)" : "");
18970 					else
18971 						verbose(env, "%d: safe\n", env->insn_idx);
18972 				}
18973 				goto process_bpf_exit;
18974 			}
18975 		}
18976 
18977 		if (is_jmp_point(env, env->insn_idx)) {
18978 			err = push_insn_history(env, state, 0, 0);
18979 			if (err)
18980 				return err;
18981 		}
18982 
18983 		if (signal_pending(current))
18984 			return -EAGAIN;
18985 
18986 		if (need_resched())
18987 			cond_resched();
18988 
18989 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18990 			verbose(env, "\nfrom %d to %d%s:",
18991 				env->prev_insn_idx, env->insn_idx,
18992 				env->cur_state->speculative ?
18993 				" (speculative execution)" : "");
18994 			print_verifier_state(env, state, state->curframe, true);
18995 			do_print_state = false;
18996 		}
18997 
18998 		if (env->log.level & BPF_LOG_LEVEL) {
18999 			const struct bpf_insn_cbs cbs = {
19000 				.cb_call	= disasm_kfunc_name,
19001 				.cb_print	= verbose,
19002 				.private_data	= env,
19003 			};
19004 
19005 			if (verifier_state_scratched(env))
19006 				print_insn_state(env, state, state->curframe);
19007 
19008 			verbose_linfo(env, env->insn_idx, "; ");
19009 			env->prev_log_pos = env->log.end_pos;
19010 			verbose(env, "%d: ", env->insn_idx);
19011 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
19012 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
19013 			env->prev_log_pos = env->log.end_pos;
19014 		}
19015 
19016 		if (bpf_prog_is_offloaded(env->prog->aux)) {
19017 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
19018 							   env->prev_insn_idx);
19019 			if (err)
19020 				return err;
19021 		}
19022 
19023 		regs = cur_regs(env);
19024 		sanitize_mark_insn_seen(env);
19025 		prev_insn_idx = env->insn_idx;
19026 
19027 		if (class == BPF_ALU || class == BPF_ALU64) {
19028 			err = check_alu_op(env, insn);
19029 			if (err)
19030 				return err;
19031 
19032 		} else if (class == BPF_LDX) {
19033 			enum bpf_reg_type src_reg_type;
19034 
19035 			/* check for reserved fields is already done */
19036 
19037 			/* check src operand */
19038 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
19039 			if (err)
19040 				return err;
19041 
19042 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
19043 			if (err)
19044 				return err;
19045 
19046 			src_reg_type = regs[insn->src_reg].type;
19047 
19048 			/* check that memory (src_reg + off) is readable,
19049 			 * the state of dst_reg will be updated by this func
19050 			 */
19051 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
19052 					       insn->off, BPF_SIZE(insn->code),
19053 					       BPF_READ, insn->dst_reg, false,
19054 					       BPF_MODE(insn->code) == BPF_MEMSX);
19055 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
19056 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
19057 			if (err)
19058 				return err;
19059 		} else if (class == BPF_STX) {
19060 			enum bpf_reg_type dst_reg_type;
19061 
19062 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19063 				err = check_atomic(env, env->insn_idx, insn);
19064 				if (err)
19065 					return err;
19066 				env->insn_idx++;
19067 				continue;
19068 			}
19069 
19070 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19071 				verbose(env, "BPF_STX uses reserved fields\n");
19072 				return -EINVAL;
19073 			}
19074 
19075 			/* check src1 operand */
19076 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
19077 			if (err)
19078 				return err;
19079 			/* check src2 operand */
19080 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19081 			if (err)
19082 				return err;
19083 
19084 			dst_reg_type = regs[insn->dst_reg].type;
19085 
19086 			/* check that memory (dst_reg + off) is writeable */
19087 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19088 					       insn->off, BPF_SIZE(insn->code),
19089 					       BPF_WRITE, insn->src_reg, false, false);
19090 			if (err)
19091 				return err;
19092 
19093 			err = save_aux_ptr_type(env, dst_reg_type, false);
19094 			if (err)
19095 				return err;
19096 		} else if (class == BPF_ST) {
19097 			enum bpf_reg_type dst_reg_type;
19098 
19099 			if (BPF_MODE(insn->code) != BPF_MEM ||
19100 			    insn->src_reg != BPF_REG_0) {
19101 				verbose(env, "BPF_ST uses reserved fields\n");
19102 				return -EINVAL;
19103 			}
19104 			/* check src operand */
19105 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19106 			if (err)
19107 				return err;
19108 
19109 			dst_reg_type = regs[insn->dst_reg].type;
19110 
19111 			/* check that memory (dst_reg + off) is writeable */
19112 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19113 					       insn->off, BPF_SIZE(insn->code),
19114 					       BPF_WRITE, -1, false, false);
19115 			if (err)
19116 				return err;
19117 
19118 			err = save_aux_ptr_type(env, dst_reg_type, false);
19119 			if (err)
19120 				return err;
19121 		} else if (class == BPF_JMP || class == BPF_JMP32) {
19122 			u8 opcode = BPF_OP(insn->code);
19123 
19124 			env->jmps_processed++;
19125 			if (opcode == BPF_CALL) {
19126 				if (BPF_SRC(insn->code) != BPF_K ||
19127 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
19128 				     && insn->off != 0) ||
19129 				    (insn->src_reg != BPF_REG_0 &&
19130 				     insn->src_reg != BPF_PSEUDO_CALL &&
19131 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19132 				    insn->dst_reg != BPF_REG_0 ||
19133 				    class == BPF_JMP32) {
19134 					verbose(env, "BPF_CALL uses reserved fields\n");
19135 					return -EINVAL;
19136 				}
19137 
19138 				if (env->cur_state->active_locks) {
19139 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
19140 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19141 					     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19142 						verbose(env, "function calls are not allowed while holding a lock\n");
19143 						return -EINVAL;
19144 					}
19145 				}
19146 				if (insn->src_reg == BPF_PSEUDO_CALL) {
19147 					err = check_func_call(env, insn, &env->insn_idx);
19148 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19149 					err = check_kfunc_call(env, insn, &env->insn_idx);
19150 					if (!err && is_bpf_throw_kfunc(insn)) {
19151 						exception_exit = true;
19152 						goto process_bpf_exit_full;
19153 					}
19154 				} else {
19155 					err = check_helper_call(env, insn, &env->insn_idx);
19156 				}
19157 				if (err)
19158 					return err;
19159 
19160 				mark_reg_scratched(env, BPF_REG_0);
19161 			} else if (opcode == BPF_JA) {
19162 				if (BPF_SRC(insn->code) != BPF_K ||
19163 				    insn->src_reg != BPF_REG_0 ||
19164 				    insn->dst_reg != BPF_REG_0 ||
19165 				    (class == BPF_JMP && insn->imm != 0) ||
19166 				    (class == BPF_JMP32 && insn->off != 0)) {
19167 					verbose(env, "BPF_JA uses reserved fields\n");
19168 					return -EINVAL;
19169 				}
19170 
19171 				if (class == BPF_JMP)
19172 					env->insn_idx += insn->off + 1;
19173 				else
19174 					env->insn_idx += insn->imm + 1;
19175 				continue;
19176 
19177 			} else if (opcode == BPF_EXIT) {
19178 				if (BPF_SRC(insn->code) != BPF_K ||
19179 				    insn->imm != 0 ||
19180 				    insn->src_reg != BPF_REG_0 ||
19181 				    insn->dst_reg != BPF_REG_0 ||
19182 				    class == BPF_JMP32) {
19183 					verbose(env, "BPF_EXIT uses reserved fields\n");
19184 					return -EINVAL;
19185 				}
19186 process_bpf_exit_full:
19187 				/* We must do check_reference_leak here before
19188 				 * prepare_func_exit to handle the case when
19189 				 * state->curframe > 0, it may be a callback
19190 				 * function, for which reference_state must
19191 				 * match caller reference state when it exits.
19192 				 */
19193 				err = check_resource_leak(env, exception_exit, !env->cur_state->curframe,
19194 							  "BPF_EXIT instruction in main prog");
19195 				if (err)
19196 					return err;
19197 
19198 				/* The side effect of the prepare_func_exit
19199 				 * which is being skipped is that it frees
19200 				 * bpf_func_state. Typically, process_bpf_exit
19201 				 * will only be hit with outermost exit.
19202 				 * copy_verifier_state in pop_stack will handle
19203 				 * freeing of any extra bpf_func_state left over
19204 				 * from not processing all nested function
19205 				 * exits. We also skip return code checks as
19206 				 * they are not needed for exceptional exits.
19207 				 */
19208 				if (exception_exit)
19209 					goto process_bpf_exit;
19210 
19211 				if (state->curframe) {
19212 					/* exit from nested function */
19213 					err = prepare_func_exit(env, &env->insn_idx);
19214 					if (err)
19215 						return err;
19216 					do_print_state = true;
19217 					continue;
19218 				}
19219 
19220 				err = check_return_code(env, BPF_REG_0, "R0");
19221 				if (err)
19222 					return err;
19223 process_bpf_exit:
19224 				mark_verifier_state_scratched(env);
19225 				update_branch_counts(env, env->cur_state);
19226 				err = pop_stack(env, &prev_insn_idx,
19227 						&env->insn_idx, pop_log);
19228 				if (err < 0) {
19229 					if (err != -ENOENT)
19230 						return err;
19231 					break;
19232 				} else {
19233 					do_print_state = true;
19234 					continue;
19235 				}
19236 			} else {
19237 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
19238 				if (err)
19239 					return err;
19240 			}
19241 		} else if (class == BPF_LD) {
19242 			u8 mode = BPF_MODE(insn->code);
19243 
19244 			if (mode == BPF_ABS || mode == BPF_IND) {
19245 				err = check_ld_abs(env, insn);
19246 				if (err)
19247 					return err;
19248 
19249 			} else if (mode == BPF_IMM) {
19250 				err = check_ld_imm(env, insn);
19251 				if (err)
19252 					return err;
19253 
19254 				env->insn_idx++;
19255 				sanitize_mark_insn_seen(env);
19256 			} else {
19257 				verbose(env, "invalid BPF_LD mode\n");
19258 				return -EINVAL;
19259 			}
19260 		} else {
19261 			verbose(env, "unknown insn class %d\n", class);
19262 			return -EINVAL;
19263 		}
19264 
19265 		env->insn_idx++;
19266 	}
19267 
19268 	return 0;
19269 }
19270 
19271 static int find_btf_percpu_datasec(struct btf *btf)
19272 {
19273 	const struct btf_type *t;
19274 	const char *tname;
19275 	int i, n;
19276 
19277 	/*
19278 	 * Both vmlinux and module each have their own ".data..percpu"
19279 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
19280 	 * types to look at only module's own BTF types.
19281 	 */
19282 	n = btf_nr_types(btf);
19283 	if (btf_is_module(btf))
19284 		i = btf_nr_types(btf_vmlinux);
19285 	else
19286 		i = 1;
19287 
19288 	for(; i < n; i++) {
19289 		t = btf_type_by_id(btf, i);
19290 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
19291 			continue;
19292 
19293 		tname = btf_name_by_offset(btf, t->name_off);
19294 		if (!strcmp(tname, ".data..percpu"))
19295 			return i;
19296 	}
19297 
19298 	return -ENOENT;
19299 }
19300 
19301 /*
19302  * Add btf to the used_btfs array and return the index. (If the btf was
19303  * already added, then just return the index.) Upon successful insertion
19304  * increase btf refcnt, and, if present, also refcount the corresponding
19305  * kernel module.
19306  */
19307 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
19308 {
19309 	struct btf_mod_pair *btf_mod;
19310 	int i;
19311 
19312 	/* check whether we recorded this BTF (and maybe module) already */
19313 	for (i = 0; i < env->used_btf_cnt; i++)
19314 		if (env->used_btfs[i].btf == btf)
19315 			return i;
19316 
19317 	if (env->used_btf_cnt >= MAX_USED_BTFS)
19318 		return -E2BIG;
19319 
19320 	btf_get(btf);
19321 
19322 	btf_mod = &env->used_btfs[env->used_btf_cnt];
19323 	btf_mod->btf = btf;
19324 	btf_mod->module = NULL;
19325 
19326 	/* if we reference variables from kernel module, bump its refcount */
19327 	if (btf_is_module(btf)) {
19328 		btf_mod->module = btf_try_get_module(btf);
19329 		if (!btf_mod->module) {
19330 			btf_put(btf);
19331 			return -ENXIO;
19332 		}
19333 	}
19334 
19335 	return env->used_btf_cnt++;
19336 }
19337 
19338 /* replace pseudo btf_id with kernel symbol address */
19339 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
19340 				 struct bpf_insn *insn,
19341 				 struct bpf_insn_aux_data *aux,
19342 				 struct btf *btf)
19343 {
19344 	const struct btf_var_secinfo *vsi;
19345 	const struct btf_type *datasec;
19346 	const struct btf_type *t;
19347 	const char *sym_name;
19348 	bool percpu = false;
19349 	u32 type, id = insn->imm;
19350 	s32 datasec_id;
19351 	u64 addr;
19352 	int i;
19353 
19354 	t = btf_type_by_id(btf, id);
19355 	if (!t) {
19356 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
19357 		return -ENOENT;
19358 	}
19359 
19360 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
19361 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
19362 		return -EINVAL;
19363 	}
19364 
19365 	sym_name = btf_name_by_offset(btf, t->name_off);
19366 	addr = kallsyms_lookup_name(sym_name);
19367 	if (!addr) {
19368 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
19369 			sym_name);
19370 		return -ENOENT;
19371 	}
19372 	insn[0].imm = (u32)addr;
19373 	insn[1].imm = addr >> 32;
19374 
19375 	if (btf_type_is_func(t)) {
19376 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19377 		aux->btf_var.mem_size = 0;
19378 		return 0;
19379 	}
19380 
19381 	datasec_id = find_btf_percpu_datasec(btf);
19382 	if (datasec_id > 0) {
19383 		datasec = btf_type_by_id(btf, datasec_id);
19384 		for_each_vsi(i, datasec, vsi) {
19385 			if (vsi->type == id) {
19386 				percpu = true;
19387 				break;
19388 			}
19389 		}
19390 	}
19391 
19392 	type = t->type;
19393 	t = btf_type_skip_modifiers(btf, type, NULL);
19394 	if (percpu) {
19395 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
19396 		aux->btf_var.btf = btf;
19397 		aux->btf_var.btf_id = type;
19398 	} else if (!btf_type_is_struct(t)) {
19399 		const struct btf_type *ret;
19400 		const char *tname;
19401 		u32 tsize;
19402 
19403 		/* resolve the type size of ksym. */
19404 		ret = btf_resolve_size(btf, t, &tsize);
19405 		if (IS_ERR(ret)) {
19406 			tname = btf_name_by_offset(btf, t->name_off);
19407 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
19408 				tname, PTR_ERR(ret));
19409 			return -EINVAL;
19410 		}
19411 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19412 		aux->btf_var.mem_size = tsize;
19413 	} else {
19414 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
19415 		aux->btf_var.btf = btf;
19416 		aux->btf_var.btf_id = type;
19417 	}
19418 
19419 	return 0;
19420 }
19421 
19422 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
19423 			       struct bpf_insn *insn,
19424 			       struct bpf_insn_aux_data *aux)
19425 {
19426 	struct btf *btf;
19427 	int btf_fd;
19428 	int err;
19429 
19430 	btf_fd = insn[1].imm;
19431 	if (btf_fd) {
19432 		CLASS(fd, f)(btf_fd);
19433 
19434 		btf = __btf_get_by_fd(f);
19435 		if (IS_ERR(btf)) {
19436 			verbose(env, "invalid module BTF object FD specified.\n");
19437 			return -EINVAL;
19438 		}
19439 	} else {
19440 		if (!btf_vmlinux) {
19441 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
19442 			return -EINVAL;
19443 		}
19444 		btf = btf_vmlinux;
19445 	}
19446 
19447 	err = __check_pseudo_btf_id(env, insn, aux, btf);
19448 	if (err)
19449 		return err;
19450 
19451 	err = __add_used_btf(env, btf);
19452 	if (err < 0)
19453 		return err;
19454 	return 0;
19455 }
19456 
19457 static bool is_tracing_prog_type(enum bpf_prog_type type)
19458 {
19459 	switch (type) {
19460 	case BPF_PROG_TYPE_KPROBE:
19461 	case BPF_PROG_TYPE_TRACEPOINT:
19462 	case BPF_PROG_TYPE_PERF_EVENT:
19463 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19464 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
19465 		return true;
19466 	default:
19467 		return false;
19468 	}
19469 }
19470 
19471 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
19472 {
19473 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
19474 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
19475 }
19476 
19477 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
19478 					struct bpf_map *map,
19479 					struct bpf_prog *prog)
19480 
19481 {
19482 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19483 
19484 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
19485 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
19486 		if (is_tracing_prog_type(prog_type)) {
19487 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
19488 			return -EINVAL;
19489 		}
19490 	}
19491 
19492 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
19493 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
19494 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
19495 			return -EINVAL;
19496 		}
19497 
19498 		if (is_tracing_prog_type(prog_type)) {
19499 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
19500 			return -EINVAL;
19501 		}
19502 	}
19503 
19504 	if (btf_record_has_field(map->record, BPF_TIMER)) {
19505 		if (is_tracing_prog_type(prog_type)) {
19506 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
19507 			return -EINVAL;
19508 		}
19509 	}
19510 
19511 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
19512 		if (is_tracing_prog_type(prog_type)) {
19513 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
19514 			return -EINVAL;
19515 		}
19516 	}
19517 
19518 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
19519 	    !bpf_offload_prog_map_match(prog, map)) {
19520 		verbose(env, "offload device mismatch between prog and map\n");
19521 		return -EINVAL;
19522 	}
19523 
19524 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
19525 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
19526 		return -EINVAL;
19527 	}
19528 
19529 	if (prog->sleepable)
19530 		switch (map->map_type) {
19531 		case BPF_MAP_TYPE_HASH:
19532 		case BPF_MAP_TYPE_LRU_HASH:
19533 		case BPF_MAP_TYPE_ARRAY:
19534 		case BPF_MAP_TYPE_PERCPU_HASH:
19535 		case BPF_MAP_TYPE_PERCPU_ARRAY:
19536 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
19537 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
19538 		case BPF_MAP_TYPE_HASH_OF_MAPS:
19539 		case BPF_MAP_TYPE_RINGBUF:
19540 		case BPF_MAP_TYPE_USER_RINGBUF:
19541 		case BPF_MAP_TYPE_INODE_STORAGE:
19542 		case BPF_MAP_TYPE_SK_STORAGE:
19543 		case BPF_MAP_TYPE_TASK_STORAGE:
19544 		case BPF_MAP_TYPE_CGRP_STORAGE:
19545 		case BPF_MAP_TYPE_QUEUE:
19546 		case BPF_MAP_TYPE_STACK:
19547 		case BPF_MAP_TYPE_ARENA:
19548 			break;
19549 		default:
19550 			verbose(env,
19551 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
19552 			return -EINVAL;
19553 		}
19554 
19555 	if (bpf_map_is_cgroup_storage(map) &&
19556 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
19557 		verbose(env, "only one cgroup storage of each type is allowed\n");
19558 		return -EBUSY;
19559 	}
19560 
19561 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
19562 		if (env->prog->aux->arena) {
19563 			verbose(env, "Only one arena per program\n");
19564 			return -EBUSY;
19565 		}
19566 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
19567 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
19568 			return -EPERM;
19569 		}
19570 		if (!env->prog->jit_requested) {
19571 			verbose(env, "JIT is required to use arena\n");
19572 			return -EOPNOTSUPP;
19573 		}
19574 		if (!bpf_jit_supports_arena()) {
19575 			verbose(env, "JIT doesn't support arena\n");
19576 			return -EOPNOTSUPP;
19577 		}
19578 		env->prog->aux->arena = (void *)map;
19579 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
19580 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
19581 			return -EINVAL;
19582 		}
19583 	}
19584 
19585 	return 0;
19586 }
19587 
19588 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
19589 {
19590 	int i, err;
19591 
19592 	/* check whether we recorded this map already */
19593 	for (i = 0; i < env->used_map_cnt; i++)
19594 		if (env->used_maps[i] == map)
19595 			return i;
19596 
19597 	if (env->used_map_cnt >= MAX_USED_MAPS) {
19598 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
19599 			MAX_USED_MAPS);
19600 		return -E2BIG;
19601 	}
19602 
19603 	err = check_map_prog_compatibility(env, map, env->prog);
19604 	if (err)
19605 		return err;
19606 
19607 	if (env->prog->sleepable)
19608 		atomic64_inc(&map->sleepable_refcnt);
19609 
19610 	/* hold the map. If the program is rejected by verifier,
19611 	 * the map will be released by release_maps() or it
19612 	 * will be used by the valid program until it's unloaded
19613 	 * and all maps are released in bpf_free_used_maps()
19614 	 */
19615 	bpf_map_inc(map);
19616 
19617 	env->used_maps[env->used_map_cnt++] = map;
19618 
19619 	return env->used_map_cnt - 1;
19620 }
19621 
19622 /* Add map behind fd to used maps list, if it's not already there, and return
19623  * its index.
19624  * Returns <0 on error, or >= 0 index, on success.
19625  */
19626 static int add_used_map(struct bpf_verifier_env *env, int fd)
19627 {
19628 	struct bpf_map *map;
19629 	CLASS(fd, f)(fd);
19630 
19631 	map = __bpf_map_get(f);
19632 	if (IS_ERR(map)) {
19633 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
19634 		return PTR_ERR(map);
19635 	}
19636 
19637 	return __add_used_map(env, map);
19638 }
19639 
19640 /* find and rewrite pseudo imm in ld_imm64 instructions:
19641  *
19642  * 1. if it accesses map FD, replace it with actual map pointer.
19643  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
19644  *
19645  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
19646  */
19647 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
19648 {
19649 	struct bpf_insn *insn = env->prog->insnsi;
19650 	int insn_cnt = env->prog->len;
19651 	int i, err;
19652 
19653 	err = bpf_prog_calc_tag(env->prog);
19654 	if (err)
19655 		return err;
19656 
19657 	for (i = 0; i < insn_cnt; i++, insn++) {
19658 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19659 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
19660 		    insn->imm != 0)) {
19661 			verbose(env, "BPF_LDX uses reserved fields\n");
19662 			return -EINVAL;
19663 		}
19664 
19665 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
19666 			struct bpf_insn_aux_data *aux;
19667 			struct bpf_map *map;
19668 			int map_idx;
19669 			u64 addr;
19670 			u32 fd;
19671 
19672 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
19673 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19674 			    insn[1].off != 0) {
19675 				verbose(env, "invalid bpf_ld_imm64 insn\n");
19676 				return -EINVAL;
19677 			}
19678 
19679 			if (insn[0].src_reg == 0)
19680 				/* valid generic load 64-bit imm */
19681 				goto next_insn;
19682 
19683 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19684 				aux = &env->insn_aux_data[i];
19685 				err = check_pseudo_btf_id(env, insn, aux);
19686 				if (err)
19687 					return err;
19688 				goto next_insn;
19689 			}
19690 
19691 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19692 				aux = &env->insn_aux_data[i];
19693 				aux->ptr_type = PTR_TO_FUNC;
19694 				goto next_insn;
19695 			}
19696 
19697 			/* In final convert_pseudo_ld_imm64() step, this is
19698 			 * converted into regular 64-bit imm load insn.
19699 			 */
19700 			switch (insn[0].src_reg) {
19701 			case BPF_PSEUDO_MAP_VALUE:
19702 			case BPF_PSEUDO_MAP_IDX_VALUE:
19703 				break;
19704 			case BPF_PSEUDO_MAP_FD:
19705 			case BPF_PSEUDO_MAP_IDX:
19706 				if (insn[1].imm == 0)
19707 					break;
19708 				fallthrough;
19709 			default:
19710 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19711 				return -EINVAL;
19712 			}
19713 
19714 			switch (insn[0].src_reg) {
19715 			case BPF_PSEUDO_MAP_IDX_VALUE:
19716 			case BPF_PSEUDO_MAP_IDX:
19717 				if (bpfptr_is_null(env->fd_array)) {
19718 					verbose(env, "fd_idx without fd_array is invalid\n");
19719 					return -EPROTO;
19720 				}
19721 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
19722 							    insn[0].imm * sizeof(fd),
19723 							    sizeof(fd)))
19724 					return -EFAULT;
19725 				break;
19726 			default:
19727 				fd = insn[0].imm;
19728 				break;
19729 			}
19730 
19731 			map_idx = add_used_map(env, fd);
19732 			if (map_idx < 0)
19733 				return map_idx;
19734 			map = env->used_maps[map_idx];
19735 
19736 			aux = &env->insn_aux_data[i];
19737 			aux->map_index = map_idx;
19738 
19739 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19740 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19741 				addr = (unsigned long)map;
19742 			} else {
19743 				u32 off = insn[1].imm;
19744 
19745 				if (off >= BPF_MAX_VAR_OFF) {
19746 					verbose(env, "direct value offset of %u is not allowed\n", off);
19747 					return -EINVAL;
19748 				}
19749 
19750 				if (!map->ops->map_direct_value_addr) {
19751 					verbose(env, "no direct value access support for this map type\n");
19752 					return -EINVAL;
19753 				}
19754 
19755 				err = map->ops->map_direct_value_addr(map, &addr, off);
19756 				if (err) {
19757 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19758 						map->value_size, off);
19759 					return err;
19760 				}
19761 
19762 				aux->map_off = off;
19763 				addr += off;
19764 			}
19765 
19766 			insn[0].imm = (u32)addr;
19767 			insn[1].imm = addr >> 32;
19768 
19769 next_insn:
19770 			insn++;
19771 			i++;
19772 			continue;
19773 		}
19774 
19775 		/* Basic sanity check before we invest more work here. */
19776 		if (!bpf_opcode_in_insntable(insn->code)) {
19777 			verbose(env, "unknown opcode %02x\n", insn->code);
19778 			return -EINVAL;
19779 		}
19780 	}
19781 
19782 	/* now all pseudo BPF_LD_IMM64 instructions load valid
19783 	 * 'struct bpf_map *' into a register instead of user map_fd.
19784 	 * These pointers will be used later by verifier to validate map access.
19785 	 */
19786 	return 0;
19787 }
19788 
19789 /* drop refcnt of maps used by the rejected program */
19790 static void release_maps(struct bpf_verifier_env *env)
19791 {
19792 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
19793 			     env->used_map_cnt);
19794 }
19795 
19796 /* drop refcnt of maps used by the rejected program */
19797 static void release_btfs(struct bpf_verifier_env *env)
19798 {
19799 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19800 }
19801 
19802 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19803 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19804 {
19805 	struct bpf_insn *insn = env->prog->insnsi;
19806 	int insn_cnt = env->prog->len;
19807 	int i;
19808 
19809 	for (i = 0; i < insn_cnt; i++, insn++) {
19810 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19811 			continue;
19812 		if (insn->src_reg == BPF_PSEUDO_FUNC)
19813 			continue;
19814 		insn->src_reg = 0;
19815 	}
19816 }
19817 
19818 /* single env->prog->insni[off] instruction was replaced with the range
19819  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
19820  * [0, off) and [off, end) to new locations, so the patched range stays zero
19821  */
19822 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
19823 				 struct bpf_insn_aux_data *new_data,
19824 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
19825 {
19826 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
19827 	struct bpf_insn *insn = new_prog->insnsi;
19828 	u32 old_seen = old_data[off].seen;
19829 	u32 prog_len;
19830 	int i;
19831 
19832 	/* aux info at OFF always needs adjustment, no matter fast path
19833 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
19834 	 * original insn at old prog.
19835 	 */
19836 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
19837 
19838 	if (cnt == 1)
19839 		return;
19840 	prog_len = new_prog->len;
19841 
19842 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
19843 	memcpy(new_data + off + cnt - 1, old_data + off,
19844 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
19845 	for (i = off; i < off + cnt - 1; i++) {
19846 		/* Expand insni[off]'s seen count to the patched range. */
19847 		new_data[i].seen = old_seen;
19848 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
19849 	}
19850 	env->insn_aux_data = new_data;
19851 	vfree(old_data);
19852 }
19853 
19854 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
19855 {
19856 	int i;
19857 
19858 	if (len == 1)
19859 		return;
19860 	/* NOTE: fake 'exit' subprog should be updated as well. */
19861 	for (i = 0; i <= env->subprog_cnt; i++) {
19862 		if (env->subprog_info[i].start <= off)
19863 			continue;
19864 		env->subprog_info[i].start += len - 1;
19865 	}
19866 }
19867 
19868 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
19869 {
19870 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
19871 	int i, sz = prog->aux->size_poke_tab;
19872 	struct bpf_jit_poke_descriptor *desc;
19873 
19874 	for (i = 0; i < sz; i++) {
19875 		desc = &tab[i];
19876 		if (desc->insn_idx <= off)
19877 			continue;
19878 		desc->insn_idx += len - 1;
19879 	}
19880 }
19881 
19882 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
19883 					    const struct bpf_insn *patch, u32 len)
19884 {
19885 	struct bpf_prog *new_prog;
19886 	struct bpf_insn_aux_data *new_data = NULL;
19887 
19888 	if (len > 1) {
19889 		new_data = vzalloc(array_size(env->prog->len + len - 1,
19890 					      sizeof(struct bpf_insn_aux_data)));
19891 		if (!new_data)
19892 			return NULL;
19893 	}
19894 
19895 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
19896 	if (IS_ERR(new_prog)) {
19897 		if (PTR_ERR(new_prog) == -ERANGE)
19898 			verbose(env,
19899 				"insn %d cannot be patched due to 16-bit range\n",
19900 				env->insn_aux_data[off].orig_idx);
19901 		vfree(new_data);
19902 		return NULL;
19903 	}
19904 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
19905 	adjust_subprog_starts(env, off, len);
19906 	adjust_poke_descs(new_prog, off, len);
19907 	return new_prog;
19908 }
19909 
19910 /*
19911  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
19912  * jump offset by 'delta'.
19913  */
19914 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
19915 {
19916 	struct bpf_insn *insn = prog->insnsi;
19917 	u32 insn_cnt = prog->len, i;
19918 	s32 imm;
19919 	s16 off;
19920 
19921 	for (i = 0; i < insn_cnt; i++, insn++) {
19922 		u8 code = insn->code;
19923 
19924 		if (tgt_idx <= i && i < tgt_idx + delta)
19925 			continue;
19926 
19927 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
19928 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
19929 			continue;
19930 
19931 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
19932 			if (i + 1 + insn->imm != tgt_idx)
19933 				continue;
19934 			if (check_add_overflow(insn->imm, delta, &imm))
19935 				return -ERANGE;
19936 			insn->imm = imm;
19937 		} else {
19938 			if (i + 1 + insn->off != tgt_idx)
19939 				continue;
19940 			if (check_add_overflow(insn->off, delta, &off))
19941 				return -ERANGE;
19942 			insn->off = off;
19943 		}
19944 	}
19945 	return 0;
19946 }
19947 
19948 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
19949 					      u32 off, u32 cnt)
19950 {
19951 	int i, j;
19952 
19953 	/* find first prog starting at or after off (first to remove) */
19954 	for (i = 0; i < env->subprog_cnt; i++)
19955 		if (env->subprog_info[i].start >= off)
19956 			break;
19957 	/* find first prog starting at or after off + cnt (first to stay) */
19958 	for (j = i; j < env->subprog_cnt; j++)
19959 		if (env->subprog_info[j].start >= off + cnt)
19960 			break;
19961 	/* if j doesn't start exactly at off + cnt, we are just removing
19962 	 * the front of previous prog
19963 	 */
19964 	if (env->subprog_info[j].start != off + cnt)
19965 		j--;
19966 
19967 	if (j > i) {
19968 		struct bpf_prog_aux *aux = env->prog->aux;
19969 		int move;
19970 
19971 		/* move fake 'exit' subprog as well */
19972 		move = env->subprog_cnt + 1 - j;
19973 
19974 		memmove(env->subprog_info + i,
19975 			env->subprog_info + j,
19976 			sizeof(*env->subprog_info) * move);
19977 		env->subprog_cnt -= j - i;
19978 
19979 		/* remove func_info */
19980 		if (aux->func_info) {
19981 			move = aux->func_info_cnt - j;
19982 
19983 			memmove(aux->func_info + i,
19984 				aux->func_info + j,
19985 				sizeof(*aux->func_info) * move);
19986 			aux->func_info_cnt -= j - i;
19987 			/* func_info->insn_off is set after all code rewrites,
19988 			 * in adjust_btf_func() - no need to adjust
19989 			 */
19990 		}
19991 	} else {
19992 		/* convert i from "first prog to remove" to "first to adjust" */
19993 		if (env->subprog_info[i].start == off)
19994 			i++;
19995 	}
19996 
19997 	/* update fake 'exit' subprog as well */
19998 	for (; i <= env->subprog_cnt; i++)
19999 		env->subprog_info[i].start -= cnt;
20000 
20001 	return 0;
20002 }
20003 
20004 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20005 				      u32 cnt)
20006 {
20007 	struct bpf_prog *prog = env->prog;
20008 	u32 i, l_off, l_cnt, nr_linfo;
20009 	struct bpf_line_info *linfo;
20010 
20011 	nr_linfo = prog->aux->nr_linfo;
20012 	if (!nr_linfo)
20013 		return 0;
20014 
20015 	linfo = prog->aux->linfo;
20016 
20017 	/* find first line info to remove, count lines to be removed */
20018 	for (i = 0; i < nr_linfo; i++)
20019 		if (linfo[i].insn_off >= off)
20020 			break;
20021 
20022 	l_off = i;
20023 	l_cnt = 0;
20024 	for (; i < nr_linfo; i++)
20025 		if (linfo[i].insn_off < off + cnt)
20026 			l_cnt++;
20027 		else
20028 			break;
20029 
20030 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20031 	 * last removed linfo.  prog is already modified, so prog->len == off
20032 	 * means no live instructions after (tail of the program was removed).
20033 	 */
20034 	if (prog->len != off && l_cnt &&
20035 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20036 		l_cnt--;
20037 		linfo[--i].insn_off = off + cnt;
20038 	}
20039 
20040 	/* remove the line info which refer to the removed instructions */
20041 	if (l_cnt) {
20042 		memmove(linfo + l_off, linfo + i,
20043 			sizeof(*linfo) * (nr_linfo - i));
20044 
20045 		prog->aux->nr_linfo -= l_cnt;
20046 		nr_linfo = prog->aux->nr_linfo;
20047 	}
20048 
20049 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20050 	for (i = l_off; i < nr_linfo; i++)
20051 		linfo[i].insn_off -= cnt;
20052 
20053 	/* fix up all subprogs (incl. 'exit') which start >= off */
20054 	for (i = 0; i <= env->subprog_cnt; i++)
20055 		if (env->subprog_info[i].linfo_idx > l_off) {
20056 			/* program may have started in the removed region but
20057 			 * may not be fully removed
20058 			 */
20059 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20060 				env->subprog_info[i].linfo_idx -= l_cnt;
20061 			else
20062 				env->subprog_info[i].linfo_idx = l_off;
20063 		}
20064 
20065 	return 0;
20066 }
20067 
20068 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20069 {
20070 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20071 	unsigned int orig_prog_len = env->prog->len;
20072 	int err;
20073 
20074 	if (bpf_prog_is_offloaded(env->prog->aux))
20075 		bpf_prog_offload_remove_insns(env, off, cnt);
20076 
20077 	err = bpf_remove_insns(env->prog, off, cnt);
20078 	if (err)
20079 		return err;
20080 
20081 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20082 	if (err)
20083 		return err;
20084 
20085 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20086 	if (err)
20087 		return err;
20088 
20089 	memmove(aux_data + off,	aux_data + off + cnt,
20090 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20091 
20092 	return 0;
20093 }
20094 
20095 /* The verifier does more data flow analysis than llvm and will not
20096  * explore branches that are dead at run time. Malicious programs can
20097  * have dead code too. Therefore replace all dead at-run-time code
20098  * with 'ja -1'.
20099  *
20100  * Just nops are not optimal, e.g. if they would sit at the end of the
20101  * program and through another bug we would manage to jump there, then
20102  * we'd execute beyond program memory otherwise. Returning exception
20103  * code also wouldn't work since we can have subprogs where the dead
20104  * code could be located.
20105  */
20106 static void sanitize_dead_code(struct bpf_verifier_env *env)
20107 {
20108 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20109 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20110 	struct bpf_insn *insn = env->prog->insnsi;
20111 	const int insn_cnt = env->prog->len;
20112 	int i;
20113 
20114 	for (i = 0; i < insn_cnt; i++) {
20115 		if (aux_data[i].seen)
20116 			continue;
20117 		memcpy(insn + i, &trap, sizeof(trap));
20118 		aux_data[i].zext_dst = false;
20119 	}
20120 }
20121 
20122 static bool insn_is_cond_jump(u8 code)
20123 {
20124 	u8 op;
20125 
20126 	op = BPF_OP(code);
20127 	if (BPF_CLASS(code) == BPF_JMP32)
20128 		return op != BPF_JA;
20129 
20130 	if (BPF_CLASS(code) != BPF_JMP)
20131 		return false;
20132 
20133 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
20134 }
20135 
20136 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
20137 {
20138 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20139 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20140 	struct bpf_insn *insn = env->prog->insnsi;
20141 	const int insn_cnt = env->prog->len;
20142 	int i;
20143 
20144 	for (i = 0; i < insn_cnt; i++, insn++) {
20145 		if (!insn_is_cond_jump(insn->code))
20146 			continue;
20147 
20148 		if (!aux_data[i + 1].seen)
20149 			ja.off = insn->off;
20150 		else if (!aux_data[i + 1 + insn->off].seen)
20151 			ja.off = 0;
20152 		else
20153 			continue;
20154 
20155 		if (bpf_prog_is_offloaded(env->prog->aux))
20156 			bpf_prog_offload_replace_insn(env, i, &ja);
20157 
20158 		memcpy(insn, &ja, sizeof(ja));
20159 	}
20160 }
20161 
20162 static int opt_remove_dead_code(struct bpf_verifier_env *env)
20163 {
20164 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20165 	int insn_cnt = env->prog->len;
20166 	int i, err;
20167 
20168 	for (i = 0; i < insn_cnt; i++) {
20169 		int j;
20170 
20171 		j = 0;
20172 		while (i + j < insn_cnt && !aux_data[i + j].seen)
20173 			j++;
20174 		if (!j)
20175 			continue;
20176 
20177 		err = verifier_remove_insns(env, i, j);
20178 		if (err)
20179 			return err;
20180 		insn_cnt = env->prog->len;
20181 	}
20182 
20183 	return 0;
20184 }
20185 
20186 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20187 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
20188 
20189 static int opt_remove_nops(struct bpf_verifier_env *env)
20190 {
20191 	struct bpf_insn *insn = env->prog->insnsi;
20192 	int insn_cnt = env->prog->len;
20193 	bool is_may_goto_0, is_ja;
20194 	int i, err;
20195 
20196 	for (i = 0; i < insn_cnt; i++) {
20197 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
20198 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
20199 
20200 		if (!is_may_goto_0 && !is_ja)
20201 			continue;
20202 
20203 		err = verifier_remove_insns(env, i, 1);
20204 		if (err)
20205 			return err;
20206 		insn_cnt--;
20207 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
20208 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
20209 	}
20210 
20211 	return 0;
20212 }
20213 
20214 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
20215 					 const union bpf_attr *attr)
20216 {
20217 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
20218 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20219 	int i, patch_len, delta = 0, len = env->prog->len;
20220 	struct bpf_insn *insns = env->prog->insnsi;
20221 	struct bpf_prog *new_prog;
20222 	bool rnd_hi32;
20223 
20224 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
20225 	zext_patch[1] = BPF_ZEXT_REG(0);
20226 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
20227 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
20228 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
20229 	for (i = 0; i < len; i++) {
20230 		int adj_idx = i + delta;
20231 		struct bpf_insn insn;
20232 		int load_reg;
20233 
20234 		insn = insns[adj_idx];
20235 		load_reg = insn_def_regno(&insn);
20236 		if (!aux[adj_idx].zext_dst) {
20237 			u8 code, class;
20238 			u32 imm_rnd;
20239 
20240 			if (!rnd_hi32)
20241 				continue;
20242 
20243 			code = insn.code;
20244 			class = BPF_CLASS(code);
20245 			if (load_reg == -1)
20246 				continue;
20247 
20248 			/* NOTE: arg "reg" (the fourth one) is only used for
20249 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
20250 			 *       here.
20251 			 */
20252 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
20253 				if (class == BPF_LD &&
20254 				    BPF_MODE(code) == BPF_IMM)
20255 					i++;
20256 				continue;
20257 			}
20258 
20259 			/* ctx load could be transformed into wider load. */
20260 			if (class == BPF_LDX &&
20261 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
20262 				continue;
20263 
20264 			imm_rnd = get_random_u32();
20265 			rnd_hi32_patch[0] = insn;
20266 			rnd_hi32_patch[1].imm = imm_rnd;
20267 			rnd_hi32_patch[3].dst_reg = load_reg;
20268 			patch = rnd_hi32_patch;
20269 			patch_len = 4;
20270 			goto apply_patch_buffer;
20271 		}
20272 
20273 		/* Add in an zero-extend instruction if a) the JIT has requested
20274 		 * it or b) it's a CMPXCHG.
20275 		 *
20276 		 * The latter is because: BPF_CMPXCHG always loads a value into
20277 		 * R0, therefore always zero-extends. However some archs'
20278 		 * equivalent instruction only does this load when the
20279 		 * comparison is successful. This detail of CMPXCHG is
20280 		 * orthogonal to the general zero-extension behaviour of the
20281 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
20282 		 */
20283 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
20284 			continue;
20285 
20286 		/* Zero-extension is done by the caller. */
20287 		if (bpf_pseudo_kfunc_call(&insn))
20288 			continue;
20289 
20290 		if (WARN_ON(load_reg == -1)) {
20291 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
20292 			return -EFAULT;
20293 		}
20294 
20295 		zext_patch[0] = insn;
20296 		zext_patch[1].dst_reg = load_reg;
20297 		zext_patch[1].src_reg = load_reg;
20298 		patch = zext_patch;
20299 		patch_len = 2;
20300 apply_patch_buffer:
20301 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
20302 		if (!new_prog)
20303 			return -ENOMEM;
20304 		env->prog = new_prog;
20305 		insns = new_prog->insnsi;
20306 		aux = env->insn_aux_data;
20307 		delta += patch_len - 1;
20308 	}
20309 
20310 	return 0;
20311 }
20312 
20313 /* convert load instructions that access fields of a context type into a
20314  * sequence of instructions that access fields of the underlying structure:
20315  *     struct __sk_buff    -> struct sk_buff
20316  *     struct bpf_sock_ops -> struct sock
20317  */
20318 static int convert_ctx_accesses(struct bpf_verifier_env *env)
20319 {
20320 	struct bpf_subprog_info *subprogs = env->subprog_info;
20321 	const struct bpf_verifier_ops *ops = env->ops;
20322 	int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0;
20323 	const int insn_cnt = env->prog->len;
20324 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
20325 	struct bpf_insn *insn_buf = env->insn_buf;
20326 	struct bpf_insn *insn;
20327 	u32 target_size, size_default, off;
20328 	struct bpf_prog *new_prog;
20329 	enum bpf_access_type type;
20330 	bool is_narrower_load;
20331 	int epilogue_idx = 0;
20332 
20333 	if (ops->gen_epilogue) {
20334 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
20335 						 -(subprogs[0].stack_depth + 8));
20336 		if (epilogue_cnt >= INSN_BUF_SIZE) {
20337 			verbose(env, "bpf verifier is misconfigured\n");
20338 			return -EINVAL;
20339 		} else if (epilogue_cnt) {
20340 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
20341 			cnt = 0;
20342 			subprogs[0].stack_depth += 8;
20343 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
20344 						      -subprogs[0].stack_depth);
20345 			insn_buf[cnt++] = env->prog->insnsi[0];
20346 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20347 			if (!new_prog)
20348 				return -ENOMEM;
20349 			env->prog = new_prog;
20350 			delta += cnt - 1;
20351 		}
20352 	}
20353 
20354 	if (ops->gen_prologue || env->seen_direct_write) {
20355 		if (!ops->gen_prologue) {
20356 			verbose(env, "bpf verifier is misconfigured\n");
20357 			return -EINVAL;
20358 		}
20359 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
20360 					env->prog);
20361 		if (cnt >= INSN_BUF_SIZE) {
20362 			verbose(env, "bpf verifier is misconfigured\n");
20363 			return -EINVAL;
20364 		} else if (cnt) {
20365 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20366 			if (!new_prog)
20367 				return -ENOMEM;
20368 
20369 			env->prog = new_prog;
20370 			delta += cnt - 1;
20371 		}
20372 	}
20373 
20374 	if (delta)
20375 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
20376 
20377 	if (bpf_prog_is_offloaded(env->prog->aux))
20378 		return 0;
20379 
20380 	insn = env->prog->insnsi + delta;
20381 
20382 	for (i = 0; i < insn_cnt; i++, insn++) {
20383 		bpf_convert_ctx_access_t convert_ctx_access;
20384 		u8 mode;
20385 
20386 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
20387 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
20388 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
20389 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
20390 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
20391 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
20392 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
20393 			type = BPF_READ;
20394 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
20395 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
20396 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
20397 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
20398 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
20399 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
20400 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
20401 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
20402 			type = BPF_WRITE;
20403 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
20404 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
20405 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
20406 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
20407 			env->prog->aux->num_exentries++;
20408 			continue;
20409 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
20410 			   epilogue_cnt &&
20411 			   i + delta < subprogs[1].start) {
20412 			/* Generate epilogue for the main prog */
20413 			if (epilogue_idx) {
20414 				/* jump back to the earlier generated epilogue */
20415 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
20416 				cnt = 1;
20417 			} else {
20418 				memcpy(insn_buf, epilogue_buf,
20419 				       epilogue_cnt * sizeof(*epilogue_buf));
20420 				cnt = epilogue_cnt;
20421 				/* epilogue_idx cannot be 0. It must have at
20422 				 * least one ctx ptr saving insn before the
20423 				 * epilogue.
20424 				 */
20425 				epilogue_idx = i + delta;
20426 			}
20427 			goto patch_insn_buf;
20428 		} else {
20429 			continue;
20430 		}
20431 
20432 		if (type == BPF_WRITE &&
20433 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
20434 			struct bpf_insn patch[] = {
20435 				*insn,
20436 				BPF_ST_NOSPEC(),
20437 			};
20438 
20439 			cnt = ARRAY_SIZE(patch);
20440 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
20441 			if (!new_prog)
20442 				return -ENOMEM;
20443 
20444 			delta    += cnt - 1;
20445 			env->prog = new_prog;
20446 			insn      = new_prog->insnsi + i + delta;
20447 			continue;
20448 		}
20449 
20450 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
20451 		case PTR_TO_CTX:
20452 			if (!ops->convert_ctx_access)
20453 				continue;
20454 			convert_ctx_access = ops->convert_ctx_access;
20455 			break;
20456 		case PTR_TO_SOCKET:
20457 		case PTR_TO_SOCK_COMMON:
20458 			convert_ctx_access = bpf_sock_convert_ctx_access;
20459 			break;
20460 		case PTR_TO_TCP_SOCK:
20461 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
20462 			break;
20463 		case PTR_TO_XDP_SOCK:
20464 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
20465 			break;
20466 		case PTR_TO_BTF_ID:
20467 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
20468 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
20469 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
20470 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
20471 		 * any faults for loads into such types. BPF_WRITE is disallowed
20472 		 * for this case.
20473 		 */
20474 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
20475 			if (type == BPF_READ) {
20476 				if (BPF_MODE(insn->code) == BPF_MEM)
20477 					insn->code = BPF_LDX | BPF_PROBE_MEM |
20478 						     BPF_SIZE((insn)->code);
20479 				else
20480 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
20481 						     BPF_SIZE((insn)->code);
20482 				env->prog->aux->num_exentries++;
20483 			}
20484 			continue;
20485 		case PTR_TO_ARENA:
20486 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
20487 				verbose(env, "sign extending loads from arena are not supported yet\n");
20488 				return -EOPNOTSUPP;
20489 			}
20490 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
20491 			env->prog->aux->num_exentries++;
20492 			continue;
20493 		default:
20494 			continue;
20495 		}
20496 
20497 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
20498 		size = BPF_LDST_BYTES(insn);
20499 		mode = BPF_MODE(insn->code);
20500 
20501 		/* If the read access is a narrower load of the field,
20502 		 * convert to a 4/8-byte load, to minimum program type specific
20503 		 * convert_ctx_access changes. If conversion is successful,
20504 		 * we will apply proper mask to the result.
20505 		 */
20506 		is_narrower_load = size < ctx_field_size;
20507 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
20508 		off = insn->off;
20509 		if (is_narrower_load) {
20510 			u8 size_code;
20511 
20512 			if (type == BPF_WRITE) {
20513 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
20514 				return -EINVAL;
20515 			}
20516 
20517 			size_code = BPF_H;
20518 			if (ctx_field_size == 4)
20519 				size_code = BPF_W;
20520 			else if (ctx_field_size == 8)
20521 				size_code = BPF_DW;
20522 
20523 			insn->off = off & ~(size_default - 1);
20524 			insn->code = BPF_LDX | BPF_MEM | size_code;
20525 		}
20526 
20527 		target_size = 0;
20528 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
20529 					 &target_size);
20530 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
20531 		    (ctx_field_size && !target_size)) {
20532 			verbose(env, "bpf verifier is misconfigured\n");
20533 			return -EINVAL;
20534 		}
20535 
20536 		if (is_narrower_load && size < target_size) {
20537 			u8 shift = bpf_ctx_narrow_access_offset(
20538 				off, size, size_default) * 8;
20539 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
20540 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
20541 				return -EINVAL;
20542 			}
20543 			if (ctx_field_size <= 4) {
20544 				if (shift)
20545 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
20546 									insn->dst_reg,
20547 									shift);
20548 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20549 								(1 << size * 8) - 1);
20550 			} else {
20551 				if (shift)
20552 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
20553 									insn->dst_reg,
20554 									shift);
20555 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20556 								(1ULL << size * 8) - 1);
20557 			}
20558 		}
20559 		if (mode == BPF_MEMSX)
20560 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
20561 						       insn->dst_reg, insn->dst_reg,
20562 						       size * 8, 0);
20563 
20564 patch_insn_buf:
20565 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20566 		if (!new_prog)
20567 			return -ENOMEM;
20568 
20569 		delta += cnt - 1;
20570 
20571 		/* keep walking new program and skip insns we just inserted */
20572 		env->prog = new_prog;
20573 		insn      = new_prog->insnsi + i + delta;
20574 	}
20575 
20576 	return 0;
20577 }
20578 
20579 static int jit_subprogs(struct bpf_verifier_env *env)
20580 {
20581 	struct bpf_prog *prog = env->prog, **func, *tmp;
20582 	int i, j, subprog_start, subprog_end = 0, len, subprog;
20583 	struct bpf_map *map_ptr;
20584 	struct bpf_insn *insn;
20585 	void *old_bpf_func;
20586 	int err, num_exentries;
20587 
20588 	if (env->subprog_cnt <= 1)
20589 		return 0;
20590 
20591 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20592 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
20593 			continue;
20594 
20595 		/* Upon error here we cannot fall back to interpreter but
20596 		 * need a hard reject of the program. Thus -EFAULT is
20597 		 * propagated in any case.
20598 		 */
20599 		subprog = find_subprog(env, i + insn->imm + 1);
20600 		if (subprog < 0) {
20601 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
20602 				  i + insn->imm + 1);
20603 			return -EFAULT;
20604 		}
20605 		/* temporarily remember subprog id inside insn instead of
20606 		 * aux_data, since next loop will split up all insns into funcs
20607 		 */
20608 		insn->off = subprog;
20609 		/* remember original imm in case JIT fails and fallback
20610 		 * to interpreter will be needed
20611 		 */
20612 		env->insn_aux_data[i].call_imm = insn->imm;
20613 		/* point imm to __bpf_call_base+1 from JITs point of view */
20614 		insn->imm = 1;
20615 		if (bpf_pseudo_func(insn)) {
20616 #if defined(MODULES_VADDR)
20617 			u64 addr = MODULES_VADDR;
20618 #else
20619 			u64 addr = VMALLOC_START;
20620 #endif
20621 			/* jit (e.g. x86_64) may emit fewer instructions
20622 			 * if it learns a u32 imm is the same as a u64 imm.
20623 			 * Set close enough to possible prog address.
20624 			 */
20625 			insn[0].imm = (u32)addr;
20626 			insn[1].imm = addr >> 32;
20627 		}
20628 	}
20629 
20630 	err = bpf_prog_alloc_jited_linfo(prog);
20631 	if (err)
20632 		goto out_undo_insn;
20633 
20634 	err = -ENOMEM;
20635 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
20636 	if (!func)
20637 		goto out_undo_insn;
20638 
20639 	for (i = 0; i < env->subprog_cnt; i++) {
20640 		subprog_start = subprog_end;
20641 		subprog_end = env->subprog_info[i + 1].start;
20642 
20643 		len = subprog_end - subprog_start;
20644 		/* bpf_prog_run() doesn't call subprogs directly,
20645 		 * hence main prog stats include the runtime of subprogs.
20646 		 * subprogs don't have IDs and not reachable via prog_get_next_id
20647 		 * func[i]->stats will never be accessed and stays NULL
20648 		 */
20649 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
20650 		if (!func[i])
20651 			goto out_free;
20652 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
20653 		       len * sizeof(struct bpf_insn));
20654 		func[i]->type = prog->type;
20655 		func[i]->len = len;
20656 		if (bpf_prog_calc_tag(func[i]))
20657 			goto out_free;
20658 		func[i]->is_func = 1;
20659 		func[i]->sleepable = prog->sleepable;
20660 		func[i]->aux->func_idx = i;
20661 		/* Below members will be freed only at prog->aux */
20662 		func[i]->aux->btf = prog->aux->btf;
20663 		func[i]->aux->func_info = prog->aux->func_info;
20664 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
20665 		func[i]->aux->poke_tab = prog->aux->poke_tab;
20666 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
20667 
20668 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
20669 			struct bpf_jit_poke_descriptor *poke;
20670 
20671 			poke = &prog->aux->poke_tab[j];
20672 			if (poke->insn_idx < subprog_end &&
20673 			    poke->insn_idx >= subprog_start)
20674 				poke->aux = func[i]->aux;
20675 		}
20676 
20677 		func[i]->aux->name[0] = 'F';
20678 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
20679 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
20680 			func[i]->aux->jits_use_priv_stack = true;
20681 
20682 		func[i]->jit_requested = 1;
20683 		func[i]->blinding_requested = prog->blinding_requested;
20684 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
20685 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
20686 		func[i]->aux->linfo = prog->aux->linfo;
20687 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
20688 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
20689 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
20690 		func[i]->aux->arena = prog->aux->arena;
20691 		num_exentries = 0;
20692 		insn = func[i]->insnsi;
20693 		for (j = 0; j < func[i]->len; j++, insn++) {
20694 			if (BPF_CLASS(insn->code) == BPF_LDX &&
20695 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20696 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
20697 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
20698 				num_exentries++;
20699 			if ((BPF_CLASS(insn->code) == BPF_STX ||
20700 			     BPF_CLASS(insn->code) == BPF_ST) &&
20701 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
20702 				num_exentries++;
20703 			if (BPF_CLASS(insn->code) == BPF_STX &&
20704 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
20705 				num_exentries++;
20706 		}
20707 		func[i]->aux->num_exentries = num_exentries;
20708 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
20709 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
20710 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
20711 		if (!i)
20712 			func[i]->aux->exception_boundary = env->seen_exception;
20713 		func[i] = bpf_int_jit_compile(func[i]);
20714 		if (!func[i]->jited) {
20715 			err = -ENOTSUPP;
20716 			goto out_free;
20717 		}
20718 		cond_resched();
20719 	}
20720 
20721 	/* at this point all bpf functions were successfully JITed
20722 	 * now populate all bpf_calls with correct addresses and
20723 	 * run last pass of JIT
20724 	 */
20725 	for (i = 0; i < env->subprog_cnt; i++) {
20726 		insn = func[i]->insnsi;
20727 		for (j = 0; j < func[i]->len; j++, insn++) {
20728 			if (bpf_pseudo_func(insn)) {
20729 				subprog = insn->off;
20730 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
20731 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
20732 				continue;
20733 			}
20734 			if (!bpf_pseudo_call(insn))
20735 				continue;
20736 			subprog = insn->off;
20737 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
20738 		}
20739 
20740 		/* we use the aux data to keep a list of the start addresses
20741 		 * of the JITed images for each function in the program
20742 		 *
20743 		 * for some architectures, such as powerpc64, the imm field
20744 		 * might not be large enough to hold the offset of the start
20745 		 * address of the callee's JITed image from __bpf_call_base
20746 		 *
20747 		 * in such cases, we can lookup the start address of a callee
20748 		 * by using its subprog id, available from the off field of
20749 		 * the call instruction, as an index for this list
20750 		 */
20751 		func[i]->aux->func = func;
20752 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20753 		func[i]->aux->real_func_cnt = env->subprog_cnt;
20754 	}
20755 	for (i = 0; i < env->subprog_cnt; i++) {
20756 		old_bpf_func = func[i]->bpf_func;
20757 		tmp = bpf_int_jit_compile(func[i]);
20758 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
20759 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
20760 			err = -ENOTSUPP;
20761 			goto out_free;
20762 		}
20763 		cond_resched();
20764 	}
20765 
20766 	/* finally lock prog and jit images for all functions and
20767 	 * populate kallsysm. Begin at the first subprogram, since
20768 	 * bpf_prog_load will add the kallsyms for the main program.
20769 	 */
20770 	for (i = 1; i < env->subprog_cnt; i++) {
20771 		err = bpf_prog_lock_ro(func[i]);
20772 		if (err)
20773 			goto out_free;
20774 	}
20775 
20776 	for (i = 1; i < env->subprog_cnt; i++)
20777 		bpf_prog_kallsyms_add(func[i]);
20778 
20779 	/* Last step: make now unused interpreter insns from main
20780 	 * prog consistent for later dump requests, so they can
20781 	 * later look the same as if they were interpreted only.
20782 	 */
20783 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20784 		if (bpf_pseudo_func(insn)) {
20785 			insn[0].imm = env->insn_aux_data[i].call_imm;
20786 			insn[1].imm = insn->off;
20787 			insn->off = 0;
20788 			continue;
20789 		}
20790 		if (!bpf_pseudo_call(insn))
20791 			continue;
20792 		insn->off = env->insn_aux_data[i].call_imm;
20793 		subprog = find_subprog(env, i + insn->off + 1);
20794 		insn->imm = subprog;
20795 	}
20796 
20797 	prog->jited = 1;
20798 	prog->bpf_func = func[0]->bpf_func;
20799 	prog->jited_len = func[0]->jited_len;
20800 	prog->aux->extable = func[0]->aux->extable;
20801 	prog->aux->num_exentries = func[0]->aux->num_exentries;
20802 	prog->aux->func = func;
20803 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20804 	prog->aux->real_func_cnt = env->subprog_cnt;
20805 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
20806 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
20807 	bpf_prog_jit_attempt_done(prog);
20808 	return 0;
20809 out_free:
20810 	/* We failed JIT'ing, so at this point we need to unregister poke
20811 	 * descriptors from subprogs, so that kernel is not attempting to
20812 	 * patch it anymore as we're freeing the subprog JIT memory.
20813 	 */
20814 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20815 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20816 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
20817 	}
20818 	/* At this point we're guaranteed that poke descriptors are not
20819 	 * live anymore. We can just unlink its descriptor table as it's
20820 	 * released with the main prog.
20821 	 */
20822 	for (i = 0; i < env->subprog_cnt; i++) {
20823 		if (!func[i])
20824 			continue;
20825 		func[i]->aux->poke_tab = NULL;
20826 		bpf_jit_free(func[i]);
20827 	}
20828 	kfree(func);
20829 out_undo_insn:
20830 	/* cleanup main prog to be interpreted */
20831 	prog->jit_requested = 0;
20832 	prog->blinding_requested = 0;
20833 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20834 		if (!bpf_pseudo_call(insn))
20835 			continue;
20836 		insn->off = 0;
20837 		insn->imm = env->insn_aux_data[i].call_imm;
20838 	}
20839 	bpf_prog_jit_attempt_done(prog);
20840 	return err;
20841 }
20842 
20843 static int fixup_call_args(struct bpf_verifier_env *env)
20844 {
20845 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20846 	struct bpf_prog *prog = env->prog;
20847 	struct bpf_insn *insn = prog->insnsi;
20848 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
20849 	int i, depth;
20850 #endif
20851 	int err = 0;
20852 
20853 	if (env->prog->jit_requested &&
20854 	    !bpf_prog_is_offloaded(env->prog->aux)) {
20855 		err = jit_subprogs(env);
20856 		if (err == 0)
20857 			return 0;
20858 		if (err == -EFAULT)
20859 			return err;
20860 	}
20861 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20862 	if (has_kfunc_call) {
20863 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
20864 		return -EINVAL;
20865 	}
20866 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
20867 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
20868 		 * have to be rejected, since interpreter doesn't support them yet.
20869 		 */
20870 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
20871 		return -EINVAL;
20872 	}
20873 	for (i = 0; i < prog->len; i++, insn++) {
20874 		if (bpf_pseudo_func(insn)) {
20875 			/* When JIT fails the progs with callback calls
20876 			 * have to be rejected, since interpreter doesn't support them yet.
20877 			 */
20878 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
20879 			return -EINVAL;
20880 		}
20881 
20882 		if (!bpf_pseudo_call(insn))
20883 			continue;
20884 		depth = get_callee_stack_depth(env, insn, i);
20885 		if (depth < 0)
20886 			return depth;
20887 		bpf_patch_call_args(insn, depth);
20888 	}
20889 	err = 0;
20890 #endif
20891 	return err;
20892 }
20893 
20894 /* replace a generic kfunc with a specialized version if necessary */
20895 static void specialize_kfunc(struct bpf_verifier_env *env,
20896 			     u32 func_id, u16 offset, unsigned long *addr)
20897 {
20898 	struct bpf_prog *prog = env->prog;
20899 	bool seen_direct_write;
20900 	void *xdp_kfunc;
20901 	bool is_rdonly;
20902 
20903 	if (bpf_dev_bound_kfunc_id(func_id)) {
20904 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20905 		if (xdp_kfunc) {
20906 			*addr = (unsigned long)xdp_kfunc;
20907 			return;
20908 		}
20909 		/* fallback to default kfunc when not supported by netdev */
20910 	}
20911 
20912 	if (offset)
20913 		return;
20914 
20915 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20916 		seen_direct_write = env->seen_direct_write;
20917 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20918 
20919 		if (is_rdonly)
20920 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20921 
20922 		/* restore env->seen_direct_write to its original value, since
20923 		 * may_access_direct_pkt_data mutates it
20924 		 */
20925 		env->seen_direct_write = seen_direct_write;
20926 	}
20927 }
20928 
20929 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20930 					    u16 struct_meta_reg,
20931 					    u16 node_offset_reg,
20932 					    struct bpf_insn *insn,
20933 					    struct bpf_insn *insn_buf,
20934 					    int *cnt)
20935 {
20936 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20937 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20938 
20939 	insn_buf[0] = addr[0];
20940 	insn_buf[1] = addr[1];
20941 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20942 	insn_buf[3] = *insn;
20943 	*cnt = 4;
20944 }
20945 
20946 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20947 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20948 {
20949 	const struct bpf_kfunc_desc *desc;
20950 
20951 	if (!insn->imm) {
20952 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20953 		return -EINVAL;
20954 	}
20955 
20956 	*cnt = 0;
20957 
20958 	/* insn->imm has the btf func_id. Replace it with an offset relative to
20959 	 * __bpf_call_base, unless the JIT needs to call functions that are
20960 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20961 	 */
20962 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20963 	if (!desc) {
20964 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
20965 			insn->imm);
20966 		return -EFAULT;
20967 	}
20968 
20969 	if (!bpf_jit_supports_far_kfunc_call())
20970 		insn->imm = BPF_CALL_IMM(desc->addr);
20971 	if (insn->off)
20972 		return 0;
20973 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
20974 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
20975 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20976 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20977 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20978 
20979 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
20980 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20981 				insn_idx);
20982 			return -EFAULT;
20983 		}
20984 
20985 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20986 		insn_buf[1] = addr[0];
20987 		insn_buf[2] = addr[1];
20988 		insn_buf[3] = *insn;
20989 		*cnt = 4;
20990 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
20991 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
20992 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
20993 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20994 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20995 
20996 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
20997 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20998 				insn_idx);
20999 			return -EFAULT;
21000 		}
21001 
21002 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21003 		    !kptr_struct_meta) {
21004 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
21005 				insn_idx);
21006 			return -EFAULT;
21007 		}
21008 
21009 		insn_buf[0] = addr[0];
21010 		insn_buf[1] = addr[1];
21011 		insn_buf[2] = *insn;
21012 		*cnt = 3;
21013 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21014 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21015 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21016 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21017 		int struct_meta_reg = BPF_REG_3;
21018 		int node_offset_reg = BPF_REG_4;
21019 
21020 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21021 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21022 			struct_meta_reg = BPF_REG_4;
21023 			node_offset_reg = BPF_REG_5;
21024 		}
21025 
21026 		if (!kptr_struct_meta) {
21027 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
21028 				insn_idx);
21029 			return -EFAULT;
21030 		}
21031 
21032 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21033 						node_offset_reg, insn, insn_buf, cnt);
21034 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21035 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21036 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21037 		*cnt = 1;
21038 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
21039 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
21040 
21041 		insn_buf[0] = ld_addrs[0];
21042 		insn_buf[1] = ld_addrs[1];
21043 		insn_buf[2] = *insn;
21044 		*cnt = 3;
21045 	}
21046 	return 0;
21047 }
21048 
21049 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
21050 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21051 {
21052 	struct bpf_subprog_info *info = env->subprog_info;
21053 	int cnt = env->subprog_cnt;
21054 	struct bpf_prog *prog;
21055 
21056 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21057 	if (env->hidden_subprog_cnt) {
21058 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
21059 		return -EFAULT;
21060 	}
21061 	/* We're not patching any existing instruction, just appending the new
21062 	 * ones for the hidden subprog. Hence all of the adjustment operations
21063 	 * in bpf_patch_insn_data are no-ops.
21064 	 */
21065 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21066 	if (!prog)
21067 		return -ENOMEM;
21068 	env->prog = prog;
21069 	info[cnt + 1].start = info[cnt].start;
21070 	info[cnt].start = prog->len - len + 1;
21071 	env->subprog_cnt++;
21072 	env->hidden_subprog_cnt++;
21073 	return 0;
21074 }
21075 
21076 /* Do various post-verification rewrites in a single program pass.
21077  * These rewrites simplify JIT and interpreter implementations.
21078  */
21079 static int do_misc_fixups(struct bpf_verifier_env *env)
21080 {
21081 	struct bpf_prog *prog = env->prog;
21082 	enum bpf_attach_type eatype = prog->expected_attach_type;
21083 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
21084 	struct bpf_insn *insn = prog->insnsi;
21085 	const struct bpf_func_proto *fn;
21086 	const int insn_cnt = prog->len;
21087 	const struct bpf_map_ops *ops;
21088 	struct bpf_insn_aux_data *aux;
21089 	struct bpf_insn *insn_buf = env->insn_buf;
21090 	struct bpf_prog *new_prog;
21091 	struct bpf_map *map_ptr;
21092 	int i, ret, cnt, delta = 0, cur_subprog = 0;
21093 	struct bpf_subprog_info *subprogs = env->subprog_info;
21094 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21095 	u16 stack_depth_extra = 0;
21096 
21097 	if (env->seen_exception && !env->exception_callback_subprog) {
21098 		struct bpf_insn patch[] = {
21099 			env->prog->insnsi[insn_cnt - 1],
21100 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
21101 			BPF_EXIT_INSN(),
21102 		};
21103 
21104 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
21105 		if (ret < 0)
21106 			return ret;
21107 		prog = env->prog;
21108 		insn = prog->insnsi;
21109 
21110 		env->exception_callback_subprog = env->subprog_cnt - 1;
21111 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
21112 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
21113 	}
21114 
21115 	for (i = 0; i < insn_cnt;) {
21116 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
21117 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
21118 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
21119 				/* convert to 32-bit mov that clears upper 32-bit */
21120 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
21121 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
21122 				insn->off = 0;
21123 				insn->imm = 0;
21124 			} /* cast from as(0) to as(1) should be handled by JIT */
21125 			goto next_insn;
21126 		}
21127 
21128 		if (env->insn_aux_data[i + delta].needs_zext)
21129 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
21130 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
21131 
21132 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
21133 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
21134 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
21135 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
21136 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
21137 		    insn->off == 1 && insn->imm == -1) {
21138 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21139 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21140 			struct bpf_insn *patchlet;
21141 			struct bpf_insn chk_and_sdiv[] = {
21142 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21143 					     BPF_NEG | BPF_K, insn->dst_reg,
21144 					     0, 0, 0),
21145 			};
21146 			struct bpf_insn chk_and_smod[] = {
21147 				BPF_MOV32_IMM(insn->dst_reg, 0),
21148 			};
21149 
21150 			patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
21151 			cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
21152 
21153 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21154 			if (!new_prog)
21155 				return -ENOMEM;
21156 
21157 			delta    += cnt - 1;
21158 			env->prog = prog = new_prog;
21159 			insn      = new_prog->insnsi + i + delta;
21160 			goto next_insn;
21161 		}
21162 
21163 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
21164 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
21165 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
21166 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
21167 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
21168 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21169 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21170 			bool is_sdiv = isdiv && insn->off == 1;
21171 			bool is_smod = !isdiv && insn->off == 1;
21172 			struct bpf_insn *patchlet;
21173 			struct bpf_insn chk_and_div[] = {
21174 				/* [R,W]x div 0 -> 0 */
21175 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21176 					     BPF_JNE | BPF_K, insn->src_reg,
21177 					     0, 2, 0),
21178 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
21179 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21180 				*insn,
21181 			};
21182 			struct bpf_insn chk_and_mod[] = {
21183 				/* [R,W]x mod 0 -> [R,W]x */
21184 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21185 					     BPF_JEQ | BPF_K, insn->src_reg,
21186 					     0, 1 + (is64 ? 0 : 1), 0),
21187 				*insn,
21188 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21189 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21190 			};
21191 			struct bpf_insn chk_and_sdiv[] = {
21192 				/* [R,W]x sdiv 0 -> 0
21193 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
21194 				 * INT_MIN sdiv -1 -> INT_MIN
21195 				 */
21196 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21197 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21198 					     BPF_ADD | BPF_K, BPF_REG_AX,
21199 					     0, 0, 1),
21200 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21201 					     BPF_JGT | BPF_K, BPF_REG_AX,
21202 					     0, 4, 1),
21203 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21204 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21205 					     0, 1, 0),
21206 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21207 					     BPF_MOV | BPF_K, insn->dst_reg,
21208 					     0, 0, 0),
21209 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
21210 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21211 					     BPF_NEG | BPF_K, insn->dst_reg,
21212 					     0, 0, 0),
21213 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21214 				*insn,
21215 			};
21216 			struct bpf_insn chk_and_smod[] = {
21217 				/* [R,W]x mod 0 -> [R,W]x */
21218 				/* [R,W]x mod -1 -> 0 */
21219 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21220 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21221 					     BPF_ADD | BPF_K, BPF_REG_AX,
21222 					     0, 0, 1),
21223 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21224 					     BPF_JGT | BPF_K, BPF_REG_AX,
21225 					     0, 3, 1),
21226 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21227 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21228 					     0, 3 + (is64 ? 0 : 1), 1),
21229 				BPF_MOV32_IMM(insn->dst_reg, 0),
21230 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21231 				*insn,
21232 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21233 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21234 			};
21235 
21236 			if (is_sdiv) {
21237 				patchlet = chk_and_sdiv;
21238 				cnt = ARRAY_SIZE(chk_and_sdiv);
21239 			} else if (is_smod) {
21240 				patchlet = chk_and_smod;
21241 				cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
21242 			} else {
21243 				patchlet = isdiv ? chk_and_div : chk_and_mod;
21244 				cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
21245 					      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
21246 			}
21247 
21248 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21249 			if (!new_prog)
21250 				return -ENOMEM;
21251 
21252 			delta    += cnt - 1;
21253 			env->prog = prog = new_prog;
21254 			insn      = new_prog->insnsi + i + delta;
21255 			goto next_insn;
21256 		}
21257 
21258 		/* Make it impossible to de-reference a userspace address */
21259 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21260 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21261 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
21262 			struct bpf_insn *patch = &insn_buf[0];
21263 			u64 uaddress_limit = bpf_arch_uaddress_limit();
21264 
21265 			if (!uaddress_limit)
21266 				goto next_insn;
21267 
21268 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
21269 			if (insn->off)
21270 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
21271 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
21272 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
21273 			*patch++ = *insn;
21274 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
21275 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
21276 
21277 			cnt = patch - insn_buf;
21278 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21279 			if (!new_prog)
21280 				return -ENOMEM;
21281 
21282 			delta    += cnt - 1;
21283 			env->prog = prog = new_prog;
21284 			insn      = new_prog->insnsi + i + delta;
21285 			goto next_insn;
21286 		}
21287 
21288 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
21289 		if (BPF_CLASS(insn->code) == BPF_LD &&
21290 		    (BPF_MODE(insn->code) == BPF_ABS ||
21291 		     BPF_MODE(insn->code) == BPF_IND)) {
21292 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
21293 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
21294 				verbose(env, "bpf verifier is misconfigured\n");
21295 				return -EINVAL;
21296 			}
21297 
21298 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21299 			if (!new_prog)
21300 				return -ENOMEM;
21301 
21302 			delta    += cnt - 1;
21303 			env->prog = prog = new_prog;
21304 			insn      = new_prog->insnsi + i + delta;
21305 			goto next_insn;
21306 		}
21307 
21308 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
21309 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
21310 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
21311 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
21312 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
21313 			struct bpf_insn *patch = &insn_buf[0];
21314 			bool issrc, isneg, isimm;
21315 			u32 off_reg;
21316 
21317 			aux = &env->insn_aux_data[i + delta];
21318 			if (!aux->alu_state ||
21319 			    aux->alu_state == BPF_ALU_NON_POINTER)
21320 				goto next_insn;
21321 
21322 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
21323 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
21324 				BPF_ALU_SANITIZE_SRC;
21325 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
21326 
21327 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
21328 			if (isimm) {
21329 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21330 			} else {
21331 				if (isneg)
21332 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21333 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21334 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
21335 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
21336 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
21337 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
21338 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
21339 			}
21340 			if (!issrc)
21341 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
21342 			insn->src_reg = BPF_REG_AX;
21343 			if (isneg)
21344 				insn->code = insn->code == code_add ?
21345 					     code_sub : code_add;
21346 			*patch++ = *insn;
21347 			if (issrc && isneg && !isimm)
21348 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21349 			cnt = patch - insn_buf;
21350 
21351 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21352 			if (!new_prog)
21353 				return -ENOMEM;
21354 
21355 			delta    += cnt - 1;
21356 			env->prog = prog = new_prog;
21357 			insn      = new_prog->insnsi + i + delta;
21358 			goto next_insn;
21359 		}
21360 
21361 		if (is_may_goto_insn(insn)) {
21362 			int stack_off = -stack_depth - 8;
21363 
21364 			stack_depth_extra = 8;
21365 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
21366 			if (insn->off >= 0)
21367 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
21368 			else
21369 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
21370 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
21371 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
21372 			cnt = 4;
21373 
21374 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21375 			if (!new_prog)
21376 				return -ENOMEM;
21377 
21378 			delta += cnt - 1;
21379 			env->prog = prog = new_prog;
21380 			insn = new_prog->insnsi + i + delta;
21381 			goto next_insn;
21382 		}
21383 
21384 		if (insn->code != (BPF_JMP | BPF_CALL))
21385 			goto next_insn;
21386 		if (insn->src_reg == BPF_PSEUDO_CALL)
21387 			goto next_insn;
21388 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
21389 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
21390 			if (ret)
21391 				return ret;
21392 			if (cnt == 0)
21393 				goto next_insn;
21394 
21395 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21396 			if (!new_prog)
21397 				return -ENOMEM;
21398 
21399 			delta	 += cnt - 1;
21400 			env->prog = prog = new_prog;
21401 			insn	  = new_prog->insnsi + i + delta;
21402 			goto next_insn;
21403 		}
21404 
21405 		/* Skip inlining the helper call if the JIT does it. */
21406 		if (bpf_jit_inlines_helper_call(insn->imm))
21407 			goto next_insn;
21408 
21409 		if (insn->imm == BPF_FUNC_get_route_realm)
21410 			prog->dst_needed = 1;
21411 		if (insn->imm == BPF_FUNC_get_prandom_u32)
21412 			bpf_user_rnd_init_once();
21413 		if (insn->imm == BPF_FUNC_override_return)
21414 			prog->kprobe_override = 1;
21415 		if (insn->imm == BPF_FUNC_tail_call) {
21416 			/* If we tail call into other programs, we
21417 			 * cannot make any assumptions since they can
21418 			 * be replaced dynamically during runtime in
21419 			 * the program array.
21420 			 */
21421 			prog->cb_access = 1;
21422 			if (!allow_tail_call_in_subprogs(env))
21423 				prog->aux->stack_depth = MAX_BPF_STACK;
21424 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
21425 
21426 			/* mark bpf_tail_call as different opcode to avoid
21427 			 * conditional branch in the interpreter for every normal
21428 			 * call and to prevent accidental JITing by JIT compiler
21429 			 * that doesn't support bpf_tail_call yet
21430 			 */
21431 			insn->imm = 0;
21432 			insn->code = BPF_JMP | BPF_TAIL_CALL;
21433 
21434 			aux = &env->insn_aux_data[i + delta];
21435 			if (env->bpf_capable && !prog->blinding_requested &&
21436 			    prog->jit_requested &&
21437 			    !bpf_map_key_poisoned(aux) &&
21438 			    !bpf_map_ptr_poisoned(aux) &&
21439 			    !bpf_map_ptr_unpriv(aux)) {
21440 				struct bpf_jit_poke_descriptor desc = {
21441 					.reason = BPF_POKE_REASON_TAIL_CALL,
21442 					.tail_call.map = aux->map_ptr_state.map_ptr,
21443 					.tail_call.key = bpf_map_key_immediate(aux),
21444 					.insn_idx = i + delta,
21445 				};
21446 
21447 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
21448 				if (ret < 0) {
21449 					verbose(env, "adding tail call poke descriptor failed\n");
21450 					return ret;
21451 				}
21452 
21453 				insn->imm = ret + 1;
21454 				goto next_insn;
21455 			}
21456 
21457 			if (!bpf_map_ptr_unpriv(aux))
21458 				goto next_insn;
21459 
21460 			/* instead of changing every JIT dealing with tail_call
21461 			 * emit two extra insns:
21462 			 * if (index >= max_entries) goto out;
21463 			 * index &= array->index_mask;
21464 			 * to avoid out-of-bounds cpu speculation
21465 			 */
21466 			if (bpf_map_ptr_poisoned(aux)) {
21467 				verbose(env, "tail_call abusing map_ptr\n");
21468 				return -EINVAL;
21469 			}
21470 
21471 			map_ptr = aux->map_ptr_state.map_ptr;
21472 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
21473 						  map_ptr->max_entries, 2);
21474 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
21475 						    container_of(map_ptr,
21476 								 struct bpf_array,
21477 								 map)->index_mask);
21478 			insn_buf[2] = *insn;
21479 			cnt = 3;
21480 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21481 			if (!new_prog)
21482 				return -ENOMEM;
21483 
21484 			delta    += cnt - 1;
21485 			env->prog = prog = new_prog;
21486 			insn      = new_prog->insnsi + i + delta;
21487 			goto next_insn;
21488 		}
21489 
21490 		if (insn->imm == BPF_FUNC_timer_set_callback) {
21491 			/* The verifier will process callback_fn as many times as necessary
21492 			 * with different maps and the register states prepared by
21493 			 * set_timer_callback_state will be accurate.
21494 			 *
21495 			 * The following use case is valid:
21496 			 *   map1 is shared by prog1, prog2, prog3.
21497 			 *   prog1 calls bpf_timer_init for some map1 elements
21498 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
21499 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
21500 			 *   prog3 calls bpf_timer_start for some map1 elements.
21501 			 *     Those that were not both bpf_timer_init-ed and
21502 			 *     bpf_timer_set_callback-ed will return -EINVAL.
21503 			 */
21504 			struct bpf_insn ld_addrs[2] = {
21505 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
21506 			};
21507 
21508 			insn_buf[0] = ld_addrs[0];
21509 			insn_buf[1] = ld_addrs[1];
21510 			insn_buf[2] = *insn;
21511 			cnt = 3;
21512 
21513 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21514 			if (!new_prog)
21515 				return -ENOMEM;
21516 
21517 			delta    += cnt - 1;
21518 			env->prog = prog = new_prog;
21519 			insn      = new_prog->insnsi + i + delta;
21520 			goto patch_call_imm;
21521 		}
21522 
21523 		if (is_storage_get_function(insn->imm)) {
21524 			if (!in_sleepable(env) ||
21525 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
21526 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
21527 			else
21528 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
21529 			insn_buf[1] = *insn;
21530 			cnt = 2;
21531 
21532 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21533 			if (!new_prog)
21534 				return -ENOMEM;
21535 
21536 			delta += cnt - 1;
21537 			env->prog = prog = new_prog;
21538 			insn = new_prog->insnsi + i + delta;
21539 			goto patch_call_imm;
21540 		}
21541 
21542 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
21543 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
21544 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
21545 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
21546 			 */
21547 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
21548 			insn_buf[1] = *insn;
21549 			cnt = 2;
21550 
21551 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21552 			if (!new_prog)
21553 				return -ENOMEM;
21554 
21555 			delta += cnt - 1;
21556 			env->prog = prog = new_prog;
21557 			insn = new_prog->insnsi + i + delta;
21558 			goto patch_call_imm;
21559 		}
21560 
21561 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
21562 		 * and other inlining handlers are currently limited to 64 bit
21563 		 * only.
21564 		 */
21565 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21566 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
21567 		     insn->imm == BPF_FUNC_map_update_elem ||
21568 		     insn->imm == BPF_FUNC_map_delete_elem ||
21569 		     insn->imm == BPF_FUNC_map_push_elem   ||
21570 		     insn->imm == BPF_FUNC_map_pop_elem    ||
21571 		     insn->imm == BPF_FUNC_map_peek_elem   ||
21572 		     insn->imm == BPF_FUNC_redirect_map    ||
21573 		     insn->imm == BPF_FUNC_for_each_map_elem ||
21574 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
21575 			aux = &env->insn_aux_data[i + delta];
21576 			if (bpf_map_ptr_poisoned(aux))
21577 				goto patch_call_imm;
21578 
21579 			map_ptr = aux->map_ptr_state.map_ptr;
21580 			ops = map_ptr->ops;
21581 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
21582 			    ops->map_gen_lookup) {
21583 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
21584 				if (cnt == -EOPNOTSUPP)
21585 					goto patch_map_ops_generic;
21586 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
21587 					verbose(env, "bpf verifier is misconfigured\n");
21588 					return -EINVAL;
21589 				}
21590 
21591 				new_prog = bpf_patch_insn_data(env, i + delta,
21592 							       insn_buf, cnt);
21593 				if (!new_prog)
21594 					return -ENOMEM;
21595 
21596 				delta    += cnt - 1;
21597 				env->prog = prog = new_prog;
21598 				insn      = new_prog->insnsi + i + delta;
21599 				goto next_insn;
21600 			}
21601 
21602 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
21603 				     (void *(*)(struct bpf_map *map, void *key))NULL));
21604 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
21605 				     (long (*)(struct bpf_map *map, void *key))NULL));
21606 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
21607 				     (long (*)(struct bpf_map *map, void *key, void *value,
21608 					      u64 flags))NULL));
21609 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
21610 				     (long (*)(struct bpf_map *map, void *value,
21611 					      u64 flags))NULL));
21612 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
21613 				     (long (*)(struct bpf_map *map, void *value))NULL));
21614 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
21615 				     (long (*)(struct bpf_map *map, void *value))NULL));
21616 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
21617 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
21618 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
21619 				     (long (*)(struct bpf_map *map,
21620 					      bpf_callback_t callback_fn,
21621 					      void *callback_ctx,
21622 					      u64 flags))NULL));
21623 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
21624 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
21625 
21626 patch_map_ops_generic:
21627 			switch (insn->imm) {
21628 			case BPF_FUNC_map_lookup_elem:
21629 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
21630 				goto next_insn;
21631 			case BPF_FUNC_map_update_elem:
21632 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
21633 				goto next_insn;
21634 			case BPF_FUNC_map_delete_elem:
21635 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
21636 				goto next_insn;
21637 			case BPF_FUNC_map_push_elem:
21638 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
21639 				goto next_insn;
21640 			case BPF_FUNC_map_pop_elem:
21641 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
21642 				goto next_insn;
21643 			case BPF_FUNC_map_peek_elem:
21644 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
21645 				goto next_insn;
21646 			case BPF_FUNC_redirect_map:
21647 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
21648 				goto next_insn;
21649 			case BPF_FUNC_for_each_map_elem:
21650 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
21651 				goto next_insn;
21652 			case BPF_FUNC_map_lookup_percpu_elem:
21653 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
21654 				goto next_insn;
21655 			}
21656 
21657 			goto patch_call_imm;
21658 		}
21659 
21660 		/* Implement bpf_jiffies64 inline. */
21661 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21662 		    insn->imm == BPF_FUNC_jiffies64) {
21663 			struct bpf_insn ld_jiffies_addr[2] = {
21664 				BPF_LD_IMM64(BPF_REG_0,
21665 					     (unsigned long)&jiffies),
21666 			};
21667 
21668 			insn_buf[0] = ld_jiffies_addr[0];
21669 			insn_buf[1] = ld_jiffies_addr[1];
21670 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
21671 						  BPF_REG_0, 0);
21672 			cnt = 3;
21673 
21674 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
21675 						       cnt);
21676 			if (!new_prog)
21677 				return -ENOMEM;
21678 
21679 			delta    += cnt - 1;
21680 			env->prog = prog = new_prog;
21681 			insn      = new_prog->insnsi + i + delta;
21682 			goto next_insn;
21683 		}
21684 
21685 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
21686 		/* Implement bpf_get_smp_processor_id() inline. */
21687 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
21688 		    verifier_inlines_helper_call(env, insn->imm)) {
21689 			/* BPF_FUNC_get_smp_processor_id inlining is an
21690 			 * optimization, so if pcpu_hot.cpu_number is ever
21691 			 * changed in some incompatible and hard to support
21692 			 * way, it's fine to back out this inlining logic
21693 			 */
21694 #ifdef CONFIG_SMP
21695 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
21696 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
21697 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
21698 			cnt = 3;
21699 #else
21700 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
21701 			cnt = 1;
21702 #endif
21703 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21704 			if (!new_prog)
21705 				return -ENOMEM;
21706 
21707 			delta    += cnt - 1;
21708 			env->prog = prog = new_prog;
21709 			insn      = new_prog->insnsi + i + delta;
21710 			goto next_insn;
21711 		}
21712 #endif
21713 		/* Implement bpf_get_func_arg inline. */
21714 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21715 		    insn->imm == BPF_FUNC_get_func_arg) {
21716 			/* Load nr_args from ctx - 8 */
21717 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21718 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
21719 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
21720 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
21721 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
21722 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21723 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
21724 			insn_buf[7] = BPF_JMP_A(1);
21725 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21726 			cnt = 9;
21727 
21728 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21729 			if (!new_prog)
21730 				return -ENOMEM;
21731 
21732 			delta    += cnt - 1;
21733 			env->prog = prog = new_prog;
21734 			insn      = new_prog->insnsi + i + delta;
21735 			goto next_insn;
21736 		}
21737 
21738 		/* Implement bpf_get_func_ret inline. */
21739 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21740 		    insn->imm == BPF_FUNC_get_func_ret) {
21741 			if (eatype == BPF_TRACE_FEXIT ||
21742 			    eatype == BPF_MODIFY_RETURN) {
21743 				/* Load nr_args from ctx - 8 */
21744 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21745 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
21746 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
21747 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21748 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
21749 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
21750 				cnt = 6;
21751 			} else {
21752 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
21753 				cnt = 1;
21754 			}
21755 
21756 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21757 			if (!new_prog)
21758 				return -ENOMEM;
21759 
21760 			delta    += cnt - 1;
21761 			env->prog = prog = new_prog;
21762 			insn      = new_prog->insnsi + i + delta;
21763 			goto next_insn;
21764 		}
21765 
21766 		/* Implement get_func_arg_cnt inline. */
21767 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21768 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
21769 			/* Load nr_args from ctx - 8 */
21770 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21771 
21772 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21773 			if (!new_prog)
21774 				return -ENOMEM;
21775 
21776 			env->prog = prog = new_prog;
21777 			insn      = new_prog->insnsi + i + delta;
21778 			goto next_insn;
21779 		}
21780 
21781 		/* Implement bpf_get_func_ip inline. */
21782 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21783 		    insn->imm == BPF_FUNC_get_func_ip) {
21784 			/* Load IP address from ctx - 16 */
21785 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
21786 
21787 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21788 			if (!new_prog)
21789 				return -ENOMEM;
21790 
21791 			env->prog = prog = new_prog;
21792 			insn      = new_prog->insnsi + i + delta;
21793 			goto next_insn;
21794 		}
21795 
21796 		/* Implement bpf_get_branch_snapshot inline. */
21797 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
21798 		    prog->jit_requested && BITS_PER_LONG == 64 &&
21799 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
21800 			/* We are dealing with the following func protos:
21801 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
21802 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
21803 			 */
21804 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
21805 
21806 			/* struct perf_branch_entry is part of UAPI and is
21807 			 * used as an array element, so extremely unlikely to
21808 			 * ever grow or shrink
21809 			 */
21810 			BUILD_BUG_ON(br_entry_size != 24);
21811 
21812 			/* if (unlikely(flags)) return -EINVAL */
21813 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
21814 
21815 			/* Transform size (bytes) into number of entries (cnt = size / 24).
21816 			 * But to avoid expensive division instruction, we implement
21817 			 * divide-by-3 through multiplication, followed by further
21818 			 * division by 8 through 3-bit right shift.
21819 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
21820 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
21821 			 *
21822 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
21823 			 */
21824 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
21825 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
21826 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
21827 
21828 			/* call perf_snapshot_branch_stack implementation */
21829 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
21830 			/* if (entry_cnt == 0) return -ENOENT */
21831 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
21832 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
21833 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
21834 			insn_buf[7] = BPF_JMP_A(3);
21835 			/* return -EINVAL; */
21836 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21837 			insn_buf[9] = BPF_JMP_A(1);
21838 			/* return -ENOENT; */
21839 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
21840 			cnt = 11;
21841 
21842 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21843 			if (!new_prog)
21844 				return -ENOMEM;
21845 
21846 			delta    += cnt - 1;
21847 			env->prog = prog = new_prog;
21848 			insn      = new_prog->insnsi + i + delta;
21849 			goto next_insn;
21850 		}
21851 
21852 		/* Implement bpf_kptr_xchg inline */
21853 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21854 		    insn->imm == BPF_FUNC_kptr_xchg &&
21855 		    bpf_jit_supports_ptr_xchg()) {
21856 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
21857 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
21858 			cnt = 2;
21859 
21860 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21861 			if (!new_prog)
21862 				return -ENOMEM;
21863 
21864 			delta    += cnt - 1;
21865 			env->prog = prog = new_prog;
21866 			insn      = new_prog->insnsi + i + delta;
21867 			goto next_insn;
21868 		}
21869 patch_call_imm:
21870 		fn = env->ops->get_func_proto(insn->imm, env->prog);
21871 		/* all functions that have prototype and verifier allowed
21872 		 * programs to call them, must be real in-kernel functions
21873 		 */
21874 		if (!fn->func) {
21875 			verbose(env,
21876 				"kernel subsystem misconfigured func %s#%d\n",
21877 				func_id_name(insn->imm), insn->imm);
21878 			return -EFAULT;
21879 		}
21880 		insn->imm = fn->func - __bpf_call_base;
21881 next_insn:
21882 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21883 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21884 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
21885 			cur_subprog++;
21886 			stack_depth = subprogs[cur_subprog].stack_depth;
21887 			stack_depth_extra = 0;
21888 		}
21889 		i++;
21890 		insn++;
21891 	}
21892 
21893 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
21894 	for (i = 0; i < env->subprog_cnt; i++) {
21895 		int subprog_start = subprogs[i].start;
21896 		int stack_slots = subprogs[i].stack_extra / 8;
21897 
21898 		if (!stack_slots)
21899 			continue;
21900 		if (stack_slots > 1) {
21901 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
21902 			return -EFAULT;
21903 		}
21904 
21905 		/* Add ST insn to subprog prologue to init extra stack */
21906 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
21907 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
21908 		/* Copy first actual insn to preserve it */
21909 		insn_buf[1] = env->prog->insnsi[subprog_start];
21910 
21911 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
21912 		if (!new_prog)
21913 			return -ENOMEM;
21914 		env->prog = prog = new_prog;
21915 		/*
21916 		 * If may_goto is a first insn of a prog there could be a jmp
21917 		 * insn that points to it, hence adjust all such jmps to point
21918 		 * to insn after BPF_ST that inits may_goto count.
21919 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
21920 		 */
21921 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
21922 	}
21923 
21924 	/* Since poke tab is now finalized, publish aux to tracker. */
21925 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21926 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21927 		if (!map_ptr->ops->map_poke_track ||
21928 		    !map_ptr->ops->map_poke_untrack ||
21929 		    !map_ptr->ops->map_poke_run) {
21930 			verbose(env, "bpf verifier is misconfigured\n");
21931 			return -EINVAL;
21932 		}
21933 
21934 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
21935 		if (ret < 0) {
21936 			verbose(env, "tracking tail call prog failed\n");
21937 			return ret;
21938 		}
21939 	}
21940 
21941 	sort_kfunc_descs_by_imm_off(env->prog);
21942 
21943 	return 0;
21944 }
21945 
21946 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
21947 					int position,
21948 					s32 stack_base,
21949 					u32 callback_subprogno,
21950 					u32 *total_cnt)
21951 {
21952 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
21953 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
21954 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
21955 	int reg_loop_max = BPF_REG_6;
21956 	int reg_loop_cnt = BPF_REG_7;
21957 	int reg_loop_ctx = BPF_REG_8;
21958 
21959 	struct bpf_insn *insn_buf = env->insn_buf;
21960 	struct bpf_prog *new_prog;
21961 	u32 callback_start;
21962 	u32 call_insn_offset;
21963 	s32 callback_offset;
21964 	u32 cnt = 0;
21965 
21966 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
21967 	 * be careful to modify this code in sync.
21968 	 */
21969 
21970 	/* Return error and jump to the end of the patch if
21971 	 * expected number of iterations is too big.
21972 	 */
21973 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
21974 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
21975 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
21976 	/* spill R6, R7, R8 to use these as loop vars */
21977 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
21978 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
21979 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
21980 	/* initialize loop vars */
21981 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
21982 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
21983 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
21984 	/* loop header,
21985 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
21986 	 */
21987 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
21988 	/* callback call,
21989 	 * correct callback offset would be set after patching
21990 	 */
21991 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
21992 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
21993 	insn_buf[cnt++] = BPF_CALL_REL(0);
21994 	/* increment loop counter */
21995 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
21996 	/* jump to loop header if callback returned 0 */
21997 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
21998 	/* return value of bpf_loop,
21999 	 * set R0 to the number of iterations
22000 	 */
22001 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22002 	/* restore original values of R6, R7, R8 */
22003 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22004 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22005 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22006 
22007 	*total_cnt = cnt;
22008 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22009 	if (!new_prog)
22010 		return new_prog;
22011 
22012 	/* callback start is known only after patching */
22013 	callback_start = env->subprog_info[callback_subprogno].start;
22014 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22015 	call_insn_offset = position + 12;
22016 	callback_offset = callback_start - call_insn_offset - 1;
22017 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22018 
22019 	return new_prog;
22020 }
22021 
22022 static bool is_bpf_loop_call(struct bpf_insn *insn)
22023 {
22024 	return insn->code == (BPF_JMP | BPF_CALL) &&
22025 		insn->src_reg == 0 &&
22026 		insn->imm == BPF_FUNC_loop;
22027 }
22028 
22029 /* For all sub-programs in the program (including main) check
22030  * insn_aux_data to see if there are bpf_loop calls that require
22031  * inlining. If such calls are found the calls are replaced with a
22032  * sequence of instructions produced by `inline_bpf_loop` function and
22033  * subprog stack_depth is increased by the size of 3 registers.
22034  * This stack space is used to spill values of the R6, R7, R8.  These
22035  * registers are used to store the loop bound, counter and context
22036  * variables.
22037  */
22038 static int optimize_bpf_loop(struct bpf_verifier_env *env)
22039 {
22040 	struct bpf_subprog_info *subprogs = env->subprog_info;
22041 	int i, cur_subprog = 0, cnt, delta = 0;
22042 	struct bpf_insn *insn = env->prog->insnsi;
22043 	int insn_cnt = env->prog->len;
22044 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22045 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
22046 	u16 stack_depth_extra = 0;
22047 
22048 	for (i = 0; i < insn_cnt; i++, insn++) {
22049 		struct bpf_loop_inline_state *inline_state =
22050 			&env->insn_aux_data[i + delta].loop_inline_state;
22051 
22052 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
22053 			struct bpf_prog *new_prog;
22054 
22055 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
22056 			new_prog = inline_bpf_loop(env,
22057 						   i + delta,
22058 						   -(stack_depth + stack_depth_extra),
22059 						   inline_state->callback_subprogno,
22060 						   &cnt);
22061 			if (!new_prog)
22062 				return -ENOMEM;
22063 
22064 			delta     += cnt - 1;
22065 			env->prog  = new_prog;
22066 			insn       = new_prog->insnsi + i + delta;
22067 		}
22068 
22069 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22070 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22071 			cur_subprog++;
22072 			stack_depth = subprogs[cur_subprog].stack_depth;
22073 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
22074 			stack_depth_extra = 0;
22075 		}
22076 	}
22077 
22078 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22079 
22080 	return 0;
22081 }
22082 
22083 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
22084  * adjust subprograms stack depth when possible.
22085  */
22086 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
22087 {
22088 	struct bpf_subprog_info *subprog = env->subprog_info;
22089 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
22090 	struct bpf_insn *insn = env->prog->insnsi;
22091 	int insn_cnt = env->prog->len;
22092 	u32 spills_num;
22093 	bool modified = false;
22094 	int i, j;
22095 
22096 	for (i = 0; i < insn_cnt; i++, insn++) {
22097 		if (aux[i].fastcall_spills_num > 0) {
22098 			spills_num = aux[i].fastcall_spills_num;
22099 			/* NOPs would be removed by opt_remove_nops() */
22100 			for (j = 1; j <= spills_num; ++j) {
22101 				*(insn - j) = NOP;
22102 				*(insn + j) = NOP;
22103 			}
22104 			modified = true;
22105 		}
22106 		if ((subprog + 1)->start == i + 1) {
22107 			if (modified && !subprog->keep_fastcall_stack)
22108 				subprog->stack_depth = -subprog->fastcall_stack_off;
22109 			subprog++;
22110 			modified = false;
22111 		}
22112 	}
22113 
22114 	return 0;
22115 }
22116 
22117 static void free_states(struct bpf_verifier_env *env)
22118 {
22119 	struct bpf_verifier_state_list *sl, *sln;
22120 	int i;
22121 
22122 	sl = env->free_list;
22123 	while (sl) {
22124 		sln = sl->next;
22125 		free_verifier_state(&sl->state, false);
22126 		kfree(sl);
22127 		sl = sln;
22128 	}
22129 	env->free_list = NULL;
22130 
22131 	if (!env->explored_states)
22132 		return;
22133 
22134 	for (i = 0; i < state_htab_size(env); i++) {
22135 		sl = env->explored_states[i];
22136 
22137 		while (sl) {
22138 			sln = sl->next;
22139 			free_verifier_state(&sl->state, false);
22140 			kfree(sl);
22141 			sl = sln;
22142 		}
22143 		env->explored_states[i] = NULL;
22144 	}
22145 }
22146 
22147 static int do_check_common(struct bpf_verifier_env *env, int subprog)
22148 {
22149 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
22150 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
22151 	struct bpf_verifier_state *state;
22152 	struct bpf_reg_state *regs;
22153 	int ret, i;
22154 
22155 	env->prev_linfo = NULL;
22156 	env->pass_cnt++;
22157 
22158 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
22159 	if (!state)
22160 		return -ENOMEM;
22161 	state->curframe = 0;
22162 	state->speculative = false;
22163 	state->branches = 1;
22164 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
22165 	if (!state->frame[0]) {
22166 		kfree(state);
22167 		return -ENOMEM;
22168 	}
22169 	env->cur_state = state;
22170 	init_func_state(env, state->frame[0],
22171 			BPF_MAIN_FUNC /* callsite */,
22172 			0 /* frameno */,
22173 			subprog);
22174 	state->first_insn_idx = env->subprog_info[subprog].start;
22175 	state->last_insn_idx = -1;
22176 
22177 	regs = state->frame[state->curframe]->regs;
22178 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
22179 		const char *sub_name = subprog_name(env, subprog);
22180 		struct bpf_subprog_arg_info *arg;
22181 		struct bpf_reg_state *reg;
22182 
22183 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
22184 		ret = btf_prepare_func_args(env, subprog);
22185 		if (ret)
22186 			goto out;
22187 
22188 		if (subprog_is_exc_cb(env, subprog)) {
22189 			state->frame[0]->in_exception_callback_fn = true;
22190 			/* We have already ensured that the callback returns an integer, just
22191 			 * like all global subprogs. We need to determine it only has a single
22192 			 * scalar argument.
22193 			 */
22194 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
22195 				verbose(env, "exception cb only supports single integer argument\n");
22196 				ret = -EINVAL;
22197 				goto out;
22198 			}
22199 		}
22200 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
22201 			arg = &sub->args[i - BPF_REG_1];
22202 			reg = &regs[i];
22203 
22204 			if (arg->arg_type == ARG_PTR_TO_CTX) {
22205 				reg->type = PTR_TO_CTX;
22206 				mark_reg_known_zero(env, regs, i);
22207 			} else if (arg->arg_type == ARG_ANYTHING) {
22208 				reg->type = SCALAR_VALUE;
22209 				mark_reg_unknown(env, regs, i);
22210 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
22211 				/* assume unspecial LOCAL dynptr type */
22212 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
22213 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
22214 				reg->type = PTR_TO_MEM;
22215 				if (arg->arg_type & PTR_MAYBE_NULL)
22216 					reg->type |= PTR_MAYBE_NULL;
22217 				mark_reg_known_zero(env, regs, i);
22218 				reg->mem_size = arg->mem_size;
22219 				reg->id = ++env->id_gen;
22220 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
22221 				reg->type = PTR_TO_BTF_ID;
22222 				if (arg->arg_type & PTR_MAYBE_NULL)
22223 					reg->type |= PTR_MAYBE_NULL;
22224 				if (arg->arg_type & PTR_UNTRUSTED)
22225 					reg->type |= PTR_UNTRUSTED;
22226 				if (arg->arg_type & PTR_TRUSTED)
22227 					reg->type |= PTR_TRUSTED;
22228 				mark_reg_known_zero(env, regs, i);
22229 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
22230 				reg->btf_id = arg->btf_id;
22231 				reg->id = ++env->id_gen;
22232 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
22233 				/* caller can pass either PTR_TO_ARENA or SCALAR */
22234 				mark_reg_unknown(env, regs, i);
22235 			} else {
22236 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
22237 					  i - BPF_REG_1, arg->arg_type);
22238 				ret = -EFAULT;
22239 				goto out;
22240 			}
22241 		}
22242 	} else {
22243 		/* if main BPF program has associated BTF info, validate that
22244 		 * it's matching expected signature, and otherwise mark BTF
22245 		 * info for main program as unreliable
22246 		 */
22247 		if (env->prog->aux->func_info_aux) {
22248 			ret = btf_prepare_func_args(env, 0);
22249 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
22250 				env->prog->aux->func_info_aux[0].unreliable = true;
22251 		}
22252 
22253 		/* 1st arg to a function */
22254 		regs[BPF_REG_1].type = PTR_TO_CTX;
22255 		mark_reg_known_zero(env, regs, BPF_REG_1);
22256 	}
22257 
22258 	ret = do_check(env);
22259 out:
22260 	/* check for NULL is necessary, since cur_state can be freed inside
22261 	 * do_check() under memory pressure.
22262 	 */
22263 	if (env->cur_state) {
22264 		free_verifier_state(env->cur_state, true);
22265 		env->cur_state = NULL;
22266 	}
22267 	while (!pop_stack(env, NULL, NULL, false));
22268 	if (!ret && pop_log)
22269 		bpf_vlog_reset(&env->log, 0);
22270 	free_states(env);
22271 	return ret;
22272 }
22273 
22274 /* Lazily verify all global functions based on their BTF, if they are called
22275  * from main BPF program or any of subprograms transitively.
22276  * BPF global subprogs called from dead code are not validated.
22277  * All callable global functions must pass verification.
22278  * Otherwise the whole program is rejected.
22279  * Consider:
22280  * int bar(int);
22281  * int foo(int f)
22282  * {
22283  *    return bar(f);
22284  * }
22285  * int bar(int b)
22286  * {
22287  *    ...
22288  * }
22289  * foo() will be verified first for R1=any_scalar_value. During verification it
22290  * will be assumed that bar() already verified successfully and call to bar()
22291  * from foo() will be checked for type match only. Later bar() will be verified
22292  * independently to check that it's safe for R1=any_scalar_value.
22293  */
22294 static int do_check_subprogs(struct bpf_verifier_env *env)
22295 {
22296 	struct bpf_prog_aux *aux = env->prog->aux;
22297 	struct bpf_func_info_aux *sub_aux;
22298 	int i, ret, new_cnt;
22299 
22300 	if (!aux->func_info)
22301 		return 0;
22302 
22303 	/* exception callback is presumed to be always called */
22304 	if (env->exception_callback_subprog)
22305 		subprog_aux(env, env->exception_callback_subprog)->called = true;
22306 
22307 again:
22308 	new_cnt = 0;
22309 	for (i = 1; i < env->subprog_cnt; i++) {
22310 		if (!subprog_is_global(env, i))
22311 			continue;
22312 
22313 		sub_aux = subprog_aux(env, i);
22314 		if (!sub_aux->called || sub_aux->verified)
22315 			continue;
22316 
22317 		env->insn_idx = env->subprog_info[i].start;
22318 		WARN_ON_ONCE(env->insn_idx == 0);
22319 		ret = do_check_common(env, i);
22320 		if (ret) {
22321 			return ret;
22322 		} else if (env->log.level & BPF_LOG_LEVEL) {
22323 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
22324 				i, subprog_name(env, i));
22325 		}
22326 
22327 		/* We verified new global subprog, it might have called some
22328 		 * more global subprogs that we haven't verified yet, so we
22329 		 * need to do another pass over subprogs to verify those.
22330 		 */
22331 		sub_aux->verified = true;
22332 		new_cnt++;
22333 	}
22334 
22335 	/* We can't loop forever as we verify at least one global subprog on
22336 	 * each pass.
22337 	 */
22338 	if (new_cnt)
22339 		goto again;
22340 
22341 	return 0;
22342 }
22343 
22344 static int do_check_main(struct bpf_verifier_env *env)
22345 {
22346 	int ret;
22347 
22348 	env->insn_idx = 0;
22349 	ret = do_check_common(env, 0);
22350 	if (!ret)
22351 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22352 	return ret;
22353 }
22354 
22355 
22356 static void print_verification_stats(struct bpf_verifier_env *env)
22357 {
22358 	int i;
22359 
22360 	if (env->log.level & BPF_LOG_STATS) {
22361 		verbose(env, "verification time %lld usec\n",
22362 			div_u64(env->verification_time, 1000));
22363 		verbose(env, "stack depth ");
22364 		for (i = 0; i < env->subprog_cnt; i++) {
22365 			u32 depth = env->subprog_info[i].stack_depth;
22366 
22367 			verbose(env, "%d", depth);
22368 			if (i + 1 < env->subprog_cnt)
22369 				verbose(env, "+");
22370 		}
22371 		verbose(env, "\n");
22372 	}
22373 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
22374 		"total_states %d peak_states %d mark_read %d\n",
22375 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
22376 		env->max_states_per_insn, env->total_states,
22377 		env->peak_states, env->longest_mark_read_walk);
22378 }
22379 
22380 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
22381 {
22382 	const struct btf_type *t, *func_proto;
22383 	const struct bpf_struct_ops_desc *st_ops_desc;
22384 	const struct bpf_struct_ops *st_ops;
22385 	const struct btf_member *member;
22386 	struct bpf_prog *prog = env->prog;
22387 	u32 btf_id, member_idx;
22388 	struct btf *btf;
22389 	const char *mname;
22390 	int err;
22391 
22392 	if (!prog->gpl_compatible) {
22393 		verbose(env, "struct ops programs must have a GPL compatible license\n");
22394 		return -EINVAL;
22395 	}
22396 
22397 	if (!prog->aux->attach_btf_id)
22398 		return -ENOTSUPP;
22399 
22400 	btf = prog->aux->attach_btf;
22401 	if (btf_is_module(btf)) {
22402 		/* Make sure st_ops is valid through the lifetime of env */
22403 		env->attach_btf_mod = btf_try_get_module(btf);
22404 		if (!env->attach_btf_mod) {
22405 			verbose(env, "struct_ops module %s is not found\n",
22406 				btf_get_name(btf));
22407 			return -ENOTSUPP;
22408 		}
22409 	}
22410 
22411 	btf_id = prog->aux->attach_btf_id;
22412 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22413 	if (!st_ops_desc) {
22414 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22415 			btf_id);
22416 		return -ENOTSUPP;
22417 	}
22418 	st_ops = st_ops_desc->st_ops;
22419 
22420 	t = st_ops_desc->type;
22421 	member_idx = prog->expected_attach_type;
22422 	if (member_idx >= btf_type_vlen(t)) {
22423 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22424 			member_idx, st_ops->name);
22425 		return -EINVAL;
22426 	}
22427 
22428 	member = &btf_type_member(t)[member_idx];
22429 	mname = btf_name_by_offset(btf, member->name_off);
22430 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22431 					       NULL);
22432 	if (!func_proto) {
22433 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22434 			mname, member_idx, st_ops->name);
22435 		return -EINVAL;
22436 	}
22437 
22438 	err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
22439 	if (err) {
22440 		verbose(env, "attach to unsupported member %s of struct %s\n",
22441 			mname, st_ops->name);
22442 		return err;
22443 	}
22444 
22445 	if (st_ops->check_member) {
22446 		err = st_ops->check_member(t, member, prog);
22447 
22448 		if (err) {
22449 			verbose(env, "attach to unsupported member %s of struct %s\n",
22450 				mname, st_ops->name);
22451 			return err;
22452 		}
22453 	}
22454 
22455 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
22456 		verbose(env, "Private stack not supported by jit\n");
22457 		return -EACCES;
22458 	}
22459 
22460 	/* btf_ctx_access() used this to provide argument type info */
22461 	prog->aux->ctx_arg_info =
22462 		st_ops_desc->arg_info[member_idx].info;
22463 	prog->aux->ctx_arg_info_size =
22464 		st_ops_desc->arg_info[member_idx].cnt;
22465 
22466 	prog->aux->attach_func_proto = func_proto;
22467 	prog->aux->attach_func_name = mname;
22468 	env->ops = st_ops->verifier_ops;
22469 
22470 	return 0;
22471 }
22472 #define SECURITY_PREFIX "security_"
22473 
22474 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22475 {
22476 	if (within_error_injection_list(addr) ||
22477 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22478 		return 0;
22479 
22480 	return -EINVAL;
22481 }
22482 
22483 /* list of non-sleepable functions that are otherwise on
22484  * ALLOW_ERROR_INJECTION list
22485  */
22486 BTF_SET_START(btf_non_sleepable_error_inject)
22487 /* Three functions below can be called from sleepable and non-sleepable context.
22488  * Assume non-sleepable from bpf safety point of view.
22489  */
22490 BTF_ID(func, __filemap_add_folio)
22491 #ifdef CONFIG_FAIL_PAGE_ALLOC
22492 BTF_ID(func, should_fail_alloc_page)
22493 #endif
22494 #ifdef CONFIG_FAILSLAB
22495 BTF_ID(func, should_failslab)
22496 #endif
22497 BTF_SET_END(btf_non_sleepable_error_inject)
22498 
22499 static int check_non_sleepable_error_inject(u32 btf_id)
22500 {
22501 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
22502 }
22503 
22504 int bpf_check_attach_target(struct bpf_verifier_log *log,
22505 			    const struct bpf_prog *prog,
22506 			    const struct bpf_prog *tgt_prog,
22507 			    u32 btf_id,
22508 			    struct bpf_attach_target_info *tgt_info)
22509 {
22510 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22511 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22512 	char trace_symbol[KSYM_SYMBOL_LEN];
22513 	const char prefix[] = "btf_trace_";
22514 	struct bpf_raw_event_map *btp;
22515 	int ret = 0, subprog = -1, i;
22516 	const struct btf_type *t;
22517 	bool conservative = true;
22518 	const char *tname, *fname;
22519 	struct btf *btf;
22520 	long addr = 0;
22521 	struct module *mod = NULL;
22522 
22523 	if (!btf_id) {
22524 		bpf_log(log, "Tracing programs must provide btf_id\n");
22525 		return -EINVAL;
22526 	}
22527 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22528 	if (!btf) {
22529 		bpf_log(log,
22530 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
22531 		return -EINVAL;
22532 	}
22533 	t = btf_type_by_id(btf, btf_id);
22534 	if (!t) {
22535 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22536 		return -EINVAL;
22537 	}
22538 	tname = btf_name_by_offset(btf, t->name_off);
22539 	if (!tname) {
22540 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22541 		return -EINVAL;
22542 	}
22543 	if (tgt_prog) {
22544 		struct bpf_prog_aux *aux = tgt_prog->aux;
22545 		bool tgt_changes_pkt_data;
22546 
22547 		if (bpf_prog_is_dev_bound(prog->aux) &&
22548 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22549 			bpf_log(log, "Target program bound device mismatch");
22550 			return -EINVAL;
22551 		}
22552 
22553 		for (i = 0; i < aux->func_info_cnt; i++)
22554 			if (aux->func_info[i].type_id == btf_id) {
22555 				subprog = i;
22556 				break;
22557 			}
22558 		if (subprog == -1) {
22559 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22560 			return -EINVAL;
22561 		}
22562 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22563 			bpf_log(log,
22564 				"%s programs cannot attach to exception callback\n",
22565 				prog_extension ? "Extension" : "FENTRY/FEXIT");
22566 			return -EINVAL;
22567 		}
22568 		conservative = aux->func_info_aux[subprog].unreliable;
22569 		if (prog_extension) {
22570 			if (conservative) {
22571 				bpf_log(log,
22572 					"Cannot replace static functions\n");
22573 				return -EINVAL;
22574 			}
22575 			if (!prog->jit_requested) {
22576 				bpf_log(log,
22577 					"Extension programs should be JITed\n");
22578 				return -EINVAL;
22579 			}
22580 			tgt_changes_pkt_data = aux->func
22581 					       ? aux->func[subprog]->aux->changes_pkt_data
22582 					       : aux->changes_pkt_data;
22583 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
22584 				bpf_log(log,
22585 					"Extension program changes packet data, while original does not\n");
22586 				return -EINVAL;
22587 			}
22588 		}
22589 		if (!tgt_prog->jited) {
22590 			bpf_log(log, "Can attach to only JITed progs\n");
22591 			return -EINVAL;
22592 		}
22593 		if (prog_tracing) {
22594 			if (aux->attach_tracing_prog) {
22595 				/*
22596 				 * Target program is an fentry/fexit which is already attached
22597 				 * to another tracing program. More levels of nesting
22598 				 * attachment are not allowed.
22599 				 */
22600 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22601 				return -EINVAL;
22602 			}
22603 		} else if (tgt_prog->type == prog->type) {
22604 			/*
22605 			 * To avoid potential call chain cycles, prevent attaching of a
22606 			 * program extension to another extension. It's ok to attach
22607 			 * fentry/fexit to extension program.
22608 			 */
22609 			bpf_log(log, "Cannot recursively attach\n");
22610 			return -EINVAL;
22611 		}
22612 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
22613 		    prog_extension &&
22614 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
22615 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
22616 			/* Program extensions can extend all program types
22617 			 * except fentry/fexit. The reason is the following.
22618 			 * The fentry/fexit programs are used for performance
22619 			 * analysis, stats and can be attached to any program
22620 			 * type. When extension program is replacing XDP function
22621 			 * it is necessary to allow performance analysis of all
22622 			 * functions. Both original XDP program and its program
22623 			 * extension. Hence attaching fentry/fexit to
22624 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22625 			 * fentry/fexit was allowed it would be possible to create
22626 			 * long call chain fentry->extension->fentry->extension
22627 			 * beyond reasonable stack size. Hence extending fentry
22628 			 * is not allowed.
22629 			 */
22630 			bpf_log(log, "Cannot extend fentry/fexit\n");
22631 			return -EINVAL;
22632 		}
22633 	} else {
22634 		if (prog_extension) {
22635 			bpf_log(log, "Cannot replace kernel functions\n");
22636 			return -EINVAL;
22637 		}
22638 	}
22639 
22640 	switch (prog->expected_attach_type) {
22641 	case BPF_TRACE_RAW_TP:
22642 		if (tgt_prog) {
22643 			bpf_log(log,
22644 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
22645 			return -EINVAL;
22646 		}
22647 		if (!btf_type_is_typedef(t)) {
22648 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22649 				btf_id);
22650 			return -EINVAL;
22651 		}
22652 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22653 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22654 				btf_id, tname);
22655 			return -EINVAL;
22656 		}
22657 		tname += sizeof(prefix) - 1;
22658 
22659 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22660 		 * names. Thus using bpf_raw_event_map to get argument names.
22661 		 */
22662 		btp = bpf_get_raw_tracepoint(tname);
22663 		if (!btp)
22664 			return -EINVAL;
22665 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22666 					trace_symbol);
22667 		bpf_put_raw_tracepoint(btp);
22668 
22669 		if (fname)
22670 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22671 
22672 		if (!fname || ret < 0) {
22673 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22674 				prefix, tname);
22675 			t = btf_type_by_id(btf, t->type);
22676 			if (!btf_type_is_ptr(t))
22677 				/* should never happen in valid vmlinux build */
22678 				return -EINVAL;
22679 		} else {
22680 			t = btf_type_by_id(btf, ret);
22681 			if (!btf_type_is_func(t))
22682 				/* should never happen in valid vmlinux build */
22683 				return -EINVAL;
22684 		}
22685 
22686 		t = btf_type_by_id(btf, t->type);
22687 		if (!btf_type_is_func_proto(t))
22688 			/* should never happen in valid vmlinux build */
22689 			return -EINVAL;
22690 
22691 		break;
22692 	case BPF_TRACE_ITER:
22693 		if (!btf_type_is_func(t)) {
22694 			bpf_log(log, "attach_btf_id %u is not a function\n",
22695 				btf_id);
22696 			return -EINVAL;
22697 		}
22698 		t = btf_type_by_id(btf, t->type);
22699 		if (!btf_type_is_func_proto(t))
22700 			return -EINVAL;
22701 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22702 		if (ret)
22703 			return ret;
22704 		break;
22705 	default:
22706 		if (!prog_extension)
22707 			return -EINVAL;
22708 		fallthrough;
22709 	case BPF_MODIFY_RETURN:
22710 	case BPF_LSM_MAC:
22711 	case BPF_LSM_CGROUP:
22712 	case BPF_TRACE_FENTRY:
22713 	case BPF_TRACE_FEXIT:
22714 		if (!btf_type_is_func(t)) {
22715 			bpf_log(log, "attach_btf_id %u is not a function\n",
22716 				btf_id);
22717 			return -EINVAL;
22718 		}
22719 		if (prog_extension &&
22720 		    btf_check_type_match(log, prog, btf, t))
22721 			return -EINVAL;
22722 		t = btf_type_by_id(btf, t->type);
22723 		if (!btf_type_is_func_proto(t))
22724 			return -EINVAL;
22725 
22726 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22727 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22728 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22729 			return -EINVAL;
22730 
22731 		if (tgt_prog && conservative)
22732 			t = NULL;
22733 
22734 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22735 		if (ret < 0)
22736 			return ret;
22737 
22738 		if (tgt_prog) {
22739 			if (subprog == 0)
22740 				addr = (long) tgt_prog->bpf_func;
22741 			else
22742 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22743 		} else {
22744 			if (btf_is_module(btf)) {
22745 				mod = btf_try_get_module(btf);
22746 				if (mod)
22747 					addr = find_kallsyms_symbol_value(mod, tname);
22748 				else
22749 					addr = 0;
22750 			} else {
22751 				addr = kallsyms_lookup_name(tname);
22752 			}
22753 			if (!addr) {
22754 				module_put(mod);
22755 				bpf_log(log,
22756 					"The address of function %s cannot be found\n",
22757 					tname);
22758 				return -ENOENT;
22759 			}
22760 		}
22761 
22762 		if (prog->sleepable) {
22763 			ret = -EINVAL;
22764 			switch (prog->type) {
22765 			case BPF_PROG_TYPE_TRACING:
22766 
22767 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
22768 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22769 				 */
22770 				if (!check_non_sleepable_error_inject(btf_id) &&
22771 				    within_error_injection_list(addr))
22772 					ret = 0;
22773 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
22774 				 * in the fmodret id set with the KF_SLEEPABLE flag.
22775 				 */
22776 				else {
22777 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
22778 										prog);
22779 
22780 					if (flags && (*flags & KF_SLEEPABLE))
22781 						ret = 0;
22782 				}
22783 				break;
22784 			case BPF_PROG_TYPE_LSM:
22785 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
22786 				 * Only some of them are sleepable.
22787 				 */
22788 				if (bpf_lsm_is_sleepable_hook(btf_id))
22789 					ret = 0;
22790 				break;
22791 			default:
22792 				break;
22793 			}
22794 			if (ret) {
22795 				module_put(mod);
22796 				bpf_log(log, "%s is not sleepable\n", tname);
22797 				return ret;
22798 			}
22799 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22800 			if (tgt_prog) {
22801 				module_put(mod);
22802 				bpf_log(log, "can't modify return codes of BPF programs\n");
22803 				return -EINVAL;
22804 			}
22805 			ret = -EINVAL;
22806 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22807 			    !check_attach_modify_return(addr, tname))
22808 				ret = 0;
22809 			if (ret) {
22810 				module_put(mod);
22811 				bpf_log(log, "%s() is not modifiable\n", tname);
22812 				return ret;
22813 			}
22814 		}
22815 
22816 		break;
22817 	}
22818 	tgt_info->tgt_addr = addr;
22819 	tgt_info->tgt_name = tname;
22820 	tgt_info->tgt_type = t;
22821 	tgt_info->tgt_mod = mod;
22822 	return 0;
22823 }
22824 
22825 BTF_SET_START(btf_id_deny)
22826 BTF_ID_UNUSED
22827 #ifdef CONFIG_SMP
22828 BTF_ID(func, migrate_disable)
22829 BTF_ID(func, migrate_enable)
22830 #endif
22831 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22832 BTF_ID(func, rcu_read_unlock_strict)
22833 #endif
22834 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22835 BTF_ID(func, preempt_count_add)
22836 BTF_ID(func, preempt_count_sub)
22837 #endif
22838 #ifdef CONFIG_PREEMPT_RCU
22839 BTF_ID(func, __rcu_read_lock)
22840 BTF_ID(func, __rcu_read_unlock)
22841 #endif
22842 BTF_SET_END(btf_id_deny)
22843 
22844 static bool can_be_sleepable(struct bpf_prog *prog)
22845 {
22846 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22847 		switch (prog->expected_attach_type) {
22848 		case BPF_TRACE_FENTRY:
22849 		case BPF_TRACE_FEXIT:
22850 		case BPF_MODIFY_RETURN:
22851 		case BPF_TRACE_ITER:
22852 			return true;
22853 		default:
22854 			return false;
22855 		}
22856 	}
22857 	return prog->type == BPF_PROG_TYPE_LSM ||
22858 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22859 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
22860 }
22861 
22862 static int check_attach_btf_id(struct bpf_verifier_env *env)
22863 {
22864 	struct bpf_prog *prog = env->prog;
22865 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22866 	struct bpf_attach_target_info tgt_info = {};
22867 	u32 btf_id = prog->aux->attach_btf_id;
22868 	struct bpf_trampoline *tr;
22869 	int ret;
22870 	u64 key;
22871 
22872 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22873 		if (prog->sleepable)
22874 			/* attach_btf_id checked to be zero already */
22875 			return 0;
22876 		verbose(env, "Syscall programs can only be sleepable\n");
22877 		return -EINVAL;
22878 	}
22879 
22880 	if (prog->sleepable && !can_be_sleepable(prog)) {
22881 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
22882 		return -EINVAL;
22883 	}
22884 
22885 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22886 		return check_struct_ops_btf_id(env);
22887 
22888 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22889 	    prog->type != BPF_PROG_TYPE_LSM &&
22890 	    prog->type != BPF_PROG_TYPE_EXT)
22891 		return 0;
22892 
22893 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22894 	if (ret)
22895 		return ret;
22896 
22897 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22898 		/* to make freplace equivalent to their targets, they need to
22899 		 * inherit env->ops and expected_attach_type for the rest of the
22900 		 * verification
22901 		 */
22902 		env->ops = bpf_verifier_ops[tgt_prog->type];
22903 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22904 	}
22905 
22906 	/* store info about the attachment target that will be used later */
22907 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22908 	prog->aux->attach_func_name = tgt_info.tgt_name;
22909 	prog->aux->mod = tgt_info.tgt_mod;
22910 
22911 	if (tgt_prog) {
22912 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22913 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22914 	}
22915 
22916 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22917 		prog->aux->attach_btf_trace = true;
22918 		return 0;
22919 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22920 		if (!bpf_iter_prog_supported(prog))
22921 			return -EINVAL;
22922 		return 0;
22923 	}
22924 
22925 	if (prog->type == BPF_PROG_TYPE_LSM) {
22926 		ret = bpf_lsm_verify_prog(&env->log, prog);
22927 		if (ret < 0)
22928 			return ret;
22929 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
22930 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
22931 		return -EINVAL;
22932 	}
22933 
22934 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22935 	tr = bpf_trampoline_get(key, &tgt_info);
22936 	if (!tr)
22937 		return -ENOMEM;
22938 
22939 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22940 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
22941 
22942 	prog->aux->dst_trampoline = tr;
22943 	return 0;
22944 }
22945 
22946 struct btf *bpf_get_btf_vmlinux(void)
22947 {
22948 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22949 		mutex_lock(&bpf_verifier_lock);
22950 		if (!btf_vmlinux)
22951 			btf_vmlinux = btf_parse_vmlinux();
22952 		mutex_unlock(&bpf_verifier_lock);
22953 	}
22954 	return btf_vmlinux;
22955 }
22956 
22957 /*
22958  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
22959  * this case expect that every file descriptor in the array is either a map or
22960  * a BTF. Everything else is considered to be trash.
22961  */
22962 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
22963 {
22964 	struct bpf_map *map;
22965 	struct btf *btf;
22966 	CLASS(fd, f)(fd);
22967 	int err;
22968 
22969 	map = __bpf_map_get(f);
22970 	if (!IS_ERR(map)) {
22971 		err = __add_used_map(env, map);
22972 		if (err < 0)
22973 			return err;
22974 		return 0;
22975 	}
22976 
22977 	btf = __btf_get_by_fd(f);
22978 	if (!IS_ERR(btf)) {
22979 		err = __add_used_btf(env, btf);
22980 		if (err < 0)
22981 			return err;
22982 		return 0;
22983 	}
22984 
22985 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
22986 	return PTR_ERR(map);
22987 }
22988 
22989 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
22990 {
22991 	size_t size = sizeof(int);
22992 	int ret;
22993 	int fd;
22994 	u32 i;
22995 
22996 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22997 
22998 	/*
22999 	 * The only difference between old (no fd_array_cnt is given) and new
23000 	 * APIs is that in the latter case the fd_array is expected to be
23001 	 * continuous and is scanned for map fds right away
23002 	 */
23003 	if (!attr->fd_array_cnt)
23004 		return 0;
23005 
23006 	/* Check for integer overflow */
23007 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
23008 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
23009 		return -EINVAL;
23010 	}
23011 
23012 	for (i = 0; i < attr->fd_array_cnt; i++) {
23013 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
23014 			return -EFAULT;
23015 
23016 		ret = add_fd_from_fd_array(env, fd);
23017 		if (ret)
23018 			return ret;
23019 	}
23020 
23021 	return 0;
23022 }
23023 
23024 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
23025 {
23026 	u64 start_time = ktime_get_ns();
23027 	struct bpf_verifier_env *env;
23028 	int i, len, ret = -EINVAL, err;
23029 	u32 log_true_size;
23030 	bool is_priv;
23031 
23032 	/* no program is valid */
23033 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
23034 		return -EINVAL;
23035 
23036 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
23037 	 * allocate/free it every time bpf_check() is called
23038 	 */
23039 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
23040 	if (!env)
23041 		return -ENOMEM;
23042 
23043 	env->bt.env = env;
23044 
23045 	len = (*prog)->len;
23046 	env->insn_aux_data =
23047 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
23048 	ret = -ENOMEM;
23049 	if (!env->insn_aux_data)
23050 		goto err_free_env;
23051 	for (i = 0; i < len; i++)
23052 		env->insn_aux_data[i].orig_idx = i;
23053 	env->prog = *prog;
23054 	env->ops = bpf_verifier_ops[env->prog->type];
23055 
23056 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
23057 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
23058 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
23059 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
23060 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
23061 
23062 	bpf_get_btf_vmlinux();
23063 
23064 	/* grab the mutex to protect few globals used by verifier */
23065 	if (!is_priv)
23066 		mutex_lock(&bpf_verifier_lock);
23067 
23068 	/* user could have requested verbose verifier output
23069 	 * and supplied buffer to store the verification trace
23070 	 */
23071 	ret = bpf_vlog_init(&env->log, attr->log_level,
23072 			    (char __user *) (unsigned long) attr->log_buf,
23073 			    attr->log_size);
23074 	if (ret)
23075 		goto err_unlock;
23076 
23077 	ret = process_fd_array(env, attr, uattr);
23078 	if (ret)
23079 		goto skip_full_check;
23080 
23081 	mark_verifier_state_clean(env);
23082 
23083 	if (IS_ERR(btf_vmlinux)) {
23084 		/* Either gcc or pahole or kernel are broken. */
23085 		verbose(env, "in-kernel BTF is malformed\n");
23086 		ret = PTR_ERR(btf_vmlinux);
23087 		goto skip_full_check;
23088 	}
23089 
23090 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
23091 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
23092 		env->strict_alignment = true;
23093 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
23094 		env->strict_alignment = false;
23095 
23096 	if (is_priv)
23097 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
23098 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
23099 
23100 	env->explored_states = kvcalloc(state_htab_size(env),
23101 				       sizeof(struct bpf_verifier_state_list *),
23102 				       GFP_USER);
23103 	ret = -ENOMEM;
23104 	if (!env->explored_states)
23105 		goto skip_full_check;
23106 
23107 	ret = check_btf_info_early(env, attr, uattr);
23108 	if (ret < 0)
23109 		goto skip_full_check;
23110 
23111 	ret = add_subprog_and_kfunc(env);
23112 	if (ret < 0)
23113 		goto skip_full_check;
23114 
23115 	ret = check_subprogs(env);
23116 	if (ret < 0)
23117 		goto skip_full_check;
23118 
23119 	ret = check_btf_info(env, attr, uattr);
23120 	if (ret < 0)
23121 		goto skip_full_check;
23122 
23123 	ret = resolve_pseudo_ldimm64(env);
23124 	if (ret < 0)
23125 		goto skip_full_check;
23126 
23127 	if (bpf_prog_is_offloaded(env->prog->aux)) {
23128 		ret = bpf_prog_offload_verifier_prep(env->prog);
23129 		if (ret)
23130 			goto skip_full_check;
23131 	}
23132 
23133 	ret = check_cfg(env);
23134 	if (ret < 0)
23135 		goto skip_full_check;
23136 
23137 	ret = check_attach_btf_id(env);
23138 	if (ret)
23139 		goto skip_full_check;
23140 
23141 	ret = mark_fastcall_patterns(env);
23142 	if (ret < 0)
23143 		goto skip_full_check;
23144 
23145 	ret = do_check_main(env);
23146 	ret = ret ?: do_check_subprogs(env);
23147 
23148 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
23149 		ret = bpf_prog_offload_finalize(env);
23150 
23151 skip_full_check:
23152 	kvfree(env->explored_states);
23153 
23154 	/* might decrease stack depth, keep it before passes that
23155 	 * allocate additional slots.
23156 	 */
23157 	if (ret == 0)
23158 		ret = remove_fastcall_spills_fills(env);
23159 
23160 	if (ret == 0)
23161 		ret = check_max_stack_depth(env);
23162 
23163 	/* instruction rewrites happen after this point */
23164 	if (ret == 0)
23165 		ret = optimize_bpf_loop(env);
23166 
23167 	if (is_priv) {
23168 		if (ret == 0)
23169 			opt_hard_wire_dead_code_branches(env);
23170 		if (ret == 0)
23171 			ret = opt_remove_dead_code(env);
23172 		if (ret == 0)
23173 			ret = opt_remove_nops(env);
23174 	} else {
23175 		if (ret == 0)
23176 			sanitize_dead_code(env);
23177 	}
23178 
23179 	if (ret == 0)
23180 		/* program is valid, convert *(u32*)(ctx + off) accesses */
23181 		ret = convert_ctx_accesses(env);
23182 
23183 	if (ret == 0)
23184 		ret = do_misc_fixups(env);
23185 
23186 	/* do 32-bit optimization after insn patching has done so those patched
23187 	 * insns could be handled correctly.
23188 	 */
23189 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
23190 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
23191 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
23192 								     : false;
23193 	}
23194 
23195 	if (ret == 0)
23196 		ret = fixup_call_args(env);
23197 
23198 	env->verification_time = ktime_get_ns() - start_time;
23199 	print_verification_stats(env);
23200 	env->prog->aux->verified_insns = env->insn_processed;
23201 
23202 	/* preserve original error even if log finalization is successful */
23203 	err = bpf_vlog_finalize(&env->log, &log_true_size);
23204 	if (err)
23205 		ret = err;
23206 
23207 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
23208 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
23209 				  &log_true_size, sizeof(log_true_size))) {
23210 		ret = -EFAULT;
23211 		goto err_release_maps;
23212 	}
23213 
23214 	if (ret)
23215 		goto err_release_maps;
23216 
23217 	if (env->used_map_cnt) {
23218 		/* if program passed verifier, update used_maps in bpf_prog_info */
23219 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
23220 							  sizeof(env->used_maps[0]),
23221 							  GFP_KERNEL);
23222 
23223 		if (!env->prog->aux->used_maps) {
23224 			ret = -ENOMEM;
23225 			goto err_release_maps;
23226 		}
23227 
23228 		memcpy(env->prog->aux->used_maps, env->used_maps,
23229 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
23230 		env->prog->aux->used_map_cnt = env->used_map_cnt;
23231 	}
23232 	if (env->used_btf_cnt) {
23233 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
23234 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
23235 							  sizeof(env->used_btfs[0]),
23236 							  GFP_KERNEL);
23237 		if (!env->prog->aux->used_btfs) {
23238 			ret = -ENOMEM;
23239 			goto err_release_maps;
23240 		}
23241 
23242 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
23243 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
23244 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
23245 	}
23246 	if (env->used_map_cnt || env->used_btf_cnt) {
23247 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
23248 		 * bpf_ld_imm64 instructions
23249 		 */
23250 		convert_pseudo_ld_imm64(env);
23251 	}
23252 
23253 	adjust_btf_func(env);
23254 
23255 err_release_maps:
23256 	if (!env->prog->aux->used_maps)
23257 		/* if we didn't copy map pointers into bpf_prog_info, release
23258 		 * them now. Otherwise free_used_maps() will release them.
23259 		 */
23260 		release_maps(env);
23261 	if (!env->prog->aux->used_btfs)
23262 		release_btfs(env);
23263 
23264 	/* extension progs temporarily inherit the attach_type of their targets
23265 	   for verification purposes, so set it back to zero before returning
23266 	 */
23267 	if (env->prog->type == BPF_PROG_TYPE_EXT)
23268 		env->prog->expected_attach_type = 0;
23269 
23270 	*prog = env->prog;
23271 
23272 	module_put(env->attach_btf_mod);
23273 err_unlock:
23274 	if (!is_priv)
23275 		mutex_unlock(&bpf_verifier_lock);
23276 	vfree(env->insn_aux_data);
23277 	kvfree(env->insn_hist);
23278 err_free_env:
23279 	kvfree(env);
23280 	return ret;
23281 }
23282